openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
10 lines • 14 kB
JavaScript
import{o as normalizeLowercaseStringOrEmpty}from"./string-coerce-CpTFcSwY.mjs";import{D as parseStrictPositiveInteger,T as parseStrictInteger}from"./number-coercion-B3CfI447.mjs";import{r as GATEWAY_SERVICE_KIND}from"./constants-tH5Q8GoI.mjs";import{d as isStringRecord,u as isStringArray}from"./record-coerce-BTbqdJ3-.mjs";import{i as throwCollectedErrors}from"./error-graph-internal-Bt2pFJBM.mjs";import"./utils-Dlk0IYAa.mjs";import{t as sleep}from"./sleep-B4CgCyZu.mjs";import{n as parseTcpPort,r as parseTcpPortFromArgs}from"./tcp-port-CL3rN59M.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{a as hasCommandProcessCleanupError,o as ignoreNonCleanupCommandError}from"./exec-result-TD4w1Z1i.mjs";import{a as ServiceInspectionError}from"./service-inspection-error-D006EyWC.mjs";import{t as mergeGatewayServiceEnv}from"./service-env-merge-Db3tXSCb.mjs";import{n as resolveLaunchAgentLabel}from"./launchd-label-Daj1UmUS.mjs";import{t as resolveGatewayServiceProbeHosts}from"./gateway-service-probe-hosts-Cvqbifz1.mjs";import{S as launchctlInspectionReason,b as formatLaunchctlResultDetail,c as resolveLaunchAgentPlistPath,m as inspectSystemLaunchDaemonOwnership,p as formatSystemLaunchDaemonOwnershipSummary,s as resolveLaunchAgentEnvironmentReadOptions,x as isLaunchctlNotLoaded,y as execLaunchctl}from"./launchd-service-files-cH3YFqVS.mjs";import{c as resolveGeneratedEnvWrapperLayout,i as decodeLaunchdPlistMetadata,l as resolveLaunchAgentProgramArguments,s as readLaunchAgentProgramArgumentsFromFile}from"./launchd-plist-Bg6wneGv.mjs";import path from"node:path";import fs from"node:fs/promises";import{isDeepStrictEqual}from"node:util";
//!src/daemon/launchctl-job.ts
function parseLaunchctlJob(e,t){if(!e.startsWith(`${t} = {\n`))throw new Error(`Cannot parse launchd job ${t}`);const n=/* @__PURE__ */ new Map;for(const[,t,r]of e.matchAll(/^\t([^\t\n=]+) = (.+)$/gm)){if(n.has(t))throw new Error(`Duplicate launchd job field ${t}`);n.set(t,r)}const block=t=>e.match(new RegExp(`^\\t${t} = \\{\\n([\\s\\S]*?)^\\t\\}`,`m`))?.[1];const r={};const i=n.get(`state`)?.trim();if(i)r.state=i;const a=parseStrictPositiveInteger(n.get(`pid`));if(a!==void 0)r.pid=a;const o=parseStrictInteger(n.get(`last exit status`));if(o!==void 0)r.lastExitStatus=o;const s=n.get(`last exit reason`)?.trim();if(s)r.lastExitReason=s;return{fields:n,runtime:r,arguments:block(`arguments`)?.split(`
`).filter(e=>e.startsWith(` `)).map(e=>e.slice(2)),environment:block(`environment`)??``,environmentBlocks:[...e.matchAll(/^\t(?:inherited |default )?environment = \{\n([\s\S]*?)^\t\}/gm)].map(e=>e[1]??``).join(`
`)}}
//!src/daemon/launchd-runtime.ts
async function readLoadedLaunchAgentState(e,t={}){const n=resolveLaunchAgentLabel(e);const r=t.plistPath??resolveLaunchAgentPlistPath(e);const i=`${path.dirname(r)===`/Library/LaunchDaemons`?`system`:resolveLaunchAgentGuiDomain()}/${n}`;const a=await execLaunchctl([`print`,i],t.timeoutMs??5e3);const o={installed:false,loadState:{status:`not-loaded`},running:false,env:e,command:null,runtime:{status:`stopped`}};if(isLaunchctlNotLoaded(a))return o;if(a.code!==0)throw new Error(`Cannot inspect launchd job ${i}: ${formatLaunchctlResultDetail(a)}`);const s=parseLaunchctlJob(a.stdout,i);const c=s.fields.get(`path`);if(!c||!path.isAbsolute(c))throw new Error(`Loaded LaunchAgent definition path is unavailable.`);const l=s.fields.get(`program`);if(!l||!path.isAbsolute(l)||!s.arguments?.length)throw new Error(`Loaded LaunchAgent command is unavailable.`);const u=[l,...s.arguments.slice(1)];const d=resolveGeneratedEnvWrapperLayout(u,resolveLaunchAgentEnvironmentReadOptions(e,n));const f={};for(const e of s.environment.split(`
`).filter(Boolean)){const t=/^\t\t([A-Za-z_][A-Za-z0-9_]*) => (.*)$/.exec(e);if(!t||Object.hasOwn(f,t[1]))throw new Error(`Loaded LaunchAgent environment is unavailable.`);f[t[1]]=t[2]}const p={programArguments:d?u.slice(d.commandStartIndex):u,...s.fields.get(`working directory`)?{workingDirectory:s.fields.get(`working directory`)}:{},...Object.keys(f).length?{environment:f}:{},sourcePath:c};const m=s.runtime;const h=m.state===`running`||m.pid!==void 0&&m.pid>1;return{installed:true,loadState:{status:`loaded`},running:h,env:mergeGatewayServiceEnv(e,p),command:p,runtime:{...m,status:h?`running`:`stopped`},launchAgent:{target:i,sourcePath:c,program:l,programArguments:s.arguments,workingDirectory:p.workingDirectory,environment:f}}}async function readCorrespondingLaunchAgentCommand(e,t,n){const r=resolveLaunchAgentLabel(e);const i=resolveLaunchAgentPlistPath(e);if(t.target!==`${resolveLaunchAgentGuiDomain()}/${r}`||path.resolve(t.sourcePath)!==path.resolve(i))return null;const a=await decodeLaunchdPlistMetadata(await fs.readFile(i),n);const o=a?.ProgramArguments;const s=a?.EnvironmentVariables??{};if(!isStringArray(o)||!isStringRecord(s)||(a?.Program??o[0])!==t.program)return null;const c={...t.environment};if(!Object.hasOwn(s,`XPC_SERVICE_NAME`)&&c.XPC_SERVICE_NAME===r)delete c.XPC_SERVICE_NAME;if(!Object.hasOwn(s,`OSLogRateLimit`))delete c.OSLogRateLimit;if(!isDeepStrictEqual(o,t.programArguments)||(a?.WorkingDirectory||void 0)!==t.workingDirectory||!isDeepStrictEqual(s,c))return null;return resolveLaunchAgentProgramArguments(a,i,{...resolveLaunchAgentEnvironmentReadOptions(e,r),requireEffective:true,timeoutMs:n})}async function readLaunchAgentProgramArguments(e,t){const n=resolveLaunchAgentLabel(e);const r=await readLaunchAgentProgramArgumentsFromFile(resolveLaunchAgentPlistPath(e),{...resolveLaunchAgentEnvironmentReadOptions(e,n),...t});if(!r&&t?.requireEffective&&!t.allowMissingDefinition){const e=t.timeoutMs&&t.timeoutMs>0?Math.min(t.timeoutMs,5e3):5e3;const[r,i]=await Promise.all([probeLaunchAgentState(`${resolveLaunchAgentGuiDomain()}/${n}`,e).catch(ignoreNonCleanupCommandError),inspectSystemLaunchDaemonOwnership(n,{timeoutMs:e,scanInstalledPlists:false})]);if(r?.state!==`not-loaded`){const e=i.status===`loaded`||i.status===`installed`?`launchd-system-owned`:(i.status===`unverifiable`?i.reason:void 0)??(r?.state===`unknown`?r.inspectionReason:void 0);if(e)throw new ServiceInspectionError(e);throw new Error(`Effective LaunchAgent service command could not be inspected.`)}}return r}const LAUNCH_AGENT_BOOTSTRAP_TEARDOWN_TIMEOUT_MS=(330+10)*1e3;const LAUNCH_AGENT_BOOTSTRAP_TEARDOWN_POLL_MS=500;async function resolveLaunchAgentGatewayContext(e){const t=e.OPENCLAW_SERVICE_KIND?.trim();if(t&&t!==`gateway`)return{env:e,port:null,probeHosts:[]};const n=await readLaunchAgentProgramArguments(e).catch(ignoreNonCleanupCommandError);return{env:mergeGatewayServiceEnv(e,n),port:parseTcpPortFromArgs(n?.programArguments)??parseTcpPort(n?.environment?.OPENCLAW_GATEWAY_PORT??``)??parseTcpPort(e.OPENCLAW_GATEWAY_PORT??``),probeHosts:await resolveGatewayServiceProbeHosts({env:e,command:n})}}function resolveLaunchAgentGuiDomain(){if(typeof process.getuid!==`function`)return`gui/501`;return`gui/${process.getuid()}`}function formatLaunchAgentGuiSessionError(e){return[`launchctl bootstrap failed: ${e.detail}`,`LaunchAgent ${e.actionHint} requires a logged-in macOS GUI session for this user (${e.domain}).`,`This usually means you are running from SSH/headless context or as the wrong user (including sudo).`,`Fix: sign in to the macOS desktop as the target user and rerun \`${e.actionHint}\`.`,`For headless VM setups, enable auto-login for the target user so macOS creates the GUI session after boot.`,`Headless deployments should use a dedicated logged-in user session or a custom LaunchDaemon (not shipped): https://docs.openclaw.ai/gateway`].join(`
`)}async function bootstrapLaunchAgentOrThrow(e){if(e.preserveAutoStart){e.assertCurrent?.();const t=e.serviceTarget.slice(e.domain.length+1);let n=e.preservedEnabled;if(n===void 0){const r=await execLaunchctl([`print-disabled`,e.domain],e.deadline);if(r.code!==0)throw new Error(`launchctl print-disabled failed: ${formatLaunchctlResultDetail(r)}`);n=parseLaunchAgentEnabled(r.stdout||r.stderr||``,t)}e.assertCurrent?.();if(!n){const t=await execLaunchctl([`enable`,e.serviceTarget],e.deadline);if(t.code!==0)throw new Error(`launchctl enable failed: ${formatLaunchctlResultDetail(t)}`)}const[r]=await Promise.allSettled([bootstrapLaunchAgentOrThrow({...e,preserveAutoStart:false,skipEnable:true})]);if(r.status===`rejected`&&hasCommandProcessCleanupError(r.reason))throw r.reason;const i=r.status===`rejected`?[r.reason]:[];if(!n)try{e.assertCurrent?.();const t=await execLaunchctl([`disable`,e.serviceTarget],e.deadline);if(t.code!==0)throw new Error(`LaunchAgent disabled policy could not be restored: ${formatLaunchctlResultDetail(t)}`)}catch(e){i.push(e)}throwCollectedErrors(i,`LaunchAgent bootstrap and disabled-policy restoration failed.`);if(r.status===`rejected`)throw r.reason;return r.value}if(!e.skipEnable){e.assertCurrent?.();if((await execLaunchctl([`enable`,e.serviceTarget],e.deadline)).code===0)e.onMutation?.(`enable`)}const t=performance.now()+LAUNCH_AGENT_BOOTSTRAP_TEARDOWN_TIMEOUT_MS;let n=e.onBootstrapAttempted;for(;;){e.assertCurrent?.();n?.();n=void 0;const r=await execLaunchctl([`bootstrap`,e.domain,e.plistPath],e.deadline);if(r.code===0){e.onMutation?.(`bootstrap`);return`bootstrapped`}const i=(r.stderr||r.stdout).trim();if(isUnsupportedGuiDomain(i))throw new Error(formatLaunchAgentGuiSessionError({detail:i,domain:e.domain,actionHint:e.actionHint}),{cause:r});if(r.termination===`exit`&&isLaunchctlOperationAlreadyInProgress(i)){const t=await probeLaunchAgentState(e.serviceTarget,e.deadline?.remainingMs());if(t.state===`running`||t.state===`stopped`){e.onMutation?.(`bootstrap`);return`already-loaded`}}const a=t-performance.now();if(!e.retryPendingTeardown||!isLaunchctlBootstrapPendingTeardown(r)||a<=0)throw new Error(`launchctl bootstrap failed: ${i}`,{cause:r});await sleep(Math.min(LAUNCH_AGENT_BOOTSTRAP_TEARDOWN_POLL_MS,a,e.deadline?.remainingMs()??Infinity),e.deadline?.signal)}}function parseLaunchAgentEnabled(e,t){const n=`"${t}"`;for(const r of e.split(`
`)){const e=r.trim();if(!e.startsWith(n))continue;const i=e.slice(n.length).trim();if(i===`=> enabled`||i===`=> false`)return true;if(i===`=> disabled`||i===`=> true`)return false;throw new Error(`launchctl print-disabled returned an unrecognized state for ${t}`)}return true}async function isLaunchAgentEnabled(e){const t=resolveLaunchAgentGuiDomain();const n=resolveLaunchAgentLabel(e.env);const r=await execLaunchctl([`print-disabled`,t],e.timeoutMs);if(r.code!==0)throw new Error(`launchctl print-disabled failed: ${formatLaunchctlResultDetail(r)}`);return parseLaunchAgentEnabled(r.stdout||r.stderr||``,n)}async function isLaunchAgentLoaded(e){const t=await probeLaunchAgentState(`${resolveLaunchAgentGuiDomain()}/${resolveLaunchAgentLabel(e.env)}`,e.timeoutMs);if(t.state===`running`||t.state===`stopped`)return true;if(t.state===`not-loaded`)return false;if(t.inspectionReason)throw new ServiceInspectionError(t.inspectionReason);throw new Error(`launchctl print failed: ${t.detail??`unknown error`}`)}async function launchAgentPlistExists(e){try{const t=resolveLaunchAgentPlistPath(e);await fs.access(t);return true}catch{return false}}async function readLaunchAgentRuntime(e,t){const n=resolveLaunchAgentGuiDomain();const r=resolveLaunchAgentLabel(e);const[i,a]=await Promise.all([probeLaunchAgentState(`${n}/${r}`,t?.timeoutMs),inspectSystemLaunchDaemonOwnership(r,{...t,scanInstalledPlists:false})]);if(a.status!==`absent`)return{status:`unknown`,detail:formatSystemLaunchDaemonOwnershipSummary(a),inspectionReason:a.status===`unverifiable`?a.reason:`launchd-system-owned`,systemLaunchDaemon:{status:a.status,serviceTarget:a.serviceTarget,...a.status===`installed`?{plistPath:a.plistPath}:{}}};const o=await launchAgentPlistExists(e);if(i.state===`not-loaded`)return o?{status:`stopped`}:{status:`unknown`,missingUnit:true};if(i.state===`unknown`){const e=o&&isUnsupportedGuiDomain(i.detail??``);return{status:`unknown`,detail:i.detail,inspectionReason:i.inspectionReason,...e?{missingGuiSession:true}:{}}}const s=i.runtime;return{status:i.state,state:s.state,pid:s.pid,lastExitStatus:s.lastExitStatus,lastExitReason:s.lastExitReason,cachedLabel:!o}}function isLaunchctlAlreadyLoaded(e){const t=normalizeLowercaseStringOrEmpty(e.stderr||e.stdout);return e.termination===`exit`&&(e.code===130||t.includes(`already exists in domain`))}function isUnsupportedGuiDomain(e){const t=normalizeLowercaseStringOrEmpty(e);return t.includes(`domain does not support specified action`)||t.includes(`could not find domain for user gui`)||t.includes(`bootstrap failed: 125`)}function isLaunchctlOperationAlreadyInProgress(e){const t=normalizeLowercaseStringOrEmpty(e);return t.includes(`operation already in progress`)||t.includes(`bootstrap failed: 37`)}function isLaunchctlBootstrapPendingTeardown(e){if(e.termination!==`exit`||isLaunchctlAlreadyLoaded(e))return false;const t=normalizeLowercaseStringOrEmpty(e.stderr||e.stdout);return t.includes(`bootstrap failed: 5`)||t.includes(`input/output error`)}async function probeLaunchAgentState(e,t){const n=await execLaunchctl([`print`,e],t);if(n.code!==0){if(isLaunchctlNotLoaded(n))return{state:`not-loaded`};return{state:`unknown`,detail:formatLaunchctlResultDetail(n)||void 0,inspectionReason:launchctlInspectionReason(n,e)}}try{const{runtime:t}=parseLaunchctlJob(n.stdout||n.stderr||``,e);return{state:normalizeLowercaseStringOrEmpty(t.state)===`running`||typeof t.pid===`number`&&t.pid>1?`running`:`stopped`,runtime:t}}catch(e){return{state:`unknown`,detail:formatErrorMessage(e)}}}export{isLaunchctlAlreadyLoaded as a,parseLaunchAgentEnabled as c,readLaunchAgentProgramArguments as d,readLaunchAgentRuntime as f,parseLaunchctlJob as g,resolveLaunchAgentGuiDomain as h,isLaunchAgentLoaded as i,probeLaunchAgentState as l,resolveLaunchAgentGatewayContext as m,formatLaunchAgentGuiSessionError as n,isUnsupportedGuiDomain as o,readLoadedLaunchAgentState as p,isLaunchAgentEnabled as r,launchAgentPlistExists as s,bootstrapLaunchAgentOrThrow as t,readCorrespondingLaunchAgentCommand as u};