openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
4 lines • 8.74 kB
JavaScript
import{r as resolveHomeRelativePath}from"./home-dir-DEN5DisQ.mjs";import{n as cloneConfigWithResolutionFacts}from"./resolution-facts-DYKtoyes.mjs";import{i as ensureAbsoluteDirectory,l as pathExists,w as statRegularFileSync,x as root}from"./fs-safe-Bxzu1j4h.mjs";import{_ as resolveDefaultAgentId,f as resolveAgentWorkspaceDir,r as resolveAgentConfig}from"./agent-scope-config-CG9CFpGX.mjs";import{r as sha256HexPrefixCore}from"./node-crypto-DPk8agfR.mjs";import"./agent-scope-Dw5XRSEh.mjs";import{h as redactMigrationPlan,l as markMigrationItemConflict,n as MIGRATION_REASON_TARGET_EXISTS,t as MIGRATION_REASON_MISSING_SOURCE_OR_TARGET,u as markMigrationItemError}from"./migration-B8ObiJfa.mjs";import{n as assertMemoryMigrationSourceRevision,t as MAX_MEMORY_MIGRATION_FILE_BYTES}from"./memory-migration-source-ChYNCcXZ.mjs";import path from"node:path";import crypto from"node:crypto";import fs from"node:fs/promises";import{hasNodeErrorCode}from"@openclaw/fs-safe/path";import{writeTextAtomic}from"@openclaw/fs-safe/atomic";
//!src/plugin-sdk/migration-runtime.ts
function resolvePlannedMigrationTargets(e){const t=e.config;const n=e.targetAgentId??resolveDefaultAgentId(t);const r=resolveAgentWorkspaceDir(t,n);const i=resolveAgentConfig(t,n)?.agentDir?.trim();const a=e.runtime?.agent?.resolveAgentDir(t,n)??(i?resolveHomeRelativePath(i):void 0)??path.join(e.stateDir,`agents`,n,`agent`);return{workspaceDir:r,stateDir:e.stateDir,agentDir:a}}function withCachedMigrationConfigRuntime(e,t){if(!e)return;const n=e.config;let r;function current(e){r??=cloneConfigWithResolutionFacts(n.current({clone:true})??t);return e?.clone?cloneConfigWithResolutionFacts(r):r}return{...e,config:{...e.config,current,mutateConfigFile:async e=>{const t=await n.mutateConfigFile(e);r=cloneConfigWithResolutionFacts(t.nextConfig);return t},replaceConfigFile:async e=>{const t=await n.replaceConfigFile(e);r=cloneConfigWithResolutionFacts(t.nextConfig);return t}}}}async function allocateMigrationBackupPath(e,t){const n=path.join(t,`item-backups`);await fs.mkdir(n,{recursive:true});const r=sha256HexPrefixCore(path.resolve(e),12);const i=await fs.mkdtemp(path.join(n,`${Date.now()}-${r}-`));return path.join(i,path.basename(e))}async function backupMigrationItemTarget(e,t,n={}){if(!await pathExists(e))return;const r=await allocateMigrationBackupPath(e,t);await fs.cp(e,r,{recursive:true,force:true,...n.dereference===void 0?{}:{dereference:n.dereference}});return r}async function backupMemoryMigrationTarget(e,t,n){const r=await allocateMigrationBackupPath(e,n);await fs.writeFile(r,t,{flag:`wx`,mode:384});return r}async function persistMemoryMigrationRecoveryRecord(e,t){await writeTextAtomic(e,JSON.stringify({version:1,...t},null,2),{mode:384,trailingNewline:true})}async function writeMemoryMigrationRecoveryRecord(e){const t=path.join(path.dirname(e.backupPath),`recovery-${crypto.randomUUID()}.json`);await persistMemoryMigrationRecoveryRecord(t,{...e,status:`prepared`});return t}function errorCode(e){return e&&typeof e===`object`&&`code`in e?String(e.code):void 0}async function openMemoryMigrationRoot(e){const t={hardlinks:`reject`,maxBytes:MAX_MEMORY_MIGRATION_FILE_BYTES,mkdir:true,symlinks:`reject`};try{return await root(e,t)}catch(e){if(errorCode(e)!==`not-found`&&errorCode(e)!==`ENOENT`)throw e}const n=await ensureAbsoluteDirectory(e,{scopeLabel:`memory import workspace`,mode:448});if(!n.ok)throw n.error;return await root(n.path,t)}function moveMemoryMigrationFile(e,t,n){return e.move(t,n,{overwrite:false,assertBeforeMutation:()=>{if(statRegularFileSync(path.join(e.rootReal,t)).missing)throw new Error(`Memory migration file no longer exists`)}})}function isFileAlreadyExistsError(e){return hasNodeErrorCode(e,`ERR_FS_CP_EEXIST`)||hasNodeErrorCode(e,`EEXIST`)}function markMigrationItemFailure(e,t,n=isFileAlreadyExistsError(t)){return n?markMigrationItemConflict(e,MIGRATION_REASON_TARGET_EXISTS):markMigrationItemError(e,t instanceof Error?t.message:String(t))}function readArchiveRelativePath(e){const t=e.details?.archiveRelativePath;const n=typeof t===`string`&&t.trim()?t:void 0;const r=e.source?path.basename(e.source):e.id;return path.normalize(n??r).split(path.sep).filter(e=>e&&e!==`.`&&e!==`..`).join(path.sep)||`item`}async function resolveUniqueArchivePath(e,t){const n=path.parse(t);let r=path.join(e,t);let i=2;while(await pathExists(r)){const t=`${n.name}-${i}${n.ext}`;r=path.join(e,n.dir,t);i+=1}return r}async function archiveMigrationItem(e,t){if(!e.source)return markMigrationItemError(e,MIGRATION_REASON_MISSING_SOURCE_OR_TARGET);try{if((await fs.lstat(e.source)).isSymbolicLink())return markMigrationItemError(e,`archive source is a symlink`);const n=path.join(t,`archive`);const r=readArchiveRelativePath(e);const i=await resolveUniqueArchivePath(n,r);await fs.mkdir(path.dirname(i),{recursive:true});await fs.cp(e.source,i,{recursive:true,force:false,errorOnExist:true,verbatimSymlinks:true});return{...e,status:`migrated`,target:i,details:{...e.details,archivePath:i,archiveRelativePath:r}}}catch(t){return markMigrationItemFailure(e,t)}}async function copyMigrationFileItem(e,t,n={}){if(!e.source||!e.target)return markMigrationItemError(e,MIGRATION_REASON_MISSING_SOURCE_OR_TARGET);let r=e;try{if(await pathExists(e.target)&&!n.overwrite)return markMigrationItemConflict(e,MIGRATION_REASON_TARGET_EXISTS);const i=n.overwrite?await backupMigrationItemTarget(e.target,t):void 0;r={...e,details:{...e.details,...i?{backupPath:i}:{}}};await fs.mkdir(path.dirname(e.target),{recursive:true});await fs.cp(e.source,e.target,{recursive:true,force:Boolean(n.overwrite),errorOnExist:!n.overwrite});return{...r,status:`migrated`}}catch(e){return markMigrationItemFailure(r,e)}}async function copyMemoryMigrationFileItem(e,t,n){if(!e.source||!e.target)return markMigrationItemError(e,MIGRATION_REASON_MISSING_SOURCE_OR_TARGET);let r;let i;let a;let o;let s;let c;let l;let u=false;let d;const persistRecoveryStatus=async(e,t)=>{if(s&&r&&c)await persistMemoryMigrationRecoveryRecord(s,{backupPath:r,recoveryPath:c,status:e,target:t})};try{const f=path.resolve(n.workspaceDir);l=path.relative(f,path.resolve(e.target));d=await openMemoryMigrationRoot(f);const{buffer:p}=await(await root(path.dirname(e.source),{hardlinks:`reject`,maxBytes:MAX_MEMORY_MIGRATION_FILE_BYTES,symlinks:`reject`})).read(path.basename(e.source));assertMemoryMigrationSourceRevision(e,p);if(n.overwrite===true&&await d.exists(l)){const n=await d.read(l);r=await backupMemoryMigrationTarget(e.target,n.buffer,t);a=path.join(`.openclaw-memory-import-staging`,crypto.randomUUID());i=path.join(a,path.basename(l));const u=path.join(d.rootReal,i);c=u;await d.mkdir(a);s=await writeMemoryMigrationRecoveryRecord({backupPath:r,recoveryPath:u,target:e.target});o=u;await moveMemoryMigrationFile(d,l,i);const f=await d.read(i);if(!f.buffer.equals(n.buffer)){r=await backupMemoryMigrationTarget(e.target,f.buffer,t);await persistRecoveryStatus(`prepared`,e.target)}}await d.create(l,p,{mkdir:true,mode:384});u=true;await persistRecoveryStatus(`complete`,e.target);if(i){await d.remove(i);i=void 0;o=void 0}if(a){await d.remove(a);await d.remove(`.openclaw-memory-import-staging`).catch(()=>void 0)}if(s)try{await fs.unlink(s);s=void 0}catch{}return{...e,status:`migrated`,details:{...e.details,...r?{backupPath:r}:{},...s?{recoveryRecordPath:s}:{}}}}catch(t){if(d&&i&&l&&!u)try{if(!await d.exists(i))o=void 0;else if(!await d.exists(l)){await moveMemoryMigrationFile(d,i,l);i=void 0;o=void 0}}catch{}await persistRecoveryStatus(u?`complete`:o?`recovery-required`:`safe`,e.target).catch(()=>void 0);const n={...e.details,...r?{backupPath:r}:{},...o?{recoveryPath:o}:{},...s?{recoveryRecordPath:s}:{}};return markMigrationItemFailure({...e,details:n},t,isFileAlreadyExistsError(t)||errorCode(t)===`already-exists`)}}async function writeMigrationReport(e,t={}){if(!e.reportDir)return;await fs.mkdir(e.reportDir,{recursive:true});await fs.writeFile(path.join(e.reportDir,`report.json`),`${JSON.stringify(redactMigrationPlan(e),null,2)}\n`,`utf8`);const n=[`# ${t.title??`Migration Report`}`,``,`Source: ${e.source}`,e.target?`Target: ${e.target}`:void 0,e.backupPath?`Backup: ${e.backupPath}`:void 0,``,`Migrated: ${e.summary.migrated}`,`Skipped: ${e.summary.skipped}`,`Conflicts: ${e.summary.conflicts}`,`Errors: ${e.summary.errors}`,``,...e.items.map(e=>`- ${e.status}: ${e.id}${e.reason?` (${e.reason})`:``}`)].filter(e=>typeof e===`string`);await fs.writeFile(path.join(e.reportDir,`summary.md`),`${n.join(`
`)}\n`,`utf8`)}export{resolvePlannedMigrationTargets as a,copyMigrationFileItem as i,backupMigrationItemTarget as n,withCachedMigrationConfigRuntime as o,copyMemoryMigrationFileItem as r,writeMigrationReport as s,archiveMigrationItem as t};