openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
432 lines (431 loc) • 15.5 kB
JavaScript
import { c as resolveUserPath, n as resolveFilesystemPath, t as expandHomePrefix } from "./home-dir-EKmgmdPG.mjs";
import { d as realpathOrResolve } from "./path-existence-Co7-GyVr.mjs";
import { r as terminalText } from "./safe-text-C80HAQ2e.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import { l as pathExists, p as shortenHomePath } from "./utils-C8YECn2Q.mjs";
import { T as resolveOAuthDir, m as resolveConfigPath } from "./paths-DAcAg5aV.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs";
import { a as resolveAgentDir } from "./agent-scope-config-DmXgFGKP.mjs";
import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs";
import { a as withDatabaseEngineSelection, t as getDatabaseEngineInput } from "./context-DE59wyBs.mjs";
import { g as withOpenClawStateDatabaseReadSnapshot } from "./openclaw-state-db-readonly-B6YHb1oF.mjs";
import { t as createConfigIO } from "./io.factory-DEa_bi2j.mjs";
import { n as resolveDatabaseEngineSelection } from "./config-1gpCgiFx.mjs";
import "./config-CMA-J084.mjs";
import { s as readExistingWorktreePaths } from "./registry-read-DAFI5cQY.mjs";
import { c as tryRealpath, t as loadSingleSkillDirectory } from "./local-loader-CaLEAbQc.mjs";
import { a as resolveSkillDiscoveryLimits, i as isSymlinkPath, r as discoverSkillCandidates } from "./skill-root-discovery-CuoPG8Ex.mjs";
import { t as resolveActivatedPluginBackupInventory } from "./manifest-backup-resources-8yQB3nRq.mjs";
import { t as buildBackupArchivePath } from "./backup-archive-path-policy-Cr8KWL_A.mjs";
import { n as isUpdateCapturePath, t as assertNotUpdateCapturePath } from "./update-capture-paths-B2WcdTCG.mjs";
import { t as createBackupResourcePlan } from "./backup-resource-inventory-BFHpUA98.mjs";
import { r as resolveBackupConfigCapture } from "./backup-config-capture-C4dP9zCI.mjs";
import { t as runWithLocalStateOwner } from "./local-state-owner-DTl7OHpC.mjs";
import { i as recordBackupRunOutcome } from "./backup-run-records-B0d7Qm1y.mjs";
import { t as buildCleanupPlan } from "./cleanup-utils-Dk4WWDhW.mjs";
import { a as resolveLegacyConfigSnapshotForBackup } from "./automatic-config-repair-BMcsN3sp.mjs";
import { existsSync } from "node:fs";
import path from "node:path";
import fs$1 from "node:fs/promises";
import { isPathInside } from "@openclaw/fs-safe/path";
//#region src/commands/backup-shared.ts
const BACKUP_MAX_DECOMPRESSION_RATIO = 1100;
/** Route only the ledger write; archive creation keeps its existing backup owner. */
async function recordBackupRunOutcomeWithOwner(e) {
const t = resolveOpenClawStateSqlitePath();
if (!existsSync(t)) return;
const n = {
...e,
createdAt: e.createdAt ?? Date.now(),
pushFailed: e.pushFailed === true ? true : void 0
};
await runWithLocalStateOwner({
method: "backup.recordOutcome",
params: { outcome: n },
target: "backup outcome ledger",
recoveryCommand: "openclaw gateway call backup.status",
assertTargetCurrent: () => {
if (!existsSync(t)) throw new Error("The state database disappeared; the backup outcome was not recorded.");
},
runLocal: ({ env: e, assertCurrent: t, signal: r }) => recordBackupRunOutcome({
...n,
env: e
}, {
assertCurrent: t,
signal: r
})
});
}
async function recordBackupOutcomeBestEffort(e, t) {
try {
assertNotUpdateCapturePath(resolveOpenClawStateSqlitePath(), resolveStateDir());
await recordBackupRunOutcomeWithOwner(t);
} catch (n) {
const r = t.kind === "git" ? "Git backup" : "backup";
e.error(terminalText`Warning: the ${r} outcome could not be recorded: ${formatErrorMessage(n)}`);
}
}
function resolveRequiredBackupPath(e, t) {
const n = e?.trim();
if (!n) throw new Error(`Missing required ${t} value.`);
return resolveUserPath(n);
}
function resolveBackupArchivePath(e, t) {
if (!e?.trim()) throw new Error(`Missing required ${t} value.`);
try {
return resolveFilesystemPath(expandHomePrefix(e));
} catch (e) {
throw new Error(terminalText`Could not resolve ${t}: ${formatErrorMessage(e)}`, { cause: e });
}
}
const BACKUP_ASSET_PRIORITY = {
state: 0,
config: 1,
credentials: 2,
workspace: 3,
agent: 4,
"managed skill": 5
};
/** Format a filesystem-safe local timestamp with explicit UTC offset for backup names. */
function buildBackupArchiveRoot(e = Date.now()) {
const t = -new Date(e).getTimezoneOffset();
const n = e + t * 6e4;
const r = new Date(n);
const i = t >= 0 ? "+" : "-";
const a = Math.abs(t);
const o = String(Math.floor(a / 60)).padStart(2, "0");
const s = String(a % 60).padStart(2, "0");
return `${String(r.getUTCFullYear()).padStart(4, "0")}-${String(r.getUTCMonth() + 1).padStart(2, "0")}-${String(r.getUTCDate()).padStart(2, "0")}T${String(r.getUTCHours()).padStart(2, "0")}-${String(r.getUTCMinutes()).padStart(2, "0")}-${String(r.getUTCSeconds()).padStart(2, "0")}.${String(r.getUTCMilliseconds()).padStart(3, "0")}${i}${o}-${s}-openclaw-backup`;
}
function buildBackupArchiveBasename(e = Date.now()) {
return `${buildBackupArchiveRoot(e)}.tar.gz`;
}
/** Resolve a backup plan from explicit paths, deduplicating assets already covered by parents. */
async function resolveBackupPlanFromPaths(e) {
const t = e.includeWorkspace ?? true;
const n = e.onlyConfig ?? false;
const r = e.stateDir;
const i = e.configPath;
for (const t of [i, ...(e.configCapture?.files ?? []).map((e) => e.canonicalPath)]) assertNotUpdateCapturePath(t, r);
const a = e.oauthDir;
const o = buildBackupArchiveRoot(e.nowMs);
const s = e.workspaceDirs ?? [];
const c = t ? s : [];
const l = t ? [] : s;
const u = n ? [] : e.agentRoots ?? [];
const d = await canonicalizePathForContainment(r);
const f = await canonicalizePathForContainment(i);
const p = await canonicalizePathForContainment(a);
const m = await createBackupResourcePlan({
stateDir: d,
configPaths: [
i,
f,
...(e.configCapture?.files ?? []).map((e) => e.canonicalPath)
],
oauthDirs: [a, p],
workspaceDirs: await Promise.all(c.map((e) => canonicalizePathForContainment(e))),
excludedWorkspaceDirs: (await Promise.all(l.map(async (e) => [path.resolve(e), await canonicalizePathForContainment(e)].filter((e) => e !== d && !isPathInside(e, d))))).flat(),
agentRoots: u,
pluginResources: e.pluginInventory?.resources ?? [],
pluginRoots: e.pluginInventory?.pluginRoots ?? [],
onlyConfig: n
});
if (n) {
const e = path.resolve(i);
const t = await pathExists(e);
const n = t ? await realpathOrResolve(e) : e;
const s = {
kind: "config",
sourcePath: n,
displayPath: shortenHomePath(n)
};
return {
stateDir: r,
configPath: i,
oauthDir: a,
workspaceDirs: [],
resources: m,
included: t ? [{
...s,
archivePath: buildBackupArchivePath(o, n)
}] : [],
skipped: t ? [] : [{
...s,
reason: "missing"
}]
};
}
const isOwnedPathCoveredBy = (e, t) => {
let n = e;
while (isPathInside(t, n)) {
if (m.isVolatile(n)) return false;
if (n === t) return true;
n = path.dirname(n);
}
return false;
};
const h = [
{
kind: "state",
sourcePath: path.resolve(r)
},
...isOwnedPathCoveredBy(f, d) ? [] : [{
kind: "config",
sourcePath: path.resolve(i)
}],
...isOwnedPathCoveredBy(p, d) ? [] : [{
kind: "credentials",
sourcePath: path.resolve(a)
}],
...(e.configCapture?.files ?? []).filter((e) => e.canonicalPath !== f).map((e) => ({
kind: "config",
sourcePath: e.canonicalPath
})),
...c.map((e) => ({
kind: "workspace",
sourcePath: path.resolve(e)
})),
...u.map((e) => ({
kind: "agent",
sourcePath: e.sourcePath
}))
];
const g = await Promise.all(h.map(async (e) => {
const t = await pathExists(e.sourcePath);
return Object.assign({}, e, {
exists: t,
canonicalPath: t ? await realpathOrResolve(e.sourcePath) : path.resolve(e.sourcePath)
});
}));
for (const e of [{
kind: "config",
sourcePath: path.resolve(i)
}, {
kind: "credentials",
sourcePath: path.resolve(a)
}]) if (isSymlinkPath(e.sourcePath)) g.push({
...e,
canonicalPath: e.sourcePath,
exists: true
});
for (const t of resolveManagedSkillSymlinkTargetCandidates({
stateDir: r,
ownerRoots: g.map((e) => e.canonicalPath),
limits: e.skillDiscoveryLimits ?? resolveSkillDiscoveryLimits()
})) g.push({
kind: "managed skill",
sourcePath: t,
canonicalPath: t,
exists: true
});
const _ = [];
const v = [];
const y = /* @__PURE__ */ new Set();
for (const e of g.toSorted(compareCandidates)) {
const t = isUpdateCapturePath(e.sourcePath, r);
const n = e.canonicalPath !== e.sourcePath && isUpdateCapturePath(e.canonicalPath, r);
if (t || n) {
v.push({
kind: e.kind,
sourcePath: e.sourcePath,
displayPath: shortenHomePath(e.sourcePath),
reason: "private"
});
continue;
}
if (y.has(e.canonicalPath)) continue;
y.add(e.canonicalPath);
_.push(e);
}
const b = [];
for (const e of _) {
if (!e.exists) {
if (e.kind === "agent" && u.some((t) => t.sourcePath === e.canonicalPath && t.sourcePath === path.join(d, "agents", t.agentId, "agent"))) continue;
v.push({
kind: e.kind,
sourcePath: e.sourcePath,
displayPath: shortenHomePath(e.sourcePath),
reason: "missing"
});
continue;
}
const t = b.find((t) => e.kind === "config" || e.kind === "credentials" ? isOwnedPathCoveredBy(e.canonicalPath, t.sourcePath) : isPathInside(t.sourcePath, e.canonicalPath));
if (t) {
v.push({
kind: e.kind,
sourcePath: e.canonicalPath,
displayPath: shortenHomePath(e.canonicalPath),
reason: "covered",
coveredBy: t.displayPath
});
continue;
}
b.push({
kind: e.kind,
sourcePath: e.canonicalPath,
displayPath: shortenHomePath(e.canonicalPath),
archivePath: buildBackupArchivePath(o, e.canonicalPath)
});
}
const x = m.regenerableRoots.filter((e) => !m.isIncluded(e.sourcePath) && b.some((t) => isPathInside(t.sourcePath, e.sourcePath)));
const S = await Promise.all(x.map((e) => pathExists(e.sourcePath)));
for (const [e, t] of x.entries()) {
if (!S[e]) continue;
v.push({
kind: t.kind,
sourcePath: t.sourcePath,
displayPath: shortenHomePath(t.sourcePath),
reason: "regenerable"
});
}
return {
stateDir: r,
configPath: i,
oauthDir: a,
workspaceDirs: c.map((e) => path.resolve(e)),
configCapture: e.configCapture,
resources: m,
included: b,
skipped: v
};
}
function compareCandidates(e, t) {
return e.canonicalPath.length - t.canonicalPath.length || BACKUP_ASSET_PRIORITY[e.kind] - BACKUP_ASSET_PRIORITY[t.kind] || e.canonicalPath.localeCompare(t.canonicalPath);
}
function resolveManagedSkillSymlinkTargetCandidates(e) {
const t = path.join(e.stateDir, "skills");
const n = /* @__PURE__ */ new Set();
const r = discoverSkillCandidates({
dir: t,
source: "openclaw-managed",
limits: e.limits,
allowedSymlinkTargetRealPaths: []
});
for (const i of r.candidates) {
if (isUpdateCapturePath(i.skillDir, e.stateDir)) continue;
if (!loadSingleSkillDirectory({
skillDir: i.skillDir,
source: "openclaw-managed",
rootRealPath: i.skillDirRealPath,
maxBytes: e.limits.maxSkillFileBytes
})) continue;
const r = path.relative(t, i.skillDir);
if (path.isAbsolute(r) || r === ".." || r.startsWith(`..${path.sep}`)) continue;
const a = [t];
for (const e of r.split(path.sep).filter(Boolean)) a.push(path.join(a.at(-1) ?? t, e));
for (const t of a) {
if (!isSymlinkPath(t)) continue;
const r = tryRealpath(t);
if (!r || e.ownerRoots.some((e) => isPathInside(e, r) || isPathInside(r, e))) continue;
n.add(r);
}
}
return [...n];
}
/** Resolve symlinks in the existing prefix while retaining a not-yet-created suffix. */
async function canonicalizePathForContainment(e) {
const t = path.resolve(e);
const n = [];
let r = t;
while (true) try {
const e = await fs$1.realpath(r);
return n.length === 0 ? e : path.join(e, ...n.toReversed());
} catch {
const e = path.dirname(r);
if (e === r) return t;
n.push(path.basename(r));
r = e;
}
}
async function resolveBackupAgentRoot(e, t) {
const n = resolveAgentDir(e, t);
assertNotUpdateCapturePath(n, resolveStateDir());
const r = await canonicalizePathForContainment(n);
return {
agentId: t,
sourcePath: r,
databasePath: path.join(r, "openclaw-agent.sqlite")
};
}
async function resolveBackupAgentRoots(e) {
return await Promise.all(listAgentIds(e).map((t) => resolveBackupAgentRoot(e, t)));
}
async function resolveBackupPlanFromDisk(e = {}) {
if (e.onlyConfig) return {
...await resolveBackupPlanFromState(e),
databaseSelection: void 0,
databaseConfig: void 0
};
assertNotUpdateCapturePath(resolveOpenClawStateSqlitePath(), resolveStateDir());
const t = await createConfigIO({
observe: false,
pluginValidation: "core-only"
}).readConfigFileSnapshot();
const n = await resolveDatabaseEngineSelection(t.config);
return {
...await withDatabaseEngineSelection(n, () => n.effectiveEngines.state === "postgres" ? resolveBackupPlanFromState(e) : withOpenClawStateDatabaseReadSnapshot(() => resolveBackupPlanFromState(e))),
databaseSelection: n,
databaseConfig: t.config
};
}
async function resolveBackupPlanFromState(e) {
const t = e.includeWorkspace ?? true;
const n = e.onlyConfig ?? false;
const r = resolveStateDir();
const i = resolveConfigPath();
const a = resolveOAuthDir();
if (n) return await resolveBackupPlanFromPaths({
stateDir: r,
configPath: i,
oauthDir: a,
includeWorkspace: false,
onlyConfig: true,
nowMs: e.nowMs
});
const o = getDatabaseEngineInput("state") !== void 0;
const s = {
observe: false,
...o ? { pluginValidation: "core-only" } : {}
};
const c = await createConfigIO(s).readConfigFileSnapshotForWrite();
const l = c.snapshot;
const u = await resolveLegacyConfigSnapshotForBackup(l) ?? l;
const d = await resolveBackupConfigCapture(c, s);
if (u.exists && !u.valid) throw new Error(`Backup discovery failed at ${shortenHomePath(u.path)}: ${u.issues.map((e) => e.message).join("; ")}. Agent and plugin ownership could not be resolved. Resolve the reported error and retry backup, or use --only-config to save the config alone.`);
const f = buildCleanupPlan({
cfg: u.config,
stateDir: r,
configPath: i,
oauthDir: a
}).workspaceDirs;
const p = await resolveBackupAgentRoots(u.config);
const m = {
config: u.config,
env: process.env,
stateDir: r,
workspaceDirs: f
};
const h = o ? (await (await import("./backup-database-discovery-CYhLn5Yb.mjs")).preparePostgresBackupDiscovery(m)).pluginInventory : resolveActivatedPluginBackupInventory(m);
if (!t && u.valid) {
f.push(...await readExistingWorktreePaths(process.env));
const e = u.config.agents?.defaults?.workspace?.trim();
if (e) f.push(resolveUserPath(e));
}
return await resolveBackupPlanFromPaths({
stateDir: r,
configPath: i,
oauthDir: a,
workspaceDirs: f,
agentRoots: p,
pluginInventory: h,
configCapture: d,
includeWorkspace: t,
onlyConfig: n,
skillDiscoveryLimits: resolveSkillDiscoveryLimits(u.config),
nowMs: e.nowMs
});
}
//#endregion
export { recordBackupOutcomeBestEffort as a, resolveBackupArchivePath as c, canonicalizePathForContainment as i, resolveBackupPlanFromDisk as l, buildBackupArchiveBasename as n, resolveBackupAgentRoot as o, buildBackupArchiveRoot as r, resolveBackupAgentRoots as s, BACKUP_MAX_DECOMPRESSION_RATIO as t, resolveRequiredBackupPath as u };