openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
452 lines (451 loc) • 17.3 kB
JavaScript
import { i as isMissingPathError } from "./errno-DFcoqIT9.mjs";
import { o as pathEntryExists } from "./path-existence-Co7-GyVr.mjs";
import { n as resolveIdentityPathViaExistingAncestorSync } from "./boundary-path-C2gXEiXe.mjs";
import { r as terminalText } from "./safe-text-C80HAQ2e.mjs";
import { d as resolveHomeDir, f as shortenHomeInString, p as shortenHomePath } from "./utils-C8YECn2Q.mjs";
import { v as resolveGatewayLockDir } from "./paths-DAcAg5aV.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { l as movePathToTrash } from "./fs-safe-BbWvmdVn.mjs";
import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs";
import { f as resolveAgentWorkspaceDir } from "./agent-scope-config-DmXgFGKP.mjs";
import { t as resolveDefaultAgentWorkspaceDir } from "./workspace-default-path-CWX4WiCH.mjs";
import "./workspace-default-DvctYF3A.mjs";
import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs";
import { g as prepareOpenClawStateDatabaseRemoval } from "./openclaw-state-db-cache-CkwtTqzF.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 { n as GatewayLockError, r as acquireGatewayLock } from "./gateway-lock-IYOwJQai.mjs";
import { l as removeCompletionRegistrations } from "./completion-runtime-DQNa6Jzl.mjs";
import { t as realpathViaExistingPrefix } from "./path-containment-DaLrXKK_.mjs";
import path from "node:path";
import fs from "node:fs/promises";
import { hasNodeErrorCode, isPathInside } from "@openclaw/fs-safe/path";
//#region 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);
}
}
/** Moves a path to Trash when it exists, logging a manual-delete fallback on failure. */
async function moveToTrash(e, t, n, r) {
return "removed" in await moveToTrashResult(e, t, n, r);
}
/**
* Allowed Trash roots for OpenClaw-owned paths: each declared path's own parent, plus the
* resolved parent when the moved path is a symlink (fs-safe checks the link target, and
* moving a link never touches the directory behind it). fs-safe's default roots (home + tmp)
* alone refuse every path of a state dir on a volume such as `/data`.
*/
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));
}
/** Determine which config, credential, and workspace paths cleanup should consider. */
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()));
}
/** Remove one path after rejecting empty/root/home targets and honoring dry-run mode. */
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 {
await fs.rm(i, {
recursive: true,
force: true
});
n.log(`Removed ${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)}`);
}
}
/**
* Spells preserved paths as the entries a removal walk of the canonical state dir reaches:
* canonical parent, final name kept (removal deletes a link entry, not its target). Comparing
* any other spelling would silently drop a preserved workspace reached through an alias.
*/
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));
}
/** Remove state plus config/OAuth paths, preserving selected paths nested inside state. */
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();
}
}
}
/** Remove all workspace directories selected by the cleanup plan. */
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];
}
/** Reset canonical session history while preserving each database's unrelated state. */
async function removeAgentSessions(e, t) {
await withStateCleanupOwnership(e, false, () => removeAgentSessionStores(e.cfg, t, false));
}
/** Hold state ownership across all three removals, continuing after individual cleanup failures. */
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-Cc3GQQ_f.mjs");
const { resolveAllAgentSessionStoreTargetsSync: a } = await import("./targets-cXkr4Sqy.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("\n"));
}
//#endregion
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 };