UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

12 lines • 33 kB
import{l as normalizeOptionalString}from"./string-coerce-CpTFcSwY.mjs";import"./src-0ci69Prg.mjs";import{t as expectDefined}from"./expect-DkJCbmLj.mjs";import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{o as writeRuntimeJson,r as defaultRuntime}from"./runtime-DIcLIHcp.mjs";import{o as getAsyncWorkSignal}from"./async-work-scope-DBcxYU4O.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import{r as parseTcpPortFromArgs}from"./tcp-port-CL3rN59M.mjs";import{b as resolveGatewayPort,h as resolveConfigPathCandidate}from"./paths-D_FOvGon.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{t as formatCliCommand}from"./command-format-D7KhNLP0.mjs";import{d as isSameGatewayLockIdentity}from"./gateway-lock-payload-CBa45_pI.mjs";import{a as hasCommandProcessCleanupError,o as ignoreNonCleanupCommandError}from"./exec-result-TD4w1Z1i.mjs";import{T as releaseOpenClawStateDatabaseCustody}from"./openclaw-state-db-cache-uycu-8uy.mjs";import{c as resolveGatewayServiceMutationError,i as formatExternalSupervisorActionRequired,o as isGatewayExternallySupervised,r as assertGatewayServiceMutationAllowed}from"./gateway-supervision-TUZKxlq7.mjs";import{t as parseDurationMs}from"./parse-duration-BueP0M46.mjs";import{t as createConfigIO}from"./io.factory-y6nIrp_4.mjs";import{r as readGatewayOwnerLease}from"./gateway-owner-lease-9K6iKMiO.mjs";import{o as terminateStaleGatewayPids}from"./restart-stale-pids-DF3h-m9n.mjs";import{a as readBestEffortConfig,l as readConfigFileSnapshotForWrite}from"./io.runtime-BvSeVFIY.mjs";import"./io-Di_yuX3t.mjs";import{p as withCommandProcessScope}from"./exec-spawn-DNCbDcyJ.mjs";import"./config-DkZ8y8Gv.mjs";import{r as theme}from"./theme-DS2CtI9X.mjs";import{t as GATEWAY_SERVER_CAPS}from"./server-capabilities-HdXShIdT.mjs";import{n as resolveGatewayRestartDrainTimeoutMs,t as resolveGatewayRestartDeferralTimeoutMs}from"./restart-budget-HbMaGsmG.mjs";import{t as resolveGatewayStartupTiming}from"./gateway-startup-timing-NJfJyTHo.mjs";import{a as hasGatewayServiceEnvironmentOverride,i as hasGatewayServiceEnvironmentDifference,o as hasGatewayServiceLauncherOverride,s as resolveManagedGatewayServiceCommand,t as assertServiceDefinitionWritable}from"./service-types-B7cjFijA.mjs";import{i as assertGatewayServiceUpdateCurrent,o as isUpdateOwnedGatewayServiceCommand,r as assertGatewayServiceFallbackAllowed}from"./service-update-authority-DqjrBTQ9.mjs";import{a as readActiveGatewayLockIdentity,d as captureStalledGatewayStartup,o as readActiveGatewayLockPort}from"./gateway-lock-CQoO1usb.mjs";import{i as writeGatewayRestartIntentSync,t as clearGatewayRestartIntentSync}from"./restart-intent-Bp7SeIHX.mjs";import{t as mergeGatewayServiceEnv}from"./service-env-merge-Db3tXSCb.mjs";import{n as isRestartEnabled}from"./commands.flags-BdxOktqL.mjs";import{t as ExpectedCliError}from"./expected-cli-error-oDVmXYil.mjs";import{t as createNullWriter}from"./null-writer-DopKjbDw.mjs";import{b as createDaemonActionContext,d as renderGatewayServiceStartHints,f as renderGatewayServiceStopHints,p as renderGatewayServiceUninstallHints,t as assertGatewayServiceActionAllowed}from"./shared-BctPQR6n.mjs";import{i as callGatewayCli}from"./call-CVqWsTxX.mjs";import{a as resolveBunRuntimeInfo,s as resolvePinnedDaemonRuntimePath}from"./runtime-paths-BOio2Rt6.mjs";import{a as formatGatewayServiceStartRepairIssues,n as resolveGatewayService}from"./service-Bz63n2ee.mjs";import{n as probePortUsage}from"./ports-probe-B-fmalcq.mjs";import{t as resolveGatewayServiceProbeHosts}from"./gateway-service-probe-hosts-Cvqbifz1.mjs";import{a as readDaemonRuntimePin,c as withDaemonRuntimePinMigration}from"./runtime-pin-state-DeLfcMhS.mjs";import{o as resolveOpenClawWrapperPath,t as OPENCLAW_WRAPPER_ENV_KEY}from"./program-args-Dls9y3ku.mjs";import{E as stopStalledGatewayStartup}from"./service-state-C07U7uy3.mjs";import{i as signalVerifiedGatewayPidSync,n as findVerifiedGatewayListenerPidsOnPortSync,r as formatGatewayPidList}from"./gateway-processes-Xuyq2r9a.mjs";import{i as findInstalledSystemdGatewayScope}from"./systemd-scope-DvdmsQC9.mjs";import{i as stopSystemdService,n as restartSystemdService}from"./systemd-lifecycle-CKiXKu66.mjs";import{i as refreshLegacySystemdServiceMetadata}from"./systemd-BLmKdJhz.mjs";import{n as createGatewayRestartDeadline}from"./restart-health-deadline-D3SucA68.mjs";import{a as postRestartHealthAttempts,n as DEFAULT_RESTART_HEALTH_DELAY_MS}from"./restart-health.constants-BS7LeiAV.mjs";import{n as probeGateway}from"./probe-B6H7uyuf.mjs";import{o as waitForGatewayHttpReadiness}from"./restart-health-probe-ByGK0KkY.mjs";import{i as formatGatewayRestartFailure,n as waitForGatewayHealthyRestart,o as renderGatewayPortHealthDiagnostics,r as waitForGatewayHealthyListener,s as renderRestartDiagnostics}from"./restart-health-rwGZnZS0.mjs";import{t as recoverInstalledLaunchAgent}from"./launchd-recovery-fO7ry3F9.mjs";import{n as NON_INTERACTIVE_GATEWAY_STOP_MESSAGE,r as isTerminalInteractive}from"./terminal-interactivity-ijJuF5PT.mjs";import{i as resolveGatewayDaemonRuntime}from"./daemon-runtime-CM-TWmEx.mjs";import{a as runServiceUninstall,i as runServiceStop,n as runServiceRestart,o as appendGatewayLifecycleAudit,r as runServiceStart,s as createGatewayLifecycleMutationAudit,t as commandInterrupted}from"./lifecycle-core-CfwSEwvB.mjs";import{t as buildGatewayInstallPlan}from"./daemon-install-helpers-CF_xtI3X.mjs";import{t as resolveGatewayInstallToken}from"./gateway-install-token-Pt-GC-0y.mjs";import{t as mergeInstallInvocationEnv}from"./install-8lyaZe63.mjs";import{a as resolveGatewayLifecycleContext,i as resolveGatewayConfigPorts,t as createGatewayLifecycleContext}from"./lifecycle-context-D09X9_mB.mjs";import path from"node:path"; //!src/cli/daemon-cli/lifecycle-safe-restart.ts const SAFE_RESTART_METADATA_REFRESH_TIMEOUT_MS=5e3;function restartFlagConflictError(e){return new ExpectedCliError({message:e,humanOutput:`${theme.error(`Error:`)} ${e}`,machineOutput:e})}function assertNativeRestartFlags(e){if(e.preserveDefinition&&e.safe)throw restartFlagConflictError(`--preserve-definition requires a native restart without --safe`);if(e.skipDeferral&&!e.safe)throw restartFlagConflictError(`--skip-deferral requires --safe`)}function resolveGatewayRestartIntentOptions(e){if(e.force&&e.wait!==void 0)throw restartFlagConflictError(`--force cannot be combined with --wait`);if(e.force)return{force:true,waitMs:resolveGatewayRestartDeferralTimeoutMs()};return e.wait===void 0?void 0:{waitMs:parseDurationMs(e.wait)}}async function runSafeGatewayRestart(e,t){if(e.force)throw restartFlagConflictError(`--safe cannot be combined with --force; omit --safe to begin a forced restart`);if(e.wait!==void 0)throw restartFlagConflictError(`--safe cannot be combined with --wait; safe restart uses gateway deferral`);const n=e.skipDeferral===true;const r={reason:`gateway.restart.safe`,...t?{safe:true,target:{pid:t.pid,ownerId:t.ownerId,port:t.port}}:{},...n?{skipDeferral:true}:{}};if(process.platform===`linux`){const reportRefreshError=e=>{defaultRuntime.error(theme.warn(`Warning: legacy systemd metadata was not refreshed: ${formatErrorMessage(e)}`))};const e=resolveGatewayServiceMutationError(`refresh legacy systemd service metadata`,process.env);if(e)reportRefreshError(e);else await refreshLegacySystemdServiceMetadata(process.env,SAFE_RESTART_METADATA_REFRESH_TIMEOUT_MS).catch(reportRefreshError)}const i=await callGatewayCli({method:`gateway.restart.request`,params:r,...t?{ignoreEnvUrlOverride:true,localPortOverride:t.port,requiredCapabilities:[GATEWAY_SERVER_CAPS.GATEWAY_RESTART_TARGET_SAFE]}:{},timeoutMs:1e4});if(t&&i.restart.pid!==t.pid)throw new Error(`invalid safe restart acknowledgement`);appendGatewayLifecycleAudit({action:`restart`,source:`safe-rpc`,mode:i.status,pid:i.restart.pid});const a=i.status===`coalesced`?`safe restart request joined an existing pending gateway restart`:i.status===`deferred`?`safe restart requested; gateway will restart after active work drains (bounded wait; may force after the timeout expires)`:n?`safe restart requested; gateway bypassing active-work deferral; shutdown may still wait for pending replies to drain`:`safe restart requested; gateway will restart momentarily`;const o={ok:true,result:i.status,message:a,preflight:i.preflight,restart:i.restart,warnings:i.preflight.blockers.length===0?void 0:[i.preflight.summary]};if(e.json)writeRuntimeJson(defaultRuntime,o);else{defaultRuntime.log(a);if(i.preflight.blockers.length>0)defaultRuntime.log(theme.warn(i.preflight.summary))}return true} //!src/cli/daemon-cli/lifecycle-systemd-scope.ts async function handleSystemScopeSystemdGateway(e){if(process.platform!==`linux`)return null;const t=await findInstalledSystemdGatewayScope(process.env).catch(()=>null);if(t?.scope!==`system`)return null;const n=createNullWriter();await(e===`stop`?stopSystemdService:restartSystemdService)({stdout:n,env:process.env,onMutation:createGatewayLifecycleMutationAudit({action:e})});const r=e===`stop`?`stopped`:`restarted`;return{result:r,message:`Gateway ${r} via system-scope systemd unit ${t.unitName}.`}} //!src/cli/daemon-cli/lifecycle-unmanaged.ts async function assertUnmanagedGatewayRestartEnabled(e){const t=(await readBestEffortConfig({observe:false}).catch(()=>void 0))?.gateway?.tls?.enabled?`wss`:`ws`;const n=await probeGateway({url:`${t}://127.0.0.1:${e}`,auth:{token:normalizeOptionalString(process.env.OPENCLAW_GATEWAY_TOKEN),password:normalizeOptionalString(process.env.OPENCLAW_GATEWAY_PASSWORD)},timeoutMs:1e3}).catch(()=>null);if(!n?.ok)return;if(isRecord(n.configSnapshot)&&!isRestartEnabled({commands:n.configSnapshot.commands}))throw new Error(`Gateway restart is disabled in the running gateway config (commands.restart=false)`)}async function signalGatewayRestart(e,t){const n=t.restartIntent?.force?{force:true,drainBudgetMs:t.restartIntent.waitMs}:t.restartIntent;const r=findVerifiedGatewayListenerPidsOnPortSync(e,{env:t.env});if(r.length===0)return null;if(r.length>1)throw new Error(`multiple gateway processes are listening on port ${e}: ${formatGatewayPidList(r)}; use "openclaw gateway status --deep" before retrying restart`);const i=expectDefined(r[0],`pids entry at 0`);if(t.ownerLease&&t.ownerLease.pid!==i)throw new Error(`Port ${e} is owned by pid ${i}, not the recorded foreground Gateway pid ${t.ownerLease.pid}; refusing restart`);const a=process.platform===`win32`;const o=await readActiveGatewayLockIdentity({env:t.env});if(!o||o.pid!==i||o.port!==e)throw new Error(`gateway lock identity does not match the verified listener on port ${e}; use "openclaw gateway status --deep" and restart through its supervisor or original terminal`);const assertTargetCurrent=async()=>{const n=await readActiveGatewayLockIdentity({env:t.env});const r=findVerifiedGatewayListenerPidsOnPortSync(e,{env:t.env});if(r.length!==1||r[0]!==i)throw new Error(`Gateway listener changed before restart on port ${e}`);if(!n||n.pid!==i||n.port!==e||n.ownerId!==o.ownerId||!isSameGatewayLockIdentity(o,n))throw new Error(`gateway lock owner changed before the restart request could be delivered on port ${e}; run "openclaw gateway status --deep" before retrying`);if(t.ownerLease){const n=readGatewayOwnerLease({env:t.env});if(!n||n.state!==`live`||n.owner!==t.ownerLease.owner||n.pid!==i||n.startedAt!==t.ownerLease.startedAt||n.mode!==`foreground`||n.port!==e||o.ownerId!==n.owner)throw new Error(`Foreground Gateway owner changed before restart on port ${e}`)}};if(t.enforceRestartConfig){await assertTargetCurrent();await assertUnmanagedGatewayRestartEnabled(e);await assertTargetCurrent()}const s=o.ownerId?false:writeGatewayRestartIntentSync({targetPid:i,reason:`gateway.restart`,...t.restartIntent?{intent:t.restartIntent}:{}});if(!o.ownerId&&!s)throw new Error(`failed to persist the gateway restart intent`);try{await assertTargetCurrent();const r=o.ownerId;if(r||a){const t=await callGatewayCli({method:`gateway.restart.request`,params:r?{reason:`gateway.restart`,target:{pid:i,ownerId:r,port:e},...n?{restartIntent:n}:{}}:{reason:`gateway.restart`,skipDeferral:true},localPortOverride:e,ignoreEnvUrlOverride:true,timeoutMs:1e4});if(r)expectDefined(t.pid===i?t:void 0,`invalid restart acknowledgement`)}else signalVerifiedGatewayPidSync(i,`SIGUSR1`,{env:t.env,port:e})}catch(e){if(s)clearGatewayRestartIntentSync();throw e}appendGatewayLifecycleAudit({action:`restart`,source:t.auditSource,mode:o.ownerId||a?`rpc`:`sigusr1`,pid:i});return{result:`restarted`,pid:i,previousLockIdentity:o,message:`Gateway restart request sent to ${t.processLabel} process on port ${e}: ${i}.`}} //!src/cli/daemon-cli/start-repair.ts const GATEWAY_TARGET_ENV_KEYS=[`HOME`,`USERPROFILE`,`OPENCLAW_HOME`,`OPENCLAW_PROFILE`,`OPENCLAW_STATE_DIR`,`OPENCLAW_CONFIG_PATH`,`OPENCLAW_GATEWAY_PORT`];function resolveInstalledGatewayTargetEnvironment(e){const t={};for(const n of GATEWAY_TARGET_ENV_KEYS){const r=e?.[n]?.trim();if(r)t[n]=r}return t}function normalizeTargetPath(e){const t=path.resolve(e);return process.platform===`win32`?t.toLowerCase():t}function assertGatewayRepairTargetMatches(e){const t=resolveInstalledGatewayTargetEnvironment(e.existingEnvironment);const n=t.OPENCLAW_STATE_DIR?.trim();const r=t.OPENCLAW_HOME?.trim()||t.HOME?.trim()||t.USERPROFILE?.trim();if(!n&&!r)throw new Error(`Refusing to repair the managed Gateway service because its installed state directory cannot be determined from the service definition. Run \`openclaw gateway install --force\` to replace it intentionally.`);const i=resolveStateDir(t);const a=resolveConfigPathCandidate(t);const o=resolveStateDir(process.env);const s=resolveConfigPathCandidate(process.env);const c=resolveGatewayPort(e.config,process.env);const l=normalizeTargetPath(a)===normalizeTargetPath(s);const u=e.installedPort??(l?resolveGatewayPort(e.config,t):null);const d=[];for(const[e,t,n]of[[`OPENCLAW_STATE_DIR`,i,o],[`OPENCLAW_CONFIG_PATH`,a,s]])if(normalizeTargetPath(t)!==normalizeTargetPath(n))d.push({name:e,installed:t,ambient:n});if(u!==null&&u!==c)d.push({name:`gateway.port`,installed:String(u),ambient:String(c)});if(d.length===0)return u??c;const f=d.map(({name:e,installed:t,ambient:n})=>`- ${e}: installed=${JSON.stringify(t)}, ambient=${JSON.stringify(n)}`).join(` `);throw new Error(`Refusing to repair the managed Gateway service because the current invocation targets a different Gateway:\n${f}\nRun \`openclaw gateway ${e.action}\` with the installed state directory, config path, and port (or unset conflicting environment overrides). To retarget intentionally, run \`openclaw gateway install --force\`.`)}async function repairLoadedGatewayServiceForStart(e){assertGatewayServiceMutationAllowed(`repair the gateway service`);const t=await e.service.readDefinitionMutationCapability?.({env:process.env,environment:e.state.env}).catch(()=>({kind:`unknown`,reason:`inspection-failed`}));if(t)assertServiceDefinitionWritable(t);if(hasGatewayServiceLauncherOverride(e.state.command)||hasGatewayServiceEnvironmentDifference(e.state.command,GATEWAY_TARGET_ENV_KEYS)){if(process.platform===`win32`)throw new Error(`Refusing to repair the managed Gateway service because an operator-owned Scheduled Task override changes its command, working directory, or Gateway target environment. Inspect the task's registered action and working directory in Task Scheduler, then resolve the override before retrying.`);const t=path.basename(e.state.command?.sourcePath??`<unit>`);throw new Error(`Refusing to repair the managed Gateway service because a systemd drop-in overrides its command, working directory, or Gateway target environment. Inspect the unit with \`systemctl --user cat ${t}\`, then update or remove the operator-owned drop-in before retrying.`)}const n=resolveManagedGatewayServiceCommand(e.state.command);const{snapshot:r,writeOptions:i}=await readConfigFileSnapshotForWrite();const a=r.valid?r.sourceConfig:r.config;const o=n?.environment;const s=n?.environmentValueSources;const c=parseTcpPortFromArgs(n?.programArguments);const l=assertGatewayRepairTargetMatches({action:e.action??`start`,config:a,existingEnvironment:o,installedPort:c});const u=mergeInstallInvocationEnv({env:process.env,existingServiceEnv:o});const d=await resolveOpenClawWrapperPath(u[OPENCLAW_WRAPPER_ENV_KEY]);const f=await withDaemonRuntimePinMigration(u,()=>readDaemonRuntimePin({kind:`gateway`,env:u},e.state.command));const p=d?void 0:f.pin?.path;const m=!d&&f.pin?.runtime||resolveGatewayDaemonRuntime(p?[p]:n?.programArguments);if(!d)await resolvePinnedDaemonRuntimePath(p,m,u);const h=m===`bun`||m===`standalone`?p??n?.programArguments[0]:void 0;if(m===`standalone`&&!p)await resolvePinnedDaemonRuntimePath(h,`standalone`,u);const g=h&&m===`bun`?await resolveBunRuntimeInfo(h):void 0;if(g?.status===`probe-failed`)throw g.error;if(g?.status===`unsupported`&&g.sqliteSelectionError)throw new Error(g.sqliteSelectionError);const _=p||m===`standalone`?m:g?.status===`supported`?`bun`:`node`;const v=await resolveGatewayInstallToken({config:a,env:u,generateIfMissing:{snapshot:r,writeOptions:i}});if(v.unavailableReason)throw new Error(v.unavailableReason);const y=[formatGatewayServiceStartRepairIssues(e.issues),...v.warnings].filter(e=>e.trim().length>0);if(!e.json){defaultRuntime.log(`Gateway service definition needs repair:`);for(const e of y)defaultRuntime.log(`- ${e}`)}const{programArguments:b,workingDirectory:x,environment:S,environmentValueSources:C}=await buildGatewayInstallPlan({env:u,port:l,runtime:_,runtimePath:_===`bun`||_===`standalone`?h:void 0,pinnedRuntimePath:f.pin?.path,wrapperPath:d,existingCommand:e.state.command,existingEnvironment:o,existingEnvironmentValueSources:s,config:a,warn:t=>{y.push(t);if(!e.json)defaultRuntime.log(`- ${t}`)}});const w={programArguments:b,workingDirectory:x,environment:Object.fromEntries(Object.entries(S).filter(e=>typeof e[1]===`string`)),environmentValueSources:Object.fromEntries(Object.entries(C??{}).filter(e=>e[1]!==void 0))};let T=w;const E=e.state.command;if(E?.managedOverrides?.environment){const e={...w.environment};const t={...w.environmentValueSources};for(const n of/* @__PURE__ */ new Set([...Object.keys(w.environment),...Object.keys(E.environment??{})])){if(!hasGatewayServiceEnvironmentOverride(E,[n]))continue;const r=E.environment?.[n];if(r===void 0){delete e[n];delete t[n]}else{e[n]=r;t[n]=E.environmentValueSources?.[n]??`inline`}}T={...w,environment:e,environmentValueSources:t,managedDefinition:w,managedOverrides:E.managedOverrides}}const D=mergeGatewayServiceEnv(u,T);const O=await createConfigIO({env:D,observe:false,pluginValidation:`skip`,suppressFutureVersionWarning:true}).readBestEffortConfig().catch(()=>void 0);const k={command:T,env:D,config:O};await e.service.install({runtimePinUpdate:{expected:f,pin:f.pin},env:u,stdout:e.stdout,warn:e.warn,beforeMutation:e.beforeServiceMutation,programArguments:b,workingDirectory:x,environment:S,environmentValueSources:C});const A=await e.service.isLoaded({env:u});if(!A)throw new Error(`Gateway service is not loaded after repair.`);return{result:e.action===`restart`?`restarted`:`started`,message:e.action===`restart`?`Gateway service definition repaired and restarted.`:"Gateway service definition repaired and started. Reopen the Control UI with `openclaw dashboard` or copy a fresh auth URL with `openclaw dashboard --no-open`.",warnings:y.length?y:void 0,loaded:A,lifecycle:k}} //!src/cli/daemon-cli/lifecycle.ts async function stopGatewayWithoutServiceManager(e,t,n){const r=await handleSystemScopeSystemdGateway(`stop`);if(r)return r;const i=mergeGatewayServiceEnv(n?.env??process.env,n?.command??null);const a=await captureStalledGatewayStartup(i);if(a){await stopStalledGatewayStartup(a,assertGatewayServiceUpdateCurrent);appendGatewayLifecycleAudit({action:`stop`,source:`cli`,mode:`sigterm`,pid:a.pid,env:i});return{result:`stopped`,message:`Stopped stalled Gateway startup pid ${a.pid}.`}}const o=findVerifiedGatewayListenerPidsOnPortSync(e,{env:i});const s=o.length>0?o:t?[t]:[];if(s.length===0){const t=await resolveGatewayServiceProbeHosts(n??{});const r=await probePortUsage(e,t);if(r!==`free`)throw new Error(r===`busy`?`Port ${e} is in use but the owning process could not be identified.`:`Could not determine whether port ${e} is still in use, so the gateway cannot be confirmed stopped.`);return null}for(const t of s){signalVerifiedGatewayPidSync(t,`SIGTERM`,{env:i,port:e});appendGatewayLifecycleAudit({action:`stop`,source:`cli`,mode:`sigterm`,pid:t})}return{result:`stopped`,message:`Gateway stop signal sent to unmanaged process${s.length===1?``:`es`} on port ${e}: ${formatGatewayPidList(s)}.`}}function resolveRestartListenerHealthWait(e){const t=resolveGatewayRestartDrainTimeoutMs(e);const n=postRestartHealthAttempts()+Math.ceil((t??0)/500);return{attempts:n,waitIndefinitelyForPreviousOwner:t===void 0,timeoutSeconds:Math.round(n*500/1e3)}}async function restartUnmanaged(e,t,n=true){const r=n?await handleSystemScopeSystemdGateway(`restart`):null;if(r)return r;return await signalGatewayRestart(e,{restartIntent:t,enforceRestartConfig:true,processLabel:`unmanaged`,auditSource:`cli`})}function isGatewaySignalRestartResult(e){return e!==null&&`pid`in e&&typeof e.pid===`number`}async function runExternalSupervisorRestart(e){const{emitMessage:t,fail:n}=createDaemonActionContext({action:`restart`,json:Boolean(e.json)});const r=resolveGatewayRestartIntentOptions(e);const i=await readActiveGatewayLockIdentity().catch(()=>void 0);if(!i?.ownerId){n(`Gateway restart failed: the active Gateway lock predates targeted restart ownership; update the running Gateway before retrying`);return false}if(e.safe)return await runSafeGatewayRestart(e,{...i,ownerId:i.ownerId});let a;try{a=await signalGatewayRestart(i.port,{restartIntent:r,enforceRestartConfig:false,processLabel:`externally supervised`,auditSource:`supervisor`})}catch(e){n(`Gateway restart failed: ${String(e)}`);return false}if(!a){n(`No verified gateway process is listening on port ${i.port}. ${formatExternalSupervisorActionRequired(`start the gateway`)}`);return false}const o=resolveRestartListenerHealthWait(r);let s;try{s=await waitForGatewayHealthyListener({port:i.port,attempts:o.attempts,delayMs:500,previousLockIdentity:a.previousLockIdentity,waitIndefinitelyForPreviousOwner:o.waitIndefinitelyForPreviousOwner,signal:getAsyncWorkSignal()})}catch(e){if(!commandInterrupted(e))throw e;return false}if(!s.healthy){n(`Gateway restart timed out after ${o.timeoutSeconds}s waiting for health checks.`,renderGatewayPortHealthDiagnostics(s));return false}t({ok:true,result:a.result,message:a.message});return true}async function runDaemonUninstall(e={}){assertGatewayServiceActionAllowed(`uninstall`,`uninstall the gateway service`);return await runServiceUninstall({serviceNoun:`Gateway`,service:resolveGatewayService(),renderFailureHints:renderGatewayServiceUninstallHints,opts:e,stopBeforeUninstall:true,assertNotLoadedAfterUninstall:true})}async function runDaemonStart(e={}){assertGatewayServiceActionAllowed(`start`,`start the gateway`);const t=resolveGatewayService();const n=(await resolveGatewayConfigPorts()).explicit;let r=await resolveGatewayLifecycleContext(t);const beforeServiceMutation=()=>{assertGatewayServiceActionAllowed(`start`,`start the gateway`);return releaseOpenClawStateDatabaseCustody()};await beforeServiceMutation();return await runServiceStart({serviceNoun:`Gateway`,service:t,beforeServiceMutation,renderStartHints:renderGatewayServiceStartHints,onNotLoaded:process.platform===`darwin`?async()=>{const e=await recoverInstalledLaunchAgent({result:`started`});if(e)appendGatewayLifecycleAudit({action:`start`,source:`cli`,mode:`launchd-bootstrap`});return e}:void 0,repairLoadedService:async({json:e,stdout:n,warn:i,state:a,issues:o})=>{const s=await repairLoadedGatewayServiceForStart({service:t,json:e,stdout:n,warn:i,state:a,issues:o,beforeServiceMutation});if(s)r=createGatewayLifecycleContext(t,s.lifecycle);return s},postStartCheck:async({fail:e,warnings:t})=>{const{deadlineMs:i}=resolveGatewayStartupTiming();const a=n??r.port;const o=performance.now()+i;const s=Math.ceil(i/500);const c=createGatewayRestartDeadline({timeoutMs:i,signal:getAsyncWorkSignal()});const[l,u]=await Promise.all([withCommandProcessScope(()=>waitForGatewayHealthyRestart({service:r.probeService,port:a,attempts:s,delayMs:500,timeoutMs:i,deadline:c,deadlineOutcome:`snapshot`,env:r.env,config:r.config??{},supervisorKeepsAlive:process.platform===`darwin`,signal:getAsyncWorkSignal()}),c.signal).finally(()=>c.dispose()),waitForGatewayHttpReadiness({config:r.config,port:a,attempts:s,deadlineAt:o,delayMs:500,signal:getAsyncWorkSignal()})]);if(l.healthy&&u.healthz===200&&u.readyz===200){t.push(...l.operatorScopeWarning?[l.operatorScopeWarning]:[]);return}t.push(...renderRestartDiagnostics(l));t.push(`Gateway HTTP readiness: /healthz=${u.healthz??`unreachable`}; /readyz=${u.readyz??`unreachable`}.`);if(l.waitOutcome===`still-starting`){e(formatGatewayRestartFailure({health:l,port:a,defaultTimeoutSeconds:Math.round(i/1e3)}).failMessage,[formatCliCommand(`openclaw gateway status --deep`)],`still-starting`);return}e(l.healthy||l.waitOutcome===`timeout`?`Gateway start timed out after ${Math.round(i/1e3)}s waiting for /healthz and /readyz.`:formatGatewayRestartFailure({health:l,port:a,defaultTimeoutSeconds:Math.round(i/1e3),action:`start`}).failMessage,[formatCliCommand(`openclaw gateway status --deep`),formatCliCommand(`openclaw doctor`)])},expectedPort:n,opts:e})}async function runDaemonStop(e={}){if(!isTerminalInteractive()&&!e.force){const{fail:t}=createDaemonActionContext({action:`stop`,json:Boolean(e.json)});t(NON_INTERACTIVE_GATEWAY_STOP_MESSAGE);return}assertGatewayServiceUpdateCurrent();assertGatewayServiceActionAllowed(`stop`,`stop the gateway`);const t=resolveGatewayService();return await runServiceStop({serviceNoun:`Gateway`,service:t,renderFailureHints:renderGatewayServiceStopHints,opts:e,stopWhenNotLoaded:process.platform===`darwin`&&Boolean(e.disable),onNotLoaded:async({stdout:e})=>{if(process.platform===`linux`){if((await t.readRuntime(process.env).catch(ignoreNonCleanupCommandError))?.status===`running`){await t.stop({env:process.env,stdout:e,onMutation:createGatewayLifecycleMutationAudit({action:`stop`})});return{result:`stopped`}}}assertGatewayServiceFallbackAllowed(`unmanaged stop`);const n=await readActiveGatewayLockIdentity().catch(()=>void 0);const r=n?null:await resolveGatewayLifecycleContext(t).catch(ignoreNonCleanupCommandError);return await stopGatewayWithoutServiceManager(n?.port??r?.port??(await resolveGatewayConfigPorts()).fallback,n?.pid,r??void 0)}})}async function runDaemonRestart(e={}){let t=Boolean(e.preserveDefinition);if(t)assertGatewayServiceActionAllowed(`restart`,`restart the gateway`);assertNativeRestartFlags(e);if(isGatewayExternallySupervised()){assertGatewayServiceFallbackAllowed(`external-supervisor restart`);return await runExternalSupervisorRestart(e)}if(e.safe){assertGatewayServiceFallbackAllowed(`safe RPC restart`);return await runSafeGatewayRestart(e)}const n=Boolean(e.json);const r=resolveGatewayService();let i=false;let a;const o=resolveGatewayRestartIntentOptions(e);const s=await resolveGatewayConfigPorts();let c=s.config;const{explicit:l,fallback:u}=s;let d=await resolveGatewayLifecycleContext(r,t).catch(e=>{if(hasCommandProcessCleanupError(e)||t)throw e;return{...createGatewayLifecycleContext(r,{env:process.env,command:void 0,config:void 0}),port:u}});let f=t?d.port:l??d.port;let p=await readActiveGatewayLockPort().catch(()=>void 0)??f;const m=postRestartHealthAttempts();const h=m*500;const g=process.platform===`win32`&&isUpdateOwnedGatewayServiceCommand();let _=false;const v=Math.round(h/1e3);let y;const beforeServiceMutation=()=>{assertGatewayServiceActionAllowed(`restart`,`restart the gateway`);return releaseOpenClawStateDatabaseCustody()};return runServiceRestart({serviceNoun:`Gateway`,service:r,renderStartHints:renderGatewayServiceStartHints,opts:{...e,...o?{restartIntent:o}:{}},readDriftContext:()=>({config:c??{},command:d.command}),expectedPort:l,beforeServiceMutation,prepareServiceEffect:g?async()=>{_=true}:void 0,restartOwnedProcess:t?void 0:async()=>{const e=readGatewayOwnerLease();if(!e||e.state===`dead`||e.mode!==`foreground`)return null;assertGatewayServiceFallbackAllowed(`foreground owner restart`);if(e.state!==`live`)throw new Error(`Cannot verify foreground Gateway owner pid ${e.pid} on ${e.host}`);p=e.port;if(!(await waitForGatewayHealthyListener({port:e.port,env:process.env,attempts:m,delayMs:500,signal:getAsyncWorkSignal()})).healthy)throw new Error(`Foreground Gateway owner pid ${e.pid} is still starting or unhealthy on port ${e.port}; it was left running`);const t=await signalGatewayRestart(e.port,{restartIntent:o,enforceRestartConfig:true,processLabel:`foreground`,auditSource:`cli`,ownerLease:e,env:process.env});if(!t)throw new Error(`Foreground Gateway owner pid ${e.pid} no longer listens on port ${e.port}`);i=true;a=t.previousLockIdentity;y=resolveRestartListenerHealthWait(o);return t},repairLoadedService:t?void 0:async({json:e,stdout:t,warn:n,state:i,issues:a})=>{const o=await repairLoadedGatewayServiceForStart({action:`restart`,service:r,json:e,stdout:t,warn:n,state:i,issues:a,beforeServiceMutation});if(o){d=createGatewayLifecycleContext(r,o.lifecycle);c=o.lifecycle.config;f=l??d.port}return o},onNotLoaded:async()=>{assertGatewayServiceFallbackAllowed(`unmanaged restart`);if(t)return null;const e=resolveGatewayServiceMutationError(`restart the gateway`);if(process.platform===`darwin`&&!e){const e=await recoverInstalledLaunchAgent({result:`restarted`});if(e){appendGatewayLifecycleAudit({action:`restart`,source:`cli`,mode:`launchd-bootstrap`});return e}}const n=await restartUnmanaged(p,o,!e);if(n){i=true;if(isGatewaySignalRestartResult(n)&&n.previousLockIdentity){a=n.previousLockIdentity;y=resolveRestartListenerHealthWait(o)}return n}if(e)throw e;return null},postRestartCheck:async({warnings:e,fail:o,stdout:s,warn:c,activationAccepted:l,preserveDefinition:u})=>{if(u){t=true;f=d.port}let g=l;const reportHealthFailure=(t,r)=>{if(n){e.push(...t,...r);return}for(const e of t)defaultRuntime.log(theme.warn(e));for(const e of r)defaultRuntime.log(theme.muted(e))};if(i){const e=await waitForGatewayHealthyListener({port:p,env:process.env,attempts:y?.attempts??m,delayMs:500,signal:getAsyncWorkSignal(),...a?{previousLockIdentity:a,waitIndefinitelyForPreviousOwner:y?.waitIndefinitelyForPreviousOwner??false}:{}});if(e.healthy)return;const t=renderGatewayPortHealthDiagnostics(e);const n=y?.timeoutSeconds??v;reportHealthFailure([`Timed out after ${n}s waiting for gateway port ${p} to become healthy.`],t);o(`Gateway restart timed out after ${n}s waiting for health checks.`,[formatCliCommand(`openclaw gateway status --deep`),formatCliCommand(`openclaw doctor`)],g?`restart-health-failed`:void 0);throw new Error(`unreachable after gateway restart health failure`)}const waitForHealthy=async()=>await waitForGatewayHealthyRestart({service:d.probeService,port:f,attempts:m,delayMs:500,...process.platform===`win32`?{timeoutMs:h}:{},env:d.env,config:d.config??{},probeHosts:await resolveGatewayServiceProbeHosts(d),requireOwnedListener:d.env.OPENCLAW_UPDATE_IN_PROGRESS!==`1`,supervisorKeepsAlive:process.platform===`darwin`,signal:getAsyncWorkSignal()});let b=await waitForHealthy();if(!_&&!b.healthy&&b.staleGatewayPids.length>0){const i=`Found stale gateway process(es): ${b.staleGatewayPids.join(`, `)}.`;e.push(i);if(!n){defaultRuntime.log(theme.warn(i));defaultRuntime.log(theme.muted(`Stopping stale process(es) and retrying restart...`))}const a=await terminateStaleGatewayPids(b.staleGatewayPids,{env:d.env,assertCurrent:assertGatewayServiceUpdateCurrent});const o=readGatewayOwnerLease({env:d.env});if(a.length>0&&(!o||o.state===`dead`)){const e=await r.restart({preserveDefinition:t,env:process.env,stdout:s,warn:c,beforeMutation:beforeServiceMutation,onMutation:createGatewayLifecycleMutationAudit({action:`restart`})});if(e.outcome===`scheduled`)return e;g=true}b=await waitForHealthy()}if(b.healthy){e.push(...b.operatorScopeWarning?[b.operatorScopeWarning]:[]);return{outcome:`completed`,readiness:b}}const x=renderRestartDiagnostics(b);const S=formatGatewayRestartFailure({health:b,port:f,defaultTimeoutSeconds:v});const C=b.waitOutcome!==`still-starting`&&b.runtime.status===`running`&&b.portUsage.status===`free`?`Gateway process is running but port ${f} is still free (startup hang/crash loop or very slow VM startup).`:null;reportHealthFailure([S.statusLine,...C?[C]:[]],x);o(S.failMessage,[formatCliCommand(`openclaw gateway status --deep`),formatCliCommand(`openclaw doctor`)],b.waitOutcome===`still-starting`?d.env.OPENCLAW_UPDATE_IN_PROGRESS===`1`?`restart-health-failed`:`still-starting`:g?`restart-health-failed`:void 0);throw new Error(`unreachable after gateway restart failure`)}})}export{runDaemonRestart,runDaemonStart,runDaemonStop,runDaemonUninstall};