UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

15 lines • 28.4 kB
import{k as resolveDateTimestampMs}from"./number-coercion-B3CfI447.mjs";import{n as sliceUtf16Safe}from"./utf16-slice-DA3Mllbx.mjs";import{a as publishFileExclusive,f as syncDirectoryIfSupported,n as getPublishFileExclusiveFailureDetails,r as isHardlinkFallbackError,s as requireDirectorySync}from"./directory-durability-o_aQCRBZ.mjs";import{i as createAbortError}from"./src-De06gkOi.mjs";import{u as resolveHomeDir}from"./utils-Dlk0IYAa.mjs";import{t as isAbortError}from"./abort-signal-BKkRe6pu.mjs";import{t as sleep}from"./sleep-B4CgCyZu.mjs";import{n as ignoreMissingPath,r as isErrno,t as hasErrnoCode}from"./errno-DUBt6SQQ.mjs";import{v as resolveGatewayLockDir}from"./paths-D_FOvGon.mjs";import"./errors-D37BJTfI.mjs";import{r as createLazyRuntimeModule}from"./lazy-runtime-Ds6M7vp4.mjs";import{o as pathEntryExists,p as safeStat}from"./path-existence-BR9MXlgL.mjs";import{u as resolveRuntimeServiceVersion}from"./version-DrZ9Nfde.mjs";import{a as withArtifactPreservingStateReads}from"./artifact-preserving-state-reads-CWuQPqxe.mjs";import{t as listDatabaseEngineStores}from"./registry-ByN-O5dB.mjs";import{a as withDatabaseEngineSelection}from"./context-DZjni16e.mjs";import{a as resolveCommandProcessSignal,p as withCommandProcessScope}from"./exec-spawn-DNCbDcyJ.mjs";import{s as recordArchiveSymbolicLink,t as buildBackupArchivePath}from"./backup-archive-path-policy-CotYunH-.mjs";import{a as isLegacyAuditMigrationBackupPath,i as hasLegacyAuditBackupSources}from"./backup-volatile-filter-C7OiuXr0.mjs";import{n as isUpdateCapturePath}from"./update-capture-paths-C5GOuESg.mjs";import{n as describeCapturedBackupSqliteSnapshots,r as sealBackupResourceInventory}from"./backup-resource-inventory-VtmOfu9w.mjs";import{u as runOfflineDatabaseBackup}from"./database-backup-yFN_P503.mjs";import{a as BackupSqliteSourceAppearedError,o as withBackupSqliteDiscoveryRetry}from"./backup-sqlite-source-groups-BENi3PrL.mjs";import{a as LegacyAuditBackupStateChangedError,i as stripSqliteSidecarSuffix,n as createBackupSqliteSnapshotPlan,o as createLegacyAuditBackupCapture,s as legacyAuditBackupCapturesMatch,t as classifyBackupSqliteSource}from"./backup-sqlite-snapshot-Or92jyhp.mjs";import{i as stageBackupConfigCapture}from"./backup-config-capture-CXz3HMQ-.mjs";import{t as encodeBackupManifest}from"./backup-verify-manifest-B0AbwU0Y.mjs";import{c as resolveBackupArchivePath,i as canonicalizePathForContainment,l as resolveBackupPlanFromDisk,n as buildBackupArchiveBasename,r as buildBackupArchiveRoot}from"./backup-shared-CVcoDGTC.mjs";import{t as withLegacyAuditMigrationLease}from"./state-migrations.audit-coordination-C2qj4zJ_.mjs";import{n as finishBackupScratch,r as maintainBackupScratch,t as createBackupScratchDirectory}from"./backup-scratch-C-DF8QD0.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,{availableParallelism}from"node:os";import{promisify}from"node:util";import{sameFileIdentity}from"@openclaw/fs-safe/advanced";import{isPathInside}from"@openclaw/fs-safe/path";import{gzip}from"node:zlib";import{Readable,Transform}from"node:stream";import{finished,pipeline as pipeline$1}from"node:stream/promises"; //!src/infra/backup-gzip.ts const compress=promisify(gzip);const BLOCK_BYTES=4194304;const MAX_CONCURRENCY=4;async function*gzipInParallel(e,t=Math.min(MAX_CONCURRENCY,availableParallelism())){const n=[];let r=[];let i=0;let a=false;const submit=()=>{const e=compress(Buffer.concat(r,i));e.catch(()=>void 0);n.push(e);a=true;r=[];i=0};try{for await(const a of e)for(let e=0;e<a.length;){const o=a.subarray(e,e+BLOCK_BYTES-i);r.push(o);i+=o.length;e+=o.length;if(i===BLOCK_BYTES){submit();if(n.length>=t)yield await n.shift()}}if(i>0||!a)submit();while(n.length>0)yield await n.shift()}finally{await Promise.allSettled(n)}} //!src/infra/backup-create-stream.ts const BACKUP_ARCHIVE_IDLE_TIMEOUT_MS=3e5;function appendBackupManifest(e,t){async function*sealed(){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()}return Readable.from(gzipInParallel(sealed()),{objectMode:false})}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=n=>{if(u)return;if(n){c=n;if(n.entryPath)s=n.entryPath;if(n.bytes){const t=n.phase===`output`?`output`:n.phase===`raw`?`raw`:void 0;if(t){l[t]+=n.bytes;e.onProgress?.({stage:`archive-write`,phase:`progress`,bytes:l.raw,outputBytes:l.output})}}}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{e.onProgress?.({stage:`archive-write`,phase:`start`});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();e.onProgress?.({stage:`archive-write`,phase:`done`,bytes:l.raw,outputBytes:l.output});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)}} //!src/infra/backup-archive-publication.ts 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){if(hasErrnoCode(t,`ENOENT`)||hasErrnoCode(t,`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`)}}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)}.`)})} //!src/infra/backup-legacy-audit-snapshot.ts const MAX_LEGACY_AUDIT_CAPTURE_ATTEMPTS=3;async function createLegacyAuditStateSnapshotPlan(e){const t=e.stateDir;if(e.preserveSourceArtifacts)throw new Error(`Source-artifact-preserving backup requires legacy audit migration to finish before capture; no source write lease was acquired.`);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 n=await withLegacyAuditMigrationLease(t,()=>createLegacyAuditBackupCapture({stateDir:t,tempDir:i}));const r=await createBackupSqliteSnapshotPlan({resources:e.resources,tempDir:i,legacyAuditSnapshots:n.snapshots,legacyAuditDatabaseWitness:n.databaseWitness,onProgress:e.onProgress});await fs$1.mkdir(a,{recursive:true});const o=await withLegacyAuditMigrationLease(t,()=>createLegacyAuditBackupCapture({stateDir:t,tempDir:a}));if(!legacyAuditBackupCapturesMatch(n,o))throw new LegacyAuditBackupStateChangedError;await fs$1.rm(a,{recursive:true,force:true});return{legacyAuditSnapshots:n.snapshots,stateSqliteBackup:r}}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`)} //!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){if(e instanceof BackupSqliteSourceAppearedError)throw 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())}} //!src/infra/backup-tar-walk.ts async function*walkBackupTar(e){const t=process.platform===`win32`?0:constants.O_NOFOLLOW;const n=process.platform===`win32`?0:constants.O_NONBLOCK;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(r,i){e.signal?.throwIfAborted();e.onProgress(r);if(e.skip(r))return;let a;let o;let s;let c;let l;try{try{s=await fs$1.lstat(r,{bigint:true});o=await fs$1.lstat(r);if(i)await assertDirectory(i);if(!e.filter(r,o))return;if(o.isDirectory()){c=await fs$1.readdir(r);await assertDirectory({sourcePath:r,identity:s})}else if(o.isSymbolicLink()){l=await fs$1.readlink(r);if(process.platform===`win32`)l=l.replaceAll(`\\`,`/`)}else if(o.isFile()){a=await fs$1.open(r,constants.O_RDONLY|t|n);const e=await a.stat({bigint:true});const i=await a.stat();if(!i.isFile())throw new Error(`Backup source changed while opening: ${r}`);if(!t){const t=await fs$1.lstat(r,{bigint:true}).catch(ignoreMissingPath);if(t?.isSymbolicLink())throw new Error(`Backup source became a symbolic link while opening: ${r}`);if(!sameFileIdentity(s,e)&&(!t?.isFile()||!sameFileIdentity(t,e)))throw new Error(`Backup source identity changed while opening: ${r}`)}o=i}else return;if(i)await assertDirectory(i)}catch(t){ignoreMissingPath(t);e.onVanished(r);return}e.signal?.throwIfAborted();const u=o.isDirectory();let d=(o.mode&4095|384)&-19;if(u)d|=(d&292)>>2;const f={path:r,type:u?`Directory`:o.isSymbolicLink()?`SymbolicLink`:`File`,mode:d,size:a?o.size:0,mtime:u?void 0:o.mtime,linkpath:l};e.onEntry(r,f);if(u)f.path+=`/`;const p=Buffer.alloc(512);if(new e.tar.Header(f).encode(p))yield new e.tar.Pax(f).encode();yield p;if(a){let t=0;while(t<o.size){e.signal?.throwIfAborted();const n=Buffer.allocUnsafe(Math.min(1048576,o.size-t));const{bytesRead:i}=await a.read(n,0,n.length,t);e.signal?.throwIfAborted();if(!i)throw Object.assign(/* @__PURE__ */ new Error(`encountered unexpected EOF`),{code:`EOF`,path:r});t+=i;e.onProgress(r,i);yield n.subarray(0,i)}const n=(512-o.size%512)%512;if(n)yield Buffer.alloc(n)}}finally{await a?.close()}for(const e of c??[])yield*visit(path.join(r,e),{sourcePath:r,identity:s});if(c&&!i)await assertDirectory({sourcePath:r,identity:s})}for(const t of e.paths)yield*visit(t);yield Buffer.alloc(1024)} //!src/infra/backup-create.ts const loadTarRuntime=createLazyRuntimeModule(()=>import(`./esm--0ovmyUj.mjs`));async function resolveOutputPath(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}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,...e.localCompanion?{profile:`local-companion`}:{},createdAt:e.createdAt,archiveRoot:e.archiveRoot,runtimeVersion:resolveRuntimeServiceVersion(),platform:process.platform,nodeVersion:process.version,options:{includeWorkspace:e.includeWorkspace,...e.excludeWorktreeTemplates?{excludeWorktreeTemplates:true}:{},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}))}}async function createConsistentStateSnapshotPlan(e){const captureSqlite=t=>createBackupSqliteSnapshotPlan({resources:e.resources,tempDir:t,legacyAuditSnapshots:[],preserveSourceArtifacts:e.preserveSourceArtifacts,localCompanion:e.localCompanion,onProgress:e.onProgress});if(e.onlyConfig||!e.stateDir)return{legacyAuditSnapshots:[],stateSqliteBackup:e.onlyConfig?{inventory:sealBackupResourceInventory(e.resources,[]),snapshots:[],postgresSnapshots:[],postgresAnchors:[],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})}return createLegacyAuditStateSnapshotPlan({resources:e.resources,stateDir:t,tempDir:e.tempDir,preserveSourceArtifacts:e.preserveSourceArtifacts,onProgress:e.onProgress})}async function createBackupArchive(e={}){const t=e.localCompanion?{...e,preserveSourceArtifacts:true}:e;const capture=()=>withCommandProcessScope(()=>createBackupArchiveInScope(t),t.signal);return await(t.preserveSourceArtifacts?withArtifactPreservingStateReads(capture,{agentDatabases:true}):capture())}async function createBackupArchiveInScope(e){const t=resolveDateTimestampMs(e.nowMs);const n=Boolean(e.onlyConfig);const r=n?false:e.includeWorkspace??true;const i={...e,nowMs:t,onlyConfig:n,includeWorkspace:r};e.onProgress?.({stage:`plan`,phase:`start`});const a=await resolveBackupPlanFromDisk(i);e.onProgress?.({stage:`plan`,phase:`done`});const o=a.databaseSelection;const capture=()=>withBackupSqliteDiscoveryRetry(e=>createBackupArchiveAttempt(i,a,e),e.log);if(e.localCompanion){if(n||!o?.postgres||listDatabaseEngineStores().some(e=>e.postgres&&o.effectiveEngines[e.id]!==`postgres`))throw new Error(`Local companion capture requires PostgreSQL for all portable database families.`);return withDatabaseEngineSelection(o,capture)}if(!e.dryRun&&o?.postgres&&a.databaseConfig)return runOfflineDatabaseBackup(a.stateDir,capture,{config:a.databaseConfig,selection:o},{online:true});return capture()}async function createBackupArchiveAttempt(e,t,n){const{nowMs:r,onlyConfig:i,includeWorkspace:a}=e;const o=buildBackupArchiveRoot(r);const s=await resolveOutputPath({output:e.output,nowMs:r,includedAssets:t.included,stateDir:t.stateDir,preferHomeOutput:e.preferHomeOutput});if(t.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 c=await canonicalizePathForContainment(s);const l=t.included.find(e=>isPathInside(e.sourcePath,c));if(l)throw new Error(`Backup output must not be written inside a source path: ${s} is inside ${l.sourcePath}`);if(!e.dryRun)await assertOutputPathReady(s);const u=new Date(r).toISOString();const d=t.included.find(e=>e.kind===`state`);const f=t.resources.stateDir;const p={createdAt:u,archiveRoot:o,archivePath:s,dryRun:Boolean(e.dryRun),includeWorkspace:a,...e.excludeWorktreeTemplates?{excludeWorktreeTemplates:true}:{},...e.excludeMigrationBackups?{excludeMigrationBackups:true}:{},onlyConfig:i,...e.localCompanion?{localCompanion:true}:{},verified:false,assets:t.included,...i?{}:{agentRoots:t.resources.agentRoots.map(({agentId:e,sourcePath:t})=>({agentId:e,sourcePath:t}))},skipped:t.skipped,skippedVolatileCount:0};if(e.dryRun)return p;await prepareBackupOutputParent(s);const m=await chooseBackupTempRoot({assets:p.assets,outputPath:s});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(s)}catch(t){await finishBackupScratch(g,e.log);throw formatBackupOutputFailure(t,s,`publication`)}const y=v.tempArchivePath;let b=[];try{const r=await stageBackupConfigCapture(t.configCapture,_);const{legacyAuditSnapshots:a,stateSqliteBackup:c}=await createConsistentStateSnapshotPlan({resources:t.resources,stateDir:d?.sourcePath,tempDir:_,onlyConfig:i,preserveSourceArtifacts:e.preserveSourceArtifacts,localCompanion:e.localCompanion,onProgress:e.onProgress});const l=c.inventory;const u=c.snapshots.map(e=>e.archiveSourcePath);for(const e of n)if(!u.includes(e))throw new Error(`Newly discovered SQLite database could not be snapshotted: ${e}`);b=describeCapturedBackupSqliteSnapshots(l,u);const m=new Map(r);const h=new Set(r.values());if(t.configCapture?.files.length===0){h.add(path.resolve(t.configPath));h.add(await canonicalizePathForContainment(t.configPath))}for(const e of[...c.snapshots,...a]){m.set(path.resolve(e.sourcePath),e.archiveSourcePath);for(const t of e.skippedSourcePaths)h.add(t)}const g=new Set(l.coreDatabases.filter(e=>(e.role===`client`||e.role===`services`)&&e.identity).map(e=>path.dirname(e.sourcePath)));const x=/* @__PURE__ */ new Set([...g,...m.keys(),...p.assets.map(e=>e.sourcePath)]);const S=[];const C=await loadTarRuntime();const w=resolveGatewayLockDir(t.stateDir);const T=/* @__PURE__ */ new Map;const E=/* @__PURE__ */ new Map;const D=i||t.stateDir!==l.stateDir;const tarFilter=(n,r)=>{const a=path.resolve(n);const o=m.get(a)??a;if(D&&isUpdateCapturePath(o,t.stateDir))return false;const s=r.isDirectory();if(!i&&!(s||r.isSymbolicLink()?l.isTraversable(o):l.isIncluded(o)))return false;if(e.localCompanion&&path.basename(a).toLowerCase().endsWith(`.postgres`))throw new Error(`Local-companion checkpoints cannot contain PostgreSQL export directories: ${n}. Move the export outside the backup sources and retry.`);if(isPathInside(w,a))return false;if(d&&isLegacyAuditMigrationBackupPath(a,d.sourcePath))return false;const c=i?void 0:classifyBackupSqliteSource(a,l);if(c===`opaque-skip`){E.set(a,`skipped`);return false}if(c===`excluded`)return false;if(c===`sqlite`&&(r.isFile()||r.isSymbolicLink()))throw new BackupSqliteSourceAppearedError(stripSqliteSidecarSuffix(a));if(c===`opaque`&&r.isFile())E.set(a,`archived`);return true};const O=await writeTarArchiveWithRetry({tempArchivePath:y,log:e.log,runTar:async n=>{const r=/* @__PURE__ */ new Set;for(const[e,t]of T)if(t===`volatile`)T.delete(e);S.length=0;E.clear();const i=await writeArchiveStreamToFile({archivePath:n,onProgress:e.onProgress,createArchiveStream:(n,i)=>appendBackupManifest(walkBackupTar({tar:C,signal:i,paths:[...x],skip:e=>{if(g.has(e)){if(r.has(e))return true;r.add(e)}if(!x.has(e)&&l.isVolatile(e)){T.set(e,`volatile`);return true}return h.has(e)||c.discoveredSourcePaths.has(e)},filter:tarFilter,onVanished:e=>{if(x.has(e))throw new Error(`Required backup source disappeared: ${e}`);E.delete(e);T.set(e,`vanished`)},onProgress:(e,t)=>n({phase:t===void 0?`traversal`:`raw`,entryPath:e,bytes:t}),onEntry:(e,t)=>{T.delete(e);const n=buildBackupArchivePath(o,m.get(e)??e);if(t.type===`SymbolicLink`){const{external:e,...r}=recordArchiveSymbolicLink({archiveRoot:o,entryPath:n,linkpath:t.linkpath,platform:process.platform,state:{sourcePath:f,archivePath:buildBackupArchivePath(o,f)},hasExternalLinkReport:true,assets:p.assets});if(e)S.push(r)}t.path=n}}),()=>{p.skipped=[...t.skipped,...[...T].map(([e,t])=>({kind:`entry`,sourcePath:e,displayPath:e,reason:t}))];const n=buildManifest({...p,skipped:t.skipped},t);if(c.sharedDatabaseSourcePath!==void 0)n.paths={...n.paths,sharedDatabaseSourcePath:c.sharedDatabaseSourcePath};n.externalSymbolicLinks=S;n.sqliteSnapshots=b.map(e=>e.role===`agent`?{sourcePath:e.sourcePath,role:`agent`,agentId:e.agentId}:{sourcePath:e.sourcePath,role:`global`});n.postgresSnapshots=c.postgresSnapshots.map(e=>({archivePath:`${buildBackupArchivePath(o,e.sourcePath)}.postgres`,manifestSha256:e.manifestSha256}));if(e.localCompanion)n.postgresAnchors=c.postgresAnchors;return encodeBackupManifest(n)}),onPartialArchive:e=>{v.pendingCleanupArchives.push(e)}});try{await t.configCapture?.assertRootAlias?.()}catch(e){if(!removePreparedBackupArchive(i))v.pendingCleanupArchives.push(i);throw e}return i}}).catch(e=>{throw formatBackupOutputFailure(e,s,`write`,v.stagingDir)});p.skippedVolatileCount=[...T.values()].filter(e=>e===`volatile`).length;const k=[...[...E].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}`),...[...T].filter(([,e])=>e===`vanished`).map(([e])=>`Skipped vanished entry (ENOENT): ${e}`)];if(k.length)p.warnings=[...p.warnings??[],...k];if(S.length)p.externalSymbolicLinks=S;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:O,log:e.log})}catch(e){throw formatBackupOutputFailure(e,s,`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?.(b);return p}export{createBackupArchive as n,chooseBackupTempRoot as t};