openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
14 lines • 28.6 kB
JavaScript
import{l as normalizeOptionalString}from"./string-coerce-CpTFcSwY.mjs";import{D as parseStrictPositiveInteger,T as parseStrictInteger}from"./number-coercion-B3CfI447.mjs";import{f as resolveGatewayLaunchAgentLabel,i as GATEWAY_SERVICE_MARKER,r as GATEWAY_SERVICE_KIND}from"./constants-tH5Q8GoI.mjs";import{o as getAsyncWorkSignal}from"./async-work-scope-DBcxYU4O.mjs";import"./utils-Dlk0IYAa.mjs";import{t as sleep}from"./sleep-B4CgCyZu.mjs";import{a as isPidDefinitelyDead,i as isPidAlive,t as getFileLockProcessStartTime}from"./pid-alive-DDtSxW5l.mjs";import{a as resolveSqliteInspectionSignal}from"./sqlite-readonly-worker-context-BjXXEC4m.mjs";import{a as hasCommandProcessCleanupError}from"./exec-result-TD4w1Z1i.mjs";import{v as readGatewayOwnerLeaseFromDatabase}from"./openclaw-state-db-transaction-B9Gj3UJV.mjs";import{a as ServiceInspectionError}from"./service-inspection-error-D006EyWC.mjs";import{t as resolveServiceManagerEnv}from"./service-process-env-CqJdumJx.mjs";import{t as createManagedHandoffLeaseStore}from"./update-managed-service-handoff-lease-DI0P-NxP.mjs";import{i as readGatewayOwnerLeaseAsync}from"./gateway-owner-lease-9K6iKMiO.mjs";import{i as getSelfAndAncestorPidsSync,t as cleanStaleGatewayProcesses}from"./restart-stale-pids-DF3h-m9n.mjs";import{t as resolveDaemonHomeDir}from"./paths-DJalwizy.mjs";import{c as withGatewayServiceInstallationRecovery,i as assertGatewayServiceUpdateCurrent,o as isUpdateOwnedGatewayServiceCommand}from"./service-update-authority-DqjrBTQ9.mjs";import{n as normalizeWindowsPathSeparators,r as writeFormattedLines,t as formatLine}from"./output-CIxm7KXF.mjs";import{c as readLockPayloadSync,l as resolveGatewayLockPaths}from"./gateway-lock-CQoO1usb.mjs";import{a as writeGatewayServiceRestartIntentSync,r as prepareGatewayRestartIntentLegacyProcess,s as GatewayRestartPreparationError}from"./restart-intent-Bp7SeIHX.mjs";import{t as mergeGatewayServiceEnv}from"./service-env-merge-Db3tXSCb.mjs";import{t as resolveUpdateInstallRoot}from"./update-install-root-B8m4gTPf.mjs";import{n as resolveLaunchAgentLabel,t as assertValidLaunchAgentLabel}from"./launchd-label-Daj1UmUS.mjs";import{n as probePortUsage}from"./ports-probe-B-fmalcq.mjs";import{a as isLaunchctlAlreadyLoaded,d as readLaunchAgentProgramArguments,f as readLaunchAgentRuntime,g as parseLaunchctlJob,h as resolveLaunchAgentGuiDomain,l as probeLaunchAgentState,m as resolveLaunchAgentGatewayContext,o as isUnsupportedGuiDomain,r as isLaunchAgentEnabled,t as bootstrapLaunchAgentOrThrow}from"./launchd-runtime-CGjMI2Ve.mjs";import{b as formatLaunchctlResultDetail,c as resolveLaunchAgentPlistPath,d as writeLaunchAgentPlist,f as assertNoSystemLaunchDaemonOwnership,h as isSystemLaunchDaemonOwnershipError,i as removeBootedOutLaunchAgentPlist,l as resolveLaunchAgentPlistPathForLabel,r as readExistingLaunchAgentPlist,t as captureLaunchAgentInstallFiles,u as rewriteLaunchAgentPlistForRestart,x as isLaunchctlNotLoaded,y as execLaunchctl}from"./launchd-service-files-cH3YFqVS.mjs";import{s as readLaunchAgentProgramArgumentsFromFile}from"./launchd-plist-Bg6wneGv.mjs";import{r as resolveServiceProcessMembershipBlock,t as inspectServiceProcessMembershipSync}from"./service-process-membership-Bcp9Klpg.mjs";import{r as formatPortDiagnostics}from"./ports-format-BJNgZ8TS.mjs";import{n as inspectPortUsage}from"./ports-inspect-PmKDONYY.mjs";import{n as scheduleDetachedLaunchdRestartHandoff,t as scheduleDetachedLaunchdMaintenancePark}from"./launchd-restart-handoff-UzxA5j_y.mjs";import{t as createGatewayLifecycleMutationReporter}from"./service-mutation-BXMoc2of.mjs";import path from"node:path";import fs from"node:fs/promises";import{spawnSync}from"node:child_process";import{isDeepStrictEqual}from"node:util";
//!src/daemon/launchd-current-service.ts
function isCurrentProcessLaunchdServiceLabel(e,t=process.env){return[t.LAUNCH_JOB_LABEL,t.LAUNCH_JOB_NAME,t.XPC_SERVICE_NAME].some(t=>normalizeOptionalString(t)===e)||normalizeOptionalString(t.OPENCLAW_LAUNCHD_LABEL)===e&&normalizeOptionalString(t.OPENCLAW_SERVICE_MARKER)===`openclaw`&&Boolean(normalizeOptionalString(t.OPENCLAW_SERVICE_KIND))}async function isCurrentProcessInsideLaunchdService(e){const t=await probeLaunchAgentState(`${resolveLaunchAgentGuiDomain()}/${e}`);if(t.state===`running`&&t.runtime.pid!==void 0){const e=getSelfAndAncestorPidsSync();if(e.has(t.runtime.pid))return true;const n=resolveServiceProcessMembershipBlock(inspectServiceProcessMembershipSync(t.runtime.pid,`darwin`),e.has(1),`darwin`);if(n===`inside-gateway-service`)return true;if(n)throw new ServiceInspectionError(n);return false}if(t.state===`unknown`||t.state===`running`)throw new ServiceInspectionError(`service-membership-unverified`);return false}
//!src/daemon/launchd-stop.ts
const LAUNCH_AGENT_STOP_PORT_RELEASE_TIMEOUT_MS=330*1e3;const LAUNCH_AGENT_STOP_PORT_RELEASE_POLL_MS=100;const LAUNCH_AGENT_STOP_TIMEOUT_MS=(330+10)*1e3;function launchAgentStopError(e,t){return/* @__PURE__ */ new Error(`${t}. Run \`launchctl bootout ${e}\` from an external terminal in the service owner's logged-in macOS GUI session.`)}function verifyLaunchAgentStopProbe(e,t){if(t.state===`unknown`)throw launchAgentStopError(e,`launchctl print could not verify LaunchAgent stop: ${t.detail??`unknown error`}`);if(t.state!==`running`)return;if(t.runtime.pid===void 0)throw launchAgentStopError(e,`launchctl print reported a running job without a PID`);return t.runtime.pid}async function waitForLaunchAgentUnloaded(e,t,n,r){const i=new Set(t);const a=performance.now()+LAUNCH_AGENT_STOP_TIMEOUT_MS;let o=false;for(;;){const t=await probeLaunchAgentState(e,5e3);n?.();const s=verifyLaunchAgentStopProbe(e,t);if(s!==void 0)i.add(s);const c=[...i].filter(e=>!isPidDefinitelyDead(e));if(t.state===`not-loaded`&&c.length===0)return;if(t.state===`not-loaded`&&!o){o=true;r?.(c)}if(performance.now()>=a)throw launchAgentStopError(e,`LaunchAgent stop did not complete: ${e} is ${t.state===`not-loaded`?`unloaded`:`still loaded`}${c.length?`; PID ${c.join(`, `)} is still alive`:``}`);await sleep(Math.min(100,Math.max(0,a-performance.now())))}}async function waitForGatewayPortRelease(e,t){const n=performance.now()+LAUNCH_AGENT_STOP_PORT_RELEASE_TIMEOUT_MS;while(performance.now()<n){await sleep(Math.min(LAUNCH_AGENT_STOP_PORT_RELEASE_POLL_MS,n-performance.now()));if(await probePortUsage(e,t)===`free`)return true}return false}async function assertGatewayPortReleasedAfterStop(e,t,n){const{env:r,port:i,probeHosts:a}=await resolveLaunchAgentGatewayContext(e);if(i===null)return;await t();assertGatewayServiceUpdateCurrent();await cleanStaleGatewayProcesses(i,{env:r,assertCurrent:n});const o=await inspectPortUsage(i,{probeHosts:a}).catch(()=>null);if(o?.status!==`busy`)return;if(await waitForGatewayPortRelease(i,a))return;throw new Error([`gateway port ${i} is still busy after LaunchAgent stop`,...formatPortDiagnostics(o)].join(`
`))}async function stopLaunchAgent({stdout:e,env:t,disable:n,onMutation:r,assertCurrent:i,updateHandoff:a}){const o=resolveSqliteInspectionSignal(getAsyncWorkSignal());const s=t??process.env;const c=resolveLaunchAgentGuiDomain();const l=resolveLaunchAgentLabel(s);const u=`${c}/${l}`;const d=createGatewayLifecycleMutationReporter(r);const f=isUpdateOwnedGatewayServiceCommand();let p=s;const assertNativeCurrent=()=>{o?.throwIfAborted();i?.();assertGatewayServiceUpdateCurrent()};const m=await isCurrentProcessInsideLaunchdService(l);const assertStopCurrent=async()=>{assertNativeCurrent();const e=f&&a?createManagedHandoffLeaseStore().read(resolveUpdateInstallRoot(a.root)):void 0;const t=e?.kind===`current`&&(e.lease.helper.pid!==e.lease.executor.pid||e.lease.helper.startIdentity!==e.lease.executor.startIdentity);if(m||t||f&&p.OPENCLAW_UPDATE_RUN_HANDOFF===`1`){if(!(f&&a&&await(await import(`./update-managed-service-handoff-current-v86yNamz.mjs`)).isCurrentManagedServiceUpdateHandoffProcess({...a,env:p})))throw launchAgentStopError(u,`Refusing to stop LaunchAgent ${l} from inside the same launchd service`)}assertNativeCurrent()};await assertStopCurrent();const h=verifyLaunchAgentStopProbe(u,await probeLaunchAgentState(u,5e3));const g=new Set(h===void 0?[]:[h]);let _;let assertServingCurrent=async()=>assertNativeCurrent();let v;try{if(f){const e=await readLaunchAgentProgramArguments(s,{requireEffective:true});assertNativeCurrent();if(!e)throw new GatewayRestartPreparationError(`service-command`);p=mergeGatewayServiceEnv(s,e);await assertStopCurrent();const t=await readGatewayOwnerLeaseAsync({env:p,signal:o});assertNativeCurrent();const n=t?void 0:resolveGatewayLockPaths(p).stateLockPath;const r=n?readLockPayloadSync(n,true):void 0;const i=await prepareGatewayRestartIntentLegacyProcess({env:p,command:e,runtimePid:h,readRuntime:()=>readLaunchAgentRuntime(s),assertCurrent:assertNativeCurrent});const a=await probeLaunchAgentState(u,5e3);await assertStopCurrent();if(verifyLaunchAgentStopProbe(u,a)!==h)throw new GatewayRestartPreparationError(`serving-owner`);const assertServingPhysicalCurrent=()=>{assertNativeCurrent();if(i&&(!r||!n||!isPidAlive(i.pid)||getFileLockProcessStartTime(i.pid,p)!==i.startTime||!isPidAlive(r.pid)||getFileLockProcessStartTime(r.pid,p)!==r.startTime||!isDeepStrictEqual(r,readLockPayloadSync(n,true))))throw new GatewayRestartPreparationError(`serving-owner`)};const assertOwnerMatches=e=>{if(e?.owner!==t?.owner||e?.pid!==t?.pid||e?.startedAt!==t?.startedAt||e?.state!==t?.state)throw new GatewayRestartPreparationError(`serving-owner`)};const assertIntentCurrent=e=>{assertServingPhysicalCurrent();if(e)assertOwnerMatches(readGatewayOwnerLeaseFromDatabase(e))};assertServingCurrent=async()=>{const e=await readGatewayOwnerLeaseAsync({env:p,signal:o});assertServingPhysicalCurrent();assertOwnerMatches(e)};writeGatewayServiceRestartIntentSync({env:p,service:{kind:`launchd`,name:l},nativePid:h,nativeStopped:a.state!==`running`,legacyProcess:i,reason:`update.run`,assertCurrent:assertIntentCurrent,onRecorded:e=>{_=e}});const c=t?.pid??r?.pid;if(c!==void 0)g.add(c)}if(n){await assertStopCurrent();await assertServingCurrent();const e=await execLaunchctl([`disable`,u]);if(e.code===0)d(`disable`);else v=`launchctl disable failed; used bootout fallback without persisting disable: ${formatLaunchctlResultDetail(e)}`}await assertStopCurrent();await assertServingCurrent();const e=await execLaunchctl([`bootout`,u],LAUNCH_AGENT_STOP_TIMEOUT_MS);if(e.code!==0&&!isLaunchctlNotLoaded(e))throw launchAgentStopError(u,`launchctl bootout failed: ${formatLaunchctlResultDetail(e)}`)}catch(e){_?.();throw e}d(n?`disable-bootout`:`bootout`);await waitForLaunchAgentUnloaded(u,[...g],i,t=>{e.write(`${formatLine(`Warning`,`Waiting for Gateway PID ${t.join(`, `)} to exit and release its databases before continuing.`)}\n`)});if(v)e.write(`${formatLine(`Warning`,v)}\n`);await assertGatewayPortReleasedAfterStop(s,assertStopCurrent,assertNativeCurrent);i?.();e.write(`${formatLine(v?`Stopped LaunchAgent (degraded)`:`Stopped LaunchAgent`,u)}\n`)}async function parkCurrentLaunchAgentForMaintenance(){const e=process.env;const t=resolveLaunchAgentGuiDomain();const n=resolveLaunchAgentLabel(e);if(!await isCurrentProcessInsideLaunchdService(n))return false;const r=`${t}/${n}`;const i=await execLaunchctl([`disable`,r]);if(i.code!==0)throw new Error(`launchctl disable failed while parking ${r}: ${formatLaunchctlResultDetail(i)}`);const a=scheduleDetachedLaunchdMaintenancePark({env:e,waitForPid:process.pid});const o=!a.ok?a.error:await a.value?void 0:`helper failed to spawn`;if(o){const e=await execLaunchctl([`enable`,r]);const t=e.code===0?`restored launchd enable state`:`launchctl enable rollback failed: ${formatLaunchctlResultDetail(e)}`;throw new Error(`launchd maintenance park handoff failed: ${o}; ${t}`)}return true}
//!src/daemon/launchd-install.ts
async function uninstallLaunchAgent({env:e,stdout:t}){await assertExternalLaunchAgentMutation(e,`uninstall`);const n=resolveLaunchAgentGuiDomain();const r=resolveLaunchAgentLabel(e);const i=resolveLaunchAgentPlistPath(e);if((await probeLaunchAgentState(`${n}/${r}`)).state!==`not-loaded`)await bootoutLaunchAgent(`${n}/${r}`);try{await fs.lstat(i)}catch(e){if(e.code!==`ENOENT`)throw createLaunchAgentRemovalError(e);t.write(`LaunchAgent not found at ${i}\n`);return}const a=normalizeWindowsPathSeparators(resolveDaemonHomeDir(e));const o=path.posix.join(a,`.Trash`);const s=path.join(o,`${r}-${Date.now()}.plist`);try{const{trashed:e}=await removeBootedOutLaunchAgentPlist(i,s);t.write(`${e?formatLine(`Moved LaunchAgent to Trash`,s):formatLine(`Removed LaunchAgent`,i)}\n`)}catch(e){if(e.code===`ENOENT`)try{await fs.lstat(i)}catch(e){if(e.code===`ENOENT`){t.write(`LaunchAgent not found at ${i}\n`);return}throw createLaunchAgentRemovalError(e)}throw createLaunchAgentRemovalError(e)}}function createLaunchAgentRemovalError(e){const t=e.code;return/* @__PURE__ */ new Error(`LaunchAgent removal failed${t?` (${t})`:``}. Check permissions and retry.`)}async function assertExternalLaunchAgentMutation(e,t){const n=process.env.OPENCLAW_LAUNCHD_LABEL?.trim();const r=/* @__PURE__ */ new Set([resolveLaunchAgentLabel(e),...n?[assertValidLaunchAgentLabel(n)]:[]]);for(const n of r)if(await isCurrentProcessInsideLaunchdService(n))throw new Error(`Refusing to ${t} LaunchAgent ${resolveLaunchAgentLabel(e)} from inside ${n}; run this command from an external shell.`)}async function stageLaunchAgent(e){const{plistPath:t,stdoutPath:n}=await writeLaunchAgentPlist(e);writeFormattedLines(e.stdout,[{label:`Staged LaunchAgent`,value:t},{label:`Logs`,value:n}]);return{plistPath:t}}async function bootoutLaunchAgent(e){assertGatewayServiceUpdateCurrent();const t=await execLaunchctl([`bootout`,e]);assertGatewayServiceUpdateCurrent();if(t.code!==0&&!isLaunchctlNotLoaded(t))throw new Error(`launchctl bootout failed: ${formatLaunchctlResultDetail(t)}`)}async function installLaunchAgent(e){const t=resolveLaunchAgentPlistPath(e.env);const n=resolveLaunchAgentLabel(e.env);const r=resolveLaunchAgentGuiDomain();const i=`${r}/${n}`;const{publication:a,loaded:o,previousPid:s,restoreLoaded:c,enabled:l}=await withGatewayServiceInstallationRecovery(async()=>{await assertExternalLaunchAgentMutation(e.env,`install`);const n=e.definitionTransaction?{kind:`transaction`,hooks:e.definitionTransaction}:{kind:`local`,files:await captureLaunchAgentInstallFiles(e.env)};const r=n.kind===`local`?n.files.originals.get(t).snapshot:await readExistingLaunchAgentPlist(t);const a=e.preserveAutoStart?await isLaunchAgentEnabled({env:e.env}):void 0;const o=await probeLaunchAgentState(i);if(o.state===`unknown`)throw new Error(`launchctl print could not determine whether ${i} is loaded: ${o.detail??`unknown error`}`);const s=o.state!==`not-loaded`;const c=s&&r!==null;if(s&&!c)e.warn?.(`LaunchAgent ${i} plist is missing; replacing the registration without a previous definition to restore.`);return{publication:n,loaded:s,previousPid:o.state===`running`?o.runtime.pid:void 0,restoreLoaded:c,enabled:a}},async()=>false);const bootstrap=(t,n)=>bootstrapLaunchAgentOrThrow({domain:r,serviceTarget:i,plistPath:t,actionHint:n,retryPendingTeardown:true,assertCurrent:assertGatewayServiceUpdateCurrent,preserveAutoStart:e.preserveAutoStart,preservedEnabled:l});let u=false;const install=async()=>{const t=await writeLaunchAgentPlist(e,a.kind===`local`?a.files:void 0);await(a.kind===`local`?a.files.assertCurrent():a.hooks.beforeWrite());await assertNoSystemLaunchDaemonOwnership(n);assertGatewayServiceUpdateCurrent();u=true;if(o)await bootoutLaunchAgent(i);await bootstrap(t.plistPath,`openclaw gateway install --force`);assertGatewayServiceUpdateCurrent();return t};const{plistPath:d,stdoutPath:f}=a.kind===`transaction`?await install():await withGatewayServiceInstallationRecovery(install,async()=>{const r=a.files;let o;if(u){await r.assertCurrent();const t=await probeLaunchAgentState(i);if(t.state===`unknown`)throw new Error(`launchctl print could not determine whether ${i} is loaded during LaunchAgent rollback: ${t.detail??`unknown error`}`);if(t.state!==`not-loaded`){await r.assertCurrent();await bootoutLaunchAgent(i)}const n=[s,t.state===`running`?t.runtime.pid:0];o=await waitForLaunchAgentUnloaded(i,n.filter(e=>e!==void 0&&e>1),assertGatewayServiceUpdateCurrent,t=>e.stdout.write(`${formatLine(`Warning`,`Waiting for Gateway PID ${t.join(`, `)} to exit before restoring the previous LaunchAgent.`)}\n`)).then(()=>void 0,e=>({error:e}));o??=await e.beforeRecovery?.().then(()=>void 0,e=>({error:e}))}const l=await r.restore();if(u&&c){await r.assertCurrent();await assertNoSystemLaunchDaemonOwnership(n);await bootstrap(t,`openclaw gateway start`)}if(o)throw o.error;return l||u});writeFormattedLines(e.stdout,[{label:`Installed LaunchAgent`,value:d},{label:`Logs`,value:f}]);return{plistPath:d}}
//!src/daemon/launchd-lifecycle.ts
const LAUNCHCTL_PROTECTED_PID_TIMEOUT_MS=2e3;function readLaunchAgentPidForCleanupSync(e){const t=spawnSync(`launchctl`,[`print`,e],{env:resolveServiceManagerEnv(),encoding:`utf8`,timeout:LAUNCHCTL_PROTECTED_PID_TIMEOUT_MS});const n={stdout:t.stdout??``,stderr:t.error?.message??t.stderr??``,code:t.error?1:t.status??1};if(n.code!==0)throw new Error(`launchctl print failed: ${formatLaunchctlResultDetail(n)}`);const r=parseLaunchctlJob(n.stdout||n.stderr||``,e).runtime.pid;if(r===void 0)throw new Error(`launchctl print did not report a running pid`);return r}async function repairLaunchAgentBootstrap(e){const t=e.env??process.env;const n=resolveLaunchAgentGuiDomain();const r=resolveLaunchAgentLabel(t);const i=resolveLaunchAgentPlistPath(t);const a=`${n}/${r}`;try{await assertNoSystemLaunchDaemonOwnership(r)}catch(e){if(!isSystemLaunchDaemonOwnershipError(e))throw e;return{ok:false,status:e.ownership.status===`unverifiable`?`system-launchdaemon-unverifiable`:`system-launchdaemon-conflict`,detail:e.message}}const o=e.warn??(e=>console.warn(formatLine(`Warning`,e)));await rewriteLaunchAgentPlistForRestart({env:t,label:r,plistPath:i,warn:o});try{if(await bootstrapLaunchAgentOrThrow({domain:n,serviceTarget:a,plistPath:i,actionHint:`openclaw gateway start`,deadline:e.deadline})===`bootstrapped`)return{ok:true,status:`repaired`}}catch(e){if(hasCommandProcessCleanupError(e))throw e;const t=e instanceof Error?e.cause:void 0;if(!t||typeof t!==`object`||!(`stderr`in t)||typeof t.stderr!==`string`||!(`stdout`in t)||typeof t.stdout!==`string`||!(`code`in t)||typeof t.code!==`number`||!(`termination`in t))throw e;const r=(t.stderr||t.stdout).trim();if(isUnsupportedGuiDomain(r))return{ok:false,status:`gui-session-unavailable`,detail:r,domain:n};if(t.termination!==`exit`||!isLaunchctlAlreadyLoaded({code:t.code,termination:`exit`,stderr:t.stderr,stdout:t.stdout}))return{ok:false,status:`bootstrap-failed`,detail:r||void 0}}if((await readLaunchAgentRuntime(t,{timeoutMs:e.deadline?.remainingMs()})).status===`running`)return{ok:true,status:`already-loaded`};const s=await execLaunchctl([`kickstart`,a],e.deadline);if(s.code!==0)return{ok:false,status:`kickstart-failed`,detail:(s.stderr||s.stdout).trim()||void 0};return{ok:true,status:`already-loaded`}}function writeLaunchAgentActionLine(e,t,n){try{e.write(`${formatLine(t,n)}\n`)}catch(e){if(e?.code!==`EPIPE`)throw e}}async function ensureLaunchAgentLoadedAfterFailure(e){e.assertCurrent?.();const t=await execLaunchctl([`print`,e.serviceTarget],e.deadline);e.assertCurrent?.();if(t.code===0)try{const{runtime:n}=parseLaunchctlJob(t.stdout||t.stderr,e.serviceTarget);return{loaded:true,stopped:!n.pid&&(n.state===`not running`||n.state===`waiting`)}}catch{return{loaded:true}}try{await bootstrapLaunchAgentOrThrow({...e,actionHint:`openclaw gateway start`});return{loaded:true}}catch(e){if(hasCommandProcessCleanupError(e))throw e;return{loaded:false,detail:e instanceof Error?e.message:String(e)}}}async function rethrowLaunchAgentActivationFailure(e,t,n){if(hasCommandProcessCleanupError(t))throw t;const r=await ensureLaunchAgentLoadedAfterFailure(e);const i=t instanceof Error?t.message:String(t);const a=`LaunchAgent ${e.serviceTarget} is loaded`;const o=r.loaded&&r.stopped?`${a}, but OpenClaw couldn't start it. Fix the error above and retry the ${n} command.`:`${a}. Run openclaw gateway status --deep to inspect startup.`;throw new Error(r.loaded?`${i}\n${o}`:[i,`LaunchAgent ${e.serviceTarget} is not loaded and could not be restored: ${r.detail}`,`The gateway is down and launchd has no job left to respawn it.`,`Fix: run \`openclaw gateway start\`, or \`launchctl bootstrap ${e.domain} ${e.plistPath}\`.`].join(`
`),{cause:t})}async function needsLaunchAgentBootstrap(e,t,n,r){if(e.code===0||isLaunchctlNotLoaded(e))return e.code!==0;n?.();const i=await probeLaunchAgentState(t,r?.remainingMs());n?.();return i.state===`not-loaded`}async function prepareLaunchAgentActivation(e,t){const{assertCurrent:n,preserveAutoStart:r,preserveDefinition:i,onRestartAttempted:a,deadline:o}=e;const s=e.env??process.env;const c=resolveLaunchAgentGuiDomain();const l=resolveLaunchAgentLabel(s);const u=resolveLaunchAgentPlistPath(s);const d=`${c}/${l}`;const f=createGatewayLifecycleMutationReporter(e.onMutation);await assertNoSystemLaunchDaemonOwnership(l);const p={domain:c,serviceTarget:d,plistPath:u,onMutation:f,assertCurrent:n,preserveAutoStart:r,retryPendingTeardown:i,deadline:o};const finishKickstart=e=>{if(e.code!==0)throw new Error(`launchctl kickstart failed: ${e.stderr||e.stdout}`.trim());f(`kickstart`)};const bootstrapAndStart=async e=>{await bootstrapLaunchAgentOrThrow({...p,actionHint:`openclaw gateway ${t}`,...e});if(t===`start`||i||e.reload){n?.();finishKickstart(await execLaunchctl([`kickstart`,d],o))}};return{serviceEnv:s,label:l,plistPath:u,serviceTarget:d,reportMutation:f,async enable(){if(r)return false;n?.();const e=await execLaunchctl([`enable`,d],o);if(e.code===0)f(`enable`);return e.code===0},bootstrapAndStart,async kickstart(e){n?.();if(t===`restart`)a?.();const r=await execLaunchctl([`kickstart`,...t===`restart`?[`-k`]:[],d],o);if(await needsLaunchAgentBootstrap(r,d,n,o))await bootstrapAndStart({skipEnable:e});else finishKickstart(r)},rethrow:(e,n=i)=>rethrowLaunchAgentActivationFailure({...p,retryPendingTeardown:n},e,t)}}async function startLaunchAgent(e){const{stdout:t}=e;const n=await prepareLaunchAgentActivation(e,`start`);const r=await n.enable();try{await n.kickstart(r)}catch(e){await n.rethrow(e)}writeLaunchAgentActionLine(t,`Started LaunchAgent`,n.serviceTarget)}async function restartLaunchAgent(e){const{preserveDefinition:t,stdout:n,warn:r,assertCurrent:i}=e;const a=await prepareLaunchAgentActivation(e,`restart`);const{serviceEnv:o,label:s,plistPath:c,serviceTarget:l,reportMutation:u}=a;const d=await isCurrentProcessInsideLaunchdService(s);try{if(!d){const{env:t,port:n,probeHosts:r}=await resolveLaunchAgentGatewayContext(o);if(n!==null){assertGatewayServiceUpdateCurrent();await cleanStaleGatewayProcesses(n,{env:t,assertCurrent:()=>{assertGatewayServiceUpdateCurrent();i?.()},resolveProtectedPid:()=>{const e=readLaunchAgentPidForCleanupSync(l);assertGatewayServiceUpdateCurrent();return e}});const a=await inspectPortUsage(n,{probeHosts:r}).catch(()=>null);if(a?.status===`busy`){const t=(await readLaunchAgentRuntime(o,{timeoutMs:e.deadline?.remainingMs()})).pid;if(!(t!==void 0&&a.listeners.length>0&&a.listeners.every(e=>e.pid===t)))throw new Error([`gateway port ${n} is busy but is not verifiably owned by LaunchAgent ${s}`,...formatPortDiagnostics(a)].join(`
`))}}}}catch(e){if(t)await a.rethrow(e);throw e}const f=!t&&await rewriteLaunchAgentPlistForRestart({env:o,label:s,plistPath:c,stdout:n,warn:r});if(d){if(isUpdateOwnedGatewayServiceCommand())throw new Error(`UPDATE_NATIVE_AUTHORITY: update-owned native restart requires an external executor, not a detached service handoff.`);const e=scheduleDetachedLaunchdRestartHandoff({env:o,mode:f?`reload`:`kickstart`,waitForPid:process.pid});if(!e.ok)throw new Error(`launchd restart handoff failed: ${e.error}`);if(!await e.value)throw new Error(`launchd restart handoff failed: helper failed to spawn`);u(f?`handoff-reload`:`handoff-kickstart`);writeLaunchAgentActionLine(n,`Scheduled LaunchAgent restart`,l);return{outcome:`scheduled`}}try{await a.enable();if(f){i?.();const t=await execLaunchctl([`bootout`,l],e.deadline);if(t.code!==0&&!isLaunchctlNotLoaded(t))throw new Error(`launchctl bootout failed: ${formatLaunchctlResultDetail(t)}`);if(t.code===0)u(`bootout`);await a.bootstrapAndStart({retryPendingTeardown:true,onBootstrapAttempted:e.onRestartAttempted,reload:true})}else await a.kickstart()}catch(e){await a.rethrow(e,t||f)}writeLaunchAgentActionLine(n,`Restarted LaunchAgent`,l);return{outcome:`completed`}}
//!src/daemon/launchd-update-jobs.ts
const OPENCLAW_UPDATE_LAUNCHD_LABEL_PREFIX=`ai.openclaw.update.`;const MANUAL_UPDATE_LAUNCHD_LABEL_PATTERN=/^ai\.openclaw\.manual-update\.\d+$/;const OPENCLAW_PROFILE_UPDATE_LAUNCHD_LABEL_PATTERN=/^ai\.openclaw\.[A-Za-z0-9._-]+\.update\.[A-Za-z0-9._-]+$/;const OPENCLAW_DIRECT_CLI_NAMES=/* @__PURE__ */ new Set([`openclaw`,`openclaw.mjs`]);const OPENCLAW_NODE_RUNTIME_NAMES=/* @__PURE__ */ new Set([`bun`,`bun.exe`,`node`,`node.exe`]);function normalizeOpenClawUpdateLaunchdLabelCandidate(e){if(typeof e!==`string`)return null;const t=e.trim();if(t.startsWith(OPENCLAW_UPDATE_LAUNCHD_LABEL_PREFIX)||MANUAL_UPDATE_LAUNCHD_LABEL_PATTERN.test(t))return{label:t,requiresMetadata:false};return OPENCLAW_PROFILE_UPDATE_LAUNCHD_LABEL_PATTERN.test(t)?{label:t,requiresMetadata:true}:null}function isCurrentGatewayLaunchdLabel(e,t){if(e===resolveGatewayLaunchAgentLabel(t.OPENCLAW_PROFILE))return true;if(t.OPENCLAW_SERVICE_MARKER?.trim()!==`openclaw`||t.OPENCLAW_SERVICE_KIND?.trim()!==`gateway`)return false;const n=t.OPENCLAW_LAUNCHD_LABEL?.trim();return Boolean(n&&e===n)}function resolveCurrentOpenClawUpdateLaunchdJobLabel(e=process.env){for(const t of[e.LAUNCH_JOB_LABEL,e.LAUNCH_JOB_NAME,e.XPC_SERVICE_NAME,e.OPENCLAW_LAUNCHD_LABEL]){const n=normalizeOpenClawUpdateLaunchdLabelCandidate(t);if(n&&!isCurrentGatewayLaunchdLabel(n.label,e))return n}return null}function parseLaunchctlListOpenClawUpdateJobCandidates(e){const t=[];for(const n of e.split(/\r?\n/)){const e=n.trim();if(!e)continue;const[r,i,...a]=e.split(/\s+/);const o=normalizeOpenClawUpdateLaunchdLabelCandidate(a.join(` `));if(!o)continue;const s=r===`-`?void 0:parseStrictPositiveInteger(r??``);const c=parseStrictInteger(i??``);t.push({label:o.label,requiresMetadata:o.requiresMetadata,...s!==void 0?{pid:s}:{},...c!==void 0?{lastExitStatus:c}:{}})}return t.toSorted((e,t)=>e.label.localeCompare(t.label))}function hasOpenClawUpdateLaunchdMarker(e){return e?.OPENCLAW_UPDATE_RUN_HANDOFF?.trim()===`1`}function isOpenClawUpdateProgramArguments(e){if(!Array.isArray(e)||e.length===0)return false;const t=e.findIndex(e=>e.trim()===`update`);if(t<0||!e.slice(t+1).includes(`--yes`))return false;const n=path.basename(e[0]??``).toLowerCase();return(t===1?OPENCLAW_DIRECT_CLI_NAMES.has(n):t===2&&OPENCLAW_NODE_RUNTIME_NAMES.has(n)&&path.basename(e[1]??``).toLowerCase()===`openclaw.mjs`)&&!e.some(e=>e.trim()===`gateway`)}async function isLaunchdJobConfirmedOpenClawUpdater(e){const t=resolveLaunchAgentPlistPathForLabel(e.env,e.label);const n=await readLaunchAgentProgramArgumentsFromFile(t);return hasOpenClawUpdateLaunchdMarker(n?.environment)||isOpenClawUpdateProgramArguments(n?.programArguments)}async function findStaleOpenClawUpdateLaunchdJobs(e=process.env){if(process.platform!==`darwin`)return[];const t=await execLaunchctl([`list`]);if(t.code!==0)throw new Error(`launchctl list failed (exit ${t.code}): ${formatLaunchctlResultDetail(t)}`);const n=[];for(const{requiresMetadata:r,...i}of parseLaunchctlListOpenClawUpdateJobCandidates(t.stdout)){if(isCurrentGatewayLaunchdLabel(i.label,e))continue;if(r&&!await isLaunchdJobConfirmedOpenClawUpdater({label:i.label,env:e}))continue;n.push(i)}return n}async function disableCurrentOpenClawUpdateLaunchdJob(e=process.env){const t=resolveCurrentOpenClawUpdateLaunchdJobLabel(e);if(!t||process.platform!==`darwin`)return false;const n=isCurrentProcessLaunchdServiceLabel(t.label,e);if(t.requiresMetadata&&!(n&&hasOpenClawUpdateLaunchdMarker(e)||await isLaunchdJobConfirmedOpenClawUpdater({label:t.label,env:e})))return false;const r=`${resolveLaunchAgentGuiDomain()}/${assertValidLaunchAgentLabel(t.label)}`;return(await execLaunchctl([`disable`,r])).code===0}export{startLaunchAgent as a,uninstallLaunchAgent as c,restartLaunchAgent as i,parkCurrentLaunchAgentForMaintenance as l,findStaleOpenClawUpdateLaunchdJobs as n,installLaunchAgent as o,repairLaunchAgentBootstrap as r,stageLaunchAgent as s,disableCurrentOpenClawUpdateLaunchdJob as t,stopLaunchAgent as u};