UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3 lines • 15.2 kB
import{l as normalizeOptionalString}from"./string-coerce-CpTFcSwY.mjs";import{n as isNodeRuntime}from"./runtime-binary-DNstBs1K.mjs";import{n as isTruthyEnvValue}from"./env-fLMEolk5.mjs";import{r as SUPPORTED_NODE_VERSIONS}from"./node-version-EaZf6kHy.mjs";import{t as resolveNodeStartupTlsEnvironment}from"./node-startup-env-mX6gJCig.mjs";import{r as defaultRuntime}from"./runtime-DIcLIHcp.mjs";import{n as resolveOpenClawPackageRoot}from"./openclaw-root-DP80HYD2.mjs";import{i as isMissingPathError,t as hasErrnoCode}from"./errno-DUBt6SQQ.mjs";import{n as parseTcpPort}from"./tcp-port-CL3rN59M.mjs";import{b as resolveGatewayPort}from"./paths-D_FOvGon.mjs";import{n as createLazyPromise}from"./lazy-promise-CismJCQR.mjs";import{n as isDangerousHostEnvOverrideVarName,o as normalizeEnvVarKey,r as isDangerousHostEnvVarName}from"./host-env-security-CA3pVx5Z.mjs";import{t as formatCliCommand}from"./command-format-D7KhNLP0.mjs";import{y as resolveFutureConfigActionBlock}from"./config-env-vars-DCDGIBtT.mjs";import{g as sanitizeServiceInspectionError,s as ServiceStartRefusalError}from"./service-inspection-error-D006EyWC.mjs";import{l as readConfigFileSnapshotForWrite}from"./io.runtime-BvSeVFIY.mjs";import"./io-Di_yuX3t.mjs";import{g as resolveGatewayBindHost,s as isLoopbackHost,t as defaultGatewayBindMode}from"./net-Bu4cO5Pq.mjs";import{r as replaceConfigFile}from"./mutate-DcH8aT_4.mjs";import{r as resolveGatewayAuth}from"./auth-resolve-UwT9_UjV.mjs";import{s as resolveManagedGatewayServiceCommand,t as assertServiceDefinitionWritable}from"./service-types-B7cjFijA.mjs";import{o as resolveServiceEntrypoint}from"./service-layout-Daz63_6Y.mjs";import{i as assertGatewayServiceUpdateCurrent,o as isUpdateOwnedGatewayServiceCommand}from"./service-update-authority-DqjrBTQ9.mjs";import{l as isNonFatalSystemdInstallProbeError}from"./systemd-busctl-query-CVbse9JI.mjs";import{t as mergeGatewayServiceEnv}from"./service-env-merge-Db3tXSCb.mjs";import"./auth-BwgQGI6W.mjs";import{m as resolveDaemonInstallBlockMessage,r as createDaemonInstallActionContext,x as installDaemonServiceAndEmit,y as buildDaemonServiceSnapshot}from"./shared-BctPQR6n.mjs";import{r as omitSecretEgressProxyEnvironment}from"./environment-DYol_b_c.mjs";import{l as resolvePreferredNodePath,s as resolvePinnedDaemonRuntimePath,u as resolveRecordedDaemonRuntime}from"./runtime-paths-BOio2Rt6.mjs";import{n as resolveGatewayService}from"./service-Bz63n2ee.mjs";import{c as withDaemonRuntimePinMigration,o as readDaemonRuntimePinForInstall}from"./runtime-pin-state-DeLfcMhS.mjs";import{o as resolveOpenClawWrapperPath,t as OPENCLAW_WRAPPER_ENV_KEY}from"./program-args-Dls9y3ku.mjs";import{i as isDisposableEntrypoint,r as installDurableServiceCli}from"./durable-service-entrypoint-CYy_WbI9.mjs";import{n as formatInvalidPortOption,t as formatInvalidConfigPort}from"./error-format-D9Q6t3gZ.mjs";import{i as resolveGatewayDaemonRuntime,r as isGatewayDaemonRuntime}from"./daemon-runtime-CM-TWmEx.mjs";import{n as resolveRestoreServiceCli,t as assertExpectedRuntimePin}from"./install-restore-cli-Djkq7_5B.mjs";import{o as readEmbeddedGatewayToken}from"./service-audit-DNlslbPV.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 reconcileGatewayServiceDefinition}from"./service-reconciliation-CZxsJ4bI.mjs";import{constants}from"node:fs";import fs$1 from"node:fs/promises"; //!src/cli/daemon-cli/install.ts function mergeInstallInvocationEnv(e){const t=process.platform;const normalizeInstallEnvKey=e=>t===`win32`?e.toUpperCase():e;const n={};for(const[r,i]of Object.entries(omitSecretEgressProxyEnvironment(e.env,t))){const e=normalizeEnvVarKey(r,{portable:true});if(!e||isDangerousHostEnvVarName(e))continue;n[normalizeInstallEnvKey(e)]=i}if(!e.existingServiceEnv||Object.keys(e.existingServiceEnv).length===0)return n;const r={};for(const[t,n]of Object.entries(e.existingServiceEnv)){const e=normalizeEnvVarKey(t,{portable:true});if(!e)continue;const i=e.toUpperCase();if(i===`OPENCLAW_WRAPPER`){const e=n.trim();if(e)r[normalizeInstallEnvKey(i)]=e;continue}if(i===`HOME`||i===`PATH`||i===`TMPDIR`||i===`HOMEBREW_PREFIX`||i.startsWith(`OPENCLAW_`))continue;if(isDangerousHostEnvVarName(e)||isDangerousHostEnvOverrideVarName(e)&&i!==`NODE_EXTRA_CA_CERTS`)continue;const a=n.trim();if(!a)continue;r[normalizeInstallEnvKey(e)]=a}return{...r,...n}}async function runDaemonInstall(e){let t;const{json:n,stdout:r,warnings:i,warn:a,emit:o,emitMessage:s,fail:c}=createDaemonInstallActionContext(e.json,()=>t);const l=resolveDaemonInstallBlockMessage(`gateway`);if(l){c(l);return}const u=resolveGatewayService();let d;try{d=await u.readCommand(process.env,{requireEffective:true,allowMissingDefinition:true})}catch(e){const t=sanitizeServiceInspectionError(e).message;c(e instanceof ServiceStartRefusalError?`SERVICE_DEFINITION_UNKNOWN: ${t}`:t);return}let f;try{f=await u.isLoaded({env:process.env})}catch(e){if(!isNonFatalSystemdInstallProbeError(e)){c(`Gateway service check failed: ${String(e)}`);return}f=false}const p=resolveManagedGatewayServiceCommand(d);const m=p?.environment;const h=mergeInstallInvocationEnv({env:process.env,existingServiceEnv:m});let g;try{g=await withDaemonRuntimePinMigration(h,()=>readDaemonRuntimePinForInstall({kind:`gateway`,env:h},d,e.runtime!==void 0||e.runtimePath!==void 0))}catch(e){c(`Runtime pin inspection failed: ${String(e)}`);return}if(e.expectedRuntimePin!==void 0)try{assertExpectedRuntimePin(e.expectedRuntimePin,g,`Gateway`)}catch(e){c(e instanceof Error?e.message:String(e));return}let _;let v;if(e.restoreServiceCli!==void 0)try{({serviceCli:_,runtimePath:v}=await resolveRestoreServiceCli(e.restoreServiceCli,e,h))}catch(e){c(e instanceof Error?e.message:String(e));return}if(e.expectedRuntimePin!==void 0){const{ensureConfigReady:e}=await import(`./config-guard-CkC-vIbu.mjs`);await e({runtime:defaultRuntime,commandPath:[`gateway`,`install`],suppressDoctorStdout:n})}let y=e.runtimePath??(e.runtime?void 0:g.pin?.path);const b=mergeGatewayServiceEnv(process.env,d);const assertWritable=async()=>{try{for(const e of[b,h]){const t=await u.readDefinitionMutationCapability?.({env:process.env,environment:e}).catch(()=>({kind:`unknown`,reason:`inspection-failed`}));if(t)assertServiceDefinitionWritable(t)}return true}catch(e){c(`Gateway install blocked: ${String(e)}`);return false}};if((e.force||!f)&&!await assertWritable())return;let{snapshot:x,writeOptions:S}=await readConfigFileSnapshotForWrite();const C=resolveFutureConfigActionBlock({action:`install or rewrite the gateway service`,snapshot:x});if(C){c(`Gateway install blocked: ${C.message}`,C.hints);return}let w=x.valid?x.sourceConfig:x.config;const T=parseTcpPort(e.port);if(e.port!==void 0&&T===null){c(formatInvalidPortOption(`--port`));return}const E=T??resolveGatewayPort(w);if(!Number.isFinite(E)||E<=0||E>65535){c(formatInvalidConfigPort(`gateway.port`));return}const D=e.runtime||g.pin?.runtime||resolveGatewayDaemonRuntime([y??``]);if(!isGatewayDaemonRuntime(D)){c(`Invalid --runtime (use "node", "bun", or "standalone")`);return}let O=D;let k;if(e.wrapper!==void 0){try{k=await resolveOpenClawWrapperPath(e.wrapper)}catch(e){c(`Invalid --wrapper: ${String(e)}`);return}if(!k){c(`Invalid --wrapper`);return}}if(!k)try{k=await resolveOpenClawWrapperPath(h[OPENCLAW_WRAPPER_ENV_KEY])}catch(e){c(`Invalid ${OPENCLAW_WRAPPER_ENV_KEY}: ${String(e)}`);return}let A;try{if(!k||e.runtimePath!==void 0)y=await resolvePinnedDaemonRuntimePath(y,O,h);A=k?void 0:y??v}catch(e){c(`Invalid runtime pin: ${String(e)}; reinstall with an explicit --runtime or --runtime-path to replace the saved runtime pin.`);return}const j=w.gateway?.bind??defaultGatewayBindMode(w.gateway?.tailscale?.mode??`off`);const M=await resolveGatewayBindHost(j,w.gateway?.customBindHost);function formatNoAuthNonLoopbackInstallBlock(){const e=resolveGatewayAuth({authConfig:w.gateway?.auth,env:h,tailscaleMode:w.gateway?.tailscale?.mode??`off`});const t=j===`tailnet`||!isLoopbackHost(M);if(e.mode!==`none`||!t)return;const n=[`${j===`tailnet`&&isLoopbackHost(M)?`gateway.bind=tailnet currently resolves to ${M} but can later resolve to a Tailnet interface`:`gateway.bind=${j} resolves to ${M}`}, but gateway.auth.mode=none disables Gateway auth.`];const r=normalizeOptionalString(e.token)?`token`:normalizeOptionalString(e.password)?`password`:void 0;if(r)n.push(`This config already has gateway.auth.${r}; run ${formatCliCommand(`openclaw config set gateway.auth.mode ${r}`)} and then rerun ${formatCliCommand(`openclaw gateway install --force`)}.`);else n.push(`Configure token/password auth, use trusted-proxy auth, or set ${formatCliCommand(`openclaw config set gateway.bind loopback`)} before installing the managed service.`);return n.join(` `)}const N=formatNoAuthNonLoopbackInstallBlock();if(N){c(`Gateway install blocked: ${N}`);return}let P;const F=p?.programArguments[0];const I=O===`node`&&!k&&!A&&(e.runtime===void 0||isNodeRuntime(F??``))?await resolveRecordedDaemonRuntime(F,h):void 0;if(I?.status===`supported`&&e.runtime===void 0){O=I.runtime;A=I.path}if(I?.runtime===`node`){if(I.status!==`probe-failed`&&I.capabilityError)a(I.capabilityError);const t=I.status===`probe-failed`&&await fs$1.access(I.path,constants.X_OK).then(()=>false,e=>isMissingPathError(e)||hasErrnoCode(e,`EACCES`))?`missing Gateway service Node (${I.path})`:I.status===`unsupported`?`unsupported Gateway service Node ${I.version} (${I.path})`:void 0;if(t){try{A=await resolvePreferredNodePath({env:h,runtime:`node`,preferCurrentExecPath:true})}catch(e){c(`Gateway runtime selection failed: ${String(e)}`);return}if(!A){c(`No supported Node runtime is available. Install Node ${SUPPORTED_NODE_VERSIONS}, then rerun openclaw gateway install.`);return}P=`Replacing ${t} with ${A}; refreshing the install.`}else if(I.status===`probe-failed`&&!e.force){c(`${I.error.message} Reinstall with: ${formatCliCommand(`openclaw gateway install --force`)}.`);return}}const buildInstallPlan=t=>buildGatewayInstallPlan({allowUnconfigured:e.allowUnconfigured,env:h,port:E,runtime:O,runtimePath:A,pinnedRuntimePath:y,wrapperPath:k,serviceCli:_,existingCommand:d,existingEnvironment:m,existingEnvironmentValueSources:p?.environmentValueSources,config:w,...t});if(f&&!e.force){async function getGatewayServiceAutoRefreshMessage(){const t=e.allowUnconfigured;const n=process.env;const r=e.runtime!==void 0||e.runtimePath!==void 0;try{const e=resolveManagedGatewayServiceCommand(d);if(!e)return d?void 0:`Gateway service definition is missing; refreshing the install.`;if(r)return`Gateway runtime selection changed; refreshing the install.`;const i=resolveServiceEntrypoint(e);if(i&&await isDisposableEntrypoint(i))return`Gateway service runs from a temporary npx or pnpm dlx copy that can be deleted; refreshing the install.`;const a=createLazyPromise(()=>buildInstallPlan({warn:()=>void 0}));const o=e.programArguments.includes(`--allow-unconfigured`);if(o||t){if(o!==(await a()).programArguments.includes(`--allow-unconfigured`))return`Gateway service start-mode argument differs from the current install plan; refreshing the install.`}const s=readEmbeddedGatewayToken(e);if(s){const e=await a();if(s!==normalizeOptionalString(e.environment.OPENCLAW_GATEWAY_TOKEN))return`Gateway service OPENCLAW_GATEWAY_TOKEN differs from the current install plan; refreshing the install.`}if(Boolean(k||normalizeOptionalString(h[`OPENCLAW_WRAPPER`]))||y){const t=await a();if(t.programArguments.join(`\0`)!==e.programArguments.join(`\0`))return`Gateway service command differs from the current runtime/wrapper install plan; refreshing the install.`;if(normalizeOptionalString(t.environment[`OPENCLAW_WRAPPER`])!==normalizeOptionalString(e.environment?.[`OPENCLAW_WRAPPER`]))return`Gateway service ${OPENCLAW_WRAPPER_ENV_KEY} differs from the current wrapper install plan; refreshing the install.`}const c=e.programArguments[0]?.trim();if(!c)return;const l=e.environment??{};const u=l.NODE_EXTRA_CA_CERTS?.trim();if(u&&!resolveNodeStartupTlsEnvironment({env:l,execPath:c}).NODE_EXTRA_CA_CERTS)return`Gateway service trusts the outdated macOS CA bundle; refreshing the install.`;const f=resolveNodeStartupTlsEnvironment({env:{...n,...l,NODE_EXTRA_CA_CERTS:void 0},execPath:c,includeDarwinDefaults:false}).NODE_EXTRA_CA_CERTS;if(!f)return;if(u!==f)return`Gateway service is missing the nvm TLS CA bundle; refreshing the install.`;return}catch{return}}P??=await getGatewayServiceAutoRefreshMessage();if(P){if(!await assertWritable())return}}if(P)a(P);if(x.valid&&w.gateway?.mode===void 0){const e=x.sourceConfig??x.config;await replaceConfigFile({sourceConfig:{...e,gateway:{...e.gateway,mode:`local`}},snapshot:x,writeOptions:{baseSnapshot:x,...S,...isUpdateOwnedGatewayServiceCommand()?{assertCurrent:()=>{S.assertCurrent?.();assertGatewayServiceUpdateCurrent()}}:{},skipRuntimeSnapshotRefresh:true},afterWrite:{mode:`auto`}});const t=await readConfigFileSnapshotForWrite();x=t.snapshot;S=t.writeOptions;w=x.valid?x.sourceConfig:x.config;a(`No gateway.mode found. Set gateway.mode=local for managed gateway install.`)}if(f&&!e.force&&!P){s({ok:true,result:`already-installed`,message:`Gateway service already ${u.loadedText}.`,service:buildDaemonServiceSnapshot(u,f)});if(!n)defaultRuntime.log(`Reinstall with: ${formatCliCommand(`openclaw gateway install --force`)}`);return}const L=await resolveGatewayInstallToken({config:w,env:h,explicitToken:e.token,generateIfMissing:{snapshot:x,writeOptions:S}});if(L.unavailableReason){c(`Gateway install blocked: ${L.unavailableReason}`);return}for(const e of L.warnings)a(e);const{programArguments:R,workingDirectory:z,environment:B,environmentValueSources:V,durableCliReplacement:H}=await buildInstallPlan({runtimeExplicit:e.runtime!==void 0||e.runtimePath!==void 0,installDurableCli:true,warn:a});const install=(t,n)=>async i=>{await u.install({beforeMutation:t,beforeRecovery:n,runtimePinUpdate:{expected:g,pin:y?{runtime:O,path:y}:void 0,...e.expectedRuntimePin!==void 0?{requireDefinitionMatch:true,...!_&&g.definition!==void 0?{requireRunning:true}:{}}:{}},env:h,stdout:r,warn:a,programArguments:R,workingDirectory:z,environment:B,environmentValueSources:V,definitionTransaction:i})};const U=`Gateway service installed. Runtime readiness has not been checked; startup may still be in progress. Run ${formatCliCommand(`openclaw gateway start`)} to wait until it is ready.`;await installDaemonServiceAndEmit({serviceNoun:`Gateway`,service:u,successMessage:U,onVerified:async()=>{if(!n)defaultRuntime.log(U)},warnings:i,emit:o,fail:c,install:()=>installDurableServiceCli({env:h,replacement:H,verify:()=>u.isLoaded({env:process.env}),warn:a,install:async(e,n)=>{if(isUpdateOwnedGatewayServiceCommand()||isTruthyEnvValue(process.env.OPENCLAW_UPDATE_IN_PROGRESS))t=await reconcileGatewayServiceDefinition({env:h,root:await resolveOpenClawPackageRoot({moduleUrl:import.meta.url})??void 0,command:d,expectedCommand:{programArguments:R,workingDirectory:z,environment:B,environmentValueSources:V},install:install(e,n),warn:a});else await install(e,n)()}})})}export{runDaemonInstall as n,mergeInstallInvocationEnv as t};