UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

291 lines (290 loc) • 12.7 kB
import { o as writeRuntimeJson, r as defaultRuntime } from "./runtime-B-SLYP-m.mjs"; import { r as isPathInside } from "./path-guards-TIjxtj6H.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { r as normalizeAgentIdStrict } from "./agent-id-CQjtp2ft.mjs"; import "./session-key-CqAyZeVk.mjs"; import { i as listAgentIds, n as listAgentEntries, p as tryResolveSoleAgentId } from "./agent-roster-t1ooUdXp.mjs"; import { u as resolveSessionTranscriptsDirForAgent } from "./paths-DvQ5AJvD.mjs"; import { N as normalizeAgentDirRegistryPath, a as resolveAgentDir, f as resolveAgentWorkspaceDir } from "./agent-scope-config-DmXgFGKP.mjs"; import { i as GATEWAY_CLIENT_NAMES, r as GATEWAY_CLIENT_MODES } from "./client-info-Cm1BcrMm.mjs"; import "./agent-scope-BwB8YH6y.mjs"; import { f as readAgentDeletionJournalAsync } from "./agent-deletion-journal-DgNbVVSp.mjs"; import { b as resolveAuthProfileDatabasePath } from "./sqlite-B2CoJ4Om.mjs"; import { d as resolveSharedAuthStorePath, o as prepareSharedAuthStoreOwnership } from "./path-resolve-CpNl_n1M.mjs"; import "./message-channel-DTYVLJT1.mjs"; import { c as AgentDeletionAuthorityRollbackError, l as AgentDeletionCommitUncertainError, r as withAgentDeletion, s as claimCompletedAgentDeletion } from "./agent-lifecycle-registry-CdPY7sE9.mjs"; import { r as replaceConfigFile } from "./mutate-DhAOi0-2.mjs"; import "./config-CMA-J084.mjs"; import { t as purgeAgentSessionStoreEntries } from "./sessions-D5Vvu3AE.mjs"; import { i as pruneAgentConfig, r as findAgentEntryIndex } from "./agents.config-T4w0h7rr.mjs"; import { p as withAgentExecApprovalsRemoved } from "./exec-approvals-store-BUZ9uOWF.mjs"; import "./exec-approvals-rOfoWejC.mjs"; import { l as prepareLegacyWorkspaceStateReset, u as removeLegacyWorkspaceStateForReset } from "./workspace-legacy-state-Bo5wJOkK.mjs"; import { i as prepareWorkspaceStateDeletion, n as deleteWorkspaceState } from "./workspace-state-store-DNT7G1J_.mjs"; import { r as formatCliJsonFailure } from "./failure-output-DVVDqwuu.mjs"; import { f as isImplicitLocalGatewayTarget, r as callGateway, t as buildGatewayConnectionDetails } from "./call-DVCK1deJ.mjs"; import { r as moveToTrashResult } from "./cleanup-utils-Dk4WWDhW.mjs"; import { r as isTerminalInteractive } from "./terminal-interactivity-B_L_vZTP.mjs"; import { t as createClackPrompter } from "./clack-prompter-oqVcatgQ.mjs"; import { r as logConfigUpdated } from "./logging-D0RirHBi.mjs"; import { t as withLocalAgentCronJobsRemoved } from "./local-service-a878KfUi.mjs"; import { r as requireValidConfigForWrite } from "./config-validation-Cy6dkTWs.mjs"; import { i as isSharedAuthStoreOwner, n as formatSharedAuthStoreOwnerDeleteError, r as isInheritedAuthStoreOwner, t as findOverlappingWorkspaceAgentIds } from "./agent-delete-safety-CGn0sYfd.mjs"; import { a as prepareAgentDeleteDatabases, c as resolveSurvivingDatabaseFilePaths, i as isPathOwnedBySurvivingAgent, s as readAgentDeleteDatabaseRegistry, t as assertAgentSessionStoreDeletionSafe, u as AgentSharedStoreOwnerError } from "./agent-delete-databases-CZFdBpRL.mjs"; import { t as resolveGatewayMutationFallback } from "./call-mutation-fallback-CY1rDJ7O.mjs"; //#region 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 = prepareLegacyWorkspaceStateReset(f); const t = 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.`); }); } //#endregion export { agentsDeleteCommand };