UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

16 lines • 18.9 kB
import{r as defaultRuntime,t as ExitError}from"./runtime-DIcLIHcp.mjs";import{o as getAsyncWorkSignal}from"./async-work-scope-DBcxYU4O.mjs";import{C as resolveIsNixMode}from"./paths-D_FOvGon.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{t as formatCliCommand}from"./command-format-D7KhNLP0.mjs";import{T as releaseOpenClawStateDatabaseCustody}from"./openclaw-state-db-cache-uycu-8uy.mjs";import{y as resolveFutureConfigActionBlock}from"./config-env-vars-DCDGIBtT.mjs";import{r as isPluginPackagingRuntimeOutputInvalidConfigSnapshot}from"./recovery-policy-C9I1hpUN.mjs";import{s as readConfigFileSnapshot}from"./io.runtime-BvSeVFIY.mjs";import"./config-DkZ8y8Gv.mjs";import{t as isWSL}from"./wsl-_7IqvQi4.mjs";import{n as isGatewaySecretRefUnavailableError,s as createGatewayCredentialPlan,t as GatewaySecretRefUnavailableError}from"./credentials-BL-kavyD.mjs";import{i as assertGatewayServiceUpdateCurrent}from"./service-update-authority-DqjrBTQ9.mjs";import{_ as isSystemdUserServiceAvailable}from"./systemd-busctl-query-CVbse9JI.mjs";import{c as resolveSystemdServiceName}from"./systemd-service-files-C0LoSdR4.mjs";import{a as writeGatewayServiceRestartIntentSync,i as writeGatewayRestartIntentSync,r as prepareGatewayRestartIntentLegacyProcess,s as GatewayRestartPreparationError,t as clearGatewayRestartIntentSync}from"./restart-intent-Bp7SeIHX.mjs";import{t as appendGatewayLifecycleAuditLog}from"./restart-logs-C62uUCzk.mjs";import{t as mergeGatewayServiceEnv}from"./service-env-merge-Db3tXSCb.mjs";import{i as renderSystemdUnavailableHints}from"./runtime-format-hFkv-6vU.mjs";import{S as mergeWarnings,b as createDaemonActionContext,i as filterContainerGenericHints,m as resolveDaemonInstallBlockMessage,y as buildDaemonServiceSnapshot}from"./shared-BctPQR6n.mjs";import{n as resolveLaunchAgentLabel}from"./launchd-label-Daj1UmUS.mjs";import{a as formatGatewayServiceStartRepairIssues,i as collectGatewayServiceStartRepairIssues,r as startGatewayService,t as describeGatewayServiceRestart}from"./service-Bz63n2ee.mjs";import{t as createGatewayLifecycleMutationReporter}from"./service-mutation-BXMoc2of.mjs";import{r as readGatewayServiceLoadState,t as readGatewayServiceState}from"./service-state-C07U7uy3.mjs";import"./systemd-BLmKdJhz.mjs";import{t as renderConfigValidationIssueLines}from"./issue-location-D2fdScOj.mjs";import{r as formatPluginPackagingRuntimeOutputRecoveryHint,t as formatInvalidConfigRecoveryHint}from"./config-recovery-hints-CCNKrIVF.mjs";import{r as isTerminalInteractive}from"./terminal-interactivity-ijJuF5PT.mjs";import{i as checkTokenDrift,r as checkManagedServiceEnvDrift}from"./service-audit-DNlslbPV.mjs";import{t as resolveGatewayAuthToken}from"./auth-token-resolution-BHyWE1aF.mjs"; //!src/cli/daemon-cli/gateway-token-drift.ts async function resolveGatewayTokenForDriftCheck(e){const t=e.env??process.env;const n=e.cfg.gateway?.auth?.mode;if(n===`password`||n===`none`||n===`trusted-proxy`)return;const r=createGatewayCredentialPlan({config:e.cfg,env:t});if(r.authMode===void 0&&r.passwordCanWin&&!r.tokenCanWin)return;const i=await resolveGatewayAuthToken({cfg:e.cfg,env:t,envFallback:`never`,unresolvedReasonStyle:`detailed`});if(i.token)return i.token;if(!i.secretRefConfigured)return;throw new GatewaySecretRefUnavailableError(`gateway.auth.token`)} //!src/cli/daemon-cli/lifecycle-action-preflight.ts async function getServiceActionPreflightFailure(e){let t;try{if(e===`restart`){const{readConfigSnapshotForEngineSelection:e}=await import(`./config-preflight-snapshot-CYPXIJMO.mjs`);t=await e(process.env,{isolateEnv:false});if(t.valid)t=await readConfigFileSnapshot({observe:false})}else t=await readConfigFileSnapshot({observe:false,...e===`stop`||e===`uninstall`?{pluginValidation:`core-only`}:{}});if(!t.valid)return{message:t.issues.length>0?renderConfigValidationIssueLines(t,``).join(` `):`Unknown validation issue.`,...isPluginPackagingRuntimeOutputInvalidConfigSnapshot(t)?{hints:formatPluginPackagingRuntimeOutputRecoveryHint().split(` `)}:{}}}catch(t){return e===`restart`?{message:formatErrorMessage(t)}:null}const n=resolveFutureConfigActionBlock({action:`${e} the gateway service`,snapshot:t});if(n)return{message:e===`start`?n.message:`Config was last written by OpenClaw ${n.touchedVersion}; this binary is ${n.currentVersion}.`,hints:n.hints};return null} //!src/cli/daemon-cli/lifecycle-audit.ts function appendGatewayLifecycleAudit(e){appendGatewayLifecycleAuditLog(e.env??process.env,{action:e.action,source:e.source,mode:e.mode,...e.pid===void 0?{}:{pid:e.pid},interactive:isTerminalInteractive()})}function createGatewayLifecycleMutationAudit(e){const t=createGatewayLifecycleMutationReporter(t=>{appendGatewayLifecycleAudit({action:e.action,source:e.source??`cli`,mode:t.mode,...e.env===void 0?{}:{env:e.env}})});return e=>t(e.mode)}function createServiceLifecycleMutationAudit(e){return e.serviceNoun===`Gateway`?createGatewayLifecycleMutationAudit({action:e.action}):void 0}function appendServiceLifecycleRepairAudit(e){if(e.serviceNoun!==`Gateway`)return;appendGatewayLifecycleAudit({action:e.action,source:`cli`,mode:`service-repair`,...e.pid===void 0?{}:{pid:e.pid}})} //!src/cli/daemon-cli/lifecycle-load-state.ts async function failServiceNotLoaded(e,t){let n=e.renderStartHints();if(process.platform===`linux`&&!await isSystemdUserServiceAvailable().catch(()=>false))n=[...n,...renderSystemdUnavailableHints({wsl:await isWSL(),kind:`generic_unavailable`})];t(`${e.serviceNoun} service ${e.service.notLoadedText}.`,filterContainerGenericHints(n))}async function resolveServiceLoadedOrFail(e,t,n={}){const hasInstalledDefinition=async()=>e.service.hasInstalledDefinition?await e.service.hasInstalledDefinition({env:process.env}).catch(()=>false):Boolean(await e.service.readCommand(process.env).catch(()=>null));const r=await readGatewayServiceLoadState(e.service,{env:process.env});if(r.status===`unknown`){t(`${n.inspectionFailureMessage??`${e.serviceNoun} service check failed`}: ${r.detail}`);return null}return r.status===`loaded`||Boolean(n.acceptInstalledDefinition)&&await hasInstalledDefinition()} //!src/cli/daemon-cli/lifecycle-restart-intent.ts function createServiceRestartIntent(e){let t=false;let n=process.env;return{prepare:async()=>{if(e.serviceNoun!==`Gateway`||t)return;const r=await e.service.readRuntime(process.env).catch(()=>null);assertGatewayServiceUpdateCurrent();const i=process.platform===`linux`||process.platform===`darwin`;let a;let o;if(i)try{const t=await e.service.readCommand(process.env,{requireEffective:true});assertGatewayServiceUpdateCurrent();if(!t)throw new GatewayRestartPreparationError(`service-command`);n=mergeGatewayServiceEnv(process.env,t);a=process.platform===`linux`?{kind:`systemd`,name:r?.systemd?.unit??resolveSystemdServiceName(process.env)}:{kind:`launchd`,name:resolveLaunchAgentLabel(process.env)};o=await prepareGatewayRestartIntentLegacyProcess({env:n,command:t,runtimePid:r?.pid,readRuntime:()=>e.service.readRuntime(process.env),assertCurrent:assertGatewayServiceUpdateCurrent})}catch{assertGatewayServiceUpdateCurrent();throw new GatewayRestartPreparationError(`service-command`)}assertGatewayServiceUpdateCurrent();const s={env:n,reason:`gateway.restart`,...e.intent?{intent:e.intent}:{}};t=a?writeGatewayServiceRestartIntentSync({...s,service:a,legacyProcess:o,nativeStopped:r?.status===`stopped`&&r.pid===void 0,assertCurrent:assertGatewayServiceUpdateCurrent}):writeGatewayRestartIntentSync({...s,targetPid:r?.pid});await releaseOpenClawStateDatabaseCustody()},clear:()=>{if(t){assertGatewayServiceUpdateCurrent();clearGatewayRestartIntentSync(n);t=false}}}} //!src/cli/daemon-cli/lifecycle-core.ts function commandInterrupted(e){const t=getAsyncWorkSignal();return t?.aborted===true&&(e===t.reason||e instanceof Error&&e.cause===t.reason)}function warnServiceConfig(e,t){if(!e)return;const n=[`Config needs repair: ${e.message}`,...e.hints??[],formatCliCommand(`openclaw doctor --fix`)].join(` `);t.warnings.push(n);if(!t.json)defaultRuntime.error(`WARNING: ${n}`)}async function runServiceUninstall(e){const t=Boolean(e.opts?.json);const{stdout:n,warnings:r,emit:i,fail:a}=createDaemonActionContext({action:`uninstall`,json:t});if(resolveIsNixMode(process.env)){a(`Nix mode detected; service uninstall is disabled.`);return}let o=await resolveServiceLoadedOrFail(e,a,{inspectionFailureMessage:`${e.serviceNoun} uninstall aborted because service status is unknown; resolve the inspection error before retrying`});if(o===null)return;if(o&&e.stopBeforeUninstall)try{await e.service.stop({env:process.env,stdout:n})}catch{}try{await e.service.uninstall({env:process.env,stdout:n})}catch(t){a(`${e.serviceNoun} uninstall failed: ${String(t)}`,e.renderFailureHints());return}o=await resolveServiceLoadedOrFail(e,a,{inspectionFailureMessage:`${e.serviceNoun} uninstall verification failed because service status is unknown`});if(o===null)return;if(o&&e.assertNotLoadedAfterUninstall){a(`${e.serviceNoun} service still loaded after uninstall.`,e.renderFailureHints());return}warnServiceConfig(await getServiceActionPreflightFailure(`uninstall`),{json:t,warnings:r});i({ok:true,result:`uninstalled`,service:buildDaemonServiceSnapshot(e.service,o)})}async function runServiceStart(e){const t=Boolean(e.opts?.json);const n=formatCliCommand(`openclaw ${e.serviceNoun.toLowerCase()}`);const{stdout:r,warnings:i,emitMessage:a,fail:o}=createDaemonActionContext({action:`start`,json:t});const s=t?e=>i.push(e):void 0;let c=false;const checkReadiness=async()=>{await e.postStartCheck?.({json:t,stdout:r,warnings:i,warn:s,fail:(e,t,n)=>{c=true;o(e,t,n)}});return!c};const emitStarted=async t=>{if(!await checkReadiness())return;a({ok:true,result:`started`,message:t.message,warnings:mergeWarnings(i,t.reportedWarnings),service:buildDaemonServiceSnapshot(e.service,t.loaded)})};const l=await resolveServiceLoadedOrFail(e,o);if(l===null)return;const u=await getServiceActionPreflightFailure(`start`);if(u){o(!u.hints?`${e.serviceNoun} aborted: config is invalid.\n${u.message}\n${formatInvalidConfigRecoveryHint()}`:`${e.serviceNoun} start blocked: ${u.message}`,u.hints);return}if(!l)try{const n=await e.onNotLoaded?.({json:t,stdout:r,warn:s,fail:o});if(n){await emitStarted({loaded:n.loaded??false,message:n.message,reportedWarnings:n.warnings});return}}catch(t){if(c||t instanceof ExitError)throw t;if(commandInterrupted(t))return;o(`${e.serviceNoun} start failed: ${String(t)}`,e.renderStartHints());return}try{const l=await startGatewayService(e.service,{env:process.env,stdout:r,warn:s,beforeMutation:e.beforeServiceMutation,onMutation:createServiceLifecycleMutationAudit({serviceNoun:e.serviceNoun,action:`start`})},e.expectedPort);if(l.outcome===`missing-install`){await failServiceNotLoaded(e,o);return}if(l.outcome===`already-running`){if(l.issues.length>0){const r=e.repairLoadedService?`restart`:`install --force`;const a=`${e.serviceNoun} service already running, but its installed service definition needs repair: ${formatGatewayServiceStartRepairIssues(l.issues)}; run \`${n} ${r}\` to apply.`;i.push(a);if(!t)defaultRuntime.log(a)}if(!await checkReadiness())return;const r=l.state.runtime?.pid;a({ok:true,result:`already-running`,message:`${e.serviceNoun} service already running${r===void 0?``:` (pid ${r})`}.`,service:buildDaemonServiceSnapshot(e.service,true),warnings:i.length?i:void 0});return}if(l.outcome===`repair-required`){try{const n=await e.repairLoadedService?.({json:t,stdout:r,warn:s,fail:o,state:l.state,issues:l.issues});if(n){appendServiceLifecycleRepairAudit({serviceNoun:e.serviceNoun,action:`start`});await emitStarted({loaded:n.loaded??true,message:n.message,reportedWarnings:n.warnings});return}}catch(t){if(c||t instanceof ExitError)throw t;if(commandInterrupted(t))return;o(`${e.serviceNoun} repair failed: ${String(t)}`,e.renderStartHints());return}o(`${e.serviceNoun} service needs repair before it can start: ${formatGatewayServiceStartRepairIssues(l.issues)}`,[`${n} install --force`]);return}await emitStarted({loaded:l.state.loadState.status===`loaded`})}catch(t){if(c||t instanceof ExitError)throw t;if(commandInterrupted(t))return;o(`${e.serviceNoun} start failed: ${String(t)}`,e.renderStartHints())}}async function runServiceStop(e){const t=Boolean(e.opts?.json);const{stdout:n,warnings:r,emit:i,emitMessage:a,fail:o}=createDaemonActionContext({action:`stop`,json:t});const s=createServiceLifecycleMutationAudit({serviceNoun:e.serviceNoun,action:`stop`});const c=await resolveServiceLoadedOrFail(e,o);if(c===null)return;if(!c&&!e.stopWhenNotLoaded){try{const i=await e.onNotLoaded?.({json:t,stdout:n,fail:o});if(i){warnServiceConfig(await getServiceActionPreflightFailure(`stop`),{json:t,warnings:r});a({ok:true,result:i.result,message:i.message,warnings:mergeWarnings(r,i.warnings),service:buildDaemonServiceSnapshot(e.service,false)});return}}catch(t){if(t instanceof ExitError)throw t;o(`${e.serviceNoun} stop failed: ${String(t)}`,e.renderFailureHints());return}warnServiceConfig(await getServiceActionPreflightFailure(`stop`),{json:t,warnings:r});a({ok:true,result:`not-loaded`,message:`${e.serviceNoun} service ${e.service.notLoadedText}.`,service:buildDaemonServiceSnapshot(e.service,c)});return}try{await e.service.stop({env:process.env,stdout:n,disable:e.opts?.disable,onMutation:s})}catch(t){o(`${e.serviceNoun} stop failed: ${String(t)}`,e.renderFailureHints());return}const l=c?await resolveServiceLoadedOrFail(e,o,{inspectionFailureMessage:`${e.serviceNoun} stop verification failed because service status is unknown`}):false;if(l===null)return;warnServiceConfig(await getServiceActionPreflightFailure(`stop`),{json:t,warnings:r});i({ok:true,result:`stopped`,service:buildDaemonServiceSnapshot(e.service,l)})}async function runServiceRestart(e){const t=Boolean(e.opts?.json);const{stdout:n,warnings:r,emitMessage:i,fail:a}=createDaemonActionContext({action:`restart`,json:t});const o=t?e=>r.push(e):void 0;const renderRestartFailureHints=t=>t instanceof GatewayRestartPreparationError&&t.reason===`serving-owner`?[formatCliCommand(`openclaw gateway status --deep`),`Fix the reported startup failure, then run \`${formatCliCommand(`openclaw gateway start`)}\` to wait for readiness without restarting the process.`]:e.renderStartHints();const s=e.opts?.restartIntent;const c=createServiceLifecycleMutationAudit({serviceNoun:e.serviceNoun,action:`restart`});let l=null;let u=null;let d=null;const{prepare:f,clear:p}=createServiceRestartIntent({...e,intent:s});const prepareGatewayRestartIntent=async()=>{await e.beforeServiceMutation?.();await f()};const emitScheduledRestart=(t,n)=>{i({ok:true,result:t.daemonActionResult,message:t.message,service:buildDaemonServiceSnapshot(e.service,n),warnings:r.length?r:void 0});return true};const m=await resolveServiceLoadedOrFail(e,a,{acceptInstalledDefinition:true});if(m===null)return false;const h=await getServiceActionPreflightFailure(`restart`);if(e.restartOwnedProcess)try{l=await e.restartOwnedProcess({json:t,stdout:n,warn:o,fail:a})}catch(t){if(t instanceof ExitError)throw t;if(commandInterrupted(t))return false;a(`${e.serviceNoun} restart failed: ${String(t)}`);return false}if(!m&&!l){try{l=await e.onNotLoaded?.({json:t,stdout:n,warn:o,fail:a})??null}catch(t){if(t instanceof ExitError)throw t;if(commandInterrupted(t))return false;a(`${e.serviceNoun} restart failed: ${String(t)}`);return false}if(!l){await failServiceNotLoaded(e,a);return false}if(l.warnings?.length)r.push(...l.warnings);d=l.loaded??null}if(m&&!l&&!h&&e.repairLoadedService)try{const i=await readGatewayServiceState(e.service,{env:process.env});const s=collectGatewayServiceStartRepairIssues(i,e.expectedPort);if(s.length>0){await prepareGatewayRestartIntent();u=await e.repairLoadedService({json:t,stdout:n,warn:o,fail:a,state:i,issues:s});if(!u){p();a(`${e.serviceNoun} service needs repair before restart: ${formatGatewayServiceStartRepairIssues(s)}`,[formatCliCommand(`openclaw gateway install --force`)]);return false}appendServiceLifecycleRepairAudit({serviceNoun:e.serviceNoun,action:`restart`,pid:i.runtime?.pid});if(u.warnings?.length)r.push(...u.warnings)}}catch(t){p();if(t instanceof ExitError)throw t;if(commandInterrupted(t))return false;a(`${e.serviceNoun} repair failed: ${String(t)}`,renderRestartFailureHints(t));return false}if(m&&!l&&!h&&e.readDriftContext){const warnDrift=(e,n)=>{const i=n?resolveDaemonInstallBlockMessage(`gateway`)??`Run \`${formatCliCommand(`openclaw gateway install --force`)}\` to refresh the service ${n}.`:void 0;const a=i?`${e} ${i}`:e;r.push(a);if(!t)defaultRuntime.log(`\n⚠️ ${a}\n`)};try{const{command:t,config:n}=e.readDriftContext();const r={...process.env,...t?.environment};try{const e=await resolveGatewayTokenForDriftCheck({cfg:n,env:r});const i=checkTokenDrift({serviceToken:t?.environment?.OPENCLAW_GATEWAY_TOKEN,configToken:e});if(i)warnDrift(i.message,`token source`)}catch(e){if(isGatewaySecretRefUnavailableError(e,`gateway.auth.token`))warnDrift(`Unable to verify gateway token drift: gateway.auth.token SecretRef is configured but unavailable in this command path.`)}const{collectDurableServiceEnvVars:i}=await import(`./state-dir-dotenv-GHZmknqO.mjs`);const{collectEnvSecretRefIds:a}=await import(`./resolution-facts-D4JgkRHv.mjs`);const o=checkManagedServiceEnvDrift({command:t??null,durableEnvironment:i({env:r,config:n}),secretRefKeys:a(n)});if(o)warnDrift(o.message,`environment`)}catch{}}let g=false;try{let s;if(m&&!u&&!l){if(!e.opts?.preserveDefinition)await prepareGatewayRestartIntent();try{s=await e.service.restart({prepareRestart:e.opts?.preserveDefinition?prepareGatewayRestartIntent:void 0,prepareEffect:e.prepareServiceEffect,preserveDefinition:h?true:e.opts?.preserveDefinition,env:process.env,stdout:n,warn:o,beforeMutation:e.beforeServiceMutation,onMutation:c})}catch(e){p();throw e}}warnServiceConfig(h,{json:t,warnings:r});let f=describeGatewayServiceRestart(e.serviceNoun,s??{outcome:`completed`});if(f.scheduled)return emitScheduledRestart(f,m||d===true);const _=await e.postRestartCheck?.({json:t,stdout:n,warnings:r,warn:o,activationAccepted:s?.outcome===`completed`||Boolean(l),preserveDefinition:h?true:e.opts?.preserveDefinition,fail:(e,t,n)=>{g=true;a(e,t,n)}});if(_){f=describeGatewayServiceRestart(e.serviceNoun,_);if(f.scheduled)return emitScheduledRestart(f,m||d===true)}i({ok:true,result:`restarted`,readiness:_?_.readiness:void 0,message:l?.message??u?.message,service:buildDaemonServiceSnapshot(e.service,m||d===true),warnings:r.length?r:void 0});return true}catch(t){if(g||t instanceof ExitError)throw t;if(commandInterrupted(t))return false;a(`${e.serviceNoun} restart failed: ${String(t)}`,renderRestartFailureHints(t));return false}}export{runServiceUninstall as a,runServiceStop as i,runServiceRestart as n,appendGatewayLifecycleAudit as o,runServiceStart as r,createGatewayLifecycleMutationAudit as s,commandInterrupted as t};