openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
722 lines (721 loc) • 28.8 kB
JavaScript
import { s as formatErrorMessage } from "./error-coercion-hDrHOSGy.mjs";
import { i as isMissingPathError } from "./errno-DFcoqIT9.mjs";
import { r as isPathInside } from "./path-guards-TIjxtj6H.mjs";
import "./errors-BKzCeTYb.mjs";
import { t as settlesWithin } from "./settle-within-Bj8A0Tzk.mjs";
import { t as FsSafeError, w as root } from "./fs-safe-BbWvmdVn.mjs";
import { g as toAgentStoreSessionKey, j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs";
import { p as tryResolveSoleAgentId } from "./agent-roster-t1ooUdXp.mjs";
import { l as resolveSessionStorePathCore, u as resolveSessionTranscriptsDirForAgent } from "./paths-DvQ5AJvD.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-DmXgFGKP.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { l as readConfigFileSnapshotForWrite } from "./io.runtime-DsJ2dLCQ.mjs";
import { t as runTasksWithConcurrency } from "./run-with-concurrency-B34GDKXE.mjs";
import { f as readAgentDeletionJournalAsync } from "./agent-deletion-journal-DgNbVVSp.mjs";
import { b as resolveAuthProfileDatabasePath } from "./sqlite-B2CoJ4Om.mjs";
import { d as resolveSharedAuthStorePath, l as resolveSharedAuthStoreOwnership, o as prepareSharedAuthStoreOwnership } from "./path-resolve-CpNl_n1M.mjs";
import { t as AgentDeletionPendingError } from "./session-agent-work-admission-DwGkLOZq.mjs";
import { c as AgentDeletionAuthorityRollbackError, l as AgentDeletionCommitUncertainError, r as withAgentDeletion, s as claimCompletedAgentDeletion } from "./agent-lifecycle-registry-CdPY7sE9.mjs";
import { a as createAgentRunDirectAbortError } from "./run-termination-0Ig0-bk6.mjs";
import { st as SESSION_CONTROLLER_DRAIN_TIMEOUT_MS, t as activeSessionOperations } from "./session-controller.state-BApgK0mV.mjs";
import { h as nativeAttemptAttachments } from "./run-state-jrY5s7TG.mjs";
import { a as readSessionEntrySummariesInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs";
import { G as closeAgentWorkAdmissions, K as collectActiveAgentSessionWorkAdmissions, q as startAgentWorkAdmissionInterruption } from "./session-controller.lifecycle-C_Z3sybN.mjs";
import { a as resolveSessionStoreIdentity } from "./session-store-key-CEwU3noi.mjs";
import { s as withConfigMutationExclusive } from "./mutate-DhAOi0-2.mjs";
import "./config-CMA-J084.mjs";
import { t as purgeAgentSessionStoreEntries } from "./sessions-D5Vvu3AE.mjs";
import { a as getRpcSourceIdentity, v as listRpcSourceEntries } from "./session-controller.rpc-sources-CTFbRW2t.mjs";
import { t as chatRunBelongsToAgent } from "./chat-run-owner-2pVCqGmw.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 { l as trashAllowedRoots } from "./cleanup-utils-Dk4WWDhW.mjs";
import { d as listAgentSessionMcpRuntimeIds, m as retireSessionMcpRuntimeForAgentDeletion } from "./mcp-app-model-context-Nt0AWggG.mjs";
import { a as captureEmbeddedRunDrainTarget } from "./runs-C1RO1Y6L.mjs";
import { r as drainAgentExecProcesses } from "./bash-process-control-aLfvOIsE.mjs";
import { t as movePathToTrash } from "./browser-trash-BBLAyaRb.mjs";
import { t as cleanupBrowserSessionsForLifecycleEnd } from "./browser-lifecycle-cleanup-CQ-0EGCY.mjs";
import { i as isSharedAuthStoreOwner, n as formatSharedAuthStoreOwnerDeleteError, r as isInheritedAuthStoreOwner } from "./agent-delete-safety-CGn0sYfd.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-CZFdBpRL.mjs";
import { a as isConfiguredAgent, i as deleteAgentConfigEntry, t as AgentConfigPreconditionError } from "./agents-config-mutations-CJI0-Cra.mjs";
import { n as prepareSessionLifecycleDrain } from "./sessions-lifecycle-drain-BbeGbexW.mjs";
import path from "node:path";
import fs from "node:fs/promises";
import os from "node:os";
import { resolvePathPrefixSync } from "@openclaw/fs-safe/advanced";
//#region src/gateway/server-methods/agents-delete-drain.ts
/** The deletion journal already owns ingress; session owners retain cancellation writes. */
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: ${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();
}
}
//#endregion
//#region 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);
}
//#endregion
//#region 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()
});
}
/** RPC and restart recovery share the exact journal, retirement, and filesystem owner. */
async function deleteGatewayAgent(e, t, n, r = {}) {
const { recoveryOperationId: i, writeOptions: a } = r;
let o;
try {
return await withAgentDeletion(e, async (r) => {
const s = 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 s = isConfiguredAgent(n, e);
if (await agentOwnsSharedAuthStore(n, e)) throw new AgentSharedAuthStoreOwnerError(formatSharedAuthStoreOwnerDeleteError(e));
if (!s && (!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 (s && 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 c = a?.deleteFiles ?? t;
o = closeAgentWorkAdmissions({
agentId: e,
reason: new AgentDeletionPendingError(`Agent ${e} deletion is draining active work.`)
});
return {
deletion: await r(a ?? {
agentId: e,
agentDir: resolveAgentDir(n, e),
workspaceDir: resolveAgentWorkspaceDir(n, e),
sessionsDir: resolveSessionTranscriptsDirForAgent(e),
deleteFiles: c,
phase: "draining"
}, { recoveryOperationId: i }),
lockedJournal: a,
config: n
};
});
const { deletion: c, lockedJournal: l } = s;
const u = c.entry;
if (u.phase === "draining") await drainAgentDeletionRuns(e, s.config, n, c.assertCurrentFinal);
const { closeActiveMemorySearchManagerCore: d } = await import("./memory-runtime-ppPZJk8v.mjs");
await c.assertCurrentAsync();
await d({
cfg: s.config,
agentId: e
});
await c.assertCurrentAsync();
if (u.phase === "draining") {
await drainAgentDeleteDatabaseWork(c);
await c.retire();
}
return await withConfigMutationExclusive(async (t) => {
const r = isConfiguredAgent(t, e);
const i = u.deleteFiles;
let o = !r;
let s;
let d;
try {
await c.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, u.agentDir);
d = await prepareAgentDeleteDatabases(t, e, u.agentDir, {}, c);
await c.assertCurrentAsync();
await c.fenceDatabasePaths([...u.databasePaths, ...d.fileGroups.flat()]);
if (i) {
const e = new Set(u.cleanupPaths.flatMap((e) => e.sourcePaths.map((e) => path.resolve(e))));
const t = [
u.workspaceDir,
u.agentDir,
u.sessionsDir,
...u.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, u.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 c.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 c.assertCurrentAsync();
try {
s = await deleteAgentConfigEntry({
agentId: e,
allowMissing: !r,
assertCurrent: c.assertCurrentFinal,
assertCurrentAsync: c.assertCurrentAsync,
writeOptions: a
});
} catch (t) {
try {
const n = await readConfigFileSnapshotForWrite();
if (!isConfiguredAgent(n.snapshot.sourceConfig, e)) {
o = true;
throw new AgentDeletionCommitUncertainError(t);
}
} catch (e) {
if (e instanceof AgentDeletionCommitUncertainError) throw e;
throw new AgentDeletionCommitUncertainError(t);
}
throw t;
}
if (r && !s.result) {
o = !isConfiguredAgent(s.nextConfig, e);
const t = /* @__PURE__ */ new Error("agent delete config mutation did not return its target");
if (o) throw new AgentDeletionCommitUncertainError(t);
throw t;
}
o = true;
}, c));
await c.assertCurrentAsync();
} catch (t) {
let n = !o && !l && !(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 c.rollback();
throw t;
}
await retireAgentDeleteRuntime(c, d?.agentDirs ?? [u.agentDir]);
const f = s?.result ?? {
agentDir: u.agentDir,
workspaceDir: u.workspaceDir,
sessionsDir: u.sessionsDir,
removedBindings: 0
};
const p = s?.nextConfig ?? t;
const m = normalizeAgentDirRegistryPath(f.agentDir);
const h = [];
const g = await purgeAgentSessionStoreEntries(t, e, {
runDatabaseCleanup: c.runDatabaseCleanup,
onFailure: (e) => h.push(e)
});
await c.assertCurrentAsync();
const { closeDeletedAgentDatabases: _ } = await import("./openclaw-agent-db-readers-BZI-DVlJ.mjs");
await _(e, d?.readerPaths ?? [], c);
const v = [];
if (i && !g) {
const t = resolveSurvivingDatabaseFilePaths(await readAgentDeleteDatabaseRegistry(), e);
const unclaimedBySurvivor = (n) => !isPathOwnedBySurvivingAgent(p, e, n, t);
const n = unclaimedBySurvivor(f.workspaceDir);
const r = resolveRegisteredAgentIdForDir(f.agentDir) === e && unclaimedBySurvivor(f.agentDir);
const i = unclaimedBySurvivor(f.sessionsDir);
const a = [...(r ? d?.relocatedFileGroups ?? [] : d?.fileGroups ?? []).flat(), ...u.databasePaths].filter(unclaimedBySurvivor);
const o = new Set([
...n ? [f.workspaceDir] : [],
...r ? [f.agentDir] : [],
...i ? [f.sessionsDir] : [],
...a
].map((e) => path.resolve(e)));
const s = (await prepareAgentDeleteCleanupPaths([], u.cleanupPaths)).filter((e) => e.sourcePaths.some((e) => o.has(e)) && (r || !cleanupPathCovers(e, f.agentDir, m)));
const l = normalizeAgentDirRegistryPath(f.workspaceDir);
const g = s.filter((e) => cleanupPathCovers(e, f.workspaceDir, l));
const _ = g.length > 0 ? prepareLegacyWorkspaceStateReset(f.workspaceDir) : void 0;
const y = g.length > 0 ? prepareWorkspaceStateDeletion(f.workspaceDir) : void 0;
const markCleanupPathDone = async (e, t) => {
const n = path.resolve(e.trashPath);
await c.fenceCleanupPaths(u.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 c.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(p, e, t.path, n) || cleanupPathCovers(t, f.agentDir, m) && resolveRegisteredAgentIdForDir(f.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, c);
if ("removed" in a) {
v.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 {
h.push(a.failed);
b.push({
cleanupPath: t,
protectAliases: true,
terminal: false
});
}
}
if (g.length > 0 && g.every((e) => e.done) && _ && y) try {
await removeLegacyWorkspaceStateForReset(_, { assertCurrent: c.assertCurrentFinal });
await c.assertCurrentAsync();
await deleteWorkspaceState(y, { deletion: c });
} catch {}
await c.assertCurrentAsync();
const x = s.filter((e) => cleanupPathCovers(e, f.agentDir, m));
if (x.length > 0 && x.every((e) => e.done)) unregisterResolvedAgentDir({
agentId: e,
agentDir: m
});
}
await finishAgentDeleteDatabases({
deletion: c,
agentDir: m,
deleteFiles: i,
complete: h.length === 0 && !g
});
return {
ok: true,
agentId: e,
removedBindings: f.removedBindings,
removed: v,
failed: h,
...g ? { purgeFailed: true } : {}
};
});
});
} finally {
o?.();
}
}
//#endregion
export { deleteGatewayAgent as n, AgentSharedAuthStoreOwnerError as t };