UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

230 lines (229 loc) • 9.52 kB
import { o as writeRuntimeJson } from "./runtime-B-SLYP-m.mjs"; import { r as terminalText } from "./safe-text-C80HAQ2e.mjs"; import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import { p as shortenHomePath } from "./utils-C8YECn2Q.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { n as formatDiskSpaceBytes, r as tryReadDiskSpace } from "./disk-space-B5Tl0OOd.mjs"; import { s as readConfigFileSnapshot } from "./io.runtime-DsJ2dLCQ.mjs"; import "./config-CMA-J084.mjs"; import { t as buildBackupArchivePath } from "./backup-archive-path-policy-Cr8KWL_A.mjs"; import { r as extract } from "./esm-C2faEQS9.mjs"; import { a as resolveLegacyConfigSnapshotForBackup } from "./automatic-config-repair-BMcsN3sp.mjs"; import { c as resolveBackupArchivePath, i as canonicalizePathForContainment, s as resolveBackupAgentRoots, t as BACKUP_MAX_DECOMPRESSION_RATIO } from "./backup-shared-BmR-itzA.mjs"; import { r as prepareRestoredClientCredentials } from "./client-credential-restore-CZMFMeth.mjs"; import { n as prepareBackupArchive } from "./backup-verify-CZepSavJ.mjs"; import path from "node:path"; import fs from "node:fs/promises"; import { isPathInside } from "@openclaw/fs-safe/path"; //#region src/commands/backup-restore.ts const BACKUP_RESTORE_WARNINGS = [ "Restoring an archive is time travel: every restored state surface rolls back to the archive timestamp.", "Messaging-channel credentials with ratchet state, especially WhatsApp, may desynchronize after rollback and require relinking.", "Approvals and delivery/dedupe state also roll back; review pending approvals before resuming the Gateway.", "Plugin node_modules are not archived; after activation, run `openclaw plugins update <id>` or reinstall with `openclaw plugins install <spec> --force`.", "Generated plugin-skills links are not archived; after activation, run `openclaw skills list` or start an agent session to rebuild them." ]; const BACKUP_RESTORE_FREE_SPACE_RESERVE_BYTES = 268435456; async function assertTargetOutsideLiveState(e) { const [t, n] = await Promise.all([canonicalizePathForContainment(e), canonicalizePathForContainment(resolveStateDir())]); if (isPathInside(n, t)) throw new Error(`Backup restore target must be outside the live OpenClaw state directory: ${e}`); const r = await readConfigFileSnapshot({ observe: false }); const i = await resolveLegacyConfigSnapshotForBackup(r); if (!i) return; const a = await resolveBackupAgentRoots(i.config); for (const { sourcePath: n } of a) if (isPathInside(n, t)) throw new Error(`Backup restore target must be outside the live OpenClaw agent directory: ${e}`); } async function prepareRestoreTarget(e) { try { if (!(await fs.lstat(e)).isDirectory()) throw new Error(`Backup restore target must be a directory: ${e}`); if ((await fs.readdir(e)).length > 0) throw new Error(`Backup restore target directory must be empty: ${e}`); return { created: false }; } catch (e) { if (e.code !== "ENOENT") throw e; } await fs.mkdir(e, { recursive: true, mode: 448 }); return { created: true }; } function assertRestoreCapacity(e, t) { const n = tryReadDiskSpace(e); if (!n) return; const r = t + BACKUP_RESTORE_FREE_SPACE_RESERVE_BYTES; if (r <= n.availableBytes) return; const i = path.resolve(e) === path.resolve(n.checkedPath) ? e : `${e} (volume checked at ${n.checkedPath})`; throw new Error(`Backup restore requires ${formatDiskSpaceBytes(r)} of free space at ${i} (${formatDiskSpaceBytes(t)} archive data plus ${formatDiskSpaceBytes(BACKUP_RESTORE_FREE_SPACE_RESERVE_BYTES)} reserve), but only ${formatDiskSpaceBytes(n.availableBytes)} is available. Choose a target on a volume with enough free space.`); } async function cleanupFailedRestore(e, t) { if (t) { await fs.rm(e, { recursive: true, force: true }); return; } for (const t of await fs.readdir(e)) await fs.rm(path.join(e, t), { recursive: true, force: true }); } async function extractBackupArchive(e, t, n, r) { let i; await extract({ file: e, gzip: true, maxDecompressionRatio: BACKUP_MAX_DECOMPRESSION_RATIO, cwd: t, strict: false, preserveOwner: false, filter: (e) => !r.has(e), onReadEntry: (e) => { const t = n.get(e.path); if (t !== void 0) e.linkpath = t; }, onwarn: (e, t, n) => { i ??= n instanceof Error ? n : Object.assign(/* @__PURE__ */ new Error(`${e}: ${t}`), n); } }); if (i) throw i; } async function restorePostgresExports(e, t, n, r, i, a) { if (t.length === 0) { a?.(); return; } if (!n) throw new Error("PostgreSQL archive restore requires its captured configuration."); const o = path.join(e, n); if (!isPathInside(await fs.realpath(e), await fs.realpath(o))) throw new Error("PostgreSQL recovery configuration must be inside the restored archive."); const { discardPostgresRestores: s, preparePostgresRestore: c, readBackupEngineImage: l, runOfflineDatabaseBackup: u } = await import("./database-backup-ZFHLPLfI.mjs"); const { publishVerifiedSqliteFile: d } = await import("./sqlite-snapshot-DGhn22ul.mjs"); const f = []; for (const n of t) { const t = path.join(e, n.anchorPath); const r = l(t, t); if (r.engine !== "postgres") throw new Error(`PostgreSQL backup artifact has no matched anchor: ${n.anchorPath}`); f.push({ ...n, source: r }); } await u(e, async ({ config: t, assertCurrent: n }) => { const r = await fs.mkdtemp(path.join(e, ".postgres-restore-")); const i = []; try { const s = path.join(r, "openclaw.json"); await fs.rename(o, s); for (const [a, o] of f.entries()) { const s = path.join(e, o.anchorPath); const l = path.join(r, `${a}.sqlite`); const u = await c({ directory: path.join(e, o.directoryPath), anchorPath: l, config: t, profile: "user-backup", expectedSource: o.source, assertCurrent: n }); i.push({ sourcePath: l, targetPath: s, content: u }); } for (const e of i) { n(); await fs.unlink(e.targetPath); await d({ sourcePath: e.sourcePath, sourceIdentity: await fs.lstat(e.sourcePath, { bigint: true }), targetPath: e.targetPath, expectedContent: e.content, requireAtomicPublication: true, beforePublish: async () => n(), afterPublish: (e) => e.assertTargetMatchesExpectedContent(n) }); } n(); a?.(); for (const { directoryPath: t } of f) for (const n of [ "manifest.json", "anchor.sqlite", "database.sqlite" ]) await fs.unlink(path.join(e, t, n)); n(); await fs.rename(s, o); await fs.rm(r, { recursive: true, force: true }); } catch (e) { try { await s(t, i.map(({ content: e }) => e.namespace)); } catch (t) { throw new AggregateError([e, t], `PostgreSQL restore failed and its scratch namespaces could not be cleaned: ${formatErrorMessage(t)}`, { cause: e }); } throw e; } }, { configPath: path.join(e, r ?? n), configSourcePath: o, env: { ...process.env, OPENCLAW_INCLUDE_ROOTS: path.join(e, i, "payload") }, mapIncludePath: (t) => isPathInside(e, t) ? t : path.join(e, buildBackupArchivePath(i, t)) }); } function formatRestoreResult(e) { return [ terminalText`Backup archive restored to staging: ${shortenHomePath(e.targetPath)}`, terminalText`Verified archive: ${shortenHomePath(e.archivePath)}`, terminalText`Archive root: ${e.archiveRoot}`, terminalText`Archive entries restored: ${e.entryCount}`, "", "Rollback warnings:", ...e.warnings.map((e) => terminalText`- ${e}`), "", "Activation is explicit: stop the Gateway, move the restored asset tree into place or point OPENCLAW_STATE_DIR at the restored state asset, then run `openclaw doctor`." ].join("\n"); } /** Verify first, then extract a whole backup archive into a fresh staging directory. */ async function backupRestoreCommand(e, t) { const n = resolveBackupArchivePath(t.target, "--target"); await assertTargetOutsideLiveState(n); const { result: r, hardlinkTargets: i, symbolicLinks: a, regularFileExtractionBytes: o, databaseRestoreCandidates: s, recoveryConfigPath: c, recoveryConfigContextPath: l, manifest: u } = await prepareBackupArchive(t.archive); assertRestoreCapacity(n, o); const d = await prepareRestoreTarget(n); try { await extractBackupArchive(r.archivePath, n, i, new Set(a.map(({ entryPath: e }) => e))); const e = prepareRestoredClientCredentials({ manifest: u, targetPath: n }); for (const { entryPath: e } of a) await fs.mkdir(path.dirname(path.join(n, e)), { recursive: true }); for (const { entryPath: e, linkpath: t } of a) await fs.symlink(t, path.join(n, e)); await restorePostgresExports(n, s, c, l, r.archiveRoot, e); } catch (e) { try { await cleanupFailedRestore(n, d.created); } catch (t) { throw new AggregateError([e, t], `Backup restore failed and the incomplete target could not be cleaned: ${n}. Cleanup error: ${formatErrorMessage(t)}`, { cause: e }); } throw new Error(`Backup restore failed; the incomplete target was cleaned: ${n}. ${formatErrorMessage(e)}`, { cause: e }); } const f = { ...r, targetPath: n, warnings: [ ...BACKUP_RESTORE_WARNINGS, ...r.warnings ?? [], ...(r.externalSymbolicLinks ?? []).map(({ entryPath: e, linkpath: t }) => `External link restored (target not copied through link): ${JSON.stringify(e)} -> ${JSON.stringify(t)}`) ] }; if (t.json) writeRuntimeJson(e, f); else e.log(formatRestoreResult(f)); return f; } //#endregion export { backupRestoreCommand };