UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

4 lines • 13.9 kB
import{r as terminalText}from"./safe-text-B_QTgn0s.mjs";import{d as shortenHomeInString,f as shortenHomePath,u as resolveHomeDir}from"./utils-Dlk0IYAa.mjs";import{s as movePathToTrash}from"./fs-safe-Bxzu1j4h.mjs";import{i as isMissingPathError}from"./errno-DUBt6SQQ.mjs";import{i as realpathViaExistingPrefix}from"./path-containment-Drv7Ulmz.mjs";import{v as resolveGatewayLockDir}from"./paths-D_FOvGon.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{i as listAgentIds}from"./agent-roster-4XrgUgPK.mjs";import{f as resolveAgentWorkspaceDir}from"./agent-scope-config-CG9CFpGX.mjs";import{f as resolveIdentityPathViaExistingAncestorSync,o as pathEntryExists}from"./path-existence-BR9MXlgL.mjs";import{t as resolveDefaultAgentWorkspaceDir}from"./workspace-default-path-ULYbn-EL.mjs";import"./workspace-default-Cb7cQoAN.mjs";import{s as resolveOpenClawStateSqlitePath}from"./openclaw-state-db.paths-CbgXfEg1.mjs";import{_ as prepareOpenClawStateDatabaseRemoval}from"./openclaw-state-db-cache-uycu-8uy.mjs";import{n as GatewayLockError,r as acquireGatewayLock}from"./gateway-lock-CQoO1usb.mjs";import{l as prepareLegacyWorkspaceStateReset,u as removeLegacyWorkspaceStateForReset}from"./workspace-legacy-state-oyST33uM.mjs";import{i as prepareWorkspaceStateDeletion,n as deleteWorkspaceState}from"./workspace-state-store-o0DidR-W.mjs";import{l as removeCompletionRegistrations}from"./completion-runtime-BnR_i8hK.mjs";import path from"node:path";import fs from"node:fs/promises";import{hasNodeErrorCode,isPathInside}from"@openclaw/fs-safe/path"; //!src/commands/cleanup-utils.ts const STATE_CLEANUP_LOCK_TIMEOUT_MS=250;const STATE_CLEANUP_LOCK_POLL_INTERVAL_MS=25;function trashFailure(e,t,n){n.log(`Failed to move to Trash (manual delete): ${shortenHomePath(e)}`);return{failed:{path:e,reason:formatErrorMessage(t)}}}async function moveToTrashResult(e,t,n,r){if(!e)return{failed:{path:e,reason:`path is empty`}};let i;try{i=(await fs.lstat(e)).isSymbolicLink()}catch(n){return isMissingPathError(n)?{removed:{path:e,method:`missing`}}:trashFailure(e,n,t)}try{const a=await resolveMoveToTrashSourcePath(path.resolve(e));const o=trashAllowedRoots([a],i?await fs.realpath(a).catch(()=>void 0):void 0);if(r)await r();n?.();await movePathToTrash(a,{allowedRoots:o});t.log(`Moved to Trash: ${shortenHomePath(e)}`);return{removed:{path:e,method:`trash`}}}catch(n){return trashFailure(e,n,t)}}async function moveToTrash(e,t,n,r){return`removed`in await moveToTrashResult(e,t,n,r)}function trashAllowedRoots(e,t){const n=e.map(e=>path.dirname(e));if(t!==void 0)n.push(path.dirname(t));return[...new Set(n)]}async function resolveMoveToTrashSourcePath(e){return path.join(await fs.realpath(path.dirname(e)),path.basename(e))}function buildCleanupPlan(e){const t=e.cfg;return{configInsideState:isPathInside(e.stateDir,e.configPath),oauthInsideState:isPathInside(e.stateDir,e.oauthDir),workspaceDirs:t?[...new Set(listAgentIds(t).map(e=>resolveAgentWorkspaceDir(t,e)))]:[resolveDefaultAgentWorkspaceDir()]}}function isUnsafeRemovalTarget(e){if(!e.trim())return true;const t=path.resolve(e);if(t===path.parse(t).root)return true;const n=resolveHomeDir();return Boolean(n&&t===path.resolve(n))||isPathInside(t,path.resolve(process.cwd()))}async function removePath(e,t,n){return removePathPreserving(e,[],t,n)}async function existingPaths(e){const t=[];for(const n of e){if(!n?.trim())continue;const e=path.resolve(n);try{await fs.lstat(e);t.push(e)}catch(e){if(!isMissingPathError(e))throw e}}return t}async function acquireStateCleanupOwnership(e){const t={...process.env,OPENCLAW_CONFIG_PATH:e.configPath,OPENCLAW_STATE_DIR:e.stateDir};let n;try{n=await acquireGatewayLock({allowInTests:true,env:t,pollIntervalMs:STATE_CLEANUP_LOCK_POLL_INTERVAL_MS,role:`sqlite-maintenance`,timeoutMs:STATE_CLEANUP_LOCK_TIMEOUT_MS})}catch(e){if(e instanceof GatewayLockError)throw new Error(`Cannot remove OpenClaw state while the Gateway or another state maintenance command owns this state directory. Stop the Gateway and retry.`,{cause:e});throw e}if(!n)throw new Error(`Cannot remove OpenClaw state without exclusive state ownership.`);return n}async function withStateCleanupOwnership(e,t,n){if(t)return n();const r=await acquireStateCleanupOwnership(e);try{return await r.run(()=>n(r))}finally{await r.release()}}async function removePathPreserving(e,t,n,r){if(!e?.trim())return{ok:false};const i=path.resolve(e);const a=r?.label??i;const o=shortenHomeInString(a);if(isUnsafeRemovalTarget(i)){n.error(`Refusing to remove unsafe path: ${o}`);return{ok:false}}if(t.some(e=>isPathInside(e,i)))return{ok:true};const s=t.filter(e=>isPathInside(i,e));if(r?.dryRun){const e=s.length?` preserving ${s.map(e=>shortenHomeInString(e)).join(`, `)}`:``;n.log(`[dry-run] remove ${o}${e}`);return{ok:true}}try{if(s.length>0&&(await fs.lstat(i)).isDirectory()){for(const e of await fs.readdir(i)){const r=await removePathPreserving(path.join(i,e),t,n);if(!r.ok)return r}n.log(`Removed contents of ${o}`)}else{const e=await pathEntryExists(i);await fs.rm(i,{recursive:true,force:true});n.log(e?`Removed ${o}`:`Not found: ${o}`)}return{ok:true}}catch(e){n.error(`Failed to remove ${o}: ${String(e)}`);return{ok:false}}}async function removeStateDirectoryAlias(e,t,n){if(e===t)return;try{if((await fs.lstat(e)).isSymbolicLink()){n();await fs.unlink(e)}}catch(e){if(!hasNodeErrorCode(e,`ENOENT`))throw e}}function stateCleanupInterrupted(){return/* @__PURE__ */ new Error(`OpenClaw state cleanup was interrupted by a new state operation. Stop other OpenClaw commands and retry.`)}async function captureStateCleanupAncestors(e,t){const n=/* @__PURE__ */ new Map;for(const r of e)for(let e=r;isPathInside(t,e);e=path.dirname(e)){if(!n.has(e)){const t=await fs.lstat(e,{bigint:true});if(!t.isDirectory())throw new Error(`Cannot remove OpenClaw state because its active lock directory is redirected or not a real directory: ${shortenHomeInString(e)}. Restore a real lock directory and retry.`);n.set(e,{path:e,dev:t.dev,ino:t.ino})}if(e===t)break}return[...n.values()].toSorted((e,t)=>t.path.length-e.path.length)}async function removeEmptyStateAncestors(e){for(const t of e)try{const e=await fs.lstat(t.path,{bigint:true});if(!e.isDirectory()||e.dev!==t.dev||e.ino!==t.ino)throw stateCleanupInterrupted();await fs.rmdir(t.path)}catch(e){if([`ENOENT`,`ENOTEMPTY`,`EEXIST`].some(t=>hasNodeErrorCode(e,t)))continue;throw e}}function linkedCleanupPaths(e){return[e.configInsideState?void 0:e.configPath,e.oauthInsideState?void 0:e.oauthDir].filter(e=>e!==void 0)}async function resolveStateCleanupLockPaths(e){return Promise.all([.../* @__PURE__ */ new Set([e.lockPath,e.stateLockPath])].map(resolveMoveToTrashSourcePath))}async function resolveLinkedCleanupPath(e,t){if(!await pathEntryExists(e))return;const n=await resolveMoveToTrashSourcePath(path.resolve(e));if(t.some(e=>isPathInside(n,e)))throw new Error(`Cannot remove linked cleanup path ${shortenHomeInString(e)} because it contains an active state lock. Move the linked path outside the lock directory and retry.`);return n}async function removeLinkedCleanupPaths(e,t,n,r){for(const i of linkedCleanupPaths(e)){const e=await resolveLinkedCleanupPath(i,n);r();if(e&&!(await removePath(e,t,{label:i})).ok)throw new Error(`Failed to remove linked cleanup path: ${shortenHomeInString(i)}`)}}async function preservedRemovalEntries(e,t){return(await Promise.all(e.map(async e=>{const t=await realpathViaExistingPrefix(path.dirname(e));if(!t)throw new Error(`Cannot verify preserved path ${shortenHomeInString(e)}. Fix the path or its parent folder and retry.`);return path.join(t,path.basename(e))}))).filter(e=>isPathInside(t,e))}async function removeStateAndLinkedPaths(e,t,n){const r=path.resolve(e.stateDir);const i=n?.dryRun?(n.preservePaths??[]).map(e=>path.resolve(e)):await existingPaths(n?.preservePaths??[]);if(n?.dryRun){const a=resolveIdentityPathViaExistingAncestorSync(r);const o=await preservedRemovalEntries(i,a);if(n.removeCompletionHooks)for(const e of await removeCompletionRegistrations({stateDirs:[.../* @__PURE__ */ new Set([r,a])],preservePaths:[.../* @__PURE__ */ new Set([...o,...i])],dryRun:true}))t.log(terminalText`[dry-run] remove completion registration from ${shortenHomeInString(e)}`);let s=(await removePathPreserving(o.length>0?a:e.stateDir,o,t,{dryRun:true,label:e.stateDir})).ok;for(const n of linkedCleanupPaths(e)){const e=await removePath(n,t,{dryRun:true,label:n});s&&=e.ok}return s}if(isUnsafeRemovalTarget(r)){t.error(`Refusing to remove unsafe path: ${shortenHomeInString(e.stateDir)}`);return false}const a=await acquireStateCleanupOwnership(e);let o=true;let s;const releaseLock=async()=>{if(!o)return;o=false;await a.release()};const releaseRemovalAdmission=()=>{const e=s;s=void 0;e?.release()};try{const o=a.stateDir;if(isUnsafeRemovalTarget(o))throw new Error(`Refusing to remove unsafe path: ${shortenHomeInString(o)}`);const c=await resolveStateCleanupLockPaths(a);const l=[...new Set(c.map(e=>path.dirname(e)))];for(const t of linkedCleanupPaths(e))await resolveLinkedCleanupPath(t,c);a.assertCurrent();const u=resolveOpenClawStateSqlitePath({...process.env,OPENCLAW_STATE_DIR:o});if(resolveIdentityPathViaExistingAncestorSync(u)!==u)throw new Error(`Cannot remove OpenClaw state because its active database path is redirected. Select the actual state directory before retrying cleanup.`);const d=await captureStateCleanupAncestors([...l,path.dirname(a.stateLockPath),...process.platform===`win32`?[]:[resolveGatewayLockDir(o)]],o);a.assertCurrent();const f=await a.run(()=>prepareOpenClawStateDatabaseRemoval(u,a.assertCurrent));s=f;const p=await preservedRemovalEntries(i,o);const m=p.find(e=>l.some(t=>isPathInside(t,e)||isPathInside(e,t)));if(m)throw new Error(`Cannot remove OpenClaw state while preserving ${shortenHomeInString(m)} because it overlaps the active state lock. Move the workspace outside the lock directory and retry.`);if(n?.removeCompletionHooks)for(const e of await removeCompletionRegistrations({stateDirs:[.../* @__PURE__ */ new Set([r,o])],preservePaths:[...p,...p.map(e=>path.join(r,path.relative(o,e)))],assertCurrent:()=>f.assertCurrent()}))t.log(terminalText`Removed completion registration from ${shortenHomeInString(e)}`);f.assertCurrent();if(!(await removePathPreserving(o,[...p,...c],t,{label:e.stateDir})).ok)throw new Error(`Failed to remove non-preserved OpenClaw state while ownership was held.`);s.assertCurrent();await removeLinkedCleanupPaths(e,t,c,a.assertCurrent);if(p.length===0){s.assertCurrent();await removeStateDirectoryAlias(r,o,a.assertCurrent)}s.assertCurrent();await releaseLock();await removeEmptyStateAncestors(d);if((await Promise.all([...c,...l.filter(e=>isPathInside(o,e))].map(pathEntryExists))).some(Boolean)||p.length===0&&await pathEntryExists(o))throw stateCleanupInterrupted();return true}finally{try{releaseRemovalAdmission()}finally{await releaseLock()}}}async function removeWorkspaceDirs(e,t,n){if(!n?.retainedState||n.dryRun)return removeWorkspaceEntries(e,t,n);const r=await acquireStateCleanupOwnership(n.retainedState);try{return await r.run(()=>removeWorkspaceEntries(e,t,n))}finally{await r.release()}}async function removeWorkspaceEntries(e,t,n){const r=/* @__PURE__ */ new Set;const attempt=async(e,n)=>{try{return await n()}catch(n){r.add(e);t.error?.(`Failed to clean up ${shortenHomeInString(e)}: ${String(n)}`);return}};for(const i of e){const e=`${i} (retired workspace state)`;const a=`${i} (workspace state)`;const o=await attempt(e,()=>prepareLegacyWorkspaceStateReset(i));const s=n?.removeStateRows?await attempt(a,()=>prepareWorkspaceStateDeletion(i)):void 0;if(!(n?.preserveWorkspace?{ok:true}:n?.removeWorkspace?{ok:await attempt(i,()=>n.removeWorkspace(i))===true}:await removePath(i,t,{dryRun:n?.dryRun,label:i})).ok){r.add(i);continue}if(o){const i=await attempt(e,()=>removeLegacyWorkspaceStateForReset(o,n?.dryRun?{dryRun:true}:void 0));if(i){if(n?.dryRun)for(const e of i.removedPaths)t.log(`[dry-run] remove ${shortenHomeInString(e)}`);for(const e of i.warnings){(n?.removeWorkspace?t.log:t.error)(e);r.add(e)}}}if(!n?.dryRun&&s)await attempt(a,()=>deleteWorkspaceState(s))}return[...r]}async function removeAgentSessions(e,t){await withStateCleanupOwnership(e,false,()=>removeAgentSessionStores(e.cfg,t,false))}async function removeConfigCredentialsAndSessions(e,t,{dryRun:n}){return withStateCleanupOwnership(e,n,async r=>{const i=r?await resolveStateCleanupLockPaths(r):[];let a=true;try{await removeAgentSessionStores(e.cfg,t,n)}catch(e){t.error(`Failed to reset session history: ${String(e)}`);a=false}for(const o of[e.configPath,e.oauthDir]){let e=o;if(r){try{e=await resolveLinkedCleanupPath(o,i)??o}catch(e){t.error(`Failed to remove ${shortenHomeInString(o)}: ${String(e)}`);a=false;continue}r.assertCurrent()}const s=await removePath(e,t,{dryRun:n,label:o});a&&=s.ok}return a})}async function removeAgentSessionStores(e,t,n){const{previewSessionStoreReset:r,resetSessionStore:i}=await import(`./session-accessor.sqlite-reset-D0flO4W1.mjs`);const{resolveAllAgentSessionStoreTargetsSync:a}=await import(`./targets-C8LX-ajf.mjs`);const o=[];for(const s of a(e))try{const e=r(s);const a=shortenHomePath(e.databasePath);if(n){t.log(`[dry-run] remove session history from ${a}: ${e.sessionKeys.length} sessions, ${e.transcriptCount} transcripts, ${e.archiveCount} retained archives`);for(const n of e.sessionKeys)t.log(`[dry-run] remove session ${n}`);for(const n of e.artifactPaths)t.log(`[dry-run] remove ${shortenHomePath(n)}`)}else{await i(s);t.log(`Removed session history from ${a}`)}}catch(e){o.push(`${shortenHomePath(s.storePath)}: ${String(e)}`)}if(o.length>0)throw new Error(o.join(` `))}export{removeConfigCredentialsAndSessions as a,removeWorkspaceDirs as c,removeAgentSessions as i,trashAllowedRoots as l,moveToTrash as n,removePath as o,moveToTrashResult as r,removeStateAndLinkedPaths as s,buildCleanupPlan as t};