openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
851 lines (850 loc) • 30 kB
JavaScript
import { k as resolveDateTimestampMs } from "./number-coercion-D6u-4YD8.mjs";
import { n as sliceUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { n as ignoreMissingPath, r as isErrno, t as hasErrnoCode } from "./errno-DFcoqIT9.mjs";
import { f as safeStat, o as pathEntryExists } from "./path-existence-Co7-GyVr.mjs";
import { d as resolveHomeDir } from "./utils-C8YECn2Q.mjs";
import { i as createAbortError } from "./src-BPmQBLJp.mjs";
import { t as isAbortError } from "./abort-signal-D4Q6SEw7.mjs";
import { t as sleep } from "./sleep-CkI3nkiJ.mjs";
import { v as resolveGatewayLockDir } from "./paths-DAcAg5aV.mjs";
import "./errors-BKzCeTYb.mjs";
import { l as resolveRuntimeServiceVersion } from "./version-GlxUMdxI.mjs";
import { a as publishFileExclusive, f as syncDirectoryIfSupported, n as getPublishFileExclusiveFailureDetails, r as isHardlinkFallbackError, s as requireDirectorySync } from "./directory-durability-DlnWwNmv.mjs";
import { r as createLazyRuntimeModule } from "./lazy-runtime-zGjszCtt.mjs";
import { f as withCommandProcessScope, i as resolveCommandProcessSignal } from "./exec-spawn-DMKoejF-.mjs";
import { s as recordArchiveSymbolicLink, t as buildBackupArchivePath } from "./backup-archive-path-policy-Cr8KWL_A.mjs";
import { a as isLegacyAuditMigrationBackupPath, i as hasLegacyAuditBackupSources } from "./backup-volatile-filter-Wvq7R1eh.mjs";
import { n as isUpdateCapturePath } from "./update-capture-paths-B2WcdTCG.mjs";
import { n as describeCapturedBackupSqliteSnapshots, r as sealBackupResourceInventory } from "./backup-resource-inventory-BFHpUA98.mjs";
import { s as runOfflineDatabaseBackup } from "./database-backup-B6k1k0NC.mjs";
import { a as createLegacyAuditBackupCapture, i as LegacyAuditBackupStateChangedError, n as createBackupSqliteSnapshotPlan, o as legacyAuditBackupCapturesMatch, t as classifyBackupSqliteSource } from "./backup-sqlite-snapshot-D5T0ii_w.mjs";
import { i as stageBackupConfigCapture } from "./backup-config-capture-C4dP9zCI.mjs";
import { c as resolveBackupArchivePath, i as canonicalizePathForContainment, l as resolveBackupPlanFromDisk, n as buildBackupArchiveBasename, r as buildBackupArchiveRoot } from "./backup-shared-BmR-itzA.mjs";
import { t as encodeBackupManifest } from "./backup-verify-manifest-CVAAAU_5.mjs";
import { n as finishBackupScratch, r as maintainBackupScratch, t as createBackupScratchDirectory } from "./backup-scratch-DYV2vJfy.mjs";
import { t as withLegacyAuditMigrationLease } from "./state-migrations.audit-coordination-C-Hh_-9w.mjs";
import fs, { constants, createWriteStream } from "node:fs";
import path from "node:path";
import { randomUUID } from "node:crypto";
import fs$1 from "node:fs/promises";
import os from "node:os";
import { sameFileIdentity } from "@openclaw/fs-safe/advanced";
import { isPathInside } from "@openclaw/fs-safe/path";
import { createGzip } from "node:zlib";
import { Transform, compose } from "node:stream";
import { finished, pipeline as pipeline$1 } from "node:stream/promises";
//#region src/infra/backup-create-stream.ts
const BACKUP_ARCHIVE_IDLE_TIMEOUT_MS = 3e5;
/** Seal the manifest from observed entries after the single payload traversal. */
function appendBackupManifest(e, t) {
return compose(e, async function* (e) {
let n = Buffer.alloc(0);
for await (const t of e) {
const e = Math.max(0, n.length - Math.max(0, 1024 - t.length));
if (e) yield n.subarray(0, e);
n = e < n.length ? Buffer.concat([n.subarray(e), t]) : t;
}
if (n.length > 1024) yield n.subarray(0, -1024);
yield t();
}, createGzip());
}
function removePreparedBackupArchive(e) {
let t;
try {
t = fs.lstatSync(e.archivePath, { bigint: true });
} catch {
return false;
}
if (!t.isFile() || !sameFileIdentity(e.identity, t)) return false;
try {
fs.unlinkSync(e.archivePath);
return true;
} catch {
return false;
}
}
async function writeArchiveStreamToFile(e) {
const t = new AbortController();
const n = resolveCommandProcessSignal(t.signal);
n.throwIfAborted();
let r = false;
let i;
let a;
let o;
let s;
let c;
const l = {
output: 0,
raw: 0
};
let u = false;
const describeProgress = () => {
const e = s ? `, entry=${JSON.stringify(sliceUtf16Safe(s, -512))}` : "";
return `phase=${c?.phase ?? "starting"}${e}, rawBytes=${l.raw}, outputBytes=${l.output}`;
};
const reportProgress = (e) => {
if (u) return;
if (e) {
c = e;
if (e.entryPath) s = e.entryPath;
if (e.bytes) {
const t = e.phase === "output" ? "output" : e.phase === "raw" ? "raw" : void 0;
if (t) l[t] += e.bytes;
}
}
a = a?.refresh() ?? setTimeout(() => {
o = /* @__PURE__ */ new Error(`Backup archive write stalled: no progress observed for ${BACKUP_ARCHIVE_IDLE_TIMEOUT_MS}ms (${describeProgress()})`);
t.abort(o);
}, BACKUP_ARCHIVE_IDLE_TIMEOUT_MS);
};
const d = new Transform({ transform(e, t, n) {
reportProgress({
phase: "output",
bytes: e.length
});
n(null, e);
} });
const f = createWriteStream(e.archivePath, {
flags: "wx",
flush: true,
mode: 384
});
f.once("open", (e) => {
r = true;
try {
i = fs.fstatSync(e, { bigint: true });
} catch (e) {
f.destroy(e);
}
});
try {
const t = e.createArchiveStream(reportProgress, n);
const r = pipeline$1(t, d, f, { signal: n });
reportProgress();
await r;
const a = await fs$1.lstat(e.archivePath, { bigint: true });
if (!i?.isFile() || !a.isFile() || !sameFileIdentity(i, a)) throw new Error(`Backup archive path changed while writing: ${e.archivePath}`);
n.throwIfAborted();
return {
archivePath: e.archivePath,
identity: a
};
} catch (t) {
let a = o ?? t;
if (!o && n.aborted && t instanceof Error && isAbortError(t)) {
const e = createAbortError(`${t.message} (${describeProgress()})`, { cause: t });
if ("code" in t && (typeof t.code === "string" || typeof t.code === "number")) Object.assign(e, { code: t.code });
a = e;
}
f.destroy();
await finished(f, { cleanup: true }).catch(() => void 0);
if (!r) throw a;
let s = { archivePath: e.archivePath };
if (i) s.identity = i;
else try {
const t = fs.lstatSync(e.archivePath, { bigint: true });
if (t.isFile()) s.identity = t;
} catch (e) {
if (e.code === "ENOENT") s = void 0;
}
if (s && (!s.identity || !removePreparedBackupArchive(s))) e.onPartialArchive(s);
throw a;
} finally {
u = true;
clearTimeout(a);
}
}
//#endregion
//#region src/infra/backup-archive-publication.ts
function pathsEqual(e, t) {
const n = path.resolve(e);
const r = path.resolve(t);
return process.platform === "win32" ? n.toLowerCase() === r.toLowerCase() : n === r;
}
async function removeDirectoryIfOwned(e, t) {
const n = await fs$1.lstat(e, { bigint: true }).catch(() => void 0);
if (!n || !n.isDirectory() || !sameFileIdentity(t, n)) return false;
try {
await fs$1.rmdir(e);
return true;
} catch {
return false;
}
}
async function createBackupArchivePublication(e) {
const t = path.resolve(e);
const n = path.dirname(t);
const r = await fs$1.realpath(n);
const i = await fs$1.lstat(r, { bigint: true });
if (!i.isDirectory()) throw new Error(`Backup output parent is not a directory: ${n}`);
const a = path.join(r, path.basename(t));
if (await pathEntryExists(a)) throw new Error(`Refusing to overwrite existing backup archive: ${a}`);
const o = await fs$1.mkdtemp(path.join(r, `.openclaw-backup-publish-${randomUUID()}-`));
let s;
try {
s = await fs$1.lstat(o, { bigint: true });
await fs$1.chmod(o, 448);
return {
canonicalOutputPath: a,
canonicalParentPath: r,
parentReceipt: {
path: r,
realPath: r,
identity: i
},
pendingCleanupArchives: [],
requestedOutputPath: t,
requestedParentPath: n,
stagingDir: o,
stagingIdentity: s,
tempArchivePath: path.join(o, "archive.tar.gz.tmp")
};
} catch (e) {
if (s) await removeDirectoryIfOwned(o, s);
throw e;
}
}
function retainArchiveForCleanup(e, t) {
for (const [n, r] of e.pendingCleanupArchives.entries()) {
if (!pathsEqual(r.archivePath, t.archivePath)) continue;
if (r.identity && t.identity) {
if (!sameFileIdentity(r.identity, t.identity)) continue;
} else if (!r.identity && t.identity) e.pendingCleanupArchives[n] = t;
return;
}
e.pendingCleanupArchives.push(t);
}
async function removePendingBackupArchive(e, t) {
if (!pathsEqual(path.dirname(t.archivePath), e.stagingDir)) return false;
let n = t.identity;
if (!n) {
try {
n = await fs$1.lstat(t.archivePath, { bigint: true });
} catch (e) {
return e.code === "ENOENT";
}
if (!n.isFile()) return false;
}
return removePreparedBackupArchive({
archivePath: t.archivePath,
identity: n
});
}
async function cleanupBackupArchivePublication(e, t) {
const n = e.pendingCleanupArchives.splice(0);
for (const t of n) if (!await removePendingBackupArchive(e, t)) retainArchiveForCleanup(e, t);
if (await removeDirectoryIfOwned(e.stagingDir, e.stagingIdentity)) {
await syncDirectoryIfSupported(e.canonicalParentPath).catch(() => void 0);
return;
}
if (await fs$1.lstat(e.stagingDir).catch(() => void 0)) t?.(`Backup archiver preserved changed or non-empty staging directory ${e.stagingDir}.`);
}
async function publishPreparedBackupArchive(e) {
const { plan: t, prepared: n } = e;
let r = false;
let i;
try {
try {
resolveCommandProcessSignal()?.throwIfAborted();
const e = await publishFileExclusive({
sourcePath: n.archivePath,
targetPath: t.canonicalOutputPath,
expectedSourceIdentity: n.identity,
parentReceipt: t.parentReceipt,
strategy: "link-required",
onSyncFailure: "preserve"
});
r = true;
requireDirectorySync(e.directorySync, "Backup publication directory");
} catch (e) {
const n = getPublishFileExclusiveFailureDetails(e);
r ||= n?.cleanup === "preserved";
let i;
if (e.code === "EEXIST") i = `Refusing to overwrite existing backup archive: ${t.requestedOutputPath}`;
else if (isHardlinkFallbackError(e)) i = `Atomic backup publication requires hard-link support in ${t.requestedParentPath}.`;
else if (e.code === "path-mismatch") i = `Backup archive changed during publication: ${t.requestedOutputPath}`;
else throw e;
throw new Error(i, { cause: e });
}
} catch (e) {
i = { error: e };
}
if (i && r) e.log?.(`Backup archiver preserved the final archive after publication failed: ${t.requestedOutputPath}.`);
if (!removePreparedBackupArchive(n)) {
retainArchiveForCleanup(t, n);
if (!i) e.log?.(`Backup archiver preserved changed staging file ${n.archivePath}.`);
}
const a = await removeDirectoryIfOwned(t.stagingDir, t.stagingIdentity);
if (i) throw i.error;
if (!a) e.log?.(`Backup archiver preserved changed or non-empty staging directory ${t.stagingDir}.`);
await syncDirectoryIfSupported(t.canonicalParentPath).catch((n) => {
e.log?.(`Backup archiver could not sync cleanup in ${t.canonicalParentPath}: ${n.code ?? String(n)}.`);
});
}
//#endregion
//#region src/infra/backup-output-path.ts
async function resolveBackupOutputPath(e) {
const t = buildBackupArchiveBasename(e.nowMs);
const n = e.output;
if (!n?.trim()) {
const insideSource = async (t) => {
const n = await fs$1.realpath(t).catch(() => t);
return e.includedAssets.some((e) => isPathInside(e.sourcePath, n));
};
const n = resolveHomeDir();
if (e.preferHomeOutput && n && !await insideSource(path.resolve(n))) return path.resolve(n, t);
const r = path.resolve(process.cwd());
const i = await insideSource(r) ? n ?? path.dirname(e.stateDir) : r;
return path.resolve(i, t);
}
const r = resolveBackupArchivePath(n, "--output");
if (n.endsWith("/") || n.endsWith("\\")) return path.join(r, t);
if ((await safeStat(r))?.isDirectory()) return path.join(r, t);
return r;
}
//#endregion
//#region src/infra/backup-tar-retry.ts
const BACKUP_TAR_MAX_ATTEMPTS = 3;
const BACKUP_TAR_BACKOFF_MS = [1e4, 2e4];
async function writeTarArchiveWithRetry(e) {
for (let t = 1;; t += 1) {
const n = t === 1 ? e.tempArchivePath : `${e.tempArchivePath}.retry-${t}`;
let r;
try {
return await e.runTar(n);
} catch (e) {
r = e;
}
if (!hasErrnoCode(r, "EOF") || t === BACKUP_TAR_MAX_ATTEMPTS) {
const e = r instanceof Error ? r : new Error(String(r));
const n = r?.path;
const i = `after ${t} attempt${t === 1 ? "" : "s"}`;
const a = n ? ` (last offending path: ${n}, ${i})` : ` (${i})`;
throw new Error(`Backup archive write failed: ${e.message}${a}`, { cause: e });
}
const i = BACKUP_TAR_BACKOFF_MS[t - 1] ?? 0;
const a = r.path;
e.log?.(`Backup archiver hit a live-write race${a ? ` on ${a}` : ""} (attempt ${t}/${BACKUP_TAR_MAX_ATTEMPTS}); retrying in ${Math.round(i / 1e3)}s.`);
await sleep(i, resolveCommandProcessSignal());
}
}
//#endregion
//#region src/infra/backup-tar-walk.ts
/** Open sources before emitting headers so a vanished name cannot leave a partial entry. */
async function* walkBackupTar(e) {
const t = process.platform === "win32" ? 0 : constants.O_NOFOLLOW;
const assertDirectory = async ({ sourcePath: e, identity: t }) => {
const n = await fs$1.lstat(e, { bigint: true });
if (!n.isDirectory() || !sameFileIdentity(t, n)) throw new Error(`Backup directory changed during traversal: ${e}`);
};
async function* visit(n, r) {
e.signal?.throwIfAborted();
e.onProgress(n);
if (e.skip(n)) return;
let i;
let a;
let o;
let s;
let c;
try {
try {
o = await fs$1.lstat(n, { bigint: true });
a = await fs$1.lstat(n);
if (r) await assertDirectory(r);
if (!e.filter(n, a)) return;
if (a.isDirectory()) {
s = await fs$1.readdir(n);
await assertDirectory({
sourcePath: n,
identity: o
});
} else if (a.isSymbolicLink()) {
c = await fs$1.readlink(n);
if (process.platform === "win32") c = c.replaceAll("\\", "/");
} else if (a.isFile()) {
i = await fs$1.open(n, constants.O_RDONLY | t);
const e = await i.stat({ bigint: true });
const r = await i.stat();
if (!r.isFile()) throw new Error(`Backup source changed while opening: ${n}`);
if (!t) {
const t = await fs$1.lstat(n, { bigint: true }).catch(ignoreMissingPath);
if (t?.isSymbolicLink()) throw new Error(`Backup source became a symbolic link while opening: ${n}`);
if (!sameFileIdentity(o, e) && (!t?.isFile() || !sameFileIdentity(t, e))) throw new Error(`Backup source identity changed while opening: ${n}`);
}
a = r;
} else return;
if (r) await assertDirectory(r);
} catch (t) {
ignoreMissingPath(t);
e.onVanished(n);
return;
}
e.signal?.throwIfAborted();
const l = a.isDirectory();
let u = (a.mode & 4095 | 384) & -19;
if (l) u |= (u & 292) >> 2;
const d = {
path: n,
type: l ? "Directory" : a.isSymbolicLink() ? "SymbolicLink" : "File",
mode: u,
size: i ? a.size : 0,
mtime: l ? void 0 : a.mtime,
linkpath: c
};
e.onEntry(n, d);
if (l) d.path += "/";
const f = Buffer.alloc(512);
if (new e.tar.Header(d).encode(f)) yield new e.tar.Pax(d).encode();
yield f;
if (i) {
let t = 0;
while (t < a.size) {
e.signal?.throwIfAborted();
const r = Buffer.allocUnsafe(Math.min(1048576, a.size - t));
const { bytesRead: o } = await i.read(r, 0, r.length, t);
e.signal?.throwIfAborted();
if (!o) throw Object.assign(/* @__PURE__ */ new Error("encountered unexpected EOF"), {
code: "EOF",
path: n
});
t += o;
e.onProgress(n, o);
yield r.subarray(0, o);
}
const r = (512 - a.size % 512) % 512;
if (r) yield Buffer.alloc(r);
}
} finally {
await i?.close();
}
for (const e of s ?? []) yield* visit(path.join(n, e), {
sourcePath: n,
identity: o
});
if (s && !r) await assertDirectory({
sourcePath: n,
identity: o
});
}
for (const t of e.paths) yield* visit(t);
yield Buffer.alloc(1024);
}
//#endregion
//#region src/infra/backup-create.ts
const loadTarRuntime = createLazyRuntimeModule(() => import("./esm-D7u8voq8.mjs"));
function formatBackupOutputFailure(e, t, n, r) {
const i = n === "write" && e instanceof Error ? e.cause : void 0;
const a = isErrno(e) ? e : isErrno(i) ? i : null;
if (!a) return e;
if (r) {
const t = a.path;
if (typeof t !== "string" || !isPathInside(r, path.resolve(t))) return e;
}
const o = path.dirname(t);
const s = "run `openclaw backup create --output <archive>` again.";
let c;
switch (a.code) {
case "ENOENT":
c = `Backup output directory could not be created: ${o}. Check the path and ${s}`;
break;
case "EACCES":
case "EPERM":
case "EROFS":
c = `Backup output directory is not writable: ${o}. Check the path and directory permissions, then ${s}`;
break;
case "EEXIST":
case "ENOTDIR":
if (n !== "parent") return e;
c = `Backup output parent is not a directory: ${o}. Choose a directory path and ${s}`;
break;
case "ENOSPC":
c = `The destination does not have enough free space: ${o}. Free up disk space and ${s}`;
break;
case "EDQUOT":
c = `The destination storage quota is exhausted: ${o}. Free up space or choose another path, then ${s}`;
break;
default: c = `The output path could not be prepared: ${o}. Check the path and filesystem, then ${s}`;
}
return new Error(`Backup archive creation failed: ${t}. ${c}`, { cause: e });
}
async function assertOutputPathReady(e) {
try {
await fs$1.access(e);
throw new Error(`Refusing to overwrite existing backup archive: ${e}`);
} catch (t) {
const n = t?.code;
if (n === "ENOENT" || n === "ENOTDIR") return;
throw formatBackupOutputFailure(t, e, "parent");
}
}
async function prepareBackupOutputParent(e) {
try {
await fs$1.mkdir(path.dirname(e), { recursive: true });
} catch (t) {
throw formatBackupOutputFailure(t, e, "parent");
}
}
async function chooseBackupTempRoot(e) {
const t = os.tmpdir();
const n = await canonicalizePathForContainment(t);
const r = e.assets.find((e) => isPathInside(e.sourcePath, n));
if (!r) return t;
const i = e.outputPath ? path.dirname(e.outputPath) : path.dirname(r.sourcePath);
const a = await canonicalizePathForContainment(i);
const o = e.assets.find((e) => isPathInside(e.sourcePath, a));
if (o) throw new Error(`Backup temp root cannot be placed outside every source path: ${t} and ${i} both overlap ${o.sourcePath}.`);
return i;
}
function buildManifest(e, t) {
return {
schemaVersion: 1,
createdAt: e.createdAt,
archiveRoot: e.archiveRoot,
runtimeVersion: resolveRuntimeServiceVersion(),
platform: process.platform,
nodeVersion: process.version,
options: {
includeWorkspace: e.includeWorkspace,
onlyConfig: e.onlyConfig
},
paths: {
stateDir: t.resources.stateDir,
configPath: t.configPath,
...t.configCapture?.files[0] ? { configSourcePath: t.configCapture.files[0].canonicalPath } : {},
oauthDir: t.oauthDir,
workspaceDirs: t.workspaceDirs,
...e.agentRoots ? { agentRoots: [...e.agentRoots] } : {}
},
assets: e.assets.map((e) => ({
kind: e.kind,
sourcePath: e.sourcePath,
archivePath: e.archivePath
})),
skipped: e.skipped.map((e) => ({
kind: e.kind,
sourcePath: e.sourcePath,
reason: e.reason,
coveredBy: e.coveredBy
}))
};
}
const MAX_LEGACY_AUDIT_CAPTURE_ATTEMPTS = 3;
async function createConsistentStateSnapshotPlan(e) {
const captureSqlite = (t, n) => createBackupSqliteSnapshotPlan({
resources: e.resources,
tempDir: t,
legacyAuditSnapshots: n?.snapshots ?? [],
...n ? { legacyAuditDatabaseWitness: n.databaseWitness } : {}
});
if (e.onlyConfig || !e.stateDir) return {
legacyAuditSnapshots: [],
stateSqliteBackup: e.onlyConfig ? {
inventory: sealBackupResourceInventory(e.resources, []),
snapshots: [],
postgresSnapshots: [],
discoveredSourcePaths: /* @__PURE__ */ new Set()
} : await captureSqlite(e.tempDir)
};
const t = e.stateDir;
if (!await hasLegacyAuditBackupSources(t)) {
const n = path.join(e.tempDir, "state-snapshot-no-legacy");
await fs$1.mkdir(n, { recursive: true });
const r = await captureSqlite(n);
if (!await hasLegacyAuditBackupSources(t)) return {
legacyAuditSnapshots: [],
stateSqliteBackup: r
};
await fs$1.rm(n, {
recursive: true,
force: true
});
}
let n;
for (let r = 0; r < MAX_LEGACY_AUDIT_CAPTURE_ATTEMPTS; r += 1) {
const i = path.join(e.tempDir, `state-snapshot-attempt-${r + 1}`);
const a = path.join(i, "legacy-verification");
await fs$1.mkdir(i, { recursive: true });
try {
const e = await withLegacyAuditMigrationLease(t, () => createLegacyAuditBackupCapture({
stateDir: t,
tempDir: i
}));
const n = await captureSqlite(i, e);
await fs$1.mkdir(a, { recursive: true });
const r = await withLegacyAuditMigrationLease(t, () => createLegacyAuditBackupCapture({
stateDir: t,
tempDir: a
}));
if (!legacyAuditBackupCapturesMatch(e, r)) throw new LegacyAuditBackupStateChangedError();
await fs$1.rm(a, {
recursive: true,
force: true
});
return {
legacyAuditSnapshots: e.snapshots,
stateSqliteBackup: n
};
} catch (e) {
await fs$1.rm(i, {
recursive: true,
force: true
});
if (!(e instanceof LegacyAuditBackupStateChangedError)) throw e;
n = e.message;
}
}
throw new LegacyAuditBackupStateChangedError(`${n ?? "Legacy audit state changed while backup was capturing it"}; retry backup after legacy audit migration settles`);
}
async function createBackupArchive(e = {}) {
return await withCommandProcessScope(() => createBackupArchiveInScope(e), e.signal);
}
async function createBackupArchiveInScope(e, t) {
const n = resolveDateTimestampMs(e.nowMs);
const r = buildBackupArchiveRoot(n);
const i = Boolean(e.onlyConfig);
const a = i ? false : e.includeWorkspace ?? true;
const o = t ?? await resolveBackupPlanFromDisk({
includeWorkspace: a,
onlyConfig: i,
nowMs: n
});
const s = o.databaseSelection;
if (!t && !e.dryRun && s?.postgres && o.databaseConfig) return runOfflineDatabaseBackup(o.stateDir, () => createBackupArchiveInScope({
...e,
nowMs: n
}, o), {
config: o.databaseConfig,
selection: s
});
const c = await resolveBackupOutputPath({
output: e.output,
nowMs: n,
includedAssets: o.included,
stateDir: o.stateDir,
preferHomeOutput: e.preferHomeOutput
});
if (o.included.length === 0) throw new Error(i ? "No OpenClaw config file was found to back up." : "No local OpenClaw state was found to back up.");
const l = await canonicalizePathForContainment(c);
const u = o.included.find((e) => isPathInside(e.sourcePath, l));
if (u) throw new Error(`Backup output must not be written inside a source path: ${c} is inside ${u.sourcePath}`);
if (!e.dryRun) await assertOutputPathReady(c);
const d = o.included.find((e) => e.kind === "state");
const f = o.resources.stateDir;
const p = {
createdAt: new Date(n).toISOString(),
archiveRoot: r,
archivePath: c,
dryRun: Boolean(e.dryRun),
includeWorkspace: a,
onlyConfig: i,
verified: false,
assets: o.included,
...i ? {} : { agentRoots: o.resources.agentRoots.map(({ agentId: e, sourcePath: t }) => ({
agentId: e,
sourcePath: t
})) },
skipped: o.skipped,
skippedVolatileCount: 0
};
if (e.dryRun) return p;
await prepareBackupOutputParent(c);
const m = await chooseBackupTempRoot({
assets: p.assets,
outputPath: c
});
await fs$1.mkdir(m, { recursive: true });
const h = await maintainBackupScratch({
roots: [m],
repair: true,
log: e.log
});
if (h.warnings.length) p.warnings = h.warnings;
for (const t of h.reclaimed) e.log?.(`Removed abandoned backup scratch: ${t}`);
const g = await createBackupScratchDirectory(m);
const _ = g.directory;
let v;
try {
v = await createBackupArchivePublication(c);
} catch (t) {
await finishBackupScratch(g, e.log);
throw formatBackupOutputFailure(t, c, "publication");
}
let y = [];
try {
const t = await stageBackupConfigCapture(o.configCapture, _);
const { legacyAuditSnapshots: n, stateSqliteBackup: a } = await createConsistentStateSnapshotPlan({
resources: o.resources,
stateDir: d?.sourcePath,
tempDir: _,
onlyConfig: i
});
const s = a.inventory;
y = describeCapturedBackupSqliteSnapshots(s, a.snapshots.map((e) => e.archiveSourcePath));
const l = new Map(t);
const u = new Set(t.values());
if (o.configCapture?.files.length === 0) {
u.add(path.resolve(o.configPath));
u.add(await canonicalizePathForContainment(o.configPath));
}
for (const e of [...a.snapshots, ...n]) {
l.set(path.resolve(e.sourcePath), e.archiveSourcePath);
for (const t of e.skippedSourcePaths) u.add(t);
}
const m = new Set(s.coreDatabases.filter((e) => (e.role === "client" || e.role === "services") && e.identity).map((e) => path.dirname(e.sourcePath)));
const h = /* @__PURE__ */ new Set([
...m,
...l.keys(),
...p.assets.map((e) => e.sourcePath)
]);
const g = [];
const b = await loadTarRuntime();
const x = resolveGatewayLockDir(o.stateDir);
const S = /* @__PURE__ */ new Map();
const C = /* @__PURE__ */ new Map();
const w = i || o.stateDir !== s.stateDir;
const tarFilter = (e, t) => {
const n = path.resolve(e);
const r = l.get(n) ?? n;
if (w && isUpdateCapturePath(r, o.stateDir)) return false;
const a = t.isDirectory();
if (!i && !(a || t.isSymbolicLink() ? s.isTraversable(r) : s.isIncluded(r))) return false;
if (isPathInside(x, n)) return false;
if (d && isLegacyAuditMigrationBackupPath(n, d.sourcePath)) return false;
const c = i ? void 0 : classifyBackupSqliteSource(n, s);
if (c === "opaque-skip") {
C.set(n, "skipped");
return false;
}
if (c === "excluded") return false;
if (c === "sqlite" && (t.isFile() || t.isSymbolicLink())) throw new Error(`SQLite state appeared after snapshot discovery: ${e}. Retry backup so it can be snapshotted.`);
if (c === "opaque" && t.isFile()) C.set(n, "archived");
return true;
};
const T = await writeTarArchiveWithRetry({
tempArchivePath: v.tempArchivePath,
log: e.log,
runTar: async (e) => {
const t = /* @__PURE__ */ new Set();
for (const [e, t] of S) if (t === "volatile") S.delete(e);
g.length = 0;
C.clear();
const n = await writeArchiveStreamToFile({
archivePath: e,
createArchiveStream: (e, n) => appendBackupManifest(walkBackupTar({
tar: b,
signal: n,
paths: [...h],
skip: (e) => {
if (m.has(e)) {
if (t.has(e)) return true;
t.add(e);
}
if (!h.has(e) && s.isVolatile(e)) {
S.set(e, "volatile");
return true;
}
return u.has(e) || a.discoveredSourcePaths.has(e);
},
filter: tarFilter,
onVanished: (e) => {
if (h.has(e)) throw new Error(`Required backup source disappeared: ${e}`);
C.delete(e);
S.set(e, "vanished");
},
onProgress: (t, n) => e({
phase: n === void 0 ? "traversal" : "raw",
entryPath: t,
bytes: n
}),
onEntry: (e, t) => {
S.delete(e);
const n = buildBackupArchivePath(r, l.get(e) ?? e);
if (t.type === "SymbolicLink") {
const { external: e, ...i } = recordArchiveSymbolicLink({
archiveRoot: r,
entryPath: n,
linkpath: t.linkpath,
platform: process.platform,
state: {
sourcePath: f,
archivePath: buildBackupArchivePath(r, f)
},
hasExternalLinkReport: true,
assets: p.assets
});
if (e) g.push(i);
}
t.path = n;
}
}), () => {
p.skipped = [...o.skipped, ...[...S].map(([e, t]) => ({
kind: "entry",
sourcePath: e,
displayPath: e,
reason: t
}))];
const e = buildManifest({
...p,
skipped: o.skipped
}, o);
if (a.sharedDatabaseSourcePath !== void 0) e.paths = {
...e.paths,
sharedDatabaseSourcePath: a.sharedDatabaseSourcePath
};
e.externalSymbolicLinks = g;
e.sqliteSnapshots = y.map((e) => e.role === "agent" ? {
sourcePath: e.sourcePath,
role: "agent",
agentId: e.agentId
} : {
sourcePath: e.sourcePath,
role: "global"
});
e.postgresSnapshots = a.postgresSnapshots.map((e) => ({
archivePath: `${buildBackupArchivePath(r, e.sourcePath)}.postgres`,
manifestSha256: e.manifestSha256
}));
return encodeBackupManifest(e);
}),
onPartialArchive: (e) => {
v.pendingCleanupArchives.push(e);
}
});
try {
await o.configCapture?.assertRootAlias?.();
} catch (e) {
if (!removePreparedBackupArchive(n)) v.pendingCleanupArchives.push(n);
throw e;
}
return n;
}
}).catch((e) => {
throw formatBackupOutputFailure(e, c, "write", v.stagingDir);
});
p.skippedVolatileCount = [...S.values()].filter((e) => e === "volatile").length;
const E = [...[...C].toSorted(([e], [t]) => e.localeCompare(t)).map(([e, t]) => t === "skipped" ? `Skipped unresolvable opaque SQLite link: ${e}` : `SQLite file archived as opaque bytes without a live snapshot or integrity checks: ${e}`), ...[...S].filter(([, e]) => e === "vanished").map(([e]) => `Skipped vanished entry (ENOENT): ${e}`)];
if (E.length) p.warnings = [...p.warnings ?? [], ...E];
if (g.length) p.externalSymbolicLinks = g;
if (p.skippedVolatileCount > 0) e.log?.(`Backup skipped ${p.skippedVolatileCount} volatile file${p.skippedVolatileCount === 1 ? "" : "s"} (live sessions, cron logs, queues, managed runtime paths, sockets, pid/tmp).`);
try {
await publishPreparedBackupArchive({
plan: v,
prepared: T,
log: e.log
});
} catch (e) {
throw formatBackupOutputFailure(e, c, "publication");
}
} finally {
try {
await cleanupBackupArchivePublication(v, e.log);
} finally {
const t = await finishBackupScratch(g, e.log);
if (t) p.warnings = [...p.warnings ?? [], t];
}
}
e.onSqliteSnapshots?.(y);
return p;
}
//#endregion
export { createBackupArchive as n, chooseBackupTempRoot as t };