UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3 lines • 9.52 kB
import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import{a as lstatIfExists}from"./path-existence-BR9MXlgL.mjs";import"./path-existence-runtime-BFjuPvea.mjs";import"./state-paths-CQWnUQJM.mjs";import{h as runCrabboxProcess,r as crabboxExecutionError}from"./crabbox-worker-command-DPZFykVB.mjs";import path from"node:path";import{randomUUID}from"node:crypto";import fs from"node:fs/promises"; //!extensions/crabbox/src/crabbox-managed-binary.ts const CRABBOX_MIN_VERSION=`0.83.2`;const CRABBOX_NONBLOCKING_CAPTURE_VERSION=`0.79.0`;const RELEASE_URL=`https://github.com/openclaw/crabbox/releases/download/v${CRABBOX_MIN_VERSION}`;const MAX_ARCHIVE_BYTES=134217728;const VERSION_TIMEOUT_MS=3e4;const DOWNLOAD_IDLE_TIMEOUT_MS=3e4;const DOWNLOAD_TOTAL_TIMEOUT_MS=6e5;function isCrabboxVersionAtLeast(e,t){const[n,r]=[e,t].map(e=>/^(\d+)\.(\d+)\.(\d+)(-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u.exec(e));if(!n||!r)return false;const i=n.slice(1,4).map(Number);const a=r.slice(1,4).map(Number);if([...i,...a].some(e=>!Number.isSafeInteger(e)))return false;const o=i.findIndex((e,t)=>e!==a[t]);return o===-1?!n[4]:i[o]>a[o]}async function probeCrabboxVersion(e,t=runCrabboxProcess,n){n?.throwIfAborted();let r;try{r=await t([e,`--version`],{killProcessTree:true,maxOutputBytes:65536,timeoutMs:VERSION_TIMEOUT_MS,...n?{signal:n}:{}})}catch(e){n?.throwIfAborted();return{status:`indeterminate`,reason:crabboxExecutionError(`version command`,e).message}}n?.throwIfAborted();if(r.termination!==`exit`||r.code!==0||r.outputLimitExceeded)return{status:`indeterminate`,reason:r.outputLimitExceeded?`version output exceeded 64 KiB`:r.termination===`timeout`?`version command timed out after ${VERSION_TIMEOUT_MS} ms`:`version command failed (${r.termination}, code ${r.code??`unknown`})`};const i=/(?:^|\s)v?((\d+)\.(\d+)\.(\d+)(-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)(?:\s|$)/u.exec(`${r.stdout}\n${r.stderr}`);if(!i)return{status:`indeterminate`,reason:`version output was not recognized`};if([Number(i[2]),Number(i[3]),Number(i[4])].some(e=>!Number.isSafeInteger(e)))return{status:`indeterminate`,reason:`version output was not recognized`};return{status:isCrabboxVersionAtLeast(i[1],`0.83.2`)?`supported`:`outdated`,version:i[1]}}function releaseTarget(){const e=process.platform===`win32`?`windows`:process.platform;const t=process.arch===`x64`?`amd64`:process.arch;if(![`darwin`,`linux`,`windows`].includes(e)||![`amd64`,`arm64`].includes(t))throw new Error(`Crabbox has no managed release for ${process.platform}/${process.arch}`);const n=e===`windows`?`zip`:`tar.gz`;return{directory:`${e}-${t}`,executable:e===`windows`?`crabbox.exe`:`crabbox`,asset:`crabbox_${CRABBOX_MIN_VERSION}_${e}_${t}.${n}`,tar:n===`tar.gz`}}function resolveManagedCrabboxBinaryPath(e=process.env){const t=releaseTarget();return path.join(resolveStateDir(e),`tools`,`crabbox`,CRABBOX_MIN_VERSION,t.directory,t.executable)}async function downloadReleaseFile(e,t,n,r){const[{buildTimeoutAbortSignal:i},{fetchWithSsrFGuard:a}]=await Promise.all([import(`./plugin-sdk/extension-shared.js`),import(`./plugin-sdk/ssrf-runtime.js`)]);r.throwIfAborted();const o=i({timeoutMs:DOWNLOAD_TOTAL_TIMEOUT_MS,signal:r,operation:`crabbox-release-download`});const{response:s,release:c,refreshTimeout:l}=await a({url:`${RELEASE_URL}/${t}`,requireHttps:true,timeoutMs:DOWNLOAD_IDLE_TIMEOUT_MS,signal:o.signal,policy:{hostnameAllowlist:[`github.com`,`release-assets.githubusercontent.com`]},auditContext:`crabbox-managed-release`}).catch(e=>{o.cleanup();throw e});try{if(!s.ok)throw new Error(`Crabbox release download failed for ${t} (HTTP ${s.status})`);if(Number(s.headers.get(`content-length`))>n)throw new Error(`Crabbox release file ${t} exceeds ${n} bytes`);if(!s.body)throw new Error(`Crabbox release file ${t} has no response body`);const r=s.body;const i=384&~process.umask();await e.create(t,(async function*(){for await(const e of r.values({preventCancel:true})){o.signal?.throwIfAborted();if(e.byteLength>0){l?.();yield e}}})(),{maxBytes:n,signal:o.signal,mode:i,durable:false,mkdir:false})}finally{o.cleanup();await s.body?.cancel().catch(()=>void 0);await c()}}async function probeInstallation(e,t,n){if(!(await lstatIfExists(e,`ENOENT`))?.isFile())return;const r=await probeCrabboxVersion(e,t,n);return r.status===`supported`?{binary:e,version:r.version}:void 0}async function findManagedCrabboxBinary(e={}){const t=e.runCommand??((t,n)=>runCrabboxProcess(t,{...n,baseEnv:e.env}));const n=resolveManagedCrabboxBinaryPath(e.env);if(await inspectInstallationDirectory(path.dirname(n)))return probeInstallation(n,t,e.signal)}async function inspectInstallationDirectory(e){const t=await lstatIfExists(e,`ENOENT`);if(!t)return;if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Managed Crabbox destination must be a regular directory: ${e}`);return t}async function installManagedBinary(e,t,n){const r=path.dirname(e);await inspectInstallationDirectory(r);const i=path.dirname(r);await fs.mkdir(i,{recursive:true,mode:448});const a=await fs.mkdtemp(path.join(i,`.install-`));try{const{root:i,sha256File:o}=await import(`./plugin-sdk/file-access-runtime.js`);const s=await i(a);const c=releaseTarget();await downloadReleaseFile(s,`checksums.txt`,65536,n);const l=(await s.readText(`checksums.txt`,{maxBytes:65536})).split(/\r?\n/u).flatMap(e=>{const t=/^([a-fA-F0-9]{64})\s+\*?(\S+)\s*$/u.exec(e);return t?.[2]===c.asset?[t[1].toLowerCase()]:[]});if(l.length!==1)throw new Error(`Crabbox release checksums must contain exactly one entry for ${c.asset}`);await downloadReleaseFile(s,c.asset,MAX_ARCHIVE_BYTES,n);const u=path.join(a,c.asset);if((await o(u,{maxBytes:MAX_ARCHIVE_BYTES,signal:n})).digest!==l[0])throw new Error(`Crabbox release checksum mismatch for ${c.asset}`);const{extractArchive:d}=await import(`./plugin-sdk/archive.js`);n.throwIfAborted();const f=path.join(a,`distribution`);await fs.mkdir(f,{mode:448});await d({archivePath:u,destDir:f,kind:c.tar?`tar`:`zip`,tarGzip:c.tar,timeoutMs:0,limits:{maxArchiveBytes:MAX_ARCHIVE_BYTES,maxEntries:128,maxExtractedBytes:536870912,maxEntryBytes:268435456},entryFilter:e=>e.kind===`file`||e.kind===`directory`?`extract`:`skip`,onFiltered:`reject-archive`});const p=await probeInstallation(path.join(f,c.executable),t,n);if(!p)throw new Error(`Downloaded Crabbox executable does not satisfy ${CRABBOX_MIN_VERSION}`);const m=p.version;async function publishInstallation(){const{withFileLock:i}=await import(`./plugin-sdk/file-lock.js`);n.throwIfAborted();return i(`${r}.publication`,{retries:{retries:100,factor:1,minTimeout:100,maxTimeout:100},stale:12e4,staleRecovery:`remove-if-definitely-stale`},async()=>{n.throwIfAborted();const i=await inspectInstallationDirectory(r);const a=i?await probeInstallation(e,t,n):void 0;if(a)return a;n.throwIfAborted();const o=i?`${r}.recovery-${randomUUID()}`:void 0;if(o)await fs.rename(r,o);try{n.throwIfAborted();await fs.rename(f,r);return{binary:e,version:m}}catch(e){if(o)throw new Error(`Crabbox publication failed; previous installation is preserved at ${o}`,{cause:e});throw e}})}return await publishInstallation()}finally{await fs.rm(a,{recursive:true,force:true})}}function describeRejectedProbe(e){if(e.status===`outdated`)return`probe status "outdated": version ${e.version} is older than the required ${CRABBOX_MIN_VERSION}`;return`probe status "indeterminate": ${e.reason.length>200?`${e.reason.slice(0,200)}…`:e.reason}`}const acquisitions=/* @__PURE__ */ new Map;async function ensureManagedCrabboxBinary(e={}){const{signal:t}=e;const n=e.runCommand??((t,n)=>runCrabboxProcess(t,{...n,baseEnv:e.env,cwd:e.cwd}));const r=e.binary??`crabbox`;const i=resolveManagedCrabboxBinaryPath(e.env);if(path.resolve(e.cwd??`.`,r)===i)await inspectInstallationDirectory(path.dirname(i));const a=await probeCrabboxVersion(r,n,t);if(a.status===`supported`)return{binary:r,version:a.version};const report=(e,t=`managed`)=>({...e,rejected:`Crabbox configured binary "${r}" was not used (${describeRejectedProbe(a)}); using ${t} binary "${e.binary}" (${e.version}) instead.`});const o=e.fallbackBinary;if(o&&o!==r&&path.resolve(e.cwd??`.`,o)!==i){const e=await probeCrabboxVersion(o,n,t);if(e.status===`supported`)return report({binary:o,version:e.version},`current deployed`)}const s=await findManagedCrabboxBinary({env:e.env,runCommand:n,signal:t});if(s)return report(s);const{toErrorObject:c}=await import(`./plugin-sdk/error-runtime.js`);t?.throwIfAborted();let l=acquisitions.get(i);if(l?.controller.signal.aborted){await l.promise.catch(()=>void 0);t?.throwIfAborted();l=acquisitions.get(i)}if(!l){const e=new AbortController;l={controller:e,waiters:0,promise:installManagedBinary(i,n,e.signal)};acquisitions.set(i,l);const t=l;l.promise.finally(()=>{if(acquisitions.get(i)===t)acquisitions.delete(i)}).catch(()=>void 0)}const u=l;u.waiters+=1;let d=true;const leave=()=>{if(d){d=false;u.waiters-=1;if(u.waiters===0)u.controller.abort()}};let abandon=()=>{};const f=new Promise((e,n)=>{abandon=()=>{leave();if(u.waiters>0)n(c(t?.reason,`Crabbox acquisition aborted`))}});t?.addEventListener(`abort`,abandon,{once:true});if(t?.aborted)abandon();try{const e=await Promise.race([u.promise,f]);t?.throwIfAborted();return report(e)}catch(e){t?.throwIfAborted();throw e}finally{t?.removeEventListener(`abort`,abandon);leave()}}export{isCrabboxVersionAtLeast as a,findManagedCrabboxBinary as i,CRABBOX_NONBLOCKING_CAPTURE_VERSION as n,probeCrabboxVersion as o,ensureManagedCrabboxBinary as r,resolveManagedCrabboxBinaryPath as s,CRABBOX_MIN_VERSION as t};