UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3 lines • 14.6 kB
import{c as resolveUserPath,n as resolveFilesystemPath,t as expandHomePrefix}from"./home-dir-DEN5DisQ.mjs";import{r as terminalText}from"./safe-text-B_QTgn0s.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import{f as shortenHomePath}from"./utils-Dlk0IYAa.mjs";import{l as pathExists}from"./fs-safe-Bxzu1j4h.mjs";import{t as canonicalizeContainmentRoot}from"./path-containment-Drv7Ulmz.mjs";import{T as resolveOAuthDir,m as resolveConfigPath}from"./paths-D_FOvGon.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{i as listAgentIds}from"./agent-roster-4XrgUgPK.mjs";import{a as resolveAgentDir}from"./agent-scope-config-CG9CFpGX.mjs";import{u as realpathOrResolve}from"./path-existence-BR9MXlgL.mjs";import{s as resolveOpenClawStateSqlitePath}from"./openclaw-state-db.paths-CbgXfEg1.mjs";import{n as executeExistingOpenClawStateRead,v as withOpenClawStateDatabaseReadSnapshot}from"./openclaw-state-db-readonly-Cd5_cxBs.mjs";import{a as withDatabaseEngineSelection,t as getDatabaseEngineInput}from"./context-DZjni16e.mjs";import{t as createConfigIO}from"./io.factory-y6nIrp_4.mjs";import{n as resolveDatabaseEngineSelection}from"./config-eTB-xhop.mjs";import"./config-DkZ8y8Gv.mjs";import{s as readExistingWorktreePaths}from"./registry-read-mqD__iTh.mjs";import{c as tryRealpath}from"./skill-paths-DEQTiKUZ.mjs";import{t as loadSingleSkillDirectory}from"./local-loader-DV2mfiws.mjs";import{a as resolveSkillDiscoveryLimits,i as isSymlinkPath,r as discoverSkillCandidates}from"./skill-root-discovery-25v7xJUN.mjs";import{n as throwExpectedCliError}from"./expected-cli-error-oDVmXYil.mjs";import{n as resolveAgentPortRoots}from"./agent-port-B0iL4NPS.mjs";import{r as isDoctorMigrationBackupPath}from"./doctor-migration-backup-names-CKS_r-bJ.mjs";import{t as resolveActivatedPluginBackupInventory}from"./manifest-backup-resources-DHnn3LZ9.mjs";import{t as buildBackupArchivePath}from"./backup-archive-path-policy-CotYunH-.mjs";import{n as isUpdateCapturePath,t as assertNotUpdateCapturePath}from"./update-capture-paths-C5GOuESg.mjs";import{t as createBackupResourcePlan}from"./backup-resource-inventory-VtmOfu9w.mjs";import{r as resolveBackupConfigCapture}from"./backup-config-capture-CXz3HMQ-.mjs";import{t as runWithLocalStateOwner}from"./local-state-owner-fjzTarAw.mjs";import{t as buildCleanupPlan}from"./cleanup-utils-OK0KVVTl.mjs";import{i as recordBackupRunOutcome}from"./backup-run-records-5G1D5f34.mjs";import{a as resolveLegacyConfigSnapshotForBackup}from"./automatic-config-repair-BDdrbCM_.mjs";import{existsSync}from"node:fs";import path from"node:path";import fs$1 from"node:fs/promises";import{isNotFoundPathError,isPathInside}from"@openclaw/fs-safe/path"; //!src/commands/backup-shared.ts const BACKUP_MAX_DECOMPRESSION_RATIO=1100;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)throwExpectedCliError(`Missing required ${t} value.`);return resolveUserPath(n)}function resolveBackupArchivePath(e,t){if(!e?.trim())throwExpectedCliError(`Missing required ${t} value.`);try{return resolveFilesystemPath(expandHomePrefix(e))}catch(e){return throwExpectedCliError(terminalText`Could not resolve ${t}: ${formatErrorMessage(e)}`)}}const BACKUP_ASSET_PRIORITY={state:0,config:1,credentials:2,workspace:3,agent:4,"managed skill":5};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`}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(),excludedWorktreeTemplateDirs:(await Promise.all((e.excludedWorktreeTemplateDirs??[]).map(async e=>[path.resolve(e),await canonicalizePathForContainment(e)]))).flat(),excludedMigrationBackupPaths:(await Promise.all((e.excludedMigrationBackupPaths??[]).map(async e=>[path.resolve(e),await canonicalizePathForContainment(e)]))).flat(),agentRoots:u,pluginResources:e.pluginInventory?.resources??[],pluginRoots:e.pluginInventory?.pluginRoots??[],localCompanion:e.localCompanion,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`})}for(const t of e.excludedMigrationBackupPaths??[])v.push({kind:`migration backup`,sourcePath:path.resolve(t),displayPath:shortenHomePath(path.resolve(t)),reason:`excluded`});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]}const canonicalizePathForContainment=canonicalizeContainmentRoot;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 listDoctorMigrationBackups(e){const t=await Promise.all(e.map(realpathOrResolve));const n=await Promise.all([.../* @__PURE__ */ new Set([...e,...t])].map(async e=>{const t=path.resolve(e);const n=path.dirname(t);return(await fs$1.readdir(n).catch(e=>{if(isNotFoundPathError(e))return[];throw e})).map(e=>path.join(n,e)).filter(e=>isDoctorMigrationBackupPath(t,e))}));return[...new Set(n.flat())].toSorted()}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-4ur3KcRn.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,excludedWorktreeTemplateDirs:(e.excludeWorktreeTemplates?await executeExistingOpenClawStateRead({env:process.env},{type:`worktrees.templates.list`,input:void 0}):void 0)?.records.map(e=>e.path),excludedMigrationBackupPaths:e.excludeMigrationBackups?await listDoctorMigrationBackups([resolveOpenClawStateSqlitePath(),...await resolveAgentPortRoots(m)]):void 0,agentRoots:p,pluginInventory:h,configCapture:d,localCompanion:e.localCompanion,includeWorkspace:t,onlyConfig:n,skillDiscoveryLimits:resolveSkillDiscoveryLimits(u.config),nowMs:e.nowMs})}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};