openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
3 lines • 10.8 kB
JavaScript
import{c as resolveOpenClawCliInvocation}from"../cli-invocation-Covx3kvQ.mjs";import{n as isNodeRuntime}from"../runtime-binary-DNstBs1K.mjs";import{c as isWindowsTaskSupervisorChildArgument,l as readWindowsTaskSupervisorRestartExitCode}from"../windows-task-supervisor-contract-Bz_KVoza.mjs";import{n as isTruthyEnvValue}from"../env-fLMEolk5.mjs";import{a as rewritePnpmVersionedOpenClawEntryPath}from"../openclaw-root-DP80HYD2.mjs";import{t as formatErrorMessage}from"../errors-D37BJTfI.mjs";import{t as isContainerEnvironment}from"../container-environment-C0Hd9WfF.mjs";import{h as assertPersistedStateDatabaseAccessAllowed,x as resolveStateOwnerIdentity}from"../gateway-state-owner-D_klysuh.mjs";import{s as resolveOpenClawStateSqlitePath}from"../openclaw-state-db.paths-CbgXfEg1.mjs";import{d as registerChildRuntimeRecovery,l as probeChildRuntimeExecutable}from"../child-runtime-viability-1cqYEa1U.mjs";import{x as rotateAgentEventLifecycleGeneration}from"../agent-events-Dz03BVGI.mjs";import{m as markGatewayRestartDraining,w as runWithGatewayIndependentRootWorkAdmission}from"../gateway-work-admission-CnMW3_qr.mjs";import{D as waitForActiveCronJobs,E as resetCronActiveJobs,t as advanceCronActiveJobGeneration}from"../active-jobs-QNXDOaIz.mjs";import{a as stopActiveManagedProviderLocalServices}from"../provider-runtime-lifecycle-B5eqf_rk.mjs";import{_ as abortPendingChannelReloads,a as isGatewayRestartExternallyAllowed,c as requestGatewayRestartWithSignalAdmission,d as scheduleGatewayRestart,l as resetGatewayRestartStateForInProcessRestart,m as triggerOpenClawRestart,n as consumeGatewayRestartIntent,o as markGatewayRestartHandled,s as peekGatewayRestartReason,t as consumeGatewayRestartAuthorization,u as rollbackGatewayRestartSignalAdmission}from"../restart-B5SqvVCi.mjs";import{n as prepareGatewayRestartIntentConsumption}from"../restart-intent-Bp7SeIHX.mjs";import{t as mergeGatewayServiceEnv}from"../service-env-merge-Db3tXSCb.mjs";import{i as retireActiveCronTaskRunTracking,o as waitForActiveCronTaskRuns,t as abortActiveCronTaskRuns}from"../active-run-cancellation-CrXofpbv.mjs";import{l as resetAllLanes}from"../command-queue-fBrp5ERY.mjs";import{l as resetGatewaySuspendCoordinatorForLifecycleRestart}from"../gateway-suspend-coordinator-WF7hqVpm.mjs";import{o as writeDiagnosticStabilityBundleForFailureSync}from"../diagnostic-stability-bundle-BVFlI2lH.mjs";import{o as writeGatewayRestartHandoff}from"../restart-handoff-DPRsBMaK.mjs";import{p as markUpdateRestartSentinelFailure}from"../restart-sentinel-CElXdt9r.mjs";import{n as scheduleDetachedLaunchdRestartHandoff}from"../launchd-restart-handoff-UzxA5j_y.mjs";import{n as detectGatewayRespawnSupervisor,r as detectGatewayRespawnSupervisorIdentity}from"../supervisor-markers-Uqbl0TRy.mjs";import{l as waitForSystemServiceUpdateHandoffs,n as captureForegroundUpdateHandoffStop,o as isForegroundUpdateHandoff,r as claimManagedServiceUpdateHandoff}from"../update-managed-service-handoff-current-B8AtCHi0.mjs";import{i as completeForegroundUpdateHandoffAfterClose,n as cancelManagedServiceUpdateHandoff,r as commitManagedServiceUpdateHandoff,s as requestManagedServiceUpdateHandoffPark}from"../update-managed-service-handoff-BsAof8AZ.mjs";import{o as waitForGatewayHttpReadiness}from"../restart-health-probe-ByGK0KkY.mjs";import{l as readGatewayLastShutdownAsync}from"../gateway-boot-lifecycle-4pozDn3D.mjs";import{n as reportGatewayRuntimeRecoveryOnly,t as registerGatewayNativeWorkerRecovery}from"../gateway-native-worker-recovery-qklBFe1o.mjs";import{spawn}from"node:child_process";import{isSupported}from"@openclaw/proc-safe/systemd";
//!src/infra/process-respawn.ts
function assertGatewayRespawnOutsideMaintenance(e){const t=resolveOpenClawStateSqlitePath(e);assertPersistedStateDatabaseAccessAllowed({databasePath:t,ownerPath:resolveStateOwnerIdentity(t).ownerPath,assertMaintenance:()=>{throw new Error(`Gateway respawn is blocked while offline maintenance owns the state.`)}})}function resolveGatewayRestartDecision(){if(isTruthyEnvValue(process.env.OPENCLAW_NO_RESPAWN))return{mode:`disabled`,reason:`no-respawn`};const e=detectGatewayRespawnSupervisor(process.env);if(e)return{mode:`supervised`,supervisor:e};return{mode:`disabled`,reason:`unmanaged`,detail:process.platform===`win32`?`win32: detached respawn unsupported without Scheduled Task markers`:isContainerEnvironment()?`container: use in-process restart to keep PID 1 alive`:`unmanaged: use in-process restart to keep custom supervisor PID tracking stable`}}const CHILD_RUNTIME_RESTART_REASON=`gateway.runtime-unavailable`;const NATIVE_WORKER_RESTART_REASON=`gateway.native-worker-unsettled`;function registerGatewayRuntimeRecovery(e){const{decision:t}=e;const n=e.ownsProcessLifecycle&&t.mode===`supervised`&&t.supervisor===`systemd`?isSupported():true;const r=(e.ownsProcessLifecycle&&t.mode===`supervised`?Promise.resolve().then(()=>readGatewayLastShutdownAsync()):Promise.resolve(void 0)).then(e=>({shutdown:e}),e=>({error:e}));let i=true;const recover=async(a,o,s)=>{if(!e.ownsProcessLifecycle||t.mode!==`supervised`||t.supervisor===`external`)return reportGatewayRuntimeRecoveryOnly(`no verified native service restart target.`);if(!n)return reportGatewayRuntimeRecoveryOnly(`native systemd inspection was unavailable at Gateway startup.`);const c=await r;if(`error`in c)return reportGatewayRuntimeRecoveryOnly(`restart history could not be read.`);if(c.shutdown?.reason?.includes(a)&&Date.now()-c.shutdown.completedAtMs<3e5)return reportGatewayRuntimeRecoveryOnly(`a runtime recovery restart happened within the last five minutes.`);let l;if(t.supervisor===`launchd`){const{readLoadedLaunchAgentState:e,readCorrespondingLaunchAgentCommand:t}=await import(`../launchd-runtime-Db2SXmYx.mjs`);const n=await e(process.env,{timeoutMs:5e3});const r=n.launchAgent?await t(process.env,n.launchAgent,5e3):null;l={...n,command:r,env:mergeGatewayServiceEnv(process.env,r)}}else{const{resolveGatewayService:e}=await import(`../service-flxrucEo.mjs`);const{readGatewayServiceState:t}=await import(`../service-state-CyErh4eZ.mjs`);l=await t(e(),{env:process.env,requireEffective:true,requireLoadedCommand:true,timeoutMs:5e3})}const u=l.command?.programArguments[0];if(!l.running||!u||!isNodeRuntime(u))return reportGatewayRuntimeRecoveryOnly(`the service has no verified Node command.`);const d=await probeChildRuntimeExecutable(u,{env:l.env,cwd:l.command?.workingDirectory});if(d.error||d.status!==0||!/^v\d+\.\d+\.\d+\s*$/.test(d.stdout))return reportGatewayRuntimeRecoveryOnly(`the service Node cannot start. Repair the service runtime, then restart the Gateway.`);if(!i||!e.isCurrent())return reportGatewayRuntimeRecoveryOnly(`the Gateway lifecycle is already stopping.`);return runWithGatewayIndependentRootWorkAdmission(async()=>{if(!i||!e.isCurrent())return reportGatewayRuntimeRecoveryOnly(`the Gateway lifecycle is already stopping.`);if(!o())return reportGatewayRuntimeRecoveryOnly(`the native worker has already settled.`);const t=s?requestGatewayRestartWithSignalAdmission(a,s):requestGatewayRestartWithSignalAdmission(a);return t.status===`emitted`?{status:`restart-requested`,reason:s?.requireFreshProcess?`Service Node verified; requested a bounded fresh-process restart for the unsettled native worker.`:`Service Node verified; requested a graceful fresh-process restart for the unavailable child runtime.`}:reportGatewayRuntimeRecoveryOnly(`restart request ${t.status}.`)},a)};const a=registerChildRuntimeRecovery(()=>recover(CHILD_RUNTIME_RESTART_REASON,()=>true));let o;let s;const c=/* @__PURE__ */ new Set;const request=e=>{if(s)return Promise.resolve(s);c.add(e.isCurrent);o??=recover(NATIVE_WORKER_RESTART_REASON,()=>[...c].some(e=>e()),{force:true,waitMs:0,requireFreshProcess:true}).then(e=>{if(e.status===`restart-requested`)s=e;return e}).finally(()=>{o=void 0;c.clear()});return o};const l=registerGatewayNativeWorkerRecovery(request);return()=>{i=false;a();l()}}function restartGatewayProcessWithFreshPid(e={}){const t=e.decision??resolveGatewayRestartDecision();if(t.mode===`disabled`)return t.reason===`no-respawn`?{mode:`disabled`}:{mode:`disabled`,detail:t.detail};try{assertGatewayRespawnOutsideMaintenance({...process.env,...e.env})}catch(e){return{mode:`failed`,detail:formatErrorMessage(e)}}const{supervisor:n}=t;if(n===`launchd`){const e=scheduleDetachedLaunchdRestartHandoff({mode:`start-after-exit`,waitForPid:process.pid});return e.ok?{mode:`supervised`,handoffSpawned:e.value}:{mode:`failed`,detail:e.error}}if(n===`schtasks`){if(process.argv.some(isWindowsTaskSupervisorChildArgument)){const e=readWindowsTaskSupervisorRestartExitCode(process.argv);if(e===void 0)return{mode:`failed`,detail:`Windows task supervisor restart marker is missing or invalid`};return{mode:`supervised`,exitCode:e}}const e=triggerOpenClawRestart();if(!e.ok)return{mode:`failed`,detail:e.detail??`${e.method} restart failed`}}return{mode:`supervised`}}function respawnGatewayProcessForUpdate(e={}){const t=e.decision??resolveGatewayRestartDecision();if(t.mode===`disabled`&&t.reason===`no-respawn`)return{mode:`disabled`,detail:`OPENCLAW_NO_RESPAWN`};try{const t=e.env?{...process.env,...e.env}:process.env;const[n,...r]=process.argv.slice(1);const i=resolveOpenClawCliInvocation({entryPath:n?rewritePnpmVersionedOpenClawEntryPath(n):void 0,args:r});assertGatewayRespawnOutsideMaintenance(t);const a=spawn(i.command,i.args,{env:t,detached:true,stdio:`inherit`});a.on(`error`,()=>{});a.unref();return{mode:`spawned`,pid:a.pid??void 0,child:a}}catch(e){return{mode:`failed`,detail:formatErrorMessage(e)}}}export{abortActiveCronTaskRuns,abortPendingChannelReloads,advanceCronActiveJobGeneration,cancelManagedServiceUpdateHandoff,captureForegroundUpdateHandoffStop,claimManagedServiceUpdateHandoff,commitManagedServiceUpdateHandoff,completeForegroundUpdateHandoffAfterClose,consumeGatewayRestartAuthorization,consumeGatewayRestartIntent,detectGatewayRespawnSupervisorIdentity,isForegroundUpdateHandoff,isGatewayRestartExternallyAllowed,markGatewayRestartDraining as markGatewayDraining,markGatewayRestartHandled,markUpdateRestartSentinelFailure,peekGatewayRestartReason,prepareGatewayRestartIntentConsumption,registerGatewayRuntimeRecovery,requestGatewayRestartWithSignalAdmission,requestManagedServiceUpdateHandoffPark,resetAllLanes,resetCronActiveJobs,resetGatewayRestartStateForInProcessRestart,resetGatewaySuspendCoordinatorForLifecycleRestart,resolveGatewayRestartDecision,respawnGatewayProcessForUpdate,restartGatewayProcessWithFreshPid,retireActiveCronTaskRunTracking,rollbackGatewayRestartSignalAdmission,rotateAgentEventLifecycleGeneration,scheduleGatewayRestart,stopActiveManagedProviderLocalServices,waitForActiveCronJobs,waitForActiveCronTaskRuns,waitForGatewayHttpReadiness,waitForSystemServiceUpdateHandoffs,writeDiagnosticStabilityBundleForFailureSync,writeGatewayRestartHandoff};