UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3 lines • 8.81 kB
import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import"./paths-D_FOvGon.mjs";import{t as formatCliCommand}from"./command-format-D7KhNLP0.mjs";import{t as VERSION}from"./version-DrZ9Nfde.mjs";import{a as resolveNpmGlobalPrefixLayoutFromPrefix}from"./update-npm-prefix-PBytTD1i.mjs";import fs from"node:fs";import path from"node:path";import fs$1 from"node:fs/promises"; //!src/daemon/durable-service-entrypoint.ts const realpathOrResolve=e=>fs$1.realpath(e).catch(()=>path.resolve(e));function isDisposableInstallPath(e){return e.split(path.sep).some(e=>e===`_npx`||e===`dlx`||/^dlx-\d+$/u.test(e)||/^\.?bunx-/u.test(e))}async function isDisposableEntrypoint(e){return isDisposableInstallPath(await realpathOrResolve(e))}function formatNpxCliCommand(e,t,n=process.env){return`npx ${formatCliCommand(t?`openclaw ${t}`:`openclaw`,n).replace(/^openclaw\b/u,`openclaw@${e}`)}`}async function formatUserCliCommand(e=``){if(await isDisposableEntrypoint(process.argv[1]??``))return formatNpxCliCommand(VERSION,e);return formatCliCommand(e?`openclaw ${e}`:`openclaw`)}var DurableServiceCliError=class extends Error{constructor(...e){super(...e);this.name=`DurableServiceCliError`}};function resolveDurableLayout(e){const t=resolveNpmGlobalPrefixLayoutFromPrefix(path.join(resolveStateDir(e),`npm`));const n=path.join(t.globalRoot,`openclaw`);return{layout:t,packageRoot:n,entrypoint:path.join(n,`openclaw.mjs`)}}function resolveDurableServiceBinDir(e,t=process.platform,n={}){const{binDir:r}=resolveDurableLayout(e).layout;const i=path.join(r,t===`win32`?`openclaw.cmd`:`openclaw`);return n.planned||fs.existsSync(i)?r:void 0}async function collectDurableCopyErrors(e,t){if(!await fs$1.access(path.join(e,`openclaw.mjs`)).then(()=>true,()=>false))return[`missing`];const[{collectPackageDistContentInventoryErrors:n},{collectInstalledGlobalPackageErrors:r}]=await Promise.all([import(`./package-dist-inventory-DQVlqCkz.mjs`),import(`./update-global-D17x_-eV.mjs`)]);const i=await r({packageRoot:e,expectedVersion:t});if(i.length>0)return i;return await n(e).catch(e=>[String(e)])}async function resolveDurableServiceCli(e,t,n=process.argv[1]){if(!n||!await isDisposableEntrypoint(n))return;const{layout:r,packageRoot:i,entrypoint:a}=resolveDurableLayout(e);const[{resolveOpenClawPackageRoot:o},{readPackageVersion:s}]=await Promise.all([import(`./openclaw-root-BwFF-E70.mjs`),import(`./package-json-CcZJH792.mjs`)]);const c=await o({argv1:await realpathOrResolve(n)});const l=c?await s(c):null;if(!c||!l)throw new Error(`Cannot determine the running OpenClaw version for service installation.`);if(!t.install){const t=await collectDurableCopyErrors(i,l);if(t.length===0)return{entrypoint:a};throw new DurableServiceCliError(`The background service's OpenClaw copy at ${i} cannot be reused (${t.slice(0,2).join(`; `)}). Reinstall it with: ${formatNpxCliCommand(l,`gateway install --force`,e)}`)}const{planCliEntrypoint:u}=await import(`./program-args-B_lQcBby.mjs`);const d=await u({sourceEntrypoint:n,sourceRoot:c,packageRoot:i,service:t.service});return{entrypoint:d,replacement:{version:l,globalRoot:r.globalRoot,packageRoot:i,entrypoint:d.planned}}}async function installDurableServiceCli(e){if(!e.replacement){await e.install();return}const t=e.replacement;const{prefix:n}=resolveDurableLayout(e.env).layout;await fs$1.mkdir(n,{recursive:true});const{withFileLock:r}=await import(`./file-lock-DzetRBPT.mjs`);await r(path.join(n,`.openclaw-service-install`),{retries:{retries:600,factor:1.2,minTimeout:100,maxTimeout:1e3},stale:3e4,staleRecovery:`remove-if-definitely-stale`},()=>installUnderPackageLock({...e,replacement:t}))}async function installUnderPackageLock(e){const t=e.replacement;if((await collectDurableCopyErrors(t.packageRoot,t.version)).length===0){await e.install();return}const n=await fs$1.access(t.packageRoot).then(()=>true,()=>false);const r=await stageDurableCopy(e.env,t);let i;let a=false;let o=false;let s=`failed`;const settle=async t=>{o=true;try{for(const n of await r.settle(t))e.warn(n)}catch(t){e.warn(`Durable OpenClaw copy cleanup failed: ${String(t)}`)}};const beforeRecovery=async()=>{if(!i||o)return;await i.catch(()=>void 0);if(a)await settle(n?`restore`:`retire`)};try{await e.install(()=>i??=r.activate().then(()=>{a=true}),beforeRecovery);if(!i)throw new Error(`The service install finished without its mutation hook; the durable OpenClaw copy was not installed.`);s=`installed`;s=await e.verify()?`verified`:`installed`}finally{if(!i)try{for(const t of await r.cancel())e.warn(t)}catch(t){e.warn(`Durable OpenClaw copy cleanup failed: ${String(t)}`)}else if(!o&&s===`failed`&&n&&r.published()){e.warn(`The service install failed without a settled service recovery, so the durable OpenClaw copy at ${t.packageRoot} was left as installed and the previous copy's backup was kept. Check the service, then rerun the install.`);await settle(`retain`)}else if(!o)await settle(s===`installed`?`retain`:`retire`)}}async function stageDurableCopy(e,t){const[{runGlobalPackageUpdateSteps:n},{createGlobalInstallEnv:r,resolveGlobalInstallTarget:i},{runStep:a},{runCommandWithTimeout:o},{applyPathPrepend:s},{createDeferredCore:c}]=await Promise.all([import(`./package-update-steps-BQEMjfXX.mjs`),import(`./update-global-D17x_-eV.mjs`),import(`./update-runner-command-CGmiOxUL.mjs`),import(`./exec-Nk4ZKR_f.mjs`),import(`./path-prepend-BjsdHNTB.mjs`),import(`./deferred-Bc0kpRkt.mjs`)]);const l=await r(e,{manager:`npm`});s(l,[path.dirname(process.execPath)]);const u=await i({manager:`npm`,runCommand:o,timeoutMs:3e4,env:l});await fs$1.mkdir(t.globalRoot,{recursive:true});const d=c();const f=c();const p=/* @__PURE__ */ new Error(`Durable OpenClaw copy replacement cancelled before activation`);let m;let h;let g=false;const identityOf=e=>{const t=fs.lstatSync(e,{bigint:true,throwIfNoEntry:false});return t?{dev:t.dev,ino:t.ino}:void 0};const sameIdentity=(e,t)=>e!==void 0&&t!==void 0&&e.dev===t.dev&&e.ino===t.ino;let _;let v;const failure=e=>/* @__PURE__ */ new Error(`Cannot install durable OpenClaw ${t.version} for the background service: ${e.stderrTail||e.name}`);const y=n({installTarget:{...u,globalRoot:t.globalRoot,packageRoot:t.packageRoot},installSpec:`openclaw@${t.version}`,requirePackageReplacement:true,packageName:`openclaw`,packageRoot:t.packageRoot,validateCandidate:async e=>{v=identityOf(e);_=identityOf(t.packageRoot);const n=path.join(e,path.relative(t.packageRoot,t.entrypoint));return await fs$1.access(n).then(()=>true,()=>false)?[]:[{name:`durable-cli-entrypoint`,command:`verify ${n}`,cwd:e,durationMs:0,exitCode:1,stderrTail:`The staged copy has no ${path.relative(e,n)}, which the service would run.`}]},runCommand:o,runStep:e=>a({...e,cwd:e.cwd??process.cwd(),runCommand:o,stepIndex:0,totalSteps:0}),timeoutMs:3e4,workTimeoutMs:null,env:l,beforeActivate:async()=>{d.resolve();if(!await f.promise)throw p;const e=identityOf(t.packageRoot);if(e===void 0?_!==void 0:!sameIdentity(e,_))throw new Error(`The durable OpenClaw copy at ${t.packageRoot} changed while this install waited to replace it, probably by another update; nothing was replaced. Rerun the install to replace it with OpenClaw ${t.version}.`)},onTransaction:e=>{m=e;h=identityOf(t.packageRoot)}});const b=await Promise.race([d.promise.then(()=>null),y]);if(b)throw failure(b.failedStep??{name:`the package update stopped before activation`});const unfenced=()=>void 0;const restoreAuthority=e=>()=>{const n=identityOf(t.packageRoot);if(n&&!e.some(e=>sameIdentity(n,e))){g=true;throw new Error(`The durable OpenClaw copy at ${t.packageRoot} was replaced by another install before this failed install could restore it; keeping the current copy.`)}};return{published:()=>m!==void 0,activate:async()=>{f.resolve(true);const e=await y;if(e.failedStep)throw failure(e.failedStep)},cancel:async()=>{f.resolve(false);return await y.then(()=>[],e=>e===p?[]:[`Durable OpenClaw staging cleanup failed: ${String(e)}`])},settle:async e=>{await y.catch(()=>void 0);if(!m)return[];const n=[];if(e===`restore`){const e=restoreAuthority([v,h,identityOf(m.backupRoot)]);const r=await m.rollback(e).catch(e=>{if(!g)throw e});if(g){n.push(`The durable OpenClaw copy at ${t.packageRoot} was replaced by another install before this failed install could restore it; keeping the current copy and the previous copy's backup at ${m.backupRoot}.`);return n}if(r&&r.exitCode!==0)n.push(`Could not restore the previous durable OpenClaw copy: ${r.stderrTail??r.name}`)}const r=await m.complete({activationVerified:e!==`retain`},unfenced);if(r&&r.exitCode!==0)n.push(r.stderrTail??r.name);return n}}}export{isDisposableInstallPath as a,isDisposableEntrypoint as i,formatUserCliCommand as n,resolveDurableServiceBinDir as o,installDurableServiceCli as r,resolveDurableServiceCli as s,DurableServiceCliError as t};