openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
11 lines • 15.6 kB
JavaScript
import{f as resolveGatewayLaunchAgentLabel,g as resolveGatewaySystemdServiceName,y as resolveNodeLaunchAgentLabel}from"./constants-tH5Q8GoI.mjs";import{t as ExitError}from"./runtime-DIcLIHcp.mjs";import{n as resolveOpenClawPackageRoot}from"./openclaw-root-DP80HYD2.mjs";import"./utils-Dlk0IYAa.mjs";import{t as sleep}from"./sleep-B4CgCyZu.mjs";import{b as resolveGatewayPort,o as isDefaultInstallIdentity}from"./paths-D_FOvGon.mjs";import{t as formatCliCommand}from"./command-format-D7KhNLP0.mjs";import{s as getResolvedLoggerSettings}from"./logger-bB_ZfEX5.mjs";import{n as NON_DEFAULT_INSTALL_SERVICE_SKIP_REASON}from"./gateway-supervision-TUZKxlq7.mjs";import{t as quoteCliArg}from"./quote-cli-arg-BUHoGELl.mjs";import{g as resolveGatewayBindHost,v as resolveGatewayRequiredListenHosts}from"./net-Bu4cO5Pq.mjs";import"./config-DkZ8y8Gv.mjs";import{r as isWSLEnv,t as isWSL}from"./wsl-_7IqvQi4.mjs";import"./logging-BEaj8khU.mjs";import{c as summarizeGatewayServiceLayout}from"./service-layout-Daz63_6Y.mjs";import{a as isSystemdCgroupHygieneRisk,o as isSystemdStartLimitHit,r as getSystemdCgroupHygieneSummary}from"./service-runtime-B08Eigi1.mjs";import{l as classifySystemdUnavailableDetail}from"./systemd-user-transport-JBcQeydq.mjs";import{i as readGatewayRestartHandoffSync,n as formatGatewayRestartHandoffDiagnostic}from"./restart-handoff-DPRsBMaK.mjs";import{a as buildGatewayRuntimeRecoveryHints,i as renderSystemdUnavailableHints,r as isSystemdUnavailableDetail,t as formatRuntimeStatus}from"./runtime-format-hFkv-6vU.mjs";import{n as readInstallOwner,t as formatInstallOwnerMessage}from"./install-owner-BPkbFuTm.mjs";import{n as resolveGatewayService,t as describeGatewayServiceRestart}from"./service-Bz63n2ee.mjs";import{i as isLaunchAgentLoaded,s as launchAgentPlistExists}from"./launchd-runtime-CGjMI2Ve.mjs";import{r as repairLaunchAgentBootstrap}from"./launchd-BpufAYg5.mjs";import{a as isExpectedGatewayListeners,r as formatPortDiagnostics}from"./ports-format-BJNgZ8TS.mjs";import{n as inspectPortUsage,t as inspectPortConnections}from"./ports-inspect-PmKDONYY.mjs";import{t as readGatewayServiceState}from"./service-state-C07U7uy3.mjs";import{n as findSystemGatewayServices}from"./inspect-CNcL7fmS.mjs";import{t as note}from"./note-e4DtVgg2.mjs";import{n as GATEWAY_DAEMON_RUNTIME_OPTIONS}from"./daemon-runtime-CM-TWmEx.mjs";import{n as gatewayInstallErrorHint}from"./daemon-install-helpers-CF_xtI3X.mjs";import{t as resolveGatewayInstallToken}from"./gateway-install-token-Pt-GC-0y.mjs";import{n as readLastGatewayErrorLine}from"./diagnostics-xJss8OB4.mjs";import{a as isServiceRepairDeferred,i as formatServiceRepairDeferredNote,l as shouldManageGatewayService,r as confirmDoctorServiceRepair,s as resolveServiceRepairPolicy,t as SERVICE_REPAIR_POLICY_ENV}from"./doctor-service-repair-policy-gYXaFNLg.mjs";import{n as prepareGatewayServiceInstall,t as resolveGatewaySetupRuntime}from"./gateway-setup-runtime-BwSUwVHJ.mjs";import{i as formatGatewayClosedDiagnostic,o as formatHealthCheckFailure,s as formatHealthDiagnosticNote}from"./health-format-DElePmik.mjs";import{i as healthCommandNonExiting}from"./health-CtGRycgB.mjs";
//!src/commands/doctor-format.ts
async function buildGatewayRuntimeHints(e,t={}){const n=[];if(!e)return n;const r=t.platform??process.platform;const i=t.env??process.env;const a=await(async()=>{try{return(await getResolvedLoggerSettings()).file}catch{return null}})();const o=a?[`File logs: ${a}`]:[];const s=e.inspectionFailure?.detail??e.detail;if(r===`linux`&&isSystemdUnavailableDetail(s))return[...renderSystemdUnavailableHints({wsl:isWSLEnv(i),kind:classifySystemdUnavailableDetail(s),env:i}),...o];if(e.cachedLabel&&r===`darwin`){const e=resolveGatewayLaunchAgentLabel(i.OPENCLAW_PROFILE);n.push(`LaunchAgent label cached but plist missing. Clear with: launchctl bootout gui/$UID/${e}`);n.push(`Then reinstall: ${formatCliCommand(`openclaw gateway install`,i)}`)}if(e.missingUnit){n.push(`Service not installed. Run: ${formatCliCommand(`openclaw gateway install`,i)}`);n.push(...o);return n}const c=e.missingGuiSession&&r===`darwin`;const l=r===`win32`&&e.state===`Disabled`;if(c||l||e.status===`stopped`){if(!c&&r===`linux`&&isSystemdStartLimitHit(e))n.push(`systemd stopped restarting the gateway after repeated crashes.`,`Recover with: ${formatCliCommand(`openclaw gateway restart`,i)}, then inspect logs if it keeps crashing.`);else if(!c&&!l)n.push(`Service is loaded but not running (likely exited immediately).`);n.push(...buildGatewayRuntimeRecoveryHints({kind:c?`gui-session`:l?`disabled-task`:`stopped`,restartCommand:formatCliCommand(`openclaw gateway restart`,i),logFile:a,platform:r,env:i,systemd:e.systemd}));if(c)return n}if(r===`linux`&&isSystemdCgroupHygieneRisk(e.systemd)){const t=quoteCliArg(e.systemd?.unit??`${resolveGatewaySystemdServiceName(i.OPENCLAW_PROFILE)}.service`);const r=e.systemd?.scope===`system`;const a=getSystemdCgroupHygieneSummary(e.systemd);if(a)n.push(`Systemd cgroup hygiene looks elevated: ${a}.`,`This usually means old helper or browser processes may still be attached to the gateway service.`,`Run: systemctl ${r?`--system`:`--user`} show ${t} -p KillMode -p TasksCurrent -p MemoryCurrent -p MainPID`,`Run: systemd-cgls ${r?`--unit`:`--user-unit`} ${t}`,`After reviewing service settings, run: ${formatCliCommand(`openclaw gateway restart`,i)}`)}return n}
//!src/commands/doctor-gateway-daemon-flow.ts
async function noteGatewayRuntime(e,t){const n=formatRuntimeStatus(e);const r=await buildGatewayRuntimeHints(e,{platform:process.platform,env:t});const i=n?[`Runtime: ${n}`,...r]:r;if(i.length>0)note(i.join(`
`),`Gateway`)}async function maybeRepairLaunchAgentBootstrap(e){if(process.platform!==`darwin`||!await launchAgentPlistExists(e.env)||await isLaunchAgentLoaded({env:e.env}))return{status:`skipped`};note(`LaunchAgent is installed but not loaded in launchd.`,`${e.title} LaunchAgent`);if(e.serviceRepairDeferred){note(formatServiceRepairDeferredNote(),`${e.title} LaunchAgent`);return{status:`not-loaded`}}if(!await confirmDoctorServiceRepair(e.prompter,{message:`Repair ${e.title} LaunchAgent bootstrap now?`,initialValue:true}))return{status:`not-loaded`};e.runtime.log(`Bootstrapping ${e.title} LaunchAgent...`);const t=await repairLaunchAgentBootstrap({env:e.env});if(!t.ok){if(t.status===`system-launchdaemon-conflict`||t.status===`system-launchdaemon-unverifiable`)return{status:`system-launchdaemon-blocked`,detail:t.detail};if(t.status===`gui-session-unavailable`)return{status:`gui-session-unavailable`,detail:t.detail};e.runtime.error(`${e.title} LaunchAgent bootstrap failed: ${t.detail??`unknown error`}`);return{status:`not-loaded`}}if(!await isLaunchAgentLoaded({env:e.env})){e.runtime.error(`${e.title} LaunchAgent still not loaded after repair.`);return{status:`not-loaded`}}note(`${e.title} LaunchAgent repaired.`,`${e.title} LaunchAgent`);return{status:`repaired`}}function renderBlockingSystemGatewayServices(e){return[`System-level OpenClaw gateway service detected while the user gateway service is not installed.`,...e.map(e=>`- ${e.label} (${e.detail})`),`OpenClaw will not install a second user-level gateway service automatically.`,"Run `openclaw gateway status --deep` or `openclaw doctor --deep` to inspect duplicate services.",`Set ${SERVICE_REPAIR_POLICY_ENV}=external if a system supervisor owns the gateway lifecycle.`].join(`
`)}function renderEstablishedGatewayConnections(e){return[`Established Gateway TCP clients detected:`,...e.slice(0,8).map(e=>{return`- ${e.pid?`pid=${e.pid}`:`pid=?`} ${e.direction}${e.command?` ${e.command}`:``}${e.address?` ${e.address}`:``}${e.commandLine?` cmd=${e.commandLine}`:``}`}),...e.length>8?[`- ... ${e.length-8} more connection(s)`]:[],`If logs show protocol mismatch after rollback, stop stale OpenClaw client processes listed here and rerun doctor.`].join(`
`)}async function maybeReportEstablishedGatewayClients(e,t,n){if(!t)return;const r=n??resolveGatewayPort(e,process.env);const i=(await inspectPortConnections(r).catch(()=>null))?.connections.filter(({direction:e})=>e!==`server`);if(i?.length)note(renderEstablishedGatewayConnections(i),`Gateway clients`)}async function noteGatewayPortDiagnostics(e,t){const n=resolveGatewayPort(e,process.env);const r=await resolveGatewayBindHost(e.gateway?.bind??`loopback`,e.gateway?.customBindHost);const i=await inspectPortUsage(n,{probeHosts:resolveGatewayRequiredListenHosts(r)});await maybeReportEstablishedGatewayClients(e,t,n);const a=i.status===`busy`&&!isExpectedGatewayListeners(i.listeners,i.port);if(a)note(formatPortDiagnostics(i).join(`
`),`Gateway port`);return a}async function noteGatewayServiceInspectionFailure(e){const t=[`Gateway service status could not be determined: ${e.detail}`];const n=process.platform===`linux`&&classifySystemdUnavailableDetail(e.detail);if(n)t.push(...renderSystemdUnavailableHints({wsl:await isWSL(),kind:n}));t.push(`Run ${formatCliCommand(`openclaw gateway status --deep`)} and retry doctor.`);note(t.join(`
`),`Gateway`)}async function maybeRepairGatewayDaemon(e){if(!isDefaultInstallIdentity(process.env)){note(NON_DEFAULT_INSTALL_SERVICE_SKIP_REASON,`Gateway`);return}if(e.cfg.gateway?.mode===`remote`)return;if(e.healthOk){if(process.platform===`linux`&&await shouldManageGatewayService()){const e=(await readGatewayServiceState(resolveGatewayService(),{env:process.env})).runtime?.systemd?.startRefusal;if(e)note(e.message,`Gateway`)}await maybeReportEstablishedGatewayClients(e.cfg,e.options.deep??false);return}const t=await resolveOpenClawPackageRoot({moduleUrl:import.meta.url,argv1:process.argv[1]});const n=await readInstallOwner(t);if(n){await noteGatewayPortDiagnostics(e.cfg,e.options.deep??false);note(formatInstallOwnerMessage(n),`Gateway`);return}if(!await shouldManageGatewayService()){await noteGatewayPortDiagnostics(e.cfg,e.options.deep??false);note(formatServiceRepairDeferredNote(),`Gateway`);return}const r=resolveServiceRepairPolicy();const i=isServiceRepairDeferred(r);const a=resolveGatewayService();const restartGatewayService=async()=>{try{return await a.restart({env:process.env,stdout:process.stdout})}catch(e){const t=e instanceof Error?e.message:String(e);note(`Gateway service restart failed: ${t}`,`Gateway`);return null}};const o=process.platform===`darwin`;const s=await readGatewayServiceState(a,{env:process.env});const c=await summarizeGatewayServiceLayout(s.command);const l=await readInstallOwner(c?.packageRootReal??c?.packageRoot??null);if(l){await noteGatewayPortDiagnostics(e.cfg,e.options.deep??false);note(formatInstallOwnerMessage(l),`Gateway`);return}const u=s.runtime?.systemd?.startRefusal;if(u){note(u.message,`Gateway`);return}if(s.loadState.status===`unknown`){if(a.unsupportedReason)note(a.unsupportedReason,`Gateway`);else await noteGatewayServiceInspectionFailure(s.loadState);return}let d=s.loadState.status===`loaded`;let f=s.runtime;const p=s.env;if(e.options.deep){const e=readGatewayRestartHandoffSync(p);if(e)note(formatGatewayRestartHandoffDiagnostic(e),`Gateway`)}if(o){const t=f?.missingGuiSession?{status:`gui-session-unavailable`,detail:f.detail??``}:await maybeRepairLaunchAgentBootstrap({env:process.env,title:`Gateway`,runtime:e.runtime,prompter:e.prompter,serviceRepairDeferred:i});await maybeRepairLaunchAgentBootstrap({env:{...process.env,OPENCLAW_LAUNCHD_LABEL:resolveNodeLaunchAgentLabel(process.env.OPENCLAW_PROFILE)},title:`Node`,runtime:e.runtime,prompter:e.prompter,serviceRepairDeferred:i});if(t.status===`not-loaded`)return;if(t.status===`system-launchdaemon-blocked`){note(t.detail,`Gateway`);return}if(t.status===`gui-session-unavailable`)f={status:`unknown`,detail:t.detail||f?.detail,missingGuiSession:true};if(t.status===`repaired`){const e=await readGatewayServiceState(a,{env:process.env});if(e.loadState.status===`unknown`){await noteGatewayServiceInspectionFailure(e.loadState);return}d=e.loadState.status===`loaded`;f=e.runtime}}if(o&&f?.systemLaunchDaemon){await noteGatewayRuntime(f,process.env);return}if(!await noteGatewayPortDiagnostics(e.cfg,e.options.deep??false)&&d&&f?.status===`running`){const e=await readLastGatewayErrorLine(process.env);if(e)note(`Recent Gateway log error (may be from an earlier run): ${e}`,`Gateway`)}if(!d){if(o&&(f?.missingGuiSession||f?.cachedLabel||f?.systemLaunchDaemon)){await noteGatewayRuntime(f,process.env);return}note(`Gateway service not installed.`,`Gateway`);if(process.platform===`linux`){const e=await findSystemGatewayServices();if(e.length>0){note(renderBlockingSystemGatewayServices(e),`Gateway`);return}}if(i){note(formatServiceRepairDeferredNote(),`Gateway`);return}if(!await confirmDoctorServiceRepair(e.prompter,{message:`Install gateway service now?`,initialValue:true,requiresInteractiveConfirmation:true},r)){note(`Run ${formatCliCommand(`openclaw gateway install`)} when you want to install the gateway service.`,`Gateway`);return}const t=await resolveGatewaySetupRuntime({env:process.env,existingCommand:s.command,selectRuntime:t=>e.prompter.select({message:`Gateway service runtime`,options:GATEWAY_DAEMON_RUNTIME_OPTIONS,initialValue:t},t)});const n=await resolveGatewayInstallToken({config:e.cfg,env:process.env});for(const e of n.warnings)note(e,`Gateway`);if(n.unavailableReason){note([`Gateway service install aborted.`,n.unavailableReason,`Fix gateway auth config/token input and rerun doctor.`].join(`
`),`Gateway`);return}const c=resolveGatewayPort(e.cfg,process.env);const l=await prepareGatewayServiceInstall({service:a,selection:t,port:c,existingCommand:s.command,warn:(e,t)=>note(e,t),config:e.cfg});try{await l.install()}catch(e){note(`Gateway service install failed: ${String(e)}`,`Gateway`);note(gatewayInstallErrorHint(),`Gateway`)}return}await noteGatewayRuntime(f,p);if(f?.status!==`running`){if(e.healthSkipped&&f?.status!==`stopped`)return;if(i){note(formatServiceRepairDeferredNote(),`Gateway`);return}if(await confirmDoctorServiceRepair(e.prompter,{message:`Start gateway service now?`,initialValue:true},r)){if(process.platform===`win32`&&f?.state===`Disabled`){try{await a.start({env:p,stdout:process.stdout})}catch(e){const t=e instanceof Error?e.message:String(e);note(`Gateway service start failed: ${t}`,`Gateway`)}return}const e=await restartGatewayService();if(!e)return;const t=describeGatewayServiceRestart(`Gateway`,e);if(!t.scheduled)await sleep(1500);else note(t.message,`Gateway`)}}if(process.platform===`darwin`){const e=resolveGatewayLaunchAgentLabel(process.env.OPENCLAW_PROFILE);note(`LaunchAgent loaded; stopping requires "${formatCliCommand(`openclaw gateway stop`)}" or launchctl bootout gui/$UID/${e}.`,`Gateway`)}if(f?.status!==`running`||e.healthSkipped)return;if(i){note(formatServiceRepairDeferredNote(),`Gateway`);return}if(readGatewayRestartHandoffSync(p))try{await healthCommandNonExiting({json:false,config:e.cfg},e.runtime);note(`Preserving the recent Gateway restart; skipping restart prompt.`,`Gateway`);return}catch{}if(e.options.nonInteractive===true)return;if(await confirmDoctorServiceRepair(e.prompter,{message:`Restart gateway service now?`,initialValue:false},r)){const t=await restartGatewayService();if(!t)return;const n=describeGatewayServiceRestart(`Gateway`,t);if(n.scheduled){note(n.message,`Gateway`);return}try{await healthCommandNonExiting({json:false,config:e.cfg},e.runtime)}catch(t){if(t instanceof ExitError)return;const n=formatGatewayClosedDiagnostic(t);if(n){note(n,`Gateway`);note(formatHealthDiagnosticNote(e.gatewayDetailsMessage),`Gateway connection`)}else e.runtime.error(formatHealthCheckFailure(t))}}}export{maybeRepairGatewayDaemon};