openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
7 lines • 24.9 kB
JavaScript
import{i as collectNestedErrorCandidates,s as formatErrorMessage}from"./error-coercion-DlKnt6w-.mjs";import{t as settlesWithin}from"./settle-within-DXfRNkao.mjs";import{r as isPathInside}from"./path-guards-DGttsOJI.mjs";import{t as FsSafeError,x as root}from"./fs-safe-Bxzu1j4h.mjs";import{i as isMissingPathError}from"./errno-DUBt6SQQ.mjs";import{t as formatErrorMessage$1}from"./errors-D37BJTfI.mjs";import{N as parseAgentSessionKey,g as toAgentStoreSessionKey}from"./session-key-BPgKfU2m.mjs";import{p as tryResolveSoleAgentId}from"./agent-roster-4XrgUgPK.mjs";import{l as resolveSessionStorePathCore,u as resolveSessionTranscriptsDirForAgent}from"./paths-CcxgiC3g.mjs";import{D as tryResolveAgentOperationAgentId,F as resolveRegisteredAgentIdForDir,L as unregisterResolvedAgentDir,N as normalizeAgentDirRegistryPath,a as resolveAgentDir,f as resolveAgentWorkspaceDir,z as resolvePersistedSessionStoreOwnerForKey}from"./agent-scope-config-CG9CFpGX.mjs";import{i as isSqliteWorkerError,r as hasSqliteWorkerOutcomeUnknown}from"./sqlite-worker-error-DHUQ0e2U.mjs";import{a as WorkerTaskError}from"./src-D4Y-r8_m.mjs";import"./worker-task-pool-Bg54sSAN.mjs";import"./agent-scope-Dw5XRSEh.mjs";import{l as readConfigFileSnapshotForWrite}from"./io.runtime-BvSeVFIY.mjs";import{f as readAgentDeletionJournalAsync}from"./agent-deletion-journal-Dee50E62.mjs";import{b as resolveAuthProfileDatabasePath}from"./sqlite-y_WDH-Xr.mjs";import{d as resolveSharedAuthStorePath,l as resolveSharedAuthStoreOwnership,o as prepareSharedAuthStoreOwnership}from"./path-resolve-TSS6dv07.mjs";import{t as retryAsync}from"./retry-DH5OEIsj.mjs";import{t as AgentDeletionPendingError}from"./session-agent-work-admission-B6_Seo2R.mjs";import{c as AgentDeletionAuthorityRollbackError,l as AgentDeletionCommitUncertainError,r as withAgentDeletion,s as claimCompletedAgentDeletion}from"./agent-lifecycle-registry-CT_mqsZ8.mjs";import{a as createAgentRunDirectAbortError}from"./run-termination-vr_m9wT0.mjs";import{dt as SESSION_CONTROLLER_DRAIN_TIMEOUT_MS,t as activeSessionOperations}from"./session-controller.state-BIDbpLPn.mjs";import{a as readSessionEntrySummariesInWorker}from"./session-entry-read-runtime-kAgwDw0B.mjs";import{J as startAgentWorkAdmissionInterruption,K as closeAgentWorkAdmissions,q as collectActiveAgentSessionWorkAdmissions}from"./session-controller.lifecycle-M3NLAkoz.mjs";import{h as nativeAttemptAttachments}from"./run-state-Bd0P0LYH.mjs";import{a as resolveSessionStoreIdentity}from"./session-store-key-DZXBwthg.mjs";import{s as withConfigMutationExclusive}from"./mutate-DcH8aT_4.mjs";import"./config-DkZ8y8Gv.mjs";import{t as purgeAgentSessionStoreEntries}from"./sessions-DQD7zQ95.mjs";import{a as getRpcSourceIdentity,v as listRpcSourceEntries}from"./session-controller.rpc-sources-IDCkO6sT.mjs";import{t as chatRunBelongsToAgent}from"./chat-run-owner-7fxQMRQN.mjs";import{t as runTasksWithConcurrency}from"./run-with-concurrency-BX7H2nwl.mjs";import{r as drainAgentExecProcesses}from"./bash-process-control-ByEEGn0n.mjs";import{p as withAgentExecApprovalsRemoved}from"./exec-approvals-store-CKqFK0Id.mjs";import"./exec-approvals-BLANskJu.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{d as listAgentSessionMcpRuntimeIds,m as retireSessionMcpRuntimeForAgentDeletion}from"./mcp-app-model-context-DcetPZR0.mjs";import{l as trashAllowedRoots}from"./cleanup-utils-OK0KVVTl.mjs";import{a as captureEmbeddedRunDrainTarget}from"./runs-CZphmRD3.mjs";import{t as movePathToTrash}from"./browser-trash-mAYTFZju.mjs";import{t as cleanupBrowserSessionsForLifecycleEnd}from"./browser-lifecycle-cleanup-CqXkytsC.mjs";import{i as isSharedAuthStoreOwner,n as formatSharedAuthStoreOwnerDeleteError,r as isInheritedAuthStoreOwner}from"./agent-delete-safety-tdYvLPcq.mjs";import{a as prepareAgentDeleteDatabases,c as resolveSurvivingDatabaseFilePaths,i as isPathOwnedBySurvivingAgent,l as retireAgentDeleteRuntime,n as drainAgentDeleteDatabaseWork,o as prepareJournaledAgentDirOwnership,r as finishAgentDeleteDatabases,s as readAgentDeleteDatabaseRegistry,t as assertAgentSessionStoreDeletionSafe}from"./agent-delete-databases-D3LWY7Ss.mjs";import{a as isConfiguredAgent,i as deleteAgentConfigEntry,t as AgentConfigPreconditionError}from"./agents-config-mutations-B1OB9dKQ.mjs";import{n as prepareSessionLifecycleDrain}from"./sessions-lifecycle-drain-wHfd8Oa5.mjs";import path from"node:path";import fs from"node:fs/promises";import os from"node:os";import{resolvePathPrefixSync}from"@openclaw/fs-safe/advanced";
//!src/gateway/server-methods/agents-delete-drain.ts
async function drainAgentDeletionRuns(e,t,n,r){let i=false;const assertCurrent=()=>{r();if(i)throw new Error(`Agent ${e} deletion drain has ended`)};assertCurrent();const a=resolveSessionStorePathCore(t.session?.store,{agentId:e});const o=tryResolveAgentOperationAgentId(t);const s=collectActiveAgentSessionWorkAdmissions({agentId:e});const c=[];const l=/* @__PURE__ */ new Set;const u=/* @__PURE__ */ new Map;const add=(r,i,c=a,l)=>{const d=resolveSessionStoreIdentity({cfg:t,sessionKey:r,agentId:e}).canonicalKey;const f=[.../* @__PURE__ */ new Set([r,d])];const p=[...s].find(([e,t])=>!e.startsWith(`agent:`)&&(f.some(e=>t.has(e))||Boolean(i&&t.has(i))))?.[0]??c;const m=JSON.stringify(i?[`session`,i]:[`key`,p,d]);const h=u.get(m);const g=[.../* @__PURE__ */ new Set([...f,...h?.sessionKeys??[]])];u.set(m,{action:`delete`,authorize:assertCurrent,context:n,storePath:p,agentId:e,defaultAgentId:o,sessionKey:d,sessionKeys:g,sessionId:i,session:l?{ok:true,value:{cfg:t,storePath:p,entry:l,canonicalKey:d,agentId:e}}:h?.session,lifecycleIdentities:i?[...g,i]:g})};const addOwned=t=>{if(t?.sessionKey&&chatRunBelongsToAgent({...t,defaultAgentId:o},e))add(t.sessionKey,t.sessionId)};const d=[];try{for(const t of nativeAttemptAttachments()){if(t.operation||t.sessionKey)continue;const n=captureEmbeddedRunDrainTarget(t,{agentId:e,defaultAgentId:o});if(n){c.push(n);l.add(n.sessionId)}}for(const e of activeSessionOperations())addOwned({agentId:e.agentId,sessionKey:e.key,sessionId:e.sessionId});for(const[,e]of listRpcSourceEntries())addOwned(getRpcSourceIdentity(e));for(const[t,n]of s)for(const r of n)if(parseAgentSessionKey(r)?.agentId===e)add(r,void 0,t.startsWith(`agent:`)?a:t);for(const{sessionKey:n,entry:r}of await readSessionEntrySummariesInWorker({agentId:e,storePath:a})){const i=resolvePersistedSessionStoreOwnerForKey(t,n);if((parseAgentSessionKey(n)?.agentId??(i.kind===`none`?e:i.agentId))===e)add(n,r.sessionId,a,r)}const r=[...u.values()].filter(e=>e.sessionId);for(const[e,t]of u){if(t.sessionId)continue;const n=r.filter(e=>e.sessionKeys.some(e=>t.sessionKeys.includes(e)));for(const e of n){e.sessionKeys=[.../* @__PURE__ */ new Set([...e.sessionKeys,...t.sessionKeys])];e.lifecycleIdentities=[.../* @__PURE__ */ new Set([...e.lifecycleIdentities,...t.lifecycleIdentities])]}if(n.length)u.delete(e)}assertCurrent();const f=c.map(async e=>{assertCurrent();e.abort();if(!await e.waitForEnd(15e3))throw new Error(`Embedded run in session ${e.sessionId} did not end. Wait for the run to end, then retry agents.delete; agent storage has been preserved.`)});const p=new Set(u.values());const m=[];const h=runTasksWithConcurrency({limit:4,onTaskError:e=>m.push(e),tasks:[...p].map(t=>async()=>{assertCurrent();const n=await prepareSessionLifecycleDrain({...t,onPrepared:()=>p.delete(t)});if(i){n.release();return}d.push(n);if(n.hasAuthoritativeWork())throw new Error(`Agent ${e} still has active work in ${t.sessionKey}`)})});const g=Promise.resolve().then(()=>{assertCurrent();return startAgentWorkAdmissionInterruption({agentId:e,assertCurrent,reason:createAgentRunDirectAbortError()}).released});const _=Promise.resolve().then(async()=>{const t=n.terminalSessions?.beginAgentSessionDrain(e,assertCurrent);try{await t?.drained}finally{t?.release()}});const v=await settlesWithin(Promise.all([h,g,...f,_].map(e=>e.catch(e=>{m.push(e)}))),SESSION_CONTROLLER_DRAIN_TIMEOUT_MS);if(m.length===1)throw m[0];if(m.length>1)throw new AggregateError(m,`Agent ${e} deletion failed: ${[...new Set(m.map(e=>formatErrorMessage(e)))].join(`; `)}`);if(!v){if(p.size)throw new Error(`Agent ${e} deletion preparation timed out for sessions: ${[...p].map(e=>e.sessionKey).join(`, `)}. Check session placement availability, then retry agents.delete; agent storage has been preserved.`);throw new Error(`Agent ${e} deletion is still draining active work for sessions: ${[...u.values()].map(e=>e.sessionId??e.sessionKey).concat(c.filter(e=>e.isActive()).map(e=>e.sessionId)).join(`, `)}. Wait for active work to end, then retry agents.delete; agent storage has been preserved.`)}await drainAgentExecProcesses(e,assertCurrent);for(const t of listAgentSessionMcpRuntimeIds(e))l.add(t);for(const e of u.values())if(e.sessionId)l.add(e.sessionId);for(const t of l)await retireSessionMcpRuntimeForAgentDeletion({sessionId:t,agentId:e,assertCurrent});await cleanupBrowserSessionsForLifecycleEnd({cfg:t,sessionKeys:[...u.values()].flatMap(e=>e.sessionKeys).map(t=>toAgentStoreSessionKey({agentId:e,requestKey:t})),isCurrent:()=>{assertCurrent();return true},onWarn:e=>n.logGateway.warn(e)});assertCurrent()}finally{i=true;for(const e of c)e.release();for(const e of d)e.release()}}
//!src/gateway/server-methods/agents-delete-filesystem.ts
var AgentCleanupIdentityMismatchError=class extends Error{};function cleanupFailure(e,t){return{failed:{path:e,reason:(t instanceof Error&&t.message?t.message:String(t))||`unknown error`}}}function cleanupPathIdentity(e){return e?{dev:e.dev.toString(),ino:e.ino.toString()}:null}function cleanupPathIdentityMatches(e,t){if(typeof t!==`number`)return e===t;const n=BigInt(e);return Number.isInteger(t)&&Number(n<0n?BigInt.asUintN(64,n):n)===t}async function statAgentCleanupPath(e){const t=e.parentPath;const n=await root(t,{hardlinks:`reject`,symlinks:`reject`});if(path.resolve(n.rootReal)!==t)throw new FsSafeError(`path-mismatch`,`cleanup path parent changed before deletion`);const r=await n.stat(path.basename(e.trashPath));if(r.isSymbolicLink!==(e.kind===`symlink`))throw new AgentCleanupIdentityMismatchError(`cleanup path changed from ${e.kind} before deletion`);if(r.isFile&&r.nlink>1)throw new AgentCleanupIdentityMismatchError(`hardlinked cleanup replacement preserved`);if(!r.exactIdentity)throw new AgentCleanupIdentityMismatchError(`cleanup path exact identity is unavailable`);const i=cleanupPathIdentity(r.exactIdentity);if(e.preparedIdentity===null)e.preparedIdentity=i;else if(i===null||!cleanupPathIdentityMatches(i.dev,e.preparedIdentity.dev)||!cleanupPathIdentityMatches(i.ino,e.preparedIdentity.ino))throw new AgentCleanupIdentityMismatchError(`cleanup path identity changed before deletion`);e.preparedIdentity=i}async function removeAgentPath(e,t){const n=e.path;const r=e.trashPath;try{await statAgentCleanupPath(e)}catch(e){if(e instanceof AgentCleanupIdentityMismatchError)return{skipped:{path:n,reason:e.message}};return isMissingPathError(e)?{removed:{path:n,method:`missing`}}:cleanupFailure(n,e)}try{t.assertCurrentFinal();await movePathToTrash(r,{allowedRoots:[...trashAllowedRoots(e.sourcePaths,e.kind===`symlink`?e.canonicalPath:void 0),os.homedir(),os.tmpdir()]});return{removed:{path:n,method:`trash`}}}catch(t){if(!isMissingPathError(t))return cleanupFailure(n,t);try{await statAgentCleanupPath(e);return cleanupFailure(n,t)}catch(e){return isMissingPathError(e)?{removed:{path:n,method:`missing`}}:cleanupFailure(n,e)}}}async function resolveAgentDeleteCleanupTarget(e){const t=path.resolve(e);try{return await fs.realpath(t)}catch(e){if(!isMissingPathError(e))throw e;const{existingPath:n,unresolvedSegments:r}=resolvePathPrefixSync(t);return path.resolve(n,...r)}}async function prepareAgentDeleteCleanupPaths(e,t=[]){const n=/* @__PURE__ */ new Map;const addPath=e=>{const t=n.get(e.trashPath);if(!t){n.set(e.trashPath,e);return}t.sourcePaths=[.../* @__PURE__ */ new Set([...t.sourcePaths,...e.sourcePaths])];t.done||=e.done;t.note??=e.note;t.preparationError??=e.preparationError;if(e.kind===`target`){t.kind=`target`;t.canonicalPath=e.canonicalPath;t.parentPath=e.parentPath;t.trashCoversDescendants||=e.trashCoversDescendants}};for(const e of t){const t=path.resolve(e.path);const n=path.resolve(e.canonicalPath);addPath({path:t,parentPath:path.resolve(e.parentPath),canonicalPath:normalizeAgentDirRegistryPath(n),trashPath:n,trashCoversDescendants:e.coversDescendants,kind:e.kind,preparedIdentity:e.dev===null||e.ino===null?null:{dev:e.dev,ino:e.ino},done:e.done,note:e.note,sourcePaths:e.sourcePaths.map(e=>path.resolve(e))})}for(const t of e){const e=path.resolve(t);let n=path.dirname(e);let r=e;let i;try{r=await resolveAgentDeleteCleanupTarget(t);n=await resolveAgentDeleteCleanupTarget(path.dirname(e))}catch(e){i=e}let a;try{a=await fs.lstat(t,{bigint:true})}catch(e){if(!isMissingPathError(e))i??=e}let o=a;if(r!==e)try{o=await fs.lstat(r,{bigint:true})}catch(e){if(!isMissingPathError(e))i??=e;o=void 0}const s=normalizeAgentDirRegistryPath(r);addPath({path:r,parentPath:path.dirname(r),canonicalPath:s,trashPath:r,trashCoversDescendants:o?!o.isSymbolicLink():false,kind:`target`,preparedIdentity:cleanupPathIdentity(o),done:false,preparationError:i,sourcePaths:[e]});if(a?.isSymbolicLink()&&e!==r)addPath({path:e,parentPath:n,canonicalPath:s,trashPath:path.join(n,path.basename(e)),trashCoversDescendants:false,kind:`symlink`,preparedIdentity:cleanupPathIdentity(a),done:false,sourcePaths:[e]})}const depth=e=>path.relative(path.parse(e).root,e).split(path.sep).filter(Boolean).length;const cleanupDepth=e=>Math.max(depth(e.canonicalPath),depth(e.trashPath),...e.sourcePaths.map(depth));const compareFallback=(e,t)=>{if(e.kind!==t.kind)return e.kind===`target`?-1:1;const n=cleanupDepth(t)-cleanupDepth(e);if(n!==0)return n;return depth(t.trashPath)-depth(e.trashPath)||e.trashPath.localeCompare(t.trashPath)};const mustPrecede=(e,t)=>{if(e.kind!==t.kind)return e.kind===`target`;if(isPathInside(t.trashPath,e.trashPath))return true;if(isPathInside(e.trashPath,t.trashPath))return false;const n=[t.trashPath,...t.sourcePaths];return e.sourcePaths.some(e=>n.some(t=>isPathInside(t,e)))};const r=[...n.values()].toSorted(compareFallback);const i=[];while(r.length>0){const e=r.findIndex((e,t)=>r.every((n,r)=>r===t||!mustPrecede(n,e)));i.push(...r.splice(Math.max(0,e),1))}return i}function cleanupPathCovers(e,t,n){const r=path.resolve(t);return e.sourcePaths.includes(r)||e.trashPath===r||e.trashCoversDescendants&&(e.kind===`target`||isPathInside(e.trashPath,r))&&isPathInside(e.canonicalPath,n)}
//!src/gateway/server-methods/agents-delete.ts
var AgentSharedAuthStoreOwnerError=class extends Error{};async function agentOwnsSharedAuthStore(e,t){await prepareSharedAuthStoreOwnership();const n=resolveAgentDir(e,t);return isSharedAuthStoreOwner({ownership:resolveSharedAuthStoreOwnership(),agentAuthDbPath:resolveAuthProfileDatabasePath(n),sharedAuthDbPath:resolveSharedAuthStorePath()})}async function deleteGatewayAgent(e,t,n,r={}){const i={...r};const reportFailure=t=>n.logGateway.warn(`Agent ${e} deletion failed: ${t}. Resolve the reported failure, then retry agents.delete. Pending cleanup resumes after Gateway restart.`);try{const r=await retryAsync(()=>deleteGatewayAgentAttempt(e,t,n,i),{attempts:3,minDelayMs:100,maxDelayMs:200,jitter:0,shouldRetry:e=>!hasSqliteWorkerOutcomeUnknown(e)&&(isSqliteWorkerError(e,`overloaded`)||e instanceof WorkerTaskError&&e.code===`overloaded`)});if(r.purgeFailed||r.failed?.length)reportFailure([...r.purgeFailed?[`session-store cleanup failed`]:[],...r.failed?.map(({path:e,reason:t})=>`${e}: ${t}`)??[]].join(`; `));return r}catch(e){const t=collectNestedErrorCandidates(e).filter(e=>!(e instanceof AggregateError));reportFailure([...new Set(t.map(e=>e instanceof Error?e.message:formatErrorMessage$1(e)))].join(`; `)||formatErrorMessage$1(e));throw e}}async function deleteGatewayAgentAttempt(e,t,n,r){const{recoveryOperationId:i,writeOptions:a}=r;let o;try{return await withAgentDeletion(e,async s=>{const c=await withConfigMutationExclusive(async n=>{await assertAgentSessionStoreDeletionSafe(n,e);let a=await readAgentDeletionJournalAsync(e);if(i&&(a?.operationId!==i||a.cleanupCompleted))throw new Error(`Agent ${e} deletion recovery no longer owns its journal.`);const c=isConfiguredAgent(n,e);if(await agentOwnsSharedAuthStore(n,e))throw new AgentSharedAuthStoreOwnerError(formatSharedAuthStoreOwnerDeleteError(e));if(!c&&(!a||a.cleanupCompleted))throw new AgentConfigPreconditionError(`agent "${e}" not found`);if(e===tryResolveSoleAgentId(n))throw new AgentConfigPreconditionError(`Agent "${e}" is the only configured agent and cannot be deleted.`);if(isInheritedAuthStoreOwner(n,e))throw new AgentConfigPreconditionError(`Agent "${e}" owns inherited credentials through agents.defaults.authInheritance.agentId and cannot be deleted. Relocate those credentials, then re-point or remove that binding before retrying.`);if(c&&a?.cleanupCompleted){const t=await claimCompletedAgentDeletion(e,a.operationId);const n=await readAgentDeletionJournalAsync(e);if(!t&&n)throw new Error(`agent "${e}" deletion tombstone changed before fresh deletion`);a=void 0}const l=a?.deleteFiles??t;o=closeAgentWorkAdmissions({agentId:e,reason:new AgentDeletionPendingError(`Agent ${e} deletion is draining active work.`)});const u=await s(a??{agentId:e,agentDir:resolveAgentDir(n,e),workspaceDir:resolveAgentWorkspaceDir(n,e),sessionsDir:resolveSessionTranscriptsDirForAgent(e),deleteFiles:l,phase:`draining`},{recoveryOperationId:i});r.recoveryOperationId=u.entry.operationId;return{deletion:u,lockedJournal:a,config:n}});const{deletion:l,lockedJournal:u}=c;const d=l.entry;if(d.phase===`draining`)await drainAgentDeletionRuns(e,c.config,n,l.assertCurrentFinal);const{closeActiveMemorySearchManagerCore:f}=await import(`./memory-runtime-BGiZHnsE.mjs`);await l.assertCurrentAsync();await f({cfg:c.config,agentId:e});await l.assertCurrentAsync();if(d.phase===`draining`){await drainAgentDeleteDatabaseWork(l);await l.retire()}return await withConfigMutationExclusive(async t=>{const i=isConfiguredAgent(t,e);const o=d.deleteFiles;let s=!i;let c;let f;try{await l.assertCurrentAsync();await assertAgentSessionStoreDeletionSafe(t,e);if(await agentOwnsSharedAuthStore(t,e)||isInheritedAuthStoreOwner(t,e))throw new AgentSharedAuthStoreOwnerError(formatSharedAuthStoreOwnerDeleteError(e));if(e===tryResolveSoleAgentId(t))throw new AgentConfigPreconditionError(`Agent "${e}" is the only configured agent and cannot be deleted.`);prepareJournaledAgentDirOwnership(t,e,d.agentDir);f=await prepareAgentDeleteDatabases(t,e,d.agentDir,{},l);await l.assertCurrentAsync();await l.fenceDatabasePaths([...d.databasePaths,...f.fileGroups.flat()]);if(o){const e=new Set(d.cleanupPaths.flatMap(e=>e.sourcePaths.map(e=>path.resolve(e))));const t=[d.workspaceDir,d.agentDir,d.sessionsDir,...d.databasePaths].filter(t=>!e.has(path.resolve(t)));if(t.length>0){const e=new Set(t.map(e=>path.resolve(e)));const n=await prepareAgentDeleteCleanupPaths(t,d.cleanupPaths);const r=n.find(t=>t.preparationError!==void 0&&t.sourcePaths.some(t=>e.has(path.resolve(t))));if(r)throw r.preparationError;await l.fenceCleanupPaths(n.map(e=>{const t={path:e.path,canonicalPath:e.trashPath,parentPath:e.parentPath,kind:e.kind,sourcePaths:e.sourcePaths,dev:e.preparedIdentity?.dev??null,ino:e.preparedIdentity?.ino??null,coversDescendants:e.trashCoversDescendants,done:e.done};if(e.note)t.note=e.note;return t}))}}await n.cron.removeAgentJobsTransactional(e,()=>withAgentExecApprovalsRemoved(e,async()=>{await l.assertCurrentAsync();try{c=await deleteAgentConfigEntry({agentId:e,allowMissing:!i,assertCurrent:l.assertCurrentFinal,assertCurrentAsync:l.assertCurrentAsync,writeOptions:a})}catch(t){try{const n=await readConfigFileSnapshotForWrite();if(!isConfiguredAgent(n.snapshot.sourceConfig,e)){s=true;throw new AgentDeletionCommitUncertainError(t)}}catch(e){if(e instanceof AgentDeletionCommitUncertainError)throw e;throw new AgentDeletionCommitUncertainError(t)}throw t}if(i&&!c.result){s=!isConfiguredAgent(c.nextConfig,e);const t=/* @__PURE__ */ new Error(`agent delete config mutation did not return its target`);if(s)throw new AgentDeletionCommitUncertainError(t);throw t}s=true},l));await l.assertCurrentAsync()}catch(t){let n=!s&&!u&&!(t instanceof AgentDeletionAuthorityRollbackError)&&!(t instanceof AgentDeletionCommitUncertainError);if(n)try{const t=await readConfigFileSnapshotForWrite();n=isConfiguredAgent(t.snapshot.sourceConfig,e)}catch{n=false}if(n){await l.rollback();r.recoveryOperationId=void 0}throw t}await retireAgentDeleteRuntime(l,f?.agentDirs??[d.agentDir]);const p=c?.result??{agentDir:d.agentDir,workspaceDir:d.workspaceDir,sessionsDir:d.sessionsDir,removedBindings:0};const m=c?.nextConfig??t;const h=normalizeAgentDirRegistryPath(p.agentDir);const g=[];const _=await purgeAgentSessionStoreEntries(t,e,{runDatabaseCleanup:l.runDatabaseCleanup,onFailure:e=>g.push(e)});await l.assertCurrentAsync();const{closeDeletedAgentDatabases:v}=await import(`./openclaw-agent-db-readers-DqmNf5I1.mjs`);await v(e,f?.readerPaths??[],l);const y=[];if(o&&!_){const t=resolveSurvivingDatabaseFilePaths(await readAgentDeleteDatabaseRegistry(),e);const unclaimedBySurvivor=n=>!isPathOwnedBySurvivingAgent(m,e,n,t);const n=unclaimedBySurvivor(p.workspaceDir);const r=resolveRegisteredAgentIdForDir(p.agentDir)===e&&unclaimedBySurvivor(p.agentDir);const i=unclaimedBySurvivor(p.sessionsDir);const a=[...(r?f?.relocatedFileGroups??[]:f?.fileGroups??[]).flat(),...d.databasePaths].filter(unclaimedBySurvivor);const o=new Set([...n?[p.workspaceDir]:[],...r?[p.agentDir]:[],...i?[p.sessionsDir]:[],...a].map(e=>path.resolve(e)));const s=(await prepareAgentDeleteCleanupPaths([],d.cleanupPaths)).filter(e=>e.sourcePaths.some(e=>o.has(e))&&(r||!cleanupPathCovers(e,p.agentDir,h)));const c=normalizeAgentDirRegistryPath(p.workspaceDir);const u=s.filter(e=>cleanupPathCovers(e,p.workspaceDir,c));const _=u.length>0?await prepareLegacyWorkspaceStateReset(p.workspaceDir):void 0;const v=u.length>0?await prepareWorkspaceStateDeletion(p.workspaceDir):void 0;const markCleanupPathDone=async(e,t)=>{const n=path.resolve(e.trashPath);await l.fenceCleanupPaths(d.cleanupPaths.map(r=>{if(path.resolve(r.canonicalPath)!==n||r.kind!==e.kind)return r;const i=Object.assign({},r,{done:true,dev:e.preparedIdentity?.dev??null,ino:e.preparedIdentity?.ino??null});if(t)i.note=t;return i}));e.done=true;e.note=t};const b=[];for(const t of s){await l.assertCurrentAsync();if(t.done){let e=true;let n=t.note??`completed cleanup path is occupied; replacement preserved`;try{await statAgentCleanupPath(t)}catch(t){if(isMissingPathError(t))e=false;else if(!(t instanceof AgentCleanupIdentityMismatchError))n=`completed cleanup path could not be verified; replacement preserved`}if(e){await markCleanupPathDone(t,n);b.push({cleanupPath:t,protectAliases:true,terminal:true,note:n})}continue}const n=resolveSurvivingDatabaseFilePaths(await readAgentDeleteDatabaseRegistry(),e);const r=b.find(({cleanupPath:e,protectAliases:n})=>(t.kind!==`symlink`||n)&&(e.canonicalPath===t.canonicalPath||isPathInside(t.canonicalPath,e.canonicalPath))||[e.trashPath,...n?e.sourcePaths:[]].some(e=>e===t.trashPath||isPathInside(t.trashPath,e)));const i=isPathOwnedBySurvivingAgent(m,e,t.path,n)||cleanupPathCovers(t,p.agentDir,h)&&resolveRegisteredAgentIdForDir(p.agentDir)!==e;if(r||i){const e=i||r?.terminal===true;const n=i?`replacement owned by a surviving agent`:r?.note;if(e)await markCleanupPathDone(t,n??`protected replacement preserved`);b.push({cleanupPath:t,protectAliases:r?.protectAliases??false,terminal:e,note:n});continue}const a=t.preparationError?cleanupFailure(t.path,t.preparationError):await removeAgentPath(t,l);if(`removed`in a){y.push(a.removed);await markCleanupPathDone(t)}else if(`skipped`in a){await markCleanupPathDone(t,a.skipped.reason);b.push({cleanupPath:t,protectAliases:true,terminal:true,note:a.skipped.reason})}else{g.push(a.failed);b.push({cleanupPath:t,protectAliases:true,terminal:false})}}if(u.length>0&&u.every(e=>e.done)&&_&&v)try{await removeLegacyWorkspaceStateForReset(_,{assertCurrent:l.assertCurrentFinal});await l.assertCurrentAsync();await deleteWorkspaceState(v,{deletion:l})}catch{}await l.assertCurrentAsync();const x=s.filter(e=>cleanupPathCovers(e,p.agentDir,h));if(x.length>0&&x.every(e=>e.done))unregisterResolvedAgentDir({agentId:e,agentDir:h})}await finishAgentDeleteDatabases({deletion:l,agentDir:h,deleteFiles:o,complete:g.length===0&&!_});return{ok:true,agentId:e,removedBindings:p.removedBindings,removed:y,failed:g,..._?{purgeFailed:true}:{}}})})}finally{o?.()}}export{deleteGatewayAgent as n,AgentSharedAuthStoreOwnerError as t};