UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

7 lines • 19.1 kB
import{c as resolveUserPath}from"./home-dir-DEN5DisQ.mjs";import{l as syncDirectory,s as requireDirectorySync}from"./directory-durability-o_aQCRBZ.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import{m as resolveConfigPath}from"./paths-D_FOvGon.mjs";import{f as resolveIdentityPathViaExistingAncestorSync}from"./path-existence-BR9MXlgL.mjs";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.mjs";import{Fn as object,Jn as string,Nt as array,Pn as number,lr as uuid,qn as strictObject,xn as literal}from"./schemas-DuCQi-Qb.mjs";import{i as isPidAlive}from"./pid-alive-DDtSxW5l.mjs";import{l as hasActiveGatewayStateOwner}from"./gateway-state-owner-D_klysuh.mjs";import{n as sha256Hex}from"./node-crypto-DPk8agfR.mjs";import"./crypto-digest-T8X5EZni.mjs";import{a as withArtifactPreservingStateReads}from"./artifact-preserving-state-reads-CWuQPqxe.mjs";import{n as resolveDatabaseFamilyEngines}from"./registry-ByN-O5dB.mjs";import{o as publishVerifiedSqliteFile}from"./sqlite-snapshot-D4gm3rAo.mjs";import{i as readClientCredentialFileIdentity}from"./client-credential-receipt-CEFy8dbp.mjs";import{i as GATEWAY_CLIENT_NAMES,r as GATEWAY_CLIENT_MODES}from"./client-info-Dr3-kuD1.mjs";import{t as createConfigIO}from"./io.factory-y6nIrp_4.mjs";import{o as readGatewayLockProcessStartTime}from"./gateway-owner-lease-9K6iKMiO.mjs";import{l as readConfigFileSnapshotForWrite}from"./io.runtime-BvSeVFIY.mjs";import"./io-Di_yuX3t.mjs";import{i as resolveGatewayAuthForConfig}from"./auth-resolve-UwT9_UjV.mjs";import{a as readActiveGatewayLockIdentity,c as readLockPayloadSync,l as resolveGatewayLockPaths}from"./gateway-lock-CQoO1usb.mjs";import{r as callGateway}from"./call-CVqWsTxX.mjs";import{t as buildBackupArchivePath}from"./backup-archive-path-policy-CotYunH-.mjs";import{a as captureDatabaseArtifact,i as assertDatabaseArtifact}from"./database-backup.operations-C3IunZW3.mjs";import"./database-backup-yFN_P503.mjs";import{a as runUpdateStateInspectionWorker,t as parseUpdateStateInspectionWorker}from"./update-candidate-state.inspection-CZefYmrZ.mjs";import{r as resolveBackupConfigCapture}from"./backup-config-capture-CXz3HMQ-.mjs";import{n as createUpdateDatabaseBackup}from"./update-database-backup-Nfb5jRGk.mjs";import{n as assertDoctorSqliteMaintenancePathsNotAliased}from"./doctor-sqlite-maintenance-lock-De_t-lkq.mjs";import{t as runWithLocalStateOwner}from"./local-state-owner-fjzTarAw.mjs";import{i as canonicalizePathForContainment}from"./backup-shared-CVcoDGTC.mjs";import{o as rebindRehearsalClientCredentials}from"./client-credential-restore-v5gh1bv1.mjs";import{n as prepareBackupArchive}from"./backup-verify-Lqpvf4CJ.mjs";import{t as backupRestoreCommand}from"./backup-restore-0UzTEOoT.mjs";import fs,{constants}from"node:fs";import path from"node:path";import{randomUUID}from"node:crypto";import fs$1 from"node:fs/promises";import{isPathInside}from"@openclaw/fs-safe/path"; //!src/commands/database-migration-filesystem-backup.ts async function createDatabaseMigrationFilesystemBackup(e){const t=await runUpdateStateInspectionWorker({input:{mode:`migration-filesystem-backup`,output:e.output,userPathBaseDirectory:resolveUserPath(`.`),stateDir:e.stateDir,config:e.config},nodeRunner:process.execPath,sourceEnv:e.env,stagingRoot:path.dirname(e.output),databases:[],signal:e.signal,timeoutMs:18e5,ioBudget:`deadline`});parseUpdateStateInspectionWorker(t,object({archivePath:literal(e.output),verified:literal(true)}))} //!src/commands/database-migration-quiescence.ts const RPC_TIMEOUT_MS=1e4;const RENEW_AFTER_MS=3e4;const LEASE_TTL_MS=12e4;function sameOwner(e,t){return e.ownerId===t.ownerId&&e.pid===t.pid&&e.startTime===t.startTime&&e.createdAt===t.createdAt&&e.port===t.port}async function withGatewayMigrationQuiescence(e){const t={...e.env};if(!e.requestId.trim()||!e.suspensionId.trim())throw new Error(`Migration requires the existing controller request and suspension IDs.`);const n=new AbortController;const abort=e=>{n.abort(e);return e};const onAbort=()=>n.abort(e.signal.reason);e.signal.addEventListener(`abort`,onAbort,{once:true});let r;let i;let a=false;let o=0;let s=0;try{e.signal.throwIfAborted();e.assertCurrent();const c=resolveGatewayLockPaths(t);const l=resolveIdentityPathViaExistingAncestorSync(c.configPath);const u=await readActiveGatewayLockIdentity({env:t,requireInspection:true,signal:n.signal,timeoutMs:RPC_TIMEOUT_MS});if(!u?.ownerId||!Number.isFinite(u.startTime))throw new Error(`Migration requires an inspected local Gateway owner and process identity.`);const d={...u,ownerId:u.ownerId};const f=[c.ownerLockPath,c.configLockPath,c.stateLockPath].find(e=>{const t=readLockPayloadSync(e,true);return t?.port!==void 0&&sameOwner(u,{...t,port:t.port})});if(!f)throw new Error(`Migration Gateway physical owner lock is unavailable.`);const p=fs.lstatSync(f,{bigint:true});if(!p.isFile()||p.isSymbolicLink())throw new Error(`Migration requires a regular physical Gateway owner lock.`);const assertPhysicalOwner=()=>{n.signal.throwIfAborted();e.signal.throwIfAborted();e.assertCurrent();const r=resolveGatewayLockPaths(t);if(r.stateDir!==c.stateDir||resolveIdentityPathViaExistingAncestorSync(r.configPath)!==l)throw new Error(`Migration selected state/config identity changed.`);const i=fs.lstatSync(f,{bigint:true});const a=readLockPayloadSync(f,true);if(!i.isFile()||i.dev!==p.dev||i.ino!==p.ino||!a?.port||!sameOwner(u,{...a,port:a.port})||a.role!==void 0&&a.role!==`gateway`||resolveIdentityPathViaExistingAncestorSync(a.configPath)!==l||a.stateDir!==void 0&&resolveIdentityPathViaExistingAncestorSync(a.stateDir)!==c.stateDir||!isPidAlive(u.pid)||readGatewayLockProcessStartTime(u.pid,process.platform,1e3)!==u.startTime)throw new Error(`Migration Gateway owner identity changed or cannot be verified.`)};const assertCurrent=()=>{try{assertPhysicalOwner();if(Date.now()>=o||performance.now()>=s)throw new Error(`Migration Gateway suspension expired.`)}catch(e){throw abort(e)}};assertPhysicalOwner();const m=await createConfigIO({env:t,configPath:c.configPath,observe:false,pluginValidation:`core-only`}).readConfigFileSnapshot({observe:false,isolateEnv:true});assertPhysicalOwner();if(!m.valid||m.config.gateway?.mode===`remote`)throw new Error(`Migration requires valid selected local Gateway configuration.`);const h=resolveGatewayAuthForConfig({config:m.config,env:t});const g=h.mode===`token`&&h.token?{token:h.token}:(h.mode===`password`||h.mode===`trusted-proxy`)&&h.password?{password:h.password}:void 0;if(!g)throw new Error(`Migration requires private local backend shared authentication.`);const rpc=(e,t)=>callGateway({method:e,params:t,config:m.config,configPath:c.configPath,localPortOverride:u.port,ignoreEnvUrlOverride:true,...g,skipImplicitAuth:true,deviceIdentity:null,sharedStateMode:`read-only`,clientName:GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT,mode:GATEWAY_CLIENT_MODES.BACKEND,requireLocalBackendSharedAuth:true,scopes:[`operator.admin`],timeoutMs:RPC_TIMEOUT_MS,signal:n.signal,assertDispatchCurrent:()=>{if(o){assertCurrent();if(e===`gateway.suspend.prepare`&&Math.min(o-Date.now(),s-performance.now())<12e3)throw abort(/* @__PURE__ */ new Error(`Migration suspension renewal lacks safe dispatch runway.`))}else assertPhysicalOwner()}});const acceptLease=(e,t)=>{if(e.status!==`ready`||!Number.isSafeInteger(e.expiresAtMs)||!Array.isArray(e.writeCustody)||e.writeCustody.some(e=>!Number.isSafeInteger(e.count)||e.count!==0))throw new Error(`Migration suspension is not ready with verified zero write custody.`);const n=e.expiresAtMs;const r=n-Date.now();if(r<12e3||r>LEASE_TTL_MS||performance.now()-t>=r)throw new Error(`Migration suspension has insufficient or invalid bounded lease runway.`);s=n<=o?Math.min(s,t+r):t+r;o=n;assertCurrent()};const renew=async()=>{try{assertPhysicalOwner();const t=performance.now();const n=await rpc(`gateway.suspend.status`,{suspensionId:e.suspensionId,includeLifecycle:true});assertPhysicalOwner();if(n.ownerId!==e.requestId)throw new Error(`Migration suspension is not held by the supplied controller request.`);acceptLease(n,t);const r=performance.now();const i=await rpc(`gateway.suspend.prepare`,{requestId:e.requestId,drain:false,terminalPolicy:`preserve`});assertCurrent();if(i.suspensionId!==e.suspensionId||i.activeCount!==0||!Array.isArray(i.blockers)||i.blockers.length!==0)throw new Error(`Migration suspension renewal changed identity or retained active work.`);acceptLease(i,r)}catch(e){throw abort(e)}};const revalidate=()=>{if(a)return Promise.reject(/* @__PURE__ */ new Error(`Migration quiescence scope has completed.`));if(!i)i=renew().finally(()=>{i=void 0});return i};const schedule=()=>{r=setTimeout(()=>{revalidate().then(()=>{if(!a)schedule()},()=>{})},RENEW_AFTER_MS);r.unref?.()};await revalidate();schedule();const _=await e.run({signal:n.signal,assertCurrent(){if(a)throw new Error(`Migration quiescence scope has completed.`);assertCurrent()},revalidate,owner:d,get expiresAtMs(){return o}});a=true;clearTimeout(r);await i;assertCurrent();return _}catch(e){throw abort(e)}finally{a=true;clearTimeout(r);await i?.catch(()=>{});e.signal.removeEventListener(`abort`,onAbort)}} //!src/commands/database-migration-capture.ts const absolute=string().refine(e=>path.isAbsolute(e)&&!e.includes(`\0`));const relative$1=string().refine(e=>e.length>0&&!path.isAbsolute(e)&&e.split(/[\\/]/u).every(e=>e!==`..`&&e!==`.`&&e!==``));const artifact=strictObject({file:relative$1,sha256:string().regex(/^[a-f0-9]{64}$/u),size:number().int().nonnegative()});const captured=artifact.extend({sourcePath:absolute});const manifestSchema=strictObject({schema:literal(`openclaw.database-migration-capture.v1`),profile:literal(`exact-sqlite-migration`),captureId:uuid(),createdAt:string().datetime(),sourceStateDir:absolute,sourceConfigPath:absolute,baseArchive:artifact,databases:array(captured),missingDatabases:array(absolute),configs:array(captured).min(1),quiescence:strictObject({requestId:string().min(1).max(128),suspensionId:string().min(1).max(128),ownerId:string().min(1),pid:number().int().positive(),expiresAtMs:number().int().positive()}).optional(),sourceSharedFile:strictObject({path:absolute,dev:string().regex(/^\d+$/u),ino:string().regex(/^\d+$/u)}).nullable()});function assertLogicalPaths(e){const t=path.dirname(e.sourceConfigPath);if(e.sourceStateDir!==resolveIdentityPathViaExistingAncestorSync(resolveStateDir())||e.sourceConfigPath!==path.resolve(resolveConfigPath())||e.databases.some(t=>!isPathInside(e.sourceStateDir,t.sourcePath))||e.missingDatabases.some(t=>!isPathInside(e.sourceStateDir,t))||e.configs.some(n=>n.sourcePath!==e.sourceConfigPath&&!isPathInside(t,n.sourcePath)))throw new Error(`Migration capture requires the same logical state/config paths and state-relative SQLite stores; external roots need an explicit mapping.`);const n=[...e.databases,...e.configs].map(e=>e.sourcePath);if(new Set(n).size!==n.length||!e.configs.some(t=>t.sourcePath===e.sourceConfigPath))throw new Error(`Migration capture has ambiguous database or configuration paths.`);if(e.sourceSharedFile&&(e.sourceSharedFile.path!==path.join(e.sourceStateDir,`state/openclaw.sqlite`)||!e.databases.some(t=>t.sourcePath===e.sourceSharedFile?.path)))throw new Error(`Migration capture shared/local identity witness is not a captured shared database.`)}async function privateArtifact(e,t){const n=path.join(e,t.file);const r=await fs$1.realpath(n);if(!isPathInside(e,r)||r!==n)throw new Error(`Migration capture artifact is outside its private directory.`);await assertDatabaseArtifact({path:n,sha256:t.sha256,size:t.size});return n}async function createDatabaseMigrationCapture(e){if(e.externallyQuiesced){if(e.baseArchive||!e.requestId||!e.suspensionId)throw new Error(`Externally quiesced capture requires request/suspension IDs and creates its own filesystem base; --base-archive is not accepted.`)}else if(!e.baseArchive||e.requestId||e.suspensionId)throw new Error(`Offline migration capture requires --base-archive; suspension IDs require --externally-quiesced.`);const t=e.requestId&&e.suspensionId?{requestId:e.requestId,suspensionId:e.suspensionId}:void 0;if(hasActiveGatewayStateOwner(path.join(resolveStateDir(),`state/openclaw.sqlite`)))throw new Error(`Exact migration capture requires the Gateway stopped through its service owner.`);const capture=async({env:t,assertCurrent:n,signal:r,revalidate:i=async()=>n(),quiescence:a})=>{try{var o=_usingCtx();await i();const s=path.resolve(resolveStateDir(t));const c=path.resolve(resolveConfigPath(t));const[l,u,d]=await Promise.all([canonicalizePathForContainment(path.resolve(e.output)),canonicalizePathForContainment(s),canonicalizePathForContainment(path.dirname(c))]);if(isPathInside(u,l)||isPathInside(d,l))throw new Error(`Migration capture output must be outside the source state and configuration roots.`);const f=await readConfigFileSnapshotForWrite({observe:false,skipPluginValidation:true});if(!f.snapshot.valid||f.snapshot.path!==c)throw new Error(`Migration capture requires valid pinned source configuration.`);if(Object.values(resolveDatabaseFamilyEngines(f.snapshot.config)).includes(`postgres`))throw new Error(`This migration capture accepts SQLite sources only; it never exports or restores PostgreSQL namespaces.`);const p=await resolveBackupConfigCapture(f,{env:t});const m=e.baseArchive?await prepareBackupArchive(e.baseArchive):void 0;if(m&&(m.databaseRestoreCandidates.length>0||(m.manifest.postgresAnchors?.length??0)>0))throw new Error(`Migration capture requires a SQLite-only base archive.`);if(m&&!m.manifest.assets.some(e=>e.kind===`state`&&e.sourcePath===s))throw new Error(`Base archive belongs to a different state root.`);n();await fs$1.mkdir(l,{mode:448});const h=path.join(l,`filesystem.tar.gz`);if(m){await fs$1.copyFile(m.result.archivePath,h,constants.COPYFILE_EXCL|constants.COPYFILE_FICLONE);await fs$1.chmod(h,384)}const g=await createUpdateDatabaseBackup({backupRoot:path.join(l,`native`),stateDir:s,config:f.snapshot.config,env:t,stopped:!e.externallyQuiesced,preserveSourceArtifacts:true,sourceEngine:`sqlite`,timeoutMs:6e5,signal:r,purpose:`original-state`});await i();if(!m){await createDatabaseMigrationFilesystemBackup({output:h,stateDir:s,config:f.snapshot.config,env:t,signal:r});await i()}const entry=async(e,t)=>{try{var n=_usingCtx();await n.a(await fs$1.open(t,`r+`)).sync();const r=await captureDatabaseArtifact(t);return{sourcePath:e,file:path.relative(l,t),sha256:r.sha256,size:r.size}}catch(e){n.e=e}finally{await n.d()}};const _=g.databases.map(e=>({sourcePath:e.path,file:path.relative(l,e.snapshotPath),sha256:e.sha256,size:e.sizeBytes}));const v=[];for(const[e,t]of p.files.entries()){const n=path.join(l,`config-${e}.json`);await fs$1.copyFile(t.canonicalPath,n,constants.COPYFILE_EXCL);await fs$1.chmod(n,384);v.push(await entry(t.sourcePath,n))}await p.revalidate();n();const y=await entry(s,h);const b={schema:`openclaw.database-migration-capture.v1`,profile:`exact-sqlite-migration`,captureId:randomUUID(),createdAt:(/* @__PURE__ */ new Date()).toISOString(),sourceStateDir:s,sourceConfigPath:c,baseArchive:{file:`filesystem.tar.gz`,sha256:y.sha256,size:y.size},databases:_,missingDatabases:g.missingPaths,configs:v,...a?{quiescence:a()}:{},sourceSharedFile:readClientCredentialFileIdentity(path.join(s,`state/openclaw.sqlite`))??null};assertLogicalPaths(b);await i();const x=path.join(l,`manifest.json`);const S=o.a(await fs$1.open(x,`wx`,384));const C=`${JSON.stringify(b)}\n`;await S.writeFile(C);await S.sync();requireDirectorySync(await syncDirectory(l),`Migration capture publication`);await i();n();return{ok:true,verified:true,schema:b.schema,profile:b.profile,captureId:b.captureId,directory:l,manifestPath:x,manifestSha256:sha256Hex(C),sourceStateDir:s,sourceConfigPath:c,databases:_.length,configs:v.length,...b.quiescence?{quiescence:b.quiescence}:{}}}catch(e){o.e=e}finally{await o.d()}};const run=()=>runWithLocalStateOwner({method:`database.migration-capture`,params:{},target:resolveStateDir(),databaseEngine:`configured`,onForeignOwner:t?async({env:e,signal:n,assertCurrent:r})=>withGatewayMigrationQuiescence({env:e,signal:n,assertCurrent:r,requestId:t.requestId,suspensionId:t.suspensionId,run:n=>capture({env:e,signal:n.signal,assertCurrent:n.assertCurrent,revalidate:n.revalidate,quiescence:()=>({requestId:t.requestId,suspensionId:t.suspensionId,ownerId:n.owner.ownerId,pid:n.owner.pid,expiresAtMs:n.expiresAtMs})})}):`refuse`,runLocal:async t=>{if(e.externallyQuiesced)throw new Error(`Externally quiesced capture requires the existing running Gateway owner.`);return capture(t)}});return e.externallyQuiesced?withArtifactPreservingStateReads(run,{agentDatabases:true}):run()}async function restoreDatabaseMigrationCapture(e,t){const n=await fs$1.realpath(t.capture);const r=await fs$1.readFile(path.join(n,`manifest.json`),`utf8`);if(sha256Hex(r)!==t.manifestSha256)throw new Error(`Migration capture manifest differs from its producer receipt.`);const i=manifestSchema.parse(JSON.parse(r));assertLogicalPaths(i);const a=await privateArtifact(n,i.baseArchive);const o=await Promise.all([...i.databases,...i.configs].map(async e=>({entry:e,file:await privateArtifact(n,e)})));const s=await backupRestoreCommand({...e,log:()=>{}},{archive:a,target:t.target,sourceEngine:`sqlite`});const staged=e=>path.join(s.targetPath,buildBackupArchivePath(s.archiveRoot,e));const admitStaged=e=>{const t=staged(e);assertDoctorSqliteMaintenancePathsNotAliased(`exact migration restore`,[t],[s.targetPath]);return t};try{for(const e of i.missingDatabases)for(const t of[``,`-wal`,`-shm`,`-journal`])await fs$1.rm(admitStaged(`${e}${t}`),{force:true});for(const{entry:e,file:t}of o){const n=admitStaged(e.sourcePath);await fs$1.mkdir(path.dirname(n),{recursive:true,mode:448});const r=await fs$1.realpath(path.dirname(n));if(!isPathInside(s.targetPath,r)||path.join(r,path.basename(n))!==n)throw new Error(`Migration restore destination is aliased.`);const a=await fs$1.lstat(n).catch(e=>{if(typeof e===`object`&&e!==null&&`code`in e&&e.code===`ENOENT`)return;throw e});if(a&&(!a.isFile()||a.nlink!==1))throw new Error(`Migration restore may replace only private regular staged files.`);if(a)await fs$1.unlink(n);if(i.databases.includes(e))await publishVerifiedSqliteFile({sourcePath:t,sourceIdentity:await fs$1.lstat(t,{bigint:true}),targetPath:n,expectedContent:{sha256:e.sha256,sizeBytes:e.size},requireAtomicPublication:true});else{await fs$1.copyFile(t,n,constants.COPYFILE_EXCL);await fs$1.chmod(n,384)}}const e=path.join(i.sourceStateDir,`client/credentials.sqlite`);if(i.sourceSharedFile&&i.databases.some(t=>t.sourcePath===e))rebindRehearsalClientCredentials({sourceStateRoot:i.sourceStateDir,sourceSharedFile:i.sourceSharedFile,sharedPath:staged(i.sourceSharedFile.path),localPath:staged(e)});return{...s,profile:i.profile,exactMigration:{schemaVersion:1,captureId:i.captureId,sourceStateDir:i.sourceStateDir,sourceConfigPath:i.sourceConfigPath,databases:i.databases.length,configs:i.configs.length}}}catch(e){await fs$1.rm(s.targetPath,{recursive:true,force:true});throw e}}export{createDatabaseMigrationCapture,restoreDatabaseMigrationCapture};