UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3 lines • 11 kB
import{o as writeRuntimeJson,r as defaultRuntime}from"./runtime-DIcLIHcp.mjs";import{r as isPathInside}from"./path-guards-DGttsOJI.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{r as normalizeAgentIdStrict}from"./agent-id-cOfqmfln.mjs";import"./session-key-BPgKfU2m.mjs";import{t as formatCliCommand}from"./command-format-D7KhNLP0.mjs";import{i as listAgentIds,n as listAgentEntries,p as tryResolveSoleAgentId}from"./agent-roster-4XrgUgPK.mjs";import{u as resolveSessionTranscriptsDirForAgent}from"./paths-CcxgiC3g.mjs";import{N as normalizeAgentDirRegistryPath,a as resolveAgentDir,f as resolveAgentWorkspaceDir}from"./agent-scope-config-CG9CFpGX.mjs";import{i as GATEWAY_CLIENT_NAMES,r as GATEWAY_CLIENT_MODES}from"./client-info-Dr3-kuD1.mjs";import"./agent-scope-Dw5XRSEh.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,o as prepareSharedAuthStoreOwnership}from"./path-resolve-TSS6dv07.mjs";import"./message-channel-514k57tV.mjs";import{c as AgentDeletionAuthorityRollbackError,l as AgentDeletionCommitUncertainError,r as withAgentDeletion,s as claimCompletedAgentDeletion}from"./agent-lifecycle-registry-CT_mqsZ8.mjs";import{r as replaceConfigFile}from"./mutate-DcH8aT_4.mjs";import"./config-DkZ8y8Gv.mjs";import{t as purgeAgentSessionStoreEntries}from"./sessions-DQD7zQ95.mjs";import{i as pruneAgentConfig,r as findAgentEntryIndex}from"./agents.config-BvTJi_N_.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{r as formatCliJsonFailure}from"./failure-output-Gn9zHEk3.mjs";import{f as isImplicitLocalGatewayTarget,r as callGateway,t as buildGatewayConnectionDetails}from"./call-CVqWsTxX.mjs";import{r as logConfigUpdated}from"./logging-C183DMvG.mjs";import{r as moveToTrashResult}from"./cleanup-utils-OK0KVVTl.mjs";import{r as isTerminalInteractive}from"./terminal-interactivity-ijJuF5PT.mjs";import{t as createClackPrompter}from"./clack-prompter-CkhFfk2k.mjs";import{t as withLocalAgentCronJobsRemoved}from"./local-service-CBXX4sjU.mjs";import{r as requireValidConfigForWrite}from"./config-validation-BexrhW6U.mjs";import{i as isSharedAuthStoreOwner,n as formatSharedAuthStoreOwnerDeleteError,r as isInheritedAuthStoreOwner,t as findOverlappingWorkspaceAgentIds}from"./agent-delete-safety-tdYvLPcq.mjs";import{a as prepareAgentDeleteDatabases,c as resolveSurvivingDatabaseFilePaths,i as isPathOwnedBySurvivingAgent,s as readAgentDeleteDatabaseRegistry,t as assertAgentSessionStoreDeletionSafe,u as AgentSharedStoreOwnerError}from"./agent-delete-databases-D3LWY7Ss.mjs";import{t as resolveGatewayMutationFallback}from"./call-mutation-fallback-Bk55IIrP.mjs"; //!src/commands/agents.commands.delete.ts async function agentsDeleteCommand(e){const failAgentsDelete=t=>{if(e.json){writeRuntimeJson(defaultRuntime,formatCliJsonFailure(t));defaultRuntime.exit(1,{resetStream:process.stderr})}else{defaultRuntime.error(t);defaultRuntime.exit(1)}};const t=await requireValidConfigForWrite(defaultRuntime);if(!t)return;const n=t.snapshot.sourceConfig;const r=e.id?.trim();if(!r){failAgentsDelete(`Agent id is required. Run ${formatCliCommand(`openclaw agents list`)} to choose one.`);return}const i=normalizeAgentIdStrict(r);if(!i.ok){failAgentsDelete(`Agent "${r}" not found. Run ${formatCliCommand(`openclaw agents list`)} to see configured agents.`);return}const a=i.value;if(!e.json&&a!==r)defaultRuntime.log(`Normalized agent id to "${a}".`);const o=findAgentEntryIndex(listAgentEntries(n),a)>=0;let s=o?void 0:await readAgentDeletionJournalAsync(a);if(!o&&(!s||s.cleanupCompleted)){failAgentsDelete(`Agent "${a}" not found. Run ${formatCliCommand(`openclaw agents list`)} to see configured agents.`);return}const c=o?resolveAgentDir(n,a):void 0;const l=s?.agentDir??c;if(!l)throw new Error(`Agent "${a}" deletion has no state directory.`);try{await assertAgentSessionStoreDeletionSafe(n,a)}catch(e){if(!(e instanceof AgentSharedStoreOwnerError))throw e;failAgentsDelete(e.message);return}const u=await prepareSharedAuthStoreOwnership();if(isSharedAuthStoreOwner({ownership:u,agentAuthDbPath:resolveAuthProfileDatabasePath(l),sharedAuthDbPath:resolveSharedAuthStorePath()})){failAgentsDelete(formatSharedAuthStoreOwnerDeleteError(a));return}if(o&&a===tryResolveSoleAgentId(n)){failAgentsDelete(`Agent "${a}" is the only configured agent and cannot be deleted.`);return}if(isInheritedAuthStoreOwner(n,a)){failAgentsDelete(`Agent "${a}" owns inherited credentials through agents.defaults.authInheritance.agentId and cannot be deleted. Relocate those credentials, then re-point or remove that binding before retrying.`);return}if(o){s=await readAgentDeletionJournalAsync(a);if(s?.cleanupCompleted)s=void 0}const d=s?.agentDir??c;if(!d)throw new Error(`Agent "${a}" deletion has no state directory.`);if(!e.force){if(!isTerminalInteractive()){failAgentsDelete(`Non-interactive session. Re-run with --force.`);return}if(!await createClackPrompter().confirm({message:`Delete agent "${a}" and prune workspace/state?`,initialValue:false})){defaultRuntime.log(`Cancelled.`);return}}const f=s?.workspaceDir??resolveAgentWorkspaceDir(n,a);const p=s?.sessionsDir??resolveSessionTranscriptsDirForAgent(a);const m=o?pruneAgentConfig(n,a):{config:n,removedBindings:0,removedAllow:0,clearedOwnerRefs:[]};const reportDeletion=(t,n,r,i)=>{if(e.json)writeRuntimeJson(defaultRuntime,{agentId:a,workspace:f,workspaceRetained:n||void 0,workspaceRetainedReason:n?`shared`:void 0,workspaceSharedWith:n?r:void 0,agentDir:d,sessionsDir:p,removedBindings:t.removedBindings,removedAllow:m.removedAllow,clearedOwnerRefs:m.clearedOwnerRefs.length>0?m.clearedOwnerRefs:void 0,removed:t.removed,failed:t.failed,...t.purgeFailed?{purgeFailed:true}:{},...i});else{defaultRuntime.log(`Deleted agent: ${a}`);if(m.clearedOwnerRefs.length>0)defaultRuntime.log(`Cleared owner references: ${m.clearedOwnerRefs.join(`, `)}`);if(t.purgeFailed===true)defaultRuntime.error(`Warning: session-store purge failed for deleted agent "${a}"; source data was retained. Retry deletion after resolving the storage error.`);for(const e of t.failed??[])defaultRuntime.error(`Warning: path could not be moved to Trash: ${e.reason}; remove it manually at ${e.path}`)}};let h;const{url:g}=buildGatewayConnectionDetails({config:n});const _=await isImplicitLocalGatewayTarget({config:n});try{h=await callGateway({config:n,expectUrl:g,method:`agents.delete`,params:{agentId:a,deleteFiles:true},mode:GATEWAY_CLIENT_MODES.CLI,clientName:GATEWAY_CLIENT_NAMES.CLI,requiredMethods:[`agents.delete`]})}catch(e){const t=resolveGatewayMutationFallback({error:e,localTarget:_});if(t===`unreachable`||t===`credentials-required`)h=t;else if(t===`non-local`)throw new Error(`${formatErrorMessage(e)}\nLocal agent state was left unchanged. Restore the Gateway connection and credentials, or run this command on the Gateway host (the far end of any SSH tunnel).`,{cause:e});else throw e}if(typeof h!==`string`){const t=e.json?findOverlappingWorkspaceAgentIds(n,a,f):[];reportDeletion(h,t.length>0,t,{transport:`gateway`});return}return await withAgentDeletion(a,async r=>{s=await readAgentDeletionJournalAsync(a);if(o&&s?.cleanupCompleted){if(!await claimCompletedAgentDeletion(a,s.operationId))throw new Error(`Agent "${a}" deletion tombstone changed before fresh deletion.`);s=void 0}if(!o&&(!s||s.cleanupCompleted))throw new Error(`Agent "${a}" deletion already completed.`);await assertAgentSessionStoreDeletionSafe(n,a);const i=findOverlappingWorkspaceAgentIds(n,a,f);const c=s?.deleteFiles??true;const l=await r(s??{agentId:a,agentDir:d,workspaceDir:f,sessionsDir:p,deleteFiles:c});let u=!o;try{if(l.entry.phase===`draining`){await l.runWithWorker((e,t)=>e.execute({type:`agentDeletion.assertNoDatabaseLeases`,input:{guard:t}}));await l.retire()}await prepareAgentDeleteDatabases(n,a,d,{},l);await l.assertCurrentAsync();const commitRoster=async()=>await withAgentExecApprovalsRemoved(a,async()=>{await l.assertCurrentAsync();if(o){await replaceConfigFile({...t,sourceConfig:m.config,writeOptions:{...t.writeOptions,allowedAgentRosterRemovals:[a],beforeCommit:async()=>{await t.writeOptions.beforeCommit?.();await l.assertCurrentAsync()},assertConfigPathForWrite:()=>{t.writeOptions.assertConfigPathForWrite?.();l.assertCurrentFinal()},...e.json?{skipOutputLogs:true}:{}}});u=true;if(!e.json)logConfigUpdated(defaultRuntime)}},l);if(h===`unreachable`)await withLocalAgentCronJobsRemoved(a,()=>n,commitRoster);else await commitRoster();await l.assertCurrentAsync()}catch(e){if(!s&&!u&&!(e instanceof AgentDeletionAuthorityRollbackError)&&!(e instanceof AgentDeletionCommitUncertainError))await l.rollback();throw e}const g=await purgeAgentSessionStoreEntries(n,a,{runDatabaseCleanup:l.runDatabaseCleanup});await l.assertCurrentAsync();for(const e of listAgentIds(m.config))resolveAgentDir(m.config,e);const _=resolveSurvivingDatabaseFilePaths(await readAgentDeleteDatabaseRegistry(),a);const sharedWithSurvivor=e=>isPathOwnedBySurvivingAgent(m.config,a,e,_);const v=sharedWithSurvivor(f);const y=e.json?{...defaultRuntime,log:()=>{}}:defaultRuntime;let b;const x=[];const S=[];const removePath=async e=>{const t=await moveToTrashResult(e,y,l.assertCurrentFinal);await l.assertCurrentAsync();if(`removed`in t)x.push(t.removed);else S.push(t.failed);return t};if(c&&!g&&v)y.log(`Skipped workspace removal (shared with other agents${i.length?`: ${i.join(`, `)}`:``}): ${f}`);else if(c&&!g){const e=await prepareLegacyWorkspaceStateReset(f);const t=await prepareWorkspaceStateDeletion(f);if(`removed`in await removePath(f))try{const n=await removeLegacyWorkspaceStateForReset(e,{assertCurrent:l.assertCurrentFinal});for(const e of n.warnings)y.log(e);await l.assertCurrentAsync();await deleteWorkspaceState(t,{deletion:l})}catch(e){b=e instanceof Error?e:new Error(String(e))}}if(c&&!g){const e=normalizeAgentDirRegistryPath(d);const t=l.entry.databasePaths.filter(t=>{const n=normalizeAgentDirRegistryPath(t);return!isPathInside(e,n)&&!sharedWithSurvivor(t)});for(const e of[d,p])if(!sharedWithSurvivor(e))await removePath(e);for(const e of t)await removePath(e)}if(b)throw b;await l.assertCurrentAsync();if(S.length===0&&!g)await l.finish({unregisterDatabases:c});reportDeletion({removedBindings:m.removedBindings,removed:x,failed:S,...g?{purgeFailed:true}:{}},v,i,h===`credentials-required`?{cronCleanupSkipped:true}:void 0);if(h===`credentials-required`)defaultRuntime.error(`Warning: cron cleanup was skipped for deleted agent "${a}" because the Gateway could not be authenticated; scheduled jobs may remain.`)})}export{agentsDeleteCommand};