openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
5 lines • 5.98 kB
JavaScript
import{C as isRecord,i as resolveGlobalSingleton,s as hasErrnoCode}from"./global-singleton-CTnqrmaI.js";import{x as resolveIdentityPathViaExistingAncestorSync}from"./runtime-doctor-migrations-D8alsOFs.js";import{i as isPathInside}from"./account-core-34NfXidI.js";import{G as truncateUtf16Safe,t as createSubsystemLogger}from"./subsystem-ovCC_dQD.js";import{t as formatErrorMessage}from"./errors-DKa3Vi4q.js";import fsPromises from"node:fs/promises";import path from"node:path";import os from"node:os";
//!src/infra/non-fatal-cleanup.ts
async function runBestEffortCleanup(e){try{return await e.cleanup()}catch(t){try{e.onError?.(t)}catch{}return}}
//!src/infra/temp-artifact-cleanup.ts
const log=createSubsystemLogger(`infra:temp-artifacts`);const retainedRuntimes=resolveGlobalSingleton(Symbol.for(`openclaw.retainedUpdateRuntimes`),()=>/* @__PURE__ */ new Set);function registerRetainedUpdateRuntime(e){retainedRuntimes.add(e);return()=>void retainedRuntimes.delete(e)}function reportRetainedUpdateRuntime(e,t){const n=`Runtime retained at ${e}: ${t}`;try{log.warn(n)}catch{}return n}function resolveRetainedUpdateRuntimeParents(e,t=[]){const n=e.split(path.sep);const r=n.indexOf(`node_modules`);const i=[n.slice(0,r>=0?r+1:n.length).join(path.sep),...t];let a=path.dirname(e);const o=[a];while(i.some(e=>isPathInside(e,a))){const e=path.dirname(a);if(e===a)break;a=e;o.push(a)}return o}async function isRetainedRuntimeMarker(e){if(await fsPromises.realpath(e).catch(()=>void 0)!==e)return false;const t=JSON.parse(await fsPromises.readFile(e,`utf8`));return isRecord(t)&&t.name===`openclaw`}function projectRetainedSource(e,t){const n=path.parse(t).root;return path.join(e,`tree`,Buffer.from(n).toString(`hex`),path.relative(n,t))}const retainedFileList=`retained-files.json`;const shippedRuntimeEntries=/* @__PURE__ */ new Set([retainedFileList,`tree`,`update-native-gate.mjs`]);async function recognizesShippedRuntime(e){const t=await fsPromises.readdir(e,{withFileTypes:true});if(t.length!==shippedRuntimeEntries.size||!t.every(e=>shippedRuntimeEntries.has(e.name)&&(e.name===`tree`?e.isDirectory():e.isFile())))return false;const n=await fsPromises.open(path.join(e,retainedFileList),`r`);let r;try{const e=Buffer.alloc(65536);const{bytesRead:t}=await n.read(e,0,e.length,0);r=e.toString(`utf8`,0,t)}finally{await n.close()}const i=/^\[("(?:[^"\\]|\\.)*")/u.exec(r)?.[1];const a=i?JSON.parse(i):void 0;return typeof a===`string`&&path.isAbsolute(a)&&path.normalize(a)===a&&path.basename(a)===`package.json`&&await isRetainedRuntimeMarker(projectRetainedSource(e,a))}async function recognizesRetainedRuntime(e,t){const n=projectRetainedSource(e,t);if(await isRetainedRuntimeMarker(path.join(n,`package.json`)))return true;const r=path.dirname(n);const i=path.dirname(r);const a=path.dirname(i);if(path.basename(n)!==`openclaw`||path.basename(r)!==`node_modules`||!path.basename(i).startsWith(`openclaw@`)||path.basename(a)!==`.pnpm`||await fsPromises.realpath(a).catch(()=>void 0)!==a)return false;let o=0;for await(const e of await fsPromises.opendir(a)){if(++o>4096)throw new Error(`retained pnpm version inventory exceeds the bounded lookup; inspect it before manual cleanup`);if(e.isDirectory()&&e.name.startsWith(`openclaw@`)&&await isRetainedRuntimeMarker(path.join(a,e.name,`node_modules/openclaw/package.json`)))return true}return false}async function maintainRetainedUpdateRuntimes(e){const t=[];const n=e.packageRoots.map(resolveIdentityPathViaExistingAncestorSync);const r=new Set([os.tmpdir(),...e.temporaryDirectories??[],...n.flatMap(e=>resolveRetainedUpdateRuntimeParents(e))].map(resolveIdentityPathViaExistingAncestorSync));for(const i of r)try{for(const r of await fsPromises.readdir(i,{withFileTypes:true})){if(!/^openclaw-update-runtime-[A-Za-z0-9]{6}$/u.test(r.name))continue;const a=path.join(i,r.name);try{const r=await fsPromises.lstat(a);if(!r.isDirectory()||process.getuid&&r.uid!==process.getuid())throw new Error(`directory ownership is unknown; inspect it before manual cleanup`);if(retainedRuntimes.has(a))throw new Error(`the creating update still owns this runtime`);let i=false;for(const e of n)if(await recognizesRetainedRuntime(a,e)){i=true;break}i||=await recognizesShippedRuntime(a);if(!i)throw new Error(`it does not match a runtime an OpenClaw updater created, so it is kept`);if(!e.repair){t.push(`Runtime retained at ${a}: run \`openclaw doctor --fix\` after its workers stop`);continue}const{inspectOtherOpenClawProcesses:o}=await import(`./openclaw-process-census-eUZSajw_.js`);const s=await fsPromises.lstat(a);if(s.dev!==r.dev||s.ino!==r.ino||s.ctimeMs!==r.ctimeMs||retainedRuntimes.has(a))throw new Error(`directory identity or custody changed`);e.assertCurrent();const c=o(a);if(`error`in c)throw new Error(c.error);for(const e of c.warnings??[])if(!t.includes(e))t.push(e);if(c.pids.length)throw new Error(`other OpenClaw processes are still running (PIDs: ${c.pids.join(`, `)}); let these holders finish, then rerun openclaw doctor --fix`);e.assertResourcesSettled?.(a);e.assertCurrent();let l;await removeTemporaryArtifacts(a,`Updater runtime`,e=>{l=`cleanup failed: ${formatErrorMessage(e)}`});t.push(l?reportRetainedUpdateRuntime(a,l):`Removed abandoned updater runtime: ${a}`)}catch(e){if(!hasErrnoCode(e,`ENOENT`))t.push(reportRetainedUpdateRuntime(a,formatErrorMessage(e)))}}}catch(e){if(!hasErrnoCode(e,`ENOENT`))t.push(`Cannot inspect updater runtimes in ${i}: ${formatErrorMessage(e)}`)}return t}function removeTemporaryArtifacts(e,t,n=n=>log.warn(truncateUtf16Safe(formatErrorMessage(`${t} cleanup failed; files may remain in ${e}. After the worker or session stops, check permissions and remove the retained directory: ${formatErrorMessage(n)}`),1024))){return runBestEffortCleanup({cleanup:()=>fsPromises.rm(e,{recursive:true,force:true}),onError:n})}export{maintainRetainedUpdateRuntimes,registerRetainedUpdateRuntime,removeTemporaryArtifacts,reportRetainedUpdateRuntime,resolveRetainedUpdateRuntimeParents};