openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
993 lines (992 loc) • 43.2 kB
JavaScript
import { o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { m as resolveGatewayServiceDescription } from "./constants-BZisy3jr.mjs";
import { a as extractErrorCode, r as collectErrorGraphCandidates, u as readErrorCauses } from "./error-coercion-hDrHOSGy.mjs";
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { i as isMissingPathError, n as ignoreMissingPath, t as hasErrnoCode } from "./errno-DFcoqIT9.mjs";
import { n as sanitizeForLog } from "./ansi-CZa2t0Hf.mjs";
import "./errors-BKzCeTYb.mjs";
import { o as normalizeEnvVarKey } from "./host-env-security-BrTYS4pH.mjs";
import { l as syncDirectory, o as publishFileNoClobber, s as requireDirectorySync } from "./directory-durability-DlnWwNmv.mjs";
import { Fn as object, Jn as string, Lt as boolean, Nt as array, Pn as number, Un as record, nr as tuple, or as union, qn as strictObject, sr as unknown, xn as literal } from "./schemas-Cy6abvsu.mjs";
import { n as sha256Hex } from "./node-crypto-B6yuTjmm.mjs";
import { i as hasCommandProcessCleanupError } from "./exec-result-DJMhztYN.mjs";
import { a as ServiceOwnershipRefusalError } from "./service-inspection-error-BKgh5HDJ.mjs";
import { t as getWindowsCmdExePath } from "./windows-install-roots-Df6dQDK7.mjs";
import { n as resolveGatewayStateDir, t as resolveDaemonHomeDir } from "./paths-CNsU_DAo.mjs";
import { t as quoteCliArg } from "./quote-cli-arg-J7A9UE6m.mjs";
import { t as privateFileStore } from "./private-file-store-D564pKJx.mjs";
import { c as withGatewayServiceInstallationRecovery, i as assertGatewayServiceUpdateCurrent, n as GatewayServiceAuthorityError } from "./service-update-authority-wlK0pAdP.mjs";
import { n as normalizeWindowsPathSeparators, t as formatLine } from "./output-D4pCmbg2.mjs";
import { n as formatServiceInspectionDetail } from "./service-runtime-BHR12N-P.mjs";
import { t as execFileUtf8 } from "./exec-file-DvORLSKM.mjs";
import { o as resolveGatewaySupervisorLogPaths } from "./restart-logs-zLeNdzsY.mjs";
import { a as readServiceFileState, i as publishServiceFile, n as matchesServiceFilePublication, r as matchesServiceFileState } from "./service-stage-BrbEvtmC.mjs";
import { n as resolveLaunchAgentLabel } from "./launchd-label-DdmmL_TH.mjs";
import { a as normalizeLaunchdPlistXml, i as decodeLaunchdPlistMetadata, o as quoteLaunchAgentEnvironmentValue, r as buildLaunchAgentPlist, s as readLaunchAgentProgramArgumentsFromFile, t as LAUNCH_AGENT_ENV_WRAPPER_SHELL } from "./launchd-plist-wGTZ-pik.mjs";
import path from "node:path";
import { X509Certificate, createHash, createPublicKey, randomUUID } from "node:crypto";
import fs from "node:fs/promises";
import { isDeepStrictEqual } from "node:util";
import { readRegularFile } from "@openclaw/fs-safe/advanced";
//#region src/daemon/launchd-exec.ts
async function execLaunchctl(e, t) {
const n = typeof t === "object" ? t : void 0;
let r = typeof t === "number" ? t : void 0;
if (n) r = Math.max(1, Math.min(r ?? Infinity, n.remainingMs()));
n?.signal.throwIfAborted();
const i = process.platform === "win32";
const a = i ? getWindowsCmdExePath() : "launchctl";
const o = i ? [
"/d",
"/s",
"/c",
"launchctl",
...e
] : e;
const s = await execFileUtf8(a, o, r && r > 0 ? {
timeout: r,
killSignal: "SIGKILL"
} : {});
n?.signal.throwIfAborted();
return s;
}
function launchctlInspectionReason(e, t) {
if (e.termination === "error" && ["EACCES", "EPERM"].includes(e.errorCode ?? "")) return "service-manager-access-denied";
if (e.termination === "exit" && [
1,
13,
125
].includes(e.code)) return t.startsWith("system/") ? "launchd-system-domain-unavailable" : "launchd-gui-domain-unavailable";
}
function isLaunchctlNotLoaded(e) {
const t = normalizeLowercaseStringOrEmpty(e.stderr || e.stdout);
return e.termination === "exit" && (t.includes("no such process") || t.includes("could not find service") || t.includes("not found"));
}
function formatLaunchctlResultDetail(e) {
const t = sanitizeForLog((e.stderr || e.stdout).replace(/[\r\n\t]+/g, " ")).replace(/\s+/g, " ").trim();
return truncateUtf16Safe(t, 1e3);
}
//#endregion
//#region src/daemon/launchd-env-wrapper.ts
const LAUNCH_AGENT_ENV_FILE_HEADER = "# Generated by OpenClaw. Do not edit while the gateway service is installed.";
function buildLaunchAgentEnvironmentWrapper() {
return `#!/bin/sh
set -eu
invalid_env() {
echo "Invalid LaunchAgent environment file; run openclaw gateway install --force to repair the service." >&2
exit 78
}
[ "$#" -ge 2 ] || invalid_env
env_file="$1"
shift
[ -f "$env_file" ] && [ -r "$env_file" ] || invalid_env
IFS= read -r env_header < "$env_file" || invalid_env
[ "$env_header" = '${LAUNCH_AGENT_ENV_FILE_HEADER}' ] || invalid_env
. "$env_file"
exec "$@"
`;
}
function isGeneratedLaunchAgentEnvironmentWrapper(e) {
return e === buildLaunchAgentEnvironmentWrapper() || e === `#!/bin/sh
set -eu
env_file="$1"
shift
if [ -f "$env_file" ]; then
. "$env_file"
fi
exec "$@"
`;
}
//#endregion
//#region src/daemon/launchd-legacy-ca-native.ts
const TRUST_INSPECTION_SCRIPT = String.raw`
ObjC.import("Foundation");
ObjC.import("Security");
ObjC.bindFunction("SecTrustSettingsCreateExternalRepresentation", ["int", ["int", "id *"]]);
ObjC.bindFunction("SecTrustSettingsCopyCertificates", ["int", ["int", "id *"]]);
ObjC.bindFunction("SecCertificateCopyData", ["id", ["id"]]);
ObjC.bindFunction("SecCertificateCreateWithData", ["id", ["void *", "id"]]);
ObjC.bindFunction("SecPolicyCreateBasicX509", ["id", []]);
ObjC.bindFunction("SecTrustCreateWithCertificates", ["int", ["id", "id", "id *"]]);
ObjC.bindFunction("SecTrustEvaluateWithError", ["bool", ["id", "id *"]]);
ObjC.bindFunction("SecTrustCopyResult", ["id", ["id"]]);
ObjC.bindFunction("SecTrustSetNetworkFetchAllowed", ["int", ["id", "bool"]]);
ObjC.bindFunction("SecTrustGetCertificateCount", ["long", ["id"]]);
function run(argv) {
if (argv[0] === "trust-settings") {
const domains = [];
for (let domain = 0; domain < 3; domain++) {
const external = Ref();
const exportStatus = $.SecTrustSettingsCreateExternalRepresentation(domain, external);
let exportVersion = null, records = null;
if (exportStatus === 0) {
const plist = $.NSPropertyListSerialization.propertyListWithDataOptionsFormatError(external[0], 0, null, null);
exportVersion = Number(ObjC.unwrap(plist.objectForKey("trustVersion")));
const list = plist.objectForKey("trustList");
records = ObjC.deepUnwrap(list.allKeys).map(function(key) {
const settings = ObjC.deepUnwrap(list.objectForKey(key).objectForKey("trustSettings")) || [];
if (!Array.isArray(settings)) throw new Error("Unknown native trust settings");
let deny = false;
settings.forEach(function(setting) {
if (!setting || typeof setting !== "object" || Array.isArray(setting)) throw new Error("Unknown native trust record");
const result = setting.kSecTrustSettingsResult;
if (result !== undefined && [1, 2, 3, 4].indexOf(result) === -1) throw new Error("Unknown native trust result");
if (result === 3) deny = true;
});
return {certificateSHA1: key, deny: deny};
});
}
const certs = Ref();
const certificatesStatus = $.SecTrustSettingsCopyCertificates(domain, certs);
let certificateDERBase64 = null;
if (certificatesStatus === 0) {
certificateDERBase64 = [];
const count = Number(ObjC.unwrap(certs[0].count));
for (let i = 0; i < count; i++) {
certificateDERBase64.push(ObjC.unwrap($.SecCertificateCopyData(certs[0].objectAtIndex(i)).base64EncodedStringWithOptions(0)));
}
}
domains.push({domain: domain, exportStatus: exportStatus, exportVersion: exportVersion, records: records, certificatesStatus: certificatesStatus, certificateDERBase64: certificateDERBase64});
}
return JSON.stringify({domains: domains});
}
if (argv[0] !== "evaluate" || argv.length !== 2) throw new Error("Unknown certificate inspection");
const cert = $.SecCertificateCreateWithData(null, $.NSData.alloc.initWithBase64EncodedStringOptions(argv[1], 0));
if (!cert) throw new Error("Invalid certificate");
const out = Ref();
const createStatus = $.SecTrustCreateWithCertificates($.NSArray.arrayWithObject(cert), $.SecPolicyCreateBasicX509(), out);
if (createStatus !== 0) throw new Error("Native trust creation failed");
const trust = out[0];
const networkStatus = $.SecTrustSetNetworkFetchAllowed(trust, false);
if (networkStatus !== 0) throw new Error("Native offline inspection failed");
const error = Ref();
const ok = $.SecTrustEvaluateWithError(trust, error);
return JSON.stringify({createStatus: createStatus, networkStatus: networkStatus, certificateCount: String($.SecTrustGetCertificateCount(trust)), ok: ok, errorCode: error[0] ? Number(ObjC.unwrap(error[0].code)) : null, result: ObjC.deepUnwrap($.SecTrustCopyResult(trust))});
}`;
const trustSettingsSchema = strictObject({ domains: array(strictObject({
domain: number().int().min(0).max(2),
exportStatus: literal(0),
exportVersion: literal(1),
records: array(strictObject({
certificateSHA1: string().regex(/^[a-f0-9]{40}$/iu),
deny: boolean()
})),
certificatesStatus: union([literal(0), literal(-25263)]),
certificateDERBase64: array(string()).nullable()
})).length(3) });
function certificatePublicKeyHash(e) {
const t = createPublicKey({
key: e.publicKey.export({ format: "jwk" }),
format: "jwk"
});
return createHash("sha256").update(t.export({
format: "der",
type: "spki"
})).digest("hex");
}
async function inspectNativeTrust(e) {
const t = await execFileUtf8("/usr/bin/osascript", [
"-l",
"JavaScript",
"-e",
TRUST_INSPECTION_SCRIPT,
...e
], { timeout: 15e3 });
if (t.code !== 0 || t.termination !== "exit") throw new Error("macOS trust inspection unavailable");
return JSON.parse(t.stdout);
}
/** Policy/application-scoped Deny can be invisible to Basic X509 evaluation. */
async function readNativeDistrustedPublicKeys() {
const { domains: e } = trustSettingsSchema.parse(await inspectNativeTrust(["trust-settings"]));
if (new Set(e.map(({ domain: e }) => e)).size !== 3) throw new Error("Incomplete macOS trust domains");
const t = /* @__PURE__ */ new Set();
for (const n of e) {
if (n.certificatesStatus === 0 !== (n.certificateDERBase64 !== null) || n.certificatesStatus === -25263 && n.records.length > 0) throw new Error("Incomplete macOS trust certificates");
const e = /* @__PURE__ */ new Map();
for (const t of n.certificateDERBase64 ?? []) {
const n = new X509Certificate(Buffer.from(t, "base64"));
e.set(createHash("sha1").update(n.raw).digest("hex"), n);
}
for (const r of n.records) {
if (!r.deny) continue;
const n = e.get(r.certificateSHA1.toLowerCase());
if (!n) throw new Error("Unresolved macOS distrust certificate");
t.add(certificatePublicKeyHash(n));
}
}
return t;
}
const evaluationSchema = object({
createStatus: literal(0),
networkStatus: literal(0),
certificateCount: literal("1"),
ok: boolean(),
errorCode: number().int().nullable(),
result: object({
TrustResultValue: number().int(),
TrustResultDetails: tuple([record(string(), unknown())])
})
});
/** Accept only clean native trust or the exact expected private-root non-anchor. */
async function isNativeRootEligible(e) {
const t = evaluationSchema.parse(await inspectNativeTrust(["evaluate", e.raw.toString("base64")]));
const n = t.result.TrustResultDetails[0];
if (t.ok && t.errorCode === null && [1, 4].includes(t.result.TrustResultValue) && Object.keys(n).length === 0) return true;
return !t.ok && t.errorCode === -67843 && t.result.TrustResultValue === 5 && Object.keys(n).length === 2 && n.AnchorTrusted === false && Array.isArray(n.StatusCodes) && n.StatusCodes.length === 1 && n.StatusCodes[0] === -2147409622;
}
//#endregion
//#region src/daemon/launchd-legacy-ca-migration.ts
const LEGACY_CA_PATH = "/etc/ssl/cert.pem";
const STOCK_BYTES = 333483;
const STOCK_SHA256 = "9dae8d76e55cb08991f2b672d58999ea15560d910759c16b544f843bdffbb994";
const INCIDENT_KEYS = /* @__PURE__ */ new Set([
"43bffa19d6ef651451f6841e019931e96f6f2eaeff28ab4b6f1ce4576de2717b",
"49dd353dc2b919a3770645117d0e60c16115e7d1bc259eefe734b00ea434fe5f",
"5c0660a2b164910d8ff589c18e14552e9e0ec237dcefe2cb736d41a4811f81a0",
"63ecefee431d49523bc1136c4e72d0206a477086caf606cd5cf025686c109cf8",
"92c063d67e8f14db71d288e11266ffdaf69cbf115f7bab14f3bc2f68d25e0e30",
"e0254c7fcdc265e2f0f8a428dabb75ab4ae039b4872d62f5ee57f0877d5a8a41",
"ebed6475c2c2d80fcb199f3fe8dd6e6b3ce60b77eb15d4e42c3dec0c6f5b5105",
"ec4ffa1ad0ac88081314b7aaffef6a91f97cd57291bb5ba686c5415f5eb4f6b6"
]);
function parseCertificates(e, t = false) {
const n = [...e.matchAll(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/gu)];
if (t && e.replace(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/gu, "").replace(/^\s*#.*$/gmu, "").trim()) throw new Error("Malformed appended certificate data");
return n.map(([e]) => new X509Certificate(e));
}
/** Best effort must never hide a lost writer or an uncontained native child. */
function rethrowCaMigrationAuthorityError(e) {
if (hasCommandProcessCleanupError(e)) throw e;
const t = collectErrorGraphCandidates(e, readErrorCauses).find((e) => e instanceof GatewayServiceAuthorityError);
if (t) throw t;
}
async function publishMaintainedBundle(e) {
const matchesExisting = async () => {
try {
const { buffer: t, stat: n } = await readRegularFile({ filePath: e.destination });
if (t.toString("utf8") !== e.contents || (n.mode & 511) !== 384) throw Object.assign(/* @__PURE__ */ new Error("Existing maintained CA destination conflicts with migration"), { code: "EEXIST" });
e.assertCurrent();
const r = await fs.open(e.destination, "r");
try {
await r.sync();
} finally {
await r.close();
}
e.assertCurrent();
requireDirectorySync(await syncDirectory(path.dirname(e.destination)), "Maintained CA bundle directory");
e.assertCurrent();
return true;
} catch (e) {
if (extractErrorCode(e) === "ENOENT") return false;
throw e;
}
};
if (await matchesExisting()) return;
e.assertCurrent();
const t = path.dirname(e.destination);
const n = `.migration-${randomUUID()}.pem`;
const r = path.join(t, n);
try {
await privateFileStore(t).writeText(n, e.contents);
const i = await fs.open(r, "r");
try {
await i.sync();
} finally {
await i.close();
}
e.assertCurrent();
try {
await publishFileNoClobber(r, e.destination, {
strategy: "link-required",
durability: "fail-closed"
});
} catch (e) {
if (extractErrorCode(e) !== "EEXIST" || !await matchesExisting()) throw e;
}
e.assertCurrent();
} finally {
await fs.unlink(r).catch(() => void 0);
}
}
/** Refine only CA environment at the shared native service-publication owner. */
async function prepareLaunchAgentCaEnvironment(e) {
const t = { ...e.environment };
const n = t.NODE_EXTRA_CA_CERTS?.trim();
const r = e.installedExtraCa?.trim();
if (n && n !== LEGACY_CA_PATH) return t;
if (r && r !== LEGACY_CA_PATH) {
t.NODE_EXTRA_CA_CERTS = e.installedExtraCa;
return t;
}
if (n === LEGACY_CA_PATH) {
delete t.NODE_EXTRA_CA_CERTS;
t.NODE_USE_SYSTEM_CA ??= "1";
}
if (r !== LEGACY_CA_PATH) return t;
delete t.NODE_EXTRA_CA_CERTS;
t.NODE_USE_SYSTEM_CA ??= "1";
const i = path.join(resolveGatewayStateDir(e.env), "service-ca", `${e.label}-operator-ca.pem`);
const a = `Keep legitimate operator roots in a distinct maintained PEM bundle, set NODE_EXTRA_CA_CERTS to its absolute path, and reinstall the service with openclaw gateway install --force (Gateway) or openclaw node install --force (node host). Future CA rotations belong in that maintained bundle, never ${LEGACY_CA_PATH}. Compromised keys remain rejected.`;
let o = "input";
try {
const n = await fs.readFile(LEGACY_CA_PATH);
if (n.length < STOCK_BYTES || createHash("sha256").update(n.subarray(0, STOCK_BYTES)).digest("hex") !== STOCK_SHA256) {
e.warn(`CA migration ambiguous: ${LEGACY_CA_PATH} does not retain the authenticated historical stock prefix. Its old trust override was retired; private connections may fail. ${a}`);
return t;
}
const r = parseCertificates(n.subarray(STOCK_BYTES).toString("utf8"), true);
o = "classification";
const s = new Set(parseCertificates(n.subarray(0, STOCK_BYTES).toString("utf8")).map(certificatePublicKeyHash));
const c = /* @__PURE__ */ new Map();
let l = 0;
let u = 0;
for (const e of r) {
let t;
try {
t = certificatePublicKeyHash(e);
} catch {
u++;
continue;
}
if (INCIDENT_KEYS.has(t) || s.has(t)) {
l++;
continue;
}
if (!e.ca || e.subject !== e.issuer || !e.verify(e.publicKey)) {
u++;
continue;
}
c.set(t, e);
}
const d = [];
if (c.size) {
o = "native";
const e = await readNativeDistrustedPublicKeys();
for (const [t, n] of c) {
if (e.has(t)) {
l++;
continue;
}
if (!await isNativeRootEligible(n)) {
u++;
continue;
}
d.push(n);
}
}
const f = l ? ` ${l} stock, compromised, or explicitly distrusted key occurrence(s) excluded.` : "";
if (!d.length) {
e.warn(u ? `CA migration ambiguous: no eligible operator roots could be migrated; ${u} addition(s) require manual review.${f} The legacy override was retired; private connections may fail. ${a}` : `CA migration unnecessary: no eligible operator additions beyond the historical stock bundle.${f} The legacy override was retired; macOS system trust is used.`);
return t;
}
o = "publication";
await publishMaintainedBundle({
destination: i,
contents: d.map((e) => `${e.toString().trim()}\n`).join(""),
assertCurrent: () => {
assertGatewayServiceUpdateCurrent();
e.assertCurrent();
}
});
t.NODE_EXTRA_CA_CERTS = i;
e.warn(`CA certificates migrated once to ${i} (${d.length} operator root(s)).${f} ${u ? `${u} ambiguous addition(s) were not migrated; dependent connections may fail. ` : ""}Future CA rotations belong in this maintained bundle; the original ${LEGACY_CA_PATH} is untouched and will not be synchronized.${u ? ` ${a}` : ""}`);
return t;
} catch (n) {
rethrowCaMigrationAuthorityError(n);
const r = extractErrorCode(n);
const s = r && /^[a-z0-9_-]+$/iu.test(r) ? ` (${r})` : "";
const c = o === "publication" ? `publishing ${i} without replacing operator files` : o === "native" ? "establishing macOS trust and explicit distrust" : o === "classification" ? "establishing operator certificate and key eligibility" : `reading or parsing ${LEGACY_CA_PATH}`;
e.warn(`CA migration ${o === "native" || o === "classification" ? "ambiguous" : "failed"} while ${c}${s}. The obsolete override was retired; private connections may fail. Original input and conflicting operator files were preserved. ${a}`);
return t;
}
}
//#endregion
//#region src/daemon/launchd-system.ts
/** Detects system-domain launchd ownership before mutating a user LaunchAgent. */
const SYSTEM_LAUNCH_DAEMON_DIR = "/Library/LaunchDaemons";
/**
* Renders the package-independent ownership probe used by detached restart helpers.
* The caller must refuse activation when `openclaw_system_launchd_conflict` is non-empty.
*/
function renderSystemLaunchDaemonOwnershipShellProbe(e) {
const t = `system/${e}`;
return `openclaw_system_launchd_conflict=""
openclaw_system_launchd_detail=""
openclaw_system_launchd_target=${quoteCliArg(t)}
openclaw_system_launchd_dir=${quoteCliArg(SYSTEM_LAUNCH_DAEMON_DIR)}
openclaw_system_launchd_label=${quoteCliArg(e)}
openclaw_query_system_launchd() {
openclaw_system_launchd_probe=$(launchctl print "$openclaw_system_launchd_target" 2>&1)
openclaw_system_launchd_probe_status=$?
# POSIX shell status 126/127 means execution failed; >128 can represent a signal.
# Partial absence output cannot establish that the ownership query completed.
if [ "$openclaw_system_launchd_probe_status" -eq 0 ]; then
openclaw_system_launchd_conflict="$openclaw_system_launchd_target"
openclaw_system_launchd_detail="loaded system LaunchDaemon $openclaw_system_launchd_target"
elif [ "$openclaw_system_launchd_probe_status" -eq 126 ] || [ "$openclaw_system_launchd_probe_status" -eq 127 ] || [ "$openclaw_system_launchd_probe_status" -gt 128 ] ||
! printf '%s' "$openclaw_system_launchd_probe" | /usr/bin/grep -Eiq 'could not find service|no such process|not found'; then
openclaw_system_launchd_conflict="$openclaw_system_launchd_target"
openclaw_system_launchd_detail="could not verify $openclaw_system_launchd_target (exit $openclaw_system_launchd_probe_status): $openclaw_system_launchd_probe"
fi
}
openclaw_query_system_launchd
if [ -z "$openclaw_system_launchd_conflict" ]; then
if [ ! -e "$openclaw_system_launchd_dir" ]; then
:
elif [ ! -r "$openclaw_system_launchd_dir" ] || [ ! -x "$openclaw_system_launchd_dir" ]; then
openclaw_system_launchd_conflict="$openclaw_system_launchd_dir"
openclaw_system_launchd_detail="could not inspect $openclaw_system_launchd_dir"
else
openclaw_system_launchd_entries=""
if openclaw_system_launchd_entries=$(/usr/bin/mktemp "\${TMPDIR:-/tmp}/openclaw-launchd-scan.XXXXXX" 2>&1); then
if /usr/bin/find "$openclaw_system_launchd_dir" -mindepth 1 -maxdepth 1 -name '*.plist' -print0 >"$openclaw_system_launchd_entries"; then
while IFS= read -r -d '' openclaw_system_launchd_plist; do
# Unreadable plists are treated as foreign: loaded same-label daemons are caught by the
# bracketing launchctl checks; an unloaded unreadable same-label plist is an accepted operator-created edge (#120481).
if [ ! -r "$openclaw_system_launchd_plist" ]; then
continue
fi
# Preserve exact string labels, including trailing newlines, on both parser paths.
# plutil documents exit 1 for parse failure. Signals/execution errors cannot
# establish a missing Label, even if a later lint accepts the same plist.
if openclaw_system_launchd_plist_label=$(/usr/bin/plutil -extract Label raw -expect string -n -o - -- "$openclaw_system_launchd_plist" 2>&1; openclaw_system_launchd_parse_status=$?; printf '.'; exit "$openclaw_system_launchd_parse_status"); then
openclaw_system_launchd_plist_label=\${openclaw_system_launchd_plist_label%.}
if [ "$openclaw_system_launchd_plist_label" != "$openclaw_system_launchd_label" ]; then
continue
fi
openclaw_system_launchd_conflict="$openclaw_system_launchd_plist"
openclaw_system_launchd_detail="installed same-label system LaunchDaemon plist $openclaw_system_launchd_plist"
break
elif [ "$?" -eq 1 ] && /usr/bin/plutil -lint -- "$openclaw_system_launchd_plist" >/dev/null 2>&1; then
continue
else
# Endpoint protection can deny plutil while allowing a real read. The system
# Perl reader survives package swaps and classifies errno, not diagnostic text.
openclaw_system_launchd_snapshot=$(/usr/bin/mktemp "\${TMPDIR:-/tmp}/openclaw-launchd-plist.XXXXXX")
if [ -n "$openclaw_system_launchd_snapshot" ]; then
/usr/bin/perl -e '
use strict;
use Fcntl qw(O_RDONLY O_NONBLOCK);
use Errno qw(EACCES EPERM ENOENT ENOTDIR);
sub read_failed {
my $code = 0 + $!;
exit(($code == EACCES || $code == EPERM) ? 77 :
($code == ENOENT || $code == ENOTDIR) ? 66 : 74);
}
$SIG{ALRM} = sub { exit 74; };
alarm 5;
sysopen(my $file, $ARGV[0], O_RDONLY | O_NONBLOCK) or read_failed();
-f $file or exit 74;
# Inherited PERL_UNICODE must not turn binary plist input into a UTF-8 handle.
binmode $file;
binmode STDOUT;
my $total = 0;
while (1) {
my $count = sysread($file, my $bytes, 65536);
defined($count) or read_failed();
last if !$count;
$total += $count;
$total <= 1048576 or exit 75;
print STDOUT $bytes or exit 74;
}
close($file) or read_failed();
close(STDOUT) or exit 74;
' "$openclaw_system_launchd_plist" >"$openclaw_system_launchd_snapshot" 2>/dev/null
openclaw_system_launchd_read_status=$?
if [ "$openclaw_system_launchd_read_status" -eq 77 ] || [ "$openclaw_system_launchd_read_status" -eq 66 ]; then
/bin/rm -f "$openclaw_system_launchd_snapshot"
continue
elif [ "$openclaw_system_launchd_read_status" -eq 0 ]; then
# The sentinel preserves label newlines through command substitution.
if openclaw_system_launchd_plist_label=$(/usr/bin/plutil -extract Label raw -expect string -n -o - -- - <"$openclaw_system_launchd_snapshot" 2>/dev/null; openclaw_system_launchd_parse_status=$?; printf '.'; exit "$openclaw_system_launchd_parse_status"); then
openclaw_system_launchd_plist_label=\${openclaw_system_launchd_plist_label%.}
/bin/rm -f "$openclaw_system_launchd_snapshot"
if [ "$openclaw_system_launchd_plist_label" != "$openclaw_system_launchd_label" ]; then
continue
fi
openclaw_system_launchd_conflict="$openclaw_system_launchd_plist"
openclaw_system_launchd_detail="installed same-label system LaunchDaemon plist $openclaw_system_launchd_plist"
break
elif [ "$?" -eq 1 ] && /usr/bin/plutil -lint -- - <"$openclaw_system_launchd_snapshot" >/dev/null 2>&1; then
/bin/rm -f "$openclaw_system_launchd_snapshot"
continue
fi
fi
/bin/rm -f "$openclaw_system_launchd_snapshot"
fi
openclaw_system_launchd_conflict="$openclaw_system_launchd_plist"
openclaw_system_launchd_detail="could not inspect system LaunchDaemon plist $openclaw_system_launchd_plist: $openclaw_system_launchd_plist_label"
break
fi
done <"$openclaw_system_launchd_entries"
else
openclaw_system_launchd_conflict="$openclaw_system_launchd_dir"
openclaw_system_launchd_detail="could not enumerate $openclaw_system_launchd_dir"
fi
/bin/rm -f "$openclaw_system_launchd_entries"
else
openclaw_system_launchd_conflict="$openclaw_system_launchd_dir"
openclaw_system_launchd_detail="could not create a secure system LaunchDaemon scan snapshot: $openclaw_system_launchd_entries"
fi
fi
fi
`;
}
function classifySystemLaunchDaemonQuery(e, t) {
if (t.code === 0) return {
status: "loaded",
serviceTarget: e
};
return isLaunchctlNotLoaded(t) ? {
status: "absent",
serviceTarget: e
} : {
status: "unverifiable",
serviceTarget: e,
operation: "launchctl",
detail: formatLaunchctlResultDetail(t) || `exit code ${t.code}`,
reason: launchctlInspectionReason(t, e)
};
}
async function inspectSystemLaunchDaemonOwnership(e, t = {}) {
const n = `system/${e}`;
if (process.platform !== "darwin") return {
status: "absent",
serviceTarget: n
};
const r = classifySystemLaunchDaemonQuery(n, await execLaunchctl(["print", n], t.timeoutMs));
if (r.status !== "absent") return r;
if (t.scanInstalledPlists === false) return {
status: "absent",
serviceTarget: n
};
let i;
try {
i = await fs.readdir(SYSTEM_LAUNCH_DAEMON_DIR);
} catch (e) {
if (isMissingPathError(e)) return {
status: "absent",
serviceTarget: n
};
return {
status: "unverifiable",
serviceTarget: n,
operation: "filesystem",
detail: formatServiceInspectionDetail(e)
};
}
for (const t of i.filter((e) => e.endsWith(".plist")).toSorted()) {
const r = path.posix.join(SYSTEM_LAUNCH_DAEMON_DIR, t);
try {
const t = await fs.readFile(r).catch((e) => {
if (isMissingPathError(e) || hasErrnoCode(e, "EACCES") || hasErrnoCode(e, "EPERM")) return null;
throw e;
});
if (t === null) continue;
if ((await decodeLaunchdPlistMetadata(t))?.Label === e) return {
status: "installed",
serviceTarget: n,
plistPath: r
};
} catch (e) {
return {
status: "unverifiable",
serviceTarget: n,
operation: "filesystem",
detail: `${r}: ${formatServiceInspectionDetail(e)}`
};
}
}
return {
status: "absent",
serviceTarget: n
};
}
function formatSystemLaunchDaemonOwnershipSummary(e) {
switch (e.status) {
case "loaded": return `System LaunchDaemon ${e.serviceTarget} already owns this gateway label.`;
case "installed": return `System LaunchDaemon plist ${e.plistPath} already owns this gateway label.`;
case "unverifiable": return `System LaunchDaemon ownership for ${e.serviceTarget} could not be verified: ${e.detail}`;
default: throw new Error(`Unexpected system LaunchDaemon ownership: ${String(e)}`);
}
}
function formatSystemLaunchDaemonOwnershipError(e) {
const t = e.status === "loaded" ? `Keep it as the sole gateway manager, or unload it with \`sudo launchctl bootout ${e.serviceTarget}\` and remove its plist before retrying.` : e.status === "installed" ? `Keep it as the sole gateway manager, or remove or relocate ${quoteCliArg(e.plistPath)} before retrying.` : "Fix the reported launchctl or filesystem access error, then retry.";
return [
formatSystemLaunchDaemonOwnershipSummary(e),
"Refusing to create or activate a user LaunchAgent for the same label because duplicate KeepAlive managers can restart-loop the gateway.",
"OpenClaw does not manage system LaunchDaemons, and --force does not override system ownership.",
t
].join("\n");
}
var SystemLaunchDaemonOwnershipError = class extends ServiceOwnershipRefusalError {
constructor(e) {
super("launchd-system-owned", formatSystemLaunchDaemonOwnershipError(e));
this.ownership = e;
this.code = "SYSTEM_LAUNCH_DAEMON_OWNERSHIP";
this.name = "SystemLaunchDaemonOwnershipError";
}
};
function isSystemLaunchDaemonOwnershipError(e) {
return e instanceof SystemLaunchDaemonOwnershipError;
}
async function assertNoSystemLaunchDaemonOwnership(e) {
const t = await inspectSystemLaunchDaemonOwnership(e);
if (t.status !== "absent") throw new SystemLaunchDaemonOwnershipError(t);
}
//#endregion
//#region src/daemon/launchd-service-files.ts
const LAUNCH_AGENT_DIR_MODE = 493;
const LAUNCH_AGENT_PLIST_MODE = 420;
const LAUNCH_AGENT_PRIVATE_DIR_MODE = 448;
const LAUNCH_AGENT_ENV_FILE_MODE = 384;
const LAUNCH_AGENT_ENV_WRAPPER_MODE = 448;
const LAUNCH_AGENT_ENV_DIR_NAME = "service-env";
function resolveLaunchAgentPlistPathForLabel(e, t) {
const n = normalizeWindowsPathSeparators(resolveDaemonHomeDir(e));
return path.posix.join(n, "Library", "LaunchAgents", `${t}.plist`);
}
/**
* Removes a plist whose service is already booted out, keeping a copy in Trash when allowed.
* macOS privacy protection can deny ~/.Trash to an app-launched helper while the user's
* LaunchAgents directory stays writable; stopping halfway would leave the Gateway unloaded
* with its definition still in place.
*/
async function removeBootedOutLaunchAgentPlist(e, t) {
try {
assertGatewayServiceUpdateCurrent();
await fs.mkdir(path.dirname(t), { recursive: true });
assertGatewayServiceUpdateCurrent();
await fs.rename(e, t);
return { trashed: true };
} catch (e) {
if (!hasErrnoCode(e, "EPERM") && !hasErrnoCode(e, "EACCES")) throw e;
}
assertGatewayServiceUpdateCurrent();
await fs.unlink(e);
return { trashed: false };
}
function resolveLaunchAgentEnvDir(e) {
return path.join(resolveGatewayStateDir(e), LAUNCH_AGENT_ENV_DIR_NAME);
}
function resolveLaunchAgentEnvFilePath(e, t) {
return path.join(resolveLaunchAgentEnvDir(e), `${t}.env`);
}
function resolveLaunchAgentEnvWrapperPath(e, t) {
return path.join(resolveLaunchAgentEnvDir(e), `${t}-env-wrapper.sh`);
}
function collectLaunchAgentEnvironmentEntries(e) {
const t = [];
for (const [n, r] of Object.entries(e ?? {})) {
const e = normalizeEnvVarKey(n, { portable: true });
if (!e || r === void 0 || !r.trim() && e !== "NODE_OPTIONS") continue;
t.push([e, r]);
}
return t.toSorted(([e], [t]) => e.localeCompare(t));
}
function buildLaunchAgentEnvironmentFile(e) {
return [
LAUNCH_AGENT_ENV_FILE_HEADER,
...e.map(([e, t]) => `export ${e}=${quoteLaunchAgentEnvironmentValue(t)}`),
""
].join("\n");
}
async function warnAboutLaunchAgentWrapperOverwrite(e, t, n) {
const r = await fs.readFile(e, "utf8").catch(() => null);
if (r === null || isGeneratedLaunchAgentEnvironmentWrapper(r)) return;
const i = `Existing generated LaunchAgent env wrapper at ${e} contains custom behavior and will be overwritten; move custom behavior to openclaw gateway install --wrapper <path> or OPENCLAW_WRAPPER.`;
if (n) n(i);
else t?.write(`${formatLine("Warning", i)}\n`);
}
async function prepareLaunchAgentPlist(e) {
const warn = (t) => {
if (e.warn) e.warn(t);
else e.stdout?.write(`${formatLine("Warning", t)}\n`);
};
let t;
try {
t = (await readLaunchAgentProgramArgumentsFromFile(resolveLaunchAgentPlistPathForLabel(e.env, e.label), {
...resolveLaunchAgentEnvironmentReadOptions(e.env, e.label),
requireEffective: true
}))?.environment?.NODE_EXTRA_CA_CERTS;
} catch (e) {
rethrowCaMigrationAuthorityError(e);
warn("CA migration unavailable: the installed service environment could not be inspected. The installer retains its hardened trust policy; inspect service CA configuration and configure a distinct maintained NODE_EXTRA_CA_CERTS bundle if private connections fail.");
}
const n = collectLaunchAgentEnvironmentEntries(await prepareLaunchAgentCaEnvironment({
env: e.env,
label: e.label,
environment: e.environment,
installedExtraCa: t,
assertCurrent: () => e.definitionTransaction.assertCurrent(),
warn
}));
let { programArguments: r } = e;
if (n.length > 0) {
const t = resolveLaunchAgentEnvDir(e.env);
const i = resolveLaunchAgentEnvFilePath(e.env, e.label);
const a = resolveLaunchAgentEnvWrapperPath(e.env, e.label);
const o = buildLaunchAgentEnvironmentWrapper();
await ensureSecureDirectory(t, LAUNCH_AGENT_PRIVATE_DIR_MODE);
await publishServiceFile({
filePath: i,
contents: buildLaunchAgentEnvironmentFile(n),
mode: LAUNCH_AGENT_ENV_FILE_MODE,
definitionTransaction: e.definitionTransaction
});
await warnAboutLaunchAgentWrapperOverwrite(a, e.stdout, e.warn);
await publishServiceFile({
filePath: a,
contents: o,
mode: LAUNCH_AGENT_ENV_WRAPPER_MODE,
definitionTransaction: e.definitionTransaction
});
if (!(r[0] === a && r[1] === i || r[0] === "/bin/sh" && r[1] === a && r[2] === i)) r = [
LAUNCH_AGENT_ENV_WRAPPER_SHELL,
a,
i,
...r
];
}
return buildLaunchAgentPlist({
label: e.label,
comment: resolveGatewayServiceDescription(e),
programArguments: r,
workingDirectory: e.workingDirectory,
stdoutPath: e.stdoutPath,
stderrPath: e.stdoutPath
});
}
function resolveLaunchAgentPlistPath(e) {
return resolveLaunchAgentPlistPathForLabel(e, resolveLaunchAgentLabel(e));
}
function resolveLaunchAgentEnvironmentReadOptions(e, t) {
return {
expectedEnvironmentWrapperPath: resolveLaunchAgentEnvWrapperPath(e, t),
expectedEnvironmentFilePath: resolveLaunchAgentEnvFilePath(e, t),
generatedEnvironmentLabel: t
};
}
async function readExistingLaunchAgentPlist(e) {
try {
const t = await fs.open(e, "r");
try {
return {
contents: await t.readFile(),
mode: (await t.stat()).mode & 4095
};
} finally {
await t.close();
}
} catch (e) {
return ignoreMissingPath(e) ?? null;
}
}
/** Captured file identities bound rollback to this install's actual publications. */
async function captureLaunchAgentInstallFiles(e) {
const t = resolveLaunchAgentLabel(e);
const n = [
resolveLaunchAgentPlistPath(e),
resolveLaunchAgentEnvFilePath(e, t),
resolveLaunchAgentEnvWrapperPath(e, t)
];
const r = /* @__PURE__ */ new Map();
await withGatewayServiceInstallationRecovery(async () => {
for (const e of n) {
const t = await readServiceFileState(e);
const n = await readExistingLaunchAgentPlist(e);
const i = n?.contents ?? null;
if (!isDeepStrictEqual(t, await readServiceFileState(e)) || t === null !== (i === null) || t && i && sha256Hex(i) !== t.sha256) throw new Error("LaunchAgent artifact changed while capturing its original definition.");
r.set(e, {
snapshot: n,
state: t
});
}
}, async () => false);
const i = /* @__PURE__ */ new Map();
const a = /* @__PURE__ */ new Map();
const verify = async (e) => {
const t = await readServiceFileState(e);
const n = i.get(e);
if (n ? !matchesServiceFileState(t, n) : !isDeepStrictEqual(t, r.get(e)?.state)) throw new Error(`LaunchAgent artifact changed after capture or publication: ${e}`);
return t;
};
const beforeWrite = async () => {
assertGatewayServiceUpdateCurrent();
for (const [e, t] of a) {
const n = await readServiceFileState(e);
if (matchesServiceFilePublication(n, t)) i.set(e, n);
else await verify(e);
a.delete(e);
}
for (const e of r.keys()) await verify(e);
assertGatewayServiceUpdateCurrent();
};
const refuseTaskPublication = async () => {
throw new Error("LaunchAgent file receipts cannot publish Scheduled Tasks.");
};
const o = {
assertCurrent: assertGatewayServiceUpdateCurrent,
beforeWrite,
filePrepared: async (e, t) => {
if (!r.has(e) || t === null) throw new Error("Not a captured LaunchAgent publication target.");
const n = await readServiceFileState(t);
assertGatewayServiceUpdateCurrent();
if (!n) throw new Error("Prepared LaunchAgent artifact disappeared before publication.");
a.set(e, n);
},
fileWritten: async (e, t) => {
const n = await readServiceFileState(e);
const r = a.get(e);
assertGatewayServiceUpdateCurrent();
if (!r || !matchesServiceFilePublication(n, r) || t === null || n?.sha256 !== sha256Hex(t)) throw new Error(`LaunchAgent artifact changed after publication: ${e}`);
i.set(e, n);
a.delete(e);
},
taskPrepared: refuseTaskPublication,
taskWritten: refuseTaskPublication
};
return {
originals: r,
hooks: o,
assertCurrent: beforeWrite,
restore: async () => {
if (!i.size && !a.size) return false;
await beforeWrite();
if (!i.size) return false;
const order = (e) => e === n[0] ? 1 : r.get(e).snapshot ? 0 : 2;
for (const e of [...i.keys()].toSorted((e, t) => order(e) - order(t))) {
const t = r.get(e);
if (t.snapshot !== null && t.state) {
await publishServiceFile({
filePath: e,
contents: t.snapshot.contents,
mode: t.snapshot.mode,
definitionTransaction: o
});
t.state = i.get(e);
} else {
await verify(e);
assertGatewayServiceUpdateCurrent();
await fs.unlink(e);
t.state = null;
}
i.delete(e);
}
return true;
}
};
}
async function publishLaunchAgentPlist(e) {
await publishServiceFile({
filePath: e.plistPath,
contents: e.contents,
mode: LAUNCH_AGENT_PLIST_MODE,
definitionTransaction: e.definitionTransaction,
beforeRename: () => assertNoSystemLaunchDaemonOwnership(e.label)
});
await assertNoSystemLaunchDaemonOwnership(e.label);
}
async function ensureSecureDirectory(e, t = LAUNCH_AGENT_DIR_MODE) {
assertGatewayServiceUpdateCurrent();
await fs.mkdir(e, {
recursive: true,
mode: t
});
try {
const n = (await fs.stat(e)).mode & 511;
const r = n & ~(t === LAUNCH_AGENT_PRIVATE_DIR_MODE ? 63 : 18);
if (r !== n) {
assertGatewayServiceUpdateCurrent();
await fs.chmod(e, r);
}
} catch {}
}
async function writeLaunchAgentPlist(e, t) {
assertGatewayServiceUpdateCurrent();
const n = e.definitionTransaction ?? t?.hooks;
if (!n) {
const t = await captureLaunchAgentInstallFiles(e.env);
return withGatewayServiceInstallationRecovery(() => writeLaunchAgentPlist(e, t), t.restore);
}
const { env: r, programArguments: i, workingDirectory: a, environment: o, description: s, stdout: c, warn: l } = e;
const u = resolveLaunchAgentLabel(r);
await assertNoSystemLaunchDaemonOwnership(u);
const { logDir: d, stdoutPath: f } = resolveGatewaySupervisorLogPaths(r);
await ensureSecureDirectory(d);
const p = resolveLaunchAgentPlistPathForLabel(r, u);
const m = normalizeWindowsPathSeparators(resolveDaemonHomeDir(r));
const h = path.posix.join(m, "Library");
await ensureSecureDirectory(m);
await ensureSecureDirectory(h);
await ensureSecureDirectory(path.dirname(p));
const g = o?.TMPDIR?.trim();
if (g) await ensureSecureDirectory(g, LAUNCH_AGENT_PRIVATE_DIR_MODE);
let _ = await prepareLaunchAgentPlist({
env: r,
label: u,
programArguments: i,
workingDirectory: a,
description: s,
stdoutPath: f,
environment: o,
stdout: c,
warn: l,
definitionTransaction: n
});
if (n.preservePolicy?.length) {
const { preserveServicePolicyXml: e } = await import("./service-policy-xml-Ct75aHjh.mjs");
_ = e(_, await normalizeLaunchdPlistXml(await fs.readFile(p)), n.preservePolicy, "plist");
}
await publishLaunchAgentPlist({
label: u,
plistPath: p,
contents: _,
definitionTransaction: n
});
return {
plistPath: p,
stdoutPath: f
};
}
async function rewriteLaunchAgentPlistForRestart({ env: e, label: t, plistPath: n, stdout: r, warn: i }) {
const a = await readLaunchAgentProgramArgumentsFromFile(n, resolveLaunchAgentEnvironmentReadOptions(e, t));
if (!a?.programArguments.length) return false;
const o = await captureLaunchAgentInstallFiles(e);
const s = o.hooks;
return withGatewayServiceInstallationRecovery(async () => {
const { logDir: o, stdoutPath: c } = resolveGatewaySupervisorLogPaths(e);
await ensureSecureDirectory(o);
const l = resolveGatewayServiceDescription({ env: e });
const u = {
...a.environment,
OPENCLAW_SERVICE_VERSION: void 0
};
const d = await prepareLaunchAgentPlist({
env: e,
label: t,
programArguments: a.programArguments,
workingDirectory: a.workingDirectory,
description: l,
stdoutPath: c,
environment: u,
stdout: r,
warn: i,
definitionTransaction: s
});
if (await fs.readFile(n, "utf8").catch(() => "") === d) {
assertGatewayServiceUpdateCurrent();
await fs.chmod(n, LAUNCH_AGENT_PLIST_MODE).catch(() => void 0);
return false;
}
await publishLaunchAgentPlist({
label: t,
plistPath: n,
contents: d,
definitionTransaction: s
});
return true;
}, o.restore);
}
//#endregion
export { isGeneratedLaunchAgentEnvironmentWrapper as _, resolveLaunchAgentEnvWrapperPath as a, isLaunchctlNotLoaded as b, resolveLaunchAgentPlistPathForLabel as c, assertNoSystemLaunchDaemonOwnership as d, formatSystemLaunchDaemonOwnershipSummary as f, buildLaunchAgentEnvironmentWrapper as g, renderSystemLaunchDaemonOwnershipShellProbe as h, resolveLaunchAgentEnvFilePath as i, rewriteLaunchAgentPlistForRestart as l, isSystemLaunchDaemonOwnershipError as m, readExistingLaunchAgentPlist as n, resolveLaunchAgentEnvironmentReadOptions as o, inspectSystemLaunchDaemonOwnership as p, removeBootedOutLaunchAgentPlist as r, resolveLaunchAgentPlistPath as s, captureLaunchAgentInstallFiles as t, writeLaunchAgentPlist as u, execLaunchctl as v, launchctlInspectionReason as x, formatLaunchctlResultDetail as y };