openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
7 lines • 9.05 kB
JavaScript
import{f as resolveGatewayLaunchAgentLabel,t as DURABLE_PROCESS_LAUNCHD_LABEL_PREFIX,u as isNodeLaunchAgentLabel}from"./constants-tH5Q8GoI.mjs";import{n as sanitizeForLog}from"./ansi-54CEWBZf.mjs";import{r as terminalText}from"./safe-text-B_QTgn0s.mjs";import{n as resolveLaunchAgentLabel}from"./launchd-label-Daj1UmUS.mjs";import{g as parseLaunchctlJob,h as resolveLaunchAgentGuiDomain}from"./launchd-runtime-CGjMI2Ve.mjs";import{b as formatLaunchctlResultDetail,x as isLaunchctlNotLoaded,y as execLaunchctl}from"./launchd-service-files-cH3YFqVS.mjs";import{constants}from"node:fs";import path from"node:path";import fs$1 from"node:fs/promises";
//!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)&&!e.startsWith(`ai.openclaw.durable-proc.`)&&!(/* @__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(`\\
`))return[];const t=/* @__PURE__ */ new Map;for(const n of e.split(`
`)){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(`
`)).join(`
`)}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}.`}}export{formatForeignLaunchdJobs as n,repairForeignLaunchdJob as r,findForeignLaunchdJobs as t};