openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
30 lines • 38 kB
JavaScript
import{l as normalizeOptionalString}from"./string-coerce-CpTFcSwY.mjs";import{n as isNodeRuntime}from"./runtime-binary-DNstBs1K.mjs";import{r as SUPPORTED_NODE_VERSIONS}from"./node-version-EaZf6kHy.mjs";import{h as resolveDefaultSecretProviderAlias}from"./ref-contract-CdpCUlb6.mjs";import{_ as resolveSecretInputRef}from"./types.secrets-UWdyCdE6.mjs";import{n as resolveOpenClawPackageRoot}from"./openclaw-root-DP80HYD2.mjs";import{t as sleep}from"./sleep-B4CgCyZu.mjs";import{n as ignoreMissingPath}from"./errno-DUBt6SQQ.mjs";import{r as parseTcpPortFromArgs}from"./tcp-port-CL3rN59M.mjs";import{C as resolveIsNixMode,b as resolveGatewayPort,o as isDefaultInstallIdentity}from"./paths-D_FOvGon.mjs";import{t as formatCliCommand}from"./command-format-D7KhNLP0.mjs";import{a as hasCommandProcessCleanupError}from"./exec-result-TD4w1Z1i.mjs";import{n as NON_DEFAULT_INSTALL_SERVICE_SKIP_REASON,r as assertGatewayServiceMutationAllowed}from"./gateway-supervision-TUZKxlq7.mjs";import{g as sanitizeServiceInspectionError}from"./service-inspection-error-D006EyWC.mjs";import{t as ConfigWritePostCommitError}from"./io.write-errors-CQyW8lY6.mjs";import{a as hasGatewayServiceEnvironmentOverride,o as hasGatewayServiceLauncherOverride,s as resolveManagedGatewayServiceCommand,t as assertServiceDefinitionWritable}from"./service-types-B7cjFijA.mjs";import{c as summarizeGatewayServiceLayout,o as resolveServiceEntrypoint,r as inspectGatewayServiceInstallationDrift,t as gatewayServiceCommandMatchesRoot}from"./service-layout-Daz63_6Y.mjs";import{n as GatewayServiceAuthorityError}from"./service-update-authority-DqjrBTQ9.mjs";import{p as isSystemdUnitActive}from"./systemd-busctl-query-CVbse9JI.mjs";import{t as mergeGatewayServiceEnv}from"./service-env-merge-Db3tXSCb.mjs";import{s as formatGatewayServiceInstallationDrift}from"./shared-BctPQR6n.mjs";import{n as readInstallOwner,t as formatInstallOwnerMessage}from"./install-owner-BPkbFuTm.mjs";import{f as resolveSystemNodeInfo,i as renderSystemNodeWarning,o as resolveNodeRuntimeInfo}from"./runtime-paths-BOio2Rt6.mjs";import{n as resolveGatewayService}from"./service-Bz63n2ee.mjs";import{i as removeBootedOutLaunchAgentPlist,x as isLaunchctlNotLoaded,y as execLaunchctl}from"./launchd-service-files-cH3YFqVS.mjs";import{t as withGatewayServiceOperationLock}from"./service-operation-lock-U1nLjHDf.mjs";import{a as readDaemonRuntimePin,c as withDaemonRuntimePinMigration}from"./runtime-pin-state-DeLfcMhS.mjs";import{n as inspectGatewayHeapLimit,t as formatGatewayHeapLimitReport}from"./gateway-heap-CibgWr-t.mjs";import{t as OPENCLAW_WRAPPER_ENV_KEY}from"./program-args-Dls9y3ku.mjs";import{t as readGatewayServiceState}from"./service-state-C07U7uy3.mjs";import{a as findSystemdGatewayInstallation,s as isSystemUnitActiveAndEnabled}from"./systemd-scope-DvdmsQC9.mjs";import{o as uninstallUserSystemdGatewayUnit}from"./systemd-lifecycle-CKiXKu66.mjs";import{c as normalizeServiceEnvKey,d as readManagedServiceEnvKeysFromEnvironment}from"./service-managed-env-C6mkMZgV.mjs";import"./systemd-BLmKdJhz.mjs";import{i as renderGatewayServiceCleanupHints,t as findExtraGatewayServices}from"./inspect-CNcL7fmS.mjs";import{t as note}from"./note-e4DtVgg2.mjs";import{t as DurableServiceCliError}from"./durable-service-entrypoint-CYy_WbI9.mjs";import{i as resolveGatewayDaemonRuntime}from"./daemon-runtime-CM-TWmEx.mjs";import{t as SERVICE_PROXY_ENV_KEYS}from"./service-env-DR7NRpBz.mjs";import{a as describeGatewayNodeVersionRepair,s as isNodeVersionChangeIssue}from"./node-version-prefix-Ctv7kcZw.mjs";import{a as needsNodeRuntimeMigration,n as auditGatewayServiceConfig,o as readEmbeddedGatewayToken,t as SERVICE_AUDIT_CODES}from"./service-audit-DNlslbPV.mjs";import{t as resolveGatewayAuthToken}from"./auth-token-resolution-BHyWE1aF.mjs";import{t as buildGatewayInstallPlan}from"./daemon-install-helpers-CF_xtI3X.mjs";import{a as isServiceRepairDeferred,i as formatServiceRepairDeferredNote,l as shouldManageGatewayService,r as confirmDoctorServiceRepair,s as resolveServiceRepairPolicy}from"./doctor-service-repair-policy-gYXaFNLg.mjs";import{n as cleanupLegacyLinuxUserServices,t as classifyLegacyServices}from"./doctor-gateway-legacy-services-PsgOv8t5.mjs";import path from"node:path";import fs from"node:fs/promises";import os from"node:os";import{isDeepStrictEqual}from"node:util";
//!src/commands/doctor-gateway-auth-token.ts
async function preserveGatewayAuthTokenForService(e){const{listSecretStoreEntries:t,readSecretStoreValue:n,writeSecretStoreEntryForConfigRef:r}=await import(`./secret-store-BW6BT_kd.mjs`);const i={env:e.env};const a={kind:`team`};const o=resolveDefaultSecretProviderAlias(e.cfg,`store`,{preferFirstProviderForSource:true});for(const r of await t({scope:a,database:i,assertCurrent:e.assertCurrent})){const t=await n({scope:a,database:i,name:r.name,assertCurrent:e.assertCurrent});e.assertCurrent?.();if(!t.ok){if(t.error.code===`SECRET_STORE_NOT_FOUND`)continue;throw new Error(t.error.message)}if(t.value===e.token)return{ref:{source:`store`,provider:o,id:r.name},reused:true}}const{stat:s}=await import(`node:fs/promises`);const{randomUUID:c}=await import(`node:crypto`);const{resolveOpenClawStateSqlitePath:l}=await import(`./openclaw-state-db.paths-3UU_PbvT.mjs`);const u=l(e.env);const d=await s(u).catch(ignoreMissingPath);let f;if(d){const{createVerifiedSqliteSnapshot:t}=await import(`./sqlite-snapshot-C6LLrZkv.mjs`);e.assertCurrent?.();({path:f}=await t({sourcePath:u,targetPath:`${u}.doctor-gateway-token.${c()}.bak`,preserveRowIds:true}))}return{ref:{source:`store`,provider:o,id:await r({baseName:`OPENCLAW_GATEWAY_TOKEN`,value:e.token,updatedBy:`doctor`,database:i,assertCurrent:e.assertCurrent})},reused:false,backupPath:f}}async function resolveGatewayAuthTokenForService(e,t,n={}){if(resolveSecretInputRef({value:e.gateway?.auth?.token,defaults:e.secrets?.defaults}).ref?.source===`exec`&&n.allowExecSecretRefs!==true)return{unavailableReason:`gateway.auth.token SecretRef is configured but unavailable because exec SecretRef resolution is disabled.`};const r=await resolveGatewayAuthToken({cfg:e,env:t,unresolvedReasonStyle:`detailed`});if(r.token)return{token:r.token};if(!r.secretRefConfigured)return{};if(r.unresolvedRefReason?.includes(`resolved to an empty value`))return{unavailableReason:r.unresolvedRefReason};return{unavailableReason:`gateway.auth.token SecretRef is configured but unresolved (${r.unresolvedRefReason??`unknown reason`}).`}}
//!src/commands/doctor-service-audit.ts
function formatServiceConfigIssues(e){return e.map(({message:e,detail:t})=>`- ${e}${t?` (${t})`:``}`)}function reportGatewayServiceConfigAudit(e,t,n){const r=t?.entrypointSourceCheckout?[`Gateway service entrypoint resolves to a source checkout: ${t.packageRootReal??t.packageRoot??t.entrypointReal??t.entrypoint}.`,`Run \`${formatCliCommand(`openclaw gateway install --force`)}\` from the intended package install to replace the gateway service definition.`].join(`
`):null;const i=e.issues.some(e=>e.code===SERVICE_AUDIT_CODES.gatewayEntrypointMismatch)?null:r;if(e.issues.length===0&&!n){if(i!==null)note(i,`Gateway service config`);return i}note([...i!==null?[i,``]:[],...formatServiceConfigIssues(e.issues)].join(`
`),`Gateway service config`);return i}function formatGatewayServiceRepairPreview(e){const t=[];if(e.missingSystemNode){const n=e.runtimeIssues.some(e=>e.code===SERVICE_AUDIT_CODES.gatewayRuntimeNode||e.code===SERVICE_AUDIT_CODES.gatewayRuntimeBun);t.push({checkId:`core/doctor/gateway-service`,severity:n?`error`:`warning`,category:n?`fix-now`:`recommended`,message:`No supported system Node is available; this repair retains ${e.plan.programArguments[0]}.`,fixHint:`Install system Node ${SUPPORTED_NODE_VERSIONS} and rerun Doctor to resolve the runtime finding.`,docsUrl:`https://docs.openclaw.ai/cli/doctor/checks#gateway-and-service-repairs`})}const n=e.runtimeIssues.find(isNodeVersionChangeIssue);if(n){const r=describeGatewayNodeVersionRepair({code:n.code,entrypointPath:e.plannedLayout?.entrypointReal??resolveServiceEntrypoint(e.command),plannedNodePath:e.plan.programArguments[0],recordedNodePath:e.managedDefinition.programArguments[0],pinnedRuntimePath:e.pinnedRuntimePath});if(!r.resolvesSplit)t.push({checkId:`core/doctor/gateway-service`,severity:`warning`,category:`recommended`,message:r.remains,fixHint:r.action,docsUrl:`https://docs.openclaw.ai/cli/doctor/checks#gateway-and-service-repairs`})}if(e.plannedLayout?.entrypointSourceCheckout)t.push({checkId:`core/doctor/gateway-service`,severity:`warning`,category:`recommended`,message:`This repair retains a source-checkout entrypoint.`,fixHint:`Run \`${formatCliCommand(`openclaw gateway install --force`)}\` from the intended package install to replace it.`,docsUrl:`https://docs.openclaw.ai/cli/doctor/checks#gateway-and-service-repairs`});return{preview:[`Runtime: ${e.managedDefinition.programArguments[0]} -> ${e.plan.programArguments[0]}`,`Entrypoint: ${e.currentLayout?.entrypoint??`not identified`} -> ${e.plannedLayout?.entrypoint??`not identified`}`,`PATH: ${e.command.environment?.PATH??`not set`} -> ${e.plan.environment?.PATH??`not set`}`,...(e.definitionDrift??[]).flatMap(e=>e.kind===`outdated`&&(e.key===`ExitTimeOut`||e.key===`TimeoutStopSec`)?[`Shutdown budget (${e.key}): ${String(e.current)} -> ${String(e.expected)}`]:[]),...t.map(e=>`Will remain: ${e.message} ${e.fixHint}`)].join(`
`),unresolvedFindings:t}}function reportServiceDefinitionDrift(e){const t=[...(e.definitionDrift??[]).map(e=>e.message),...e.definitionDriftError?[e.definitionDriftError]:[]];if(t.length>0)note(t.map(e=>`- ${e}`).join(`
`),`Gateway service definition`)}function isServiceInstallationOnlyRepair(e){return!e.definitionDriftError&&!e.definitionDrift?.length&&e.issues.every(e=>e.code===SERVICE_AUDIT_CODES.gatewayEntrypointMismatch)}function hasRepairableServiceDefinitionDrift(e){return!e.definitionDriftError&&e.definitionDrift?.some(e=>e.kind===`outdated`)===true&&!e.definitionDrift.some(e=>e.kind===`unknown-edit`)}function isPreservedLaunchdTimeoutWarning(e){return e.issues.every(e=>e.code===`launchd-stop-timeout`)&&e.definitionDrift?.some(e=>e.kind===`preserved`&&e.key===`ExitTimeOut`)===true}function isServiceDefinitionOnlyRepair(e){const t=/* @__PURE__ */ new Set([SERVICE_AUDIT_CODES.gatewayEgressProxyEnvEmbedded,SERVICE_AUDIT_CODES.systemdAfterNetworkOnline,SERVICE_AUDIT_CODES.systemdWantsNetworkOnline,SERVICE_AUDIT_CODES.systemdRestartSec,SERVICE_AUDIT_CODES.systemdKillModeProcessOrNone,SERVICE_AUDIT_CODES.systemdKillModeControlGroup,SERVICE_AUDIT_CODES.systemdStopTimeout,SERVICE_AUDIT_CODES.systemdExecDelegation,`launchd-run-at-load`,`launchd-keep-alive`,`launchd-stop-timeout`,`launchd-env-wrapper-outdated`]);return e.issues.every(e=>t.has(e.code))}async function canRepairRuntime(e,t,n,r,i){const a=/* @__PURE__ */ new Set([SERVICE_AUDIT_CODES.gatewayRuntimeNode,SERVICE_AUDIT_CODES.gatewayRuntimeNodeVersionManager,SERVICE_AUDIT_CODES.gatewayRuntimeNodeSystemMissing,SERVICE_AUDIT_CODES.gatewayNodePrefixSkew,SERVICE_AUDIT_CODES.gatewayPathMissing,SERVICE_AUDIT_CODES.gatewayPathMissingDirs,SERVICE_AUDIT_CODES.gatewayPathNonMinimal]);return!r?.entrypointSourceCheckout&&!hasGatewayServiceLauncherOverride(t)&&n.runtime===`node`&&n.programArguments[0]!==resolveManagedGatewayServiceCommand(t)?.programArguments[0]&&e.issues.some(e=>e.code===SERVICE_AUDIT_CODES.gatewayRuntimeNode)&&e.issues.every(e=>e.repair===`host`||a.has(e.code))&&!e.definitionDriftError&&!e.definitionDrift?.some(e=>e.kind===`unknown-edit`&&!(i===`linux`&&e.sourcePath&&e.sourcePath!==t.sourcePath&&t.definitionPaths?.includes(e.sourcePath)))&&await gatewayServiceCommandMatchesRoot(r?.packageRootReal,t)===true}function isOperatorOwnedServiceIssue(e,t,n){const hasOverride=e=>hasGatewayServiceEnvironmentOverride(t,e,{environmentValueSources:n});switch(e.code){case SERVICE_AUDIT_CODES.gatewayRuntimeNode:return hasGatewayServiceLauncherOverride(t);case SERVICE_AUDIT_CODES.gatewayPathMissing:case SERVICE_AUDIT_CODES.gatewayPathMissingDirs:case SERVICE_AUDIT_CODES.gatewayPathNonMinimal:return hasOverride([`PATH`]);case SERVICE_AUDIT_CODES.gatewayTokenEmbedded:case SERVICE_AUDIT_CODES.gatewayTokenMismatch:case SERVICE_AUDIT_CODES.gatewayTokenDrift:return hasOverride([`OPENCLAW_GATEWAY_TOKEN`]);case SERVICE_AUDIT_CODES.gatewayPasswordEmbedded:return hasOverride([`OPENCLAW_GATEWAY_PASSWORD`]);case SERVICE_AUDIT_CODES.gatewayManagedEnvEmbedded:return hasGatewayServiceEnvironmentOverride(t,e.environmentKeys??[],{environmentValueSources:n,normalizeKey:normalizeServiceEnvKey});case SERVICE_AUDIT_CODES.gatewayEgressProxyEnvEmbedded:return hasOverride(e.environmentKeys??[]);case SERVICE_AUDIT_CODES.gatewayProxyEnvEmbedded:return hasGatewayServiceEnvironmentOverride(t,(e.environmentKeys??[]).filter(e=>SERVICE_PROXY_ENV_KEYS.some(t=>t===e)),{ignoreResets:true});default:return false}}function reportGatewayServiceFailure(e,t,n){if(n)n({checkId:`core/doctor/gateway-service`,severity:`error`,category:`fix-now`,message:e,fixHint:`Run openclaw gateway status --deep from the intended install/profile. Resolve the reported permission or configuration error, then rerun openclaw doctor --fix in an interactive terminal.`,docsUrl:`https://docs.openclaw.ai/cli/doctor/checks#gateway-and-service-repairs`});else t.error(e)}function reportUnresolvedGatewayServiceFindings(e,t){if(!t){note(e.map(e=>`${e.message} ${e.fixHint}`).join(`
`),`Gateway service findings still unresolved`);return}for(const n of e)t(n)}function noteDeclinedGatewayServiceRepair(e,t){if(e)note("Skipped Gateway token preservation and service repair. Rerun `openclaw doctor --fix` in an interactive terminal to approve saving a store SecretRef in gateway.auth.token.",`Gateway service config`);if(t===null)note(`Run \`${formatCliCommand(`openclaw gateway install --force`)}\` when you want to replace the gateway service definition.`,`Gateway service config`)}
//!src/commands/doctor-gateway-installation.ts
async function canRepairRunningGatewayDefinition(e){if((await e.service.readRuntime(mergeGatewayServiceEnv(e.env,e.command)).catch(()=>null))?.status===`running`)return true;note(`Gateway native-policy repair requires a running managed service. The existing definition and stop state were preserved; inspect it with \`${formatCliCommand(`openclaw gateway status --deep`,e.env)}\` before using \`${formatCliCommand(`openclaw gateway install --force`,e.env)}\`.`,`Gateway service definition`);return false}async function installDoctorGatewayService(e){try{const install=async(t=e.maintenance?.assertCurrent)=>{const publish=async n=>{if(e.repair.kind===`definition`&&!e.maintenance){if(!await canRepairRunningGatewayDefinition({service:e.service,command:e.command,env:e.args.env}))throw new Error(`Gateway stopped before native-policy repair; its definition was preserved.`)}await e.service.install({...e.args,assertCurrent:t,definitionTransaction:n,beforeMutation:e.maintenance?.beforeMutation??e.args.beforeMutation})};if(e.repair.kind!==`installation`&&e.repair.root){const{reconcileGatewayServiceDefinition:t}=await import(`./service-reconciliation-CHME208N.mjs`);await t({env:e.args.env,root:e.repair.root,command:e.command,expectedCommand:e.args,install:publish,warn:e=>note(e,`Gateway service definition`)})}else await publish()};if(e.repair.kind===`installation`){const t={service:e.service,command:e.command,activeRoot:e.repair.root,maintenance:e.maintenance,env:e.args.env};await withGatewayServiceOperationLock(t.env,async e=>{const assertCurrent=()=>{e();t.maintenance?.assertCurrent()};await assertGatewayServiceInstallationRepairAllowed(t);assertCurrent();await install(assertCurrent);if(process.platform===`win32`&&!t.maintenance)await t.service.restart({env:t.env,stdout:process.stdout,assertCurrent})});note(`Gateway service installation reconciled with the active CLI.`,`Gateway service installation`)}else await install()}catch(t){if(t instanceof GatewayServiceAuthorityError||hasCommandProcessCleanupError(t))throw t;reportGatewayServiceFailure(`Gateway service update failed: ${String(t)}`,e.runtime,e.onFinding)}}async function assertGatewayServiceInstallationRepairAllowed(e){const{inspectManagedGatewayServiceBeforeUpdate:t,GATEWAY_SERVICE_INSPECTION_WARNING:n}=await import(`./update-command-service-plan-C4uLVD3F.mjs`);const r=e.maintenance;const i=await readGatewayServiceState(e.service,{env:process.env,requireEffective:true,requireLoadedCommand:true,...r?.managerUid!==void 0?{loadForInspection:{managerUid:r.managerUid,assertCurrent:r.assertCurrent,assertReadCurrent:r.assertReadCurrent}}:{},validateEnvBeforeStatusRead:e=>assertGatewayServiceMutationAllowed(`repair the gateway service installation`,e)}).catch(e=>{throw new Error(`${n} ${sanitizeServiceInspectionError(e).message}`,{cause:e})});const a=await t({state:i,root:e.activeRoot,allowInstallRootChange:true});r?.assertCurrent();if(a.kind===`unavailable`)throw new Error(a.message);if(!isDeepStrictEqual(i.command,e.command))throw new Error(`Gateway service definition changed during Doctor; rerun doctor to inspect the current installation.`);if(a.kind!==`owned`||!a.requiresInstallRootRefresh)throw new Error(`Gateway service installation is controlled by another owner; automatic installation repair was skipped. Inspect it with \`${formatCliCommand(`openclaw gateway status --deep`,i.env)}\`.`)}const EXECSTART_REPAIR_CODES=/* @__PURE__ */ new Set([SERVICE_AUDIT_CODES.gatewayCommandMissing,SERVICE_AUDIT_CODES.gatewayEntrypointMismatch,SERVICE_AUDIT_CODES.gatewayNodePrefixSkew,SERVICE_AUDIT_CODES.gatewayNodeVersionMissing]);function isExecStartRepairIssue(e){return EXECSTART_REPAIR_CODES.has(e.code)}function resolveSystemdScopeFromServicePath(e){const t=e?.replaceAll(`\\`,`/`)??``;return t.startsWith(`/etc/systemd/`)||t.startsWith(`/usr/lib/systemd/`)||t.startsWith(`/lib/systemd/`)?`system`:`user`}function resolveSystemdUnitNameFromServicePath(e){const t=e?path.posix.basename(e.replaceAll(`\\`,`/`)):``;return t.endsWith(`.service`)?t:`openclaw-gateway.service`}async function resolveSystemdServiceRewriteBlock(e,t,n){if(process.platform!==`linux`||!t.some(isExecStartRepairIssue))return;const r=resolveSystemdUnitNameFromServicePath(e.sourcePath);const i=resolveSystemdScopeFromServicePath(e.sourcePath);const a=await isSystemdUnitActive(process.env,r,i);if(!a.ok)return`Could not determine whether gateway service ${r} is active: ${a.error}. Leaving supervisor metadata unchanged. Check \`systemctl${i===`user`?` --user`:``} status ${r}\` and rerun doctor.`;if(!a.value)return;const o=t.find(isNodeVersionChangeIssue);t.splice(0,t.length,...t.filter(e=>!isExecStartRepairIssue(e)||isNodeVersionChangeIssue(e)));if(o){const t=`systemctl${i===`user`?` --user`:``} cat ${r}`;const a=`Gateway service ${r} is running, and its Node version does not own the installed package. ${o.message??`The service Node and install are split across versions.`}`;const s=describeGatewayNodeVersionRepair({code:o.code,entrypointPath:n?.entrypointPath??resolveServiceEntrypoint(e),plannedNodePath:n?.plannedNodePath,recordedNodePath:e.programArguments[0],pinnedRuntimePath:n?.pinnedRuntimePath});if(hasGatewayServiceLauncherOverride(e))return`${a} The effective ExecStart comes from an operator-owned systemd drop-in, so rewriting the managed unit does not change it. Inspect with \`${t}\` and point that drop-in at the Node that owns this install.${s.remains?` ${s.remains}`:``}${s.resolvesSplit?``:` ${s.action}`}`;return`${a} OpenClaw left the running launcher unchanged. ${s.remains?`${s.remains} `:``}${s.action}`}return`Gateway service ${r} is running; skipped command/entrypoint rewrites and leaving supervisor metadata unchanged. Stop the service first or use \`${formatCliCommand(`openclaw gateway install --force`)}\` when you want to replace the active launcher.`}
//!src/commands/doctor-gateway-runtime-plan.ts
async function buildExpectedGatewayServicePlan(e){const t=resolveManagedGatewayServiceCommand(e.command);const n=t?.programArguments[0];let r=e.runtimePath;if(r===void 0&&!e.pinnedRuntimePath&&e.runtime===`node`&&!e.serviceInstallEnv[`OPENCLAW_WRAPPER`]?.trim()&&n&&isNodeRuntime(n)&&(await resolveNodeRuntimeInfo(n,e.serviceInstallEnv)).status===`supported`)r=n;const plan=n=>buildGatewayInstallPlan({...n?{serviceCli:n}:{},env:e.serviceInstallEnv,port:e.port,runtime:e.runtime,runtimePath:r,pinnedRuntimePath:e.pinnedRuntimePath,existingCommand:e.command,existingEnvironment:t?.environment,existingEnvironmentValueSources:t?.environmentValueSources,warn:(e,t)=>note(e,t),config:e.cfg});const i=t&&resolveServiceEntrypoint(t);try{return await plan()}catch(e){if(!(e instanceof DurableServiceCliError)||!i)throw e;note(e.message,`Gateway service`);return await plan({executable:process.execPath,entrypoint:i})}}
//!src/commands/doctor-gateway-dueling.ts
async function maybeResolveDuelingSystemdGatewayScopes(e,t){if(process.platform!==`linux`)return;const n=await findSystemdGatewayInstallation(process.env).catch(()=>{note(`Could not verify the effective Gateway service identities. Nothing was removed; inspect both units with openclaw gateway status --deep.`,`Gateway cleanup needs an owner decision`);return null});if(n?.kind!==`dueling`)return;const{user:r,system:i}=n;note([`Both a user-scope and a system-scope OpenClaw gateway unit are installed:`,`- user: ${r.unitPath}`,`- system: ${i.unitPath}`,`They bind the same port and will SIGTERM each other in a restart loop.`].join(`
`),`Dueling gateway services detected`);if(!await isSystemUnitActiveAndEnabled(process.env,i.unitName).catch(()=>false)){note([`Could not verify the system-scope unit is both running and enabled at boot, so the`,`user-scope unit may be your working gateway. Not removing anything`,`automatically.`,`If the system-scope unit is the one you want, activate it and re-run doctor:`,`- sudo systemctl enable --now ${i.unitName}`,`If the user-scope unit is the one you want, remove the system unit:`,`- sudo systemctl disable --now ${i.unitName} && sudo rm ${i.unitPath}`].join(`
`),`Gateway cleanup needs an owner decision`);return}note([`The system-scope unit is the active and boot-enabled supervisor and is`,`treated as authoritative; the user-scope unit is the redundant leftover.`].join(`
`),`System-scope unit owns the gateway`);const a=resolveServiceRepairPolicy();if(isServiceRepairDeferred(a)){note(formatServiceRepairDeferredNote(),`Gateway cleanup skipped`);return}if(!await confirmDoctorServiceRepair(t,{message:`Remove the redundant user-scope gateway unit and keep the system-scope unit?`,initialValue:true},a)){const e=renderGatewayServiceCleanupHints();if(e.length>0)note(e.map(e=>`- ${e}`).join(`
`),`Cleanup hints`);return}const o=await findSystemdGatewayInstallation(process.env).catch(()=>null);if(o?.kind!==`dueling`||o.user.unitName!==r.unitName||o.user.unitPath!==r.unitPath||o.system.unitName!==i.unitName||o.system.unitPath!==i.unitPath||!await isSystemUnitActiveAndEnabled(process.env,i.unitName).catch(()=>false)){note(`Gateway service ownership changed or could not be verified after confirmation. Nothing was removed; inspect both units and run Doctor again.`,`Gateway cleanup needs an owner decision`);return}const s=await uninstallUserSystemdGatewayUnit({env:process.env,stdout:process.stdout,target:r}).catch(t=>{e.error(`Failed to remove redundant user-scope gateway unit: ${String(t)}`);const n=renderGatewayServiceCleanupHints();if(n.length>0)note(n.map(e=>`- ${e}`).join(`
`),`Cleanup hints`);return null});if(!s)return;note(s.removed?`Removed user-scope unit ${s.unitPath}.`:`User-scope unit already absent at ${s.unitPath}.`,`Redundant user gateway removed`);if(!s.disabled){e.log(`Removed the user-scope unit file, but systemctl was unavailable to stop it. Run: systemctl --user disable --now ${s.unitName} && systemctl --user daemon-reload`);return}const c=await findSystemdGatewayInstallation(process.env,{requireLoaded:true}).catch(()=>null);const l=`Cleanup of ${s.unitName} completed.`;if(c?.kind===`user`||c?.kind===`dueling`)e.log(`${l} Another user-scope unit remains at ${c.user.unitPath}. It was not removed. Run openclaw doctor again to inspect it before removal.`);else if(c?.kind===`system`&&c.system.unitName===i.unitName&&c.system.unitPath===i.unitPath)e.log(`${l} No other matching installed user-scope unit was found.`);else e.log(`${l} Remaining service ownership could not be verified. Run openclaw gateway status --deep and openclaw doctor before any further cleanup.`)}
//!src/commands/doctor-gateway-services.ts
const DOCTOR_LAUNCHCTL_TIMEOUT_MS=5e3;const DOCTOR_LAUNCHCTL_CONFIRM_POLL_MS=100;async function confirmLegacyLaunchdServiceUnloaded(e){const t=Date.now()+DOCTOR_LAUNCHCTL_TIMEOUT_MS;while(Date.now()<t){const n=Math.max(1,t-Date.now());const r=await execLaunchctl([`print`,e],Math.min(DOCTOR_LAUNCHCTL_TIMEOUT_MS,n));if(r.code!==0)return isLaunchctlNotLoaded(r);const i=Math.min(DOCTOR_LAUNCHCTL_CONFIRM_POLL_MS,t-Date.now());if(i<=0)break;await sleep(i)}return false}async function filterInactiveExtraGatewayServices(e){if(process.platform!==`linux`)return e;const t=[];for(const n of e){if(n.platform!==`linux`||n.legacy===true){t.push(n);continue}const e=await isSystemdUnitActive(process.env,n.label,n.scope);if(!e.ok||e.value)t.push(n)}return t}async function detectExtraGatewayServiceIssues(e={}){if(!isDefaultInstallIdentity(process.env)||!await shouldManageGatewayService())return{services:[],errors:[]};const t=await findExtraGatewayServices(process.env,{deep:e.deep});return{services:await filterInactiveExtraGatewayServices(t.services),errors:t.errors}}async function cleanupLegacyLaunchdService(e){const t=typeof process.getuid===`function`?`gui/${process.getuid()}`:`gui/501`;await execLaunchctl([`bootout`,t,e.plistPath],DOCTOR_LAUNCHCTL_TIMEOUT_MS);await execLaunchctl([`unload`,e.plistPath],DOCTOR_LAUNCHCTL_TIMEOUT_MS);if(!await confirmLegacyLaunchdServiceUnloaded(`${t}/${e.label}`))return{status:`failed`,reason:`launchctl could not confirm unload`};try{await fs.access(e.plistPath)}catch(e){if(e.code===`ENOENT`)return{status:`removed`};return{status:`failed`,reason:`could not inspect plist`}}const n=path.join(os.homedir(),`.Trash`,`${e.label}-${Date.now()}.plist`);try{const{trashed:t}=await removeBootedOutLaunchAgentPlist(e.plistPath,n);return t?{status:`removed`,destination:n}:{status:`removed`}}catch{return{status:`failed`,reason:`could not move plist`}}}async function cleanupLegacyDarwinServices(e){const t=[];const n=[];for(const r of e){if(!r.sourcePath){n.push(`${r.label} (missing plist path)`);continue}const e=await cleanupLegacyLaunchdService({label:r.label,plistPath:r.sourcePath});if(e.status===`removed`)t.push(e.destination?`${r.label} -> ${e.destination}`:r.label);else n.push(`${r.label} (${e.reason})`)}return{removed:t,failed:n}}async function maybeRepairGatewayServiceConfig(e,t,n,r,i){if(!isDefaultInstallIdentity(process.env)){note(NON_DEFAULT_INSTALL_SERVICE_SKIP_REASON,`Gateway`);return e}if(resolveIsNixMode(process.env)){note(`Nix mode detected; skip service updates.`,`Gateway`);return e}if(t===`remote`){note(`Gateway mode is remote; skipped local service audit.`,`Gateway`);return e}const a=await resolveOpenClawPackageRoot({moduleUrl:import.meta.url,argv1:process.argv[1]});const o=await readInstallOwner(a);if(o){note(formatInstallOwnerMessage(o),`Gateway runtime`);return e}const s=resolveServiceRepairPolicy();const c=isServiceRepairDeferred(s);const l=process.platform;const u=resolveGatewayService();const d=await u.readCommand(process.env).catch(()=>null);if(!d){const t=await auditGatewayServiceConfig({env:process.env,command:null,platform:l});reportServiceDefinitionDrift(t);if(t.issues.length>0)note(formatServiceConfigIssues(t.issues).join(`
`),`Gateway service config`);return e}const f=resolveManagedGatewayServiceCommand(d)??d;note(formatGatewayHeapLimitReport(inspectGatewayHeapLimit(d.environment?.NODE_OPTIONS,d.programArguments)),`Gateway heap`);const p=f.environment?.[OPENCLAW_WRAPPER_ENV_KEY]?.trim();const m=await withDaemonRuntimePinMigration(process.env,()=>readDaemonRuntimePin({kind:`gateway`,env:process.env},d));const h={...process.env,...p&&!Object.hasOwn(process.env,`OPENCLAW_WRAPPER`)?{[OPENCLAW_WRAPPER_ENV_KEY]:p}:{}};const g=normalizeOptionalString(d.environment?.[OPENCLAW_WRAPPER_ENV_KEY]);if(g)note(`Gateway service invokes ${OPENCLAW_WRAPPER_ENV_KEY}: ${g}`,`Gateway`);const _=await summarizeGatewayServiceLayout(d);const v=await readInstallOwner(_?.packageRootReal??_?.packageRoot??null);if(v){note(formatInstallOwnerMessage(v),`Gateway runtime`);return e}const y=Boolean(resolveSecretInputRef({value:e.gateway?.auth?.token,defaults:e.secrets?.defaults}).ref);const b=await resolveGatewayAuthTokenForService(e,process.env,{allowExecSecretRefs:i.allowExecSecretRefs===true});if(b.unavailableReason)note(`Unable to verify gateway service token drift: ${b.unavailableReason}`,`Gateway service config`);const x=y?void 0:b.token;const S=resolveGatewayPort(e,process.env);const C=Boolean(h[OPENCLAW_WRAPPER_ENV_KEY]?.trim());const w=C?`node`:m.pin?.runtime??resolveGatewayDaemonRuntime(f.programArguments);const T=w===`bun`||w===`standalone`?m.pin?.path??f.programArguments[0]:void 0;const E=await buildExpectedGatewayServicePlan({cfg:e,command:d,serviceInstallEnv:h,port:S,runtime:w,runtimePath:T,pinnedRuntimePath:m.pin?.path});const D=await summarizeGatewayServiceLayout(E);const O=D?.packageRootReal;const k=O?await inspectGatewayServiceInstallationDrift(_,O):void 0;const A=k&&e.gateway?.port===void 0&&!process.env.OPENCLAW_GATEWAY_PORT?.trim()?parseTcpPortFromArgs(d.programArguments)??S:S;const j=await auditGatewayServiceConfig({platform:l,env:process.env,command:d,expectedGatewayToken:x,expectedManagedServiceEnvKeys:readManagedServiceEnvKeysFromEnvironment(E.environment),expectedServicePath:E.environment.PATH,expectedDurableEnvironment:E.environment,expectedPort:A,...k?{expectedCommand:E}:{}});reportServiceDefinitionDrift(j);if(j.runtimeNote)note(j.runtimeNote,`Gateway runtime`);const M=readEmbeddedGatewayToken(d);if(y&&M)j.issues.push({code:SERVICE_AUDIT_CODES.gatewayTokenMismatch,message:`Gateway service OPENCLAW_GATEWAY_TOKEN should be unset when gateway.auth.token is SecretRef-managed`,detail:`service token is stale`,level:`recommended`});const N=!C&&!m.pin&&needsNodeRuntimeMigration(j.issues);const P=N?await resolveSystemNodeInfo({env:process.env,platform:l}):null;const F=P?.status===`supported`?P.path:null;if(N&&!F&&w!==`node`)note(renderSystemNodeWarning(P)||`System Node ${SUPPORTED_NODE_VERSIONS} not found. Install via Homebrew/apt/choco and rerun doctor to migrate off Bun/version managers.`,`Gateway runtime`);const I=N&&F?await buildExpectedGatewayServicePlan({cfg:e,command:d,serviceInstallEnv:h,port:A,runtime:`node`,runtimePath:F}):E;const L=I===E?D:await summarizeGatewayServiceLayout(I);if(L?.entrypointReal&&_?.entrypointReal&&L.entrypointReal!==_.entrypointReal)j.issues.push({code:SERVICE_AUDIT_CODES.gatewayEntrypointMismatch,message:`Gateway service entrypoint does not match the current install.`+(k?` ${formatGatewayServiceInstallationDrift(k,h,{command:d})}`:``),detail:`${_?.entrypoint} -> ${L?.entrypoint}`,level:`recommended`});const R=await canRepairRuntime(j,d,I,D,l);const z=!R&&!k&&Boolean(O)&&!D?.entrypointSourceCheckout&&hasRepairableServiceDefinitionDrift(j);const B=k?void 0:await resolveSystemdServiceRewriteBlock(d,j.issues,{entrypointPath:L?.entrypointReal,plannedNodePath:I.programArguments[0],pinnedRuntimePath:m.pin?.path});if(B)note(B,`Gateway service config`);const V=reportGatewayServiceConfigAudit(j,_,z);j.issues=j.issues.filter(e=>e.repair!==`host`);if(j.issues.length===0&&!z)return e;if(!z&&!k&&isPreservedLaunchdTimeoutWarning(j))return e;if(j.issues.length>0&&j.issues.every(e=>e.code===SERVICE_AUDIT_CODES.gatewayRuntimeProbeFailed))return e;const H=j.issues.some(e=>e.level===`aggressive`)||k!==void 0&&(j.definitionDriftError!==void 0||j.definitionDrift?.some(e=>e.kind===`unknown-edit`)===true);if(H&&!r.shouldForce&&!R)note(`Custom or unexpected service edits detected. Rerun with --force to overwrite.`,`Gateway service config`);if(c){note(formatServiceRepairDeferredNote(),`Gateway service config`);return e}if(z&&!i.serviceMaintenance&&!await canRepairRunningGatewayDefinition({service:u,command:d,env:h}))return e;if(B)return e;if(l===`linux`&&j.issues.some(e=>isExecStartRepairIssue(e)&&hasGatewayServiceLauncherOverride(d)||e.code===SERVICE_AUDIT_CODES.gatewayPortMismatch&&hasGatewayServiceLauncherOverride(d,{includeWorkingDirectory:false})||isOperatorOwnedServiceIssue(e,d,E.environmentValueSources))){const t=resolveSystemdUnitNameFromServicePath(d.sourcePath);const n=`systemctl${resolveSystemdScopeFromServicePath(d.sourcePath)===`user`?` --user`:``} cat ${t}`;note(`Gateway service command, working directory, or environment comes from an operator-owned systemd drop-in; rewriting the managed unit cannot repair it. Inspect with \`${n}\`, then update or remove the drop-in and rerun doctor.`,`Gateway service config`);return e}if(k&&O)try{await assertGatewayServiceInstallationRepairAllowed({service:u,command:d,activeRoot:O,maintenance:i.serviceMaintenance})}catch(t){note(String(t),`Gateway service installation`);return e}const U=x??readEmbeddedGatewayToken(f);const W=typeof e.gateway?.auth?.token===`string`?normalizeOptionalString(e.gateway.auth.token):void 0;const G=!y&&!W&&Boolean(U);const{preview:K,unresolvedFindings:q}=formatGatewayServiceRepairPreview({command:d,managedDefinition:f,plan:I,currentLayout:_,plannedLayout:L,missingSystemNode:N&&!F&&!R,runtimeIssues:j.issues,definitionDrift:j.definitionDrift,pinnedRuntimePath:m.pin?.path});note(K,`Gateway service repair preview`);if(!await r.confirmRuntimeRepair({message:G?`Preserve the Gateway token in the secret store, write its SecretRef to config, and reinstall the service now?`:H&&!R?`Overwrite gateway service config with the repair shown above now?`:`Apply the gateway service repair shown above now?`,initialValue:G?false:H?r.shouldForce:true,requiresInteractiveConfirmation:G||!(k&&isServiceInstallationOnlyRepair(j))&&!R&&!(z&&isServiceDefinitionOnlyRepair(j))})){noteDeclinedGatewayServiceRepair(G,V);return e}try{for(const e of[mergeGatewayServiceEnv(h,d),I.environment]){const t=await u.readDefinitionMutationCapability?.({env:h,environment:e}).catch(()=>({kind:`unknown`,reason:`inspection-failed`}));if(t)assertServiceDefinitionWritable(t)}}catch(t){reportGatewayServiceFailure(`Gateway service repair blocked: ${String(t)}`,n,i.onFinding);return e}let J=e;if(G&&U)try{await i.serviceMaintenance?.beforeMutation?.();const{ref:t,reused:n,backupPath:r}=await preserveGatewayAuthTokenForService({cfg:e,env:h,token:U,assertCurrent:i.serviceMaintenance?.assertCurrent});note(n?`Gateway token already exists in secret store entry "${t.id}"; the store was left unchanged.`:`Saved Gateway token in secret store entry "${t.id}".${r?` Backup: ${r}`:``} If config publication fails, the entry is retained and reused on the next repair.`,`Gateway`);i.serviceMaintenance?.assertCurrent();J=await i.writeConfig({...e,gateway:{...e.gateway,auth:{...e.gateway?.auth,mode:e.gateway?.auth?.mode??`token`,token:t}}});note(`Configured gateway.auth.token as a store SecretRef before reinstalling service.`,`Gateway`)}catch(t){if(t instanceof ConfigWritePostCommitError)throw t;reportGatewayServiceFailure(`Failed to persist gateway.auth.token before service repair: ${String(t)}`,n,i.onFinding);return e}const Y=await buildExpectedGatewayServicePlan({cfg:J,command:d,serviceInstallEnv:h,port:A,runtime:N&&F?`node`:w,runtimePath:N&&F?F:T,pinnedRuntimePath:m.pin?.path});await installDoctorGatewayService({onFinding:i.onFinding,service:u,command:d,maintenance:i.serviceMaintenance,runtime:n,repair:k&&O?{kind:`installation`,root:O}:z&&O?{kind:`definition`,root:O}:{kind:`config`,...O&&!D?.entrypointSourceCheckout&&(R||j.definitionDrift?.some(e=>e.kind===`preserved`))?{root:O}:{}},args:{...Y,runtimePinUpdate:{expected:m,pin:m.pin},env:h,stdout:process.stdout,warn:e=>note(e,`Gateway`)}});if(q.length>0)reportUnresolvedGatewayServiceFindings(q,i.onFinding);return J}async function maybeScanExtraGatewayServices(e,t,n){if(!isDefaultInstallIdentity(process.env)){note(NON_DEFAULT_INSTALL_SERVICE_SKIP_REASON,`Gateway`);return}const{services:r,errors:i}=await detectExtraGatewayServiceIssues(e);if(i.length>0)note(i.map(e=>`- ${e.source}: ${e.message}`).join(`
`),`Gateway service inspection incomplete`);if(r.length===0)return;note(r.map(e=>`- ${e.label} (${e.scope}, ${e.detail})`).join(`
`),`Other gateway-like services detected`);const a=r.filter(e=>e.legacy===true);if(a.length>0){const e=resolveServiceRepairPolicy();const r=isServiceRepairDeferred(e);if(r)note(formatServiceRepairDeferredNote(),`Legacy gateway cleanup skipped`);if(r?false:await confirmDoctorServiceRepair(n,{message:`Remove legacy gateway services now?`,initialValue:true},e)){const e=[];const{darwinUserServices:n,linuxUserServices:r,failed:i}=classifyLegacyServices(a);for(const[a,o]of[[n,()=>cleanupLegacyDarwinServices(n)],[r,()=>cleanupLegacyLinuxUserServices(r,t)]])if(a.length>0){const t=await o();e.push(...t.removed);i.push(...t.failed)}if(e.length>0)note(e.map(e=>`- ${e}`).join(`
`),`Legacy gateway removed`);if(i.length>0)note(i.map(e=>`- ${e}`).join(`
`),`Legacy gateway cleanup skipped`)}}const o=renderGatewayServiceCleanupHints(r.filter(e=>e.legacy!==true));if(o.length>0)note(o.map(e=>`- ${e}`).join(`
`),process.platform===`darwin`?`Cleanup hints`:`Inspection hints`);note([`Recommendation: run a single gateway per machine for most setups.`,`One gateway supports multiple agents.`,`If you need multiple gateways (e.g., a rescue bot on the same host), isolate ports + config/state (see docs: /gateway#multiple-gateways-same-host).`].join(`
`),`Gateway recommendation`)}export{detectExtraGatewayServiceIssues,maybeRepairGatewayServiceConfig,maybeResolveDuelingSystemdGatewayScopes,maybeScanExtraGatewayServices};