UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

7 lines • 18.2 kB
import{n as sanitizeForLog}from"./ansi-54CEWBZf.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import"./paths-D_FOvGon.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{n as normalizeAgentId}from"./agent-id-cOfqmfln.mjs";import"./session-key-BPgKfU2m.mjs";import{t as formatCliCommand}from"./command-format-D7KhNLP0.mjs";import{g as isReservedSystemAgentId,i as listAgentIds}from"./agent-roster-4XrgUgPK.mjs";import{l as resolveOpenClawAgentSqlitePath,n as createOpenClawAgentDatabasePathMatcher}from"./openclaw-agent-db.paths-SkzMsgQ0.mjs";import{a as resolveAgentDir,f as resolveAgentWorkspaceDir}from"./agent-scope-config-CG9CFpGX.mjs";import{a as getOpenClawDatabaseMaintenanceScope}from"./openclaw-state-maintenance-context-D-pYfco8.mjs";import{n as isPostgresSqlConnection}from"./sql-connection-nx8lLUJM.mjs";import{t as OPENCLAW_AGENT_SCHEMA_VERSION}from"./openclaw-schema-versions-rhFQpVhP.mjs";import{a as isSqliteCorruptionError}from"./sqlite-error-diagnostics-ASl1MXPN.mjs";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.mjs";import{a as executeSqliteQueryTakeFirstSync,i as executeSqliteQuerySync,s as getNodeSqliteKysely}from"./kysely-sync-R08Pt8qn.mjs";import{D as requireNativeDatabaseFile,d as invalidateSqliteSchemaFacts}from"./sqlite-schema-facts-CWOeTpUB.mjs";import{a as tableExists}from"./openclaw-state-db-schema-helpers-rYTimzjJ.mjs";import{o as readSqliteUserVersion}from"./sqlite-user-version-DaJ6mdUV.mjs";import{n as openNodeSqliteDatabase}from"./node-sqlite-DXyF1fBG.mjs";import{s as resolveOpenClawStateSqlitePath}from"./openclaw-state-db.paths-CbgXfEg1.mjs";import"./openclaw-state-db-async-lifecycle-DlV0ztcV.mjs";import{h as withExistingOpenClawStateDatabaseCurrentReadOnly,m as withExistingOpenClawStateDatabaseArtifactPreservingReadOnlyAsync}from"./openclaw-state-db-readonly-Cd5_cxBs.mjs";import{a as prepareSqliteReadOnlyLocation}from"./sqlite-snapshot-source-DbIgYrJe.mjs";import{a as resolveSqliteInspectionSignal}from"./sqlite-readonly-worker-context-BjXXEC4m.mjs";import{t as SQLITE_SIDECAR_SUFFIXES}from"./sqlite-files-731tEtYd.mjs";import{a as isStatePostgres}from"./openclaw-state-db-engine-DiCia3Ut.mjs";import"./openclaw-agent-db-contract-CiyWpx1X.mjs";import{h as writeTextAtomic}from"./json-files-BBQ_0Np0.mjs";import{Q as resolveOpenClawAgentDatabaseDiscoveryPaths,Z as prepareStateDatabaseInitialization,l as runOpenClawStateWriteTransaction}from"./openclaw-state-db-BlgxYkYw.mjs";import{t as createConfigIO}from"./io.factory-y6nIrp_4.mjs";import"./io-Di_yuX3t.mjs";import{n as quotePowerShellArg,t as quoteCliArg}from"./quote-cli-arg-BUHoGELl.mjs";import{n as parseAgentDeletionDatabasePaths}from"./agent-deletion-journal.read-DL01GJPw.mjs";import{_ as recordAgentDeletionRecoveryHolds,g as reconstructAgentDeletionJournal,p as readAgentDeletionJournalInDatabase,u as parseCleanupPaths,v as resolveAgentDeletionRecoveryHolds}from"./agent-deletion-journal-Dee50E62.mjs";import{o as readAgentDeletionMissingJournalHolds,s as readAgentDeletionRecoveryHolds}from"./agent-deletion-journal-recovery.kernel-DcfNqwh_.mjs";import{o as invalidateAgentDeletionJournalStatus}from"./agent-deletion-journal-status-WLzvY6ul.mjs";import{s as resolveConfiguredAgentDatabaseTargets}from"./targets-DZpbOEi4.mjs";import{i as hasSqliteFileFamily}from"./agent-deletion-discovery-BrXQcYYT.mjs";import{n as isTransientSqliteBackupPath}from"./backup-volatile-filter-C7OiuXr0.mjs";import{t as createAgentSchemaInspectionWorker}from"./openclaw-agent-schema-inspection-worker-BkUPol72.mjs";import{n as backupDoctorSqliteDatabases}from"./doctor-migration-backup-BYwdxiJ7.mjs";import path from"node:path";import{randomUUID}from"node:crypto";import{isDeepStrictEqual}from"node:util"; //!src/commands/doctor-agent-deletion-journal-quarantine.ts function readRecoverySource(e){const t=e.db;const n=isPostgresSqlConnection(t);if(!n)invalidateSqliteSchemaFacts(t);const r=tableExists(e.db,`migration_sources`)?readAgentDeletionRecoveryHolds(e):[];if(!tableExists(e.db,`agent_deletion_journal`)){if(n)requireNativeDatabaseFile(`postgres`,`repair`);return{missing:true,rows:[],invalid:[],held:r}}const i=executeSqliteQuerySync(e.db,getNodeSqliteKysely(e.db).selectFrom(`agent_deletion_journal`).selectAll().orderBy(`agent_id`)).rows;const a=i.filter(t=>{if(isReservedSystemAgentId(t.agent_id))return true;try{readAgentDeletionJournalInDatabase(e,t.agent_id);return false}catch(e){if(isSqliteCorruptionError(e))throw e;return true}});if(n&&a.length>0)requireNativeDatabaseFile(`postgres`,`repair`);return{missing:false,rows:i,invalid:a,held:r}}async function quarantineAgentDeletionJournal(e){const{env:t}=e;const n=resolveSqliteInspectionSignal();n?.throwIfAborted();const r=await withExistingOpenClawStateDatabaseArtifactPreservingReadOnlyAsync(readRecoverySource,{env:t})??{missing:true,rows:[],invalid:[],held:[]};if(!r.missing&&r.invalid.length===0)return;let i=r.missing?[...e.inventory]:[...r.held];if(r.missing&&r.held.length===0)try{var a=_usingCtx();const r=createOpenClawAgentDatabasePathMatcher();const o=[];const s=a.a(createAgentSchemaInspectionWorker());for(const a of i){if(e.configuredTargets.some(e=>e.agentId===a.agentId&&r(e.path,a.path)))try{const e={pathname:a.path,agentId:a.agentId,env:t,supportedVersion:42,inspectOwnership:true,inspectEmptyStore:true};let r=await s.inspect(e,n);if(!r){const t=await prepareSqliteReadOnlyLocation(a.path,{preserveSourceArtifacts:true,requireCleanup:true,signal:n});try{r=await s.inspect(e,n,t.location)}finally{if(!await t.cleanupAsync())r=null}}if(r?.emptyStore===true)continue}catch{n?.throwIfAborted()}o.push(a)}i=o}catch(e){a.e=e}finally{await a.d()}for(const n of r.invalid){const r=/* @__PURE__ */ new Set([...resolveOpenClawAgentDatabaseDiscoveryPaths({agentDir:n.agent_dir,agentId:n.agent_id,env:t}).filter(hasSqliteFileFamily),...e.inventory.filter(e=>normalizeAgentId(e.agentId)===normalizeAgentId(n.agent_id)).map(e=>e.path)]);try{for(const e of parseAgentDeletionDatabasePaths(n.database_paths_json))r.add(e)}catch{}try{for(const e of parseCleanupPaths(n.cleanup_paths_json))for(const t of e.sourcePaths)r.add(t)}catch{}i.push(...[...r].filter(e=>!SQLITE_SIDECAR_SUFFIXES.some(t=>e.endsWith(t)&&r.has(e.slice(0,-t.length)))).map(e=>({agentId:n.agent_id,path:e})))}const o=getOpenClawDatabaseMaintenanceScope();const assertCurrent=()=>{n?.throwIfAborted();o?.assertAdmission()};const s=[];const c=[];const l=new Set(i.map(e=>normalizeAgentId(e.agentId)));for(const e of l){const n=path.join(resolveStateDir(t),`agents`,e,`recovery`,`deletion-journal-${randomUUID()}.json`);assertCurrent();try{await writeTextAtomic(n,JSON.stringify({source:resolveOpenClawStateSqlitePath(t),reason:r.missing?`missing deletion journal`:`unusable deletion journal`,journal:r.invalid.filter(t=>normalizeAgentId(t.agent_id)===e),held:i.filter(t=>normalizeAgentId(t.agentId)===e)},null,2),{mode:384,dirMode:448,durable:true,beforeRename:async()=>{assertCurrent()}});s.push(n)}catch(e){c.push(`Warning: Could not save deletion recovery receipt ${n}: ${formatErrorMessage(e)}. Original journal records remain in place and stores remain held; repair the recovery directory, then run openclaw doctor --fix.`)}}assertCurrent();if(c.length>0)i.push(...e.inventory);return{held:runOpenClawStateWriteTransaction(e=>{assertCurrent();if(!isDeepStrictEqual(readRecoverySource(e),r))throw new Error(`Agent deletion journal changed before quarantine; stores were left untouched.`);if(r.missing)return reconstructAgentDeletionJournal(e,i);const t=getNodeSqliteKysely(e.db);for(const n of c.length===0?r.invalid:[]){if(isReservedSystemAgentId(n.agent_id)){executeSqliteQuerySync(e.db,t.deleteFrom(`agent_deletion_journal`).where(`agent_id`,`=`,n.agent_id));invalidateAgentDeletionJournalStatus(e.db,n.agent_id);continue}executeSqliteQuerySync(e.db,t.updateTable(`agent_deletion_journal`).set({operation_id:randomUUID(),database_paths_json:JSON.stringify([...new Set(i.filter(e=>normalizeAgentId(e.agentId)===normalizeAgentId(n.agent_id)).map(e=>e.path))]),cleanup_paths_json:`[]`,cleanup_completed:1,delete_files:0}).where(`agent_id`,`=`,n.agent_id));invalidateAgentDeletionJournalStatus(e.db,n.agent_id)}return recordAgentDeletionRecoveryHolds(e,i,{excludeMissingJournal:i.filter(e=>r.invalid.some(t=>normalizeAgentId(t.agent_id)===normalizeAgentId(e.agentId))),description:c.length===0?`Quarantined unusable agent deletion records; stores remain held for explicit recovery.`:`Preserved unusable agent deletion records in place; stores remain held for explicit recovery.`})},{env:t}),archives:s,warnings:c}} //!src/commands/doctor-agent-deletion-journal-restore.ts function readVerifiedOwner(e,t){const n=executeSqliteQueryTakeFirstSync(e,getNodeSqliteKysely(e).selectFrom(`schema_meta`).selectAll().where(`meta_key`,`=`,`primary`));if(n?.role!==`agent`||n.agent_id!==t||readSqliteUserVersion(e)!==n.schema_version)return;return n}async function inspectOwner(e,t){const n=await prepareSqliteReadOnlyLocation(e,{preserveSourceArtifacts:true});let r;let i;try{try{var a=_usingCtx();r=readVerifiedOwner(a.u(openNodeSqliteDatabase(n.location,{readOnly:true})),t)}catch(e){a.e=e}finally{a.d()}}finally{i=await n.cleanupAsync()}if(!i)throw new Error(`Could not release agent recovery inspection snapshot: ${n.location}`);return r}async function restoreDoctorMissingJournalStores(e){const t=[];const n=[];const r=[];if(e.held.length===0||isStatePostgres())return{changes:t,warnings:n,restored:r};const i=getOpenClawDatabaseMaintenanceScope();if(!i?.ownsSchemaMaintenance)return{changes:t,warnings:n,restored:r};const a=await createConfigIO({env:e.env,observe:false,pluginValidation:`core-only`}).readConfigFileSnapshot();if(!a.valid)return{changes:t,warnings:n,restored:r};const o=createOpenClawAgentDatabasePathMatcher();const s=resolveConfiguredAgentDatabaseTargets(a.sourceConfig,{env:e.env,registeredDatabases:e.held});const c=listAgentIds(a.sourceConfig);const readEligibleHolds=(e,t)=>isReservedSystemAgentId(t)?readAgentDeletionRecoveryHolds(e):readAgentDeletionMissingJournalHolds(e);const matchesReceipt=(t,n)=>{const matches=e=>readEligibleHolds(e,t.agentId).some(e=>e.agentId===t.agentId&&o(e.path,t.path))&&!readAgentDeletionJournalInDatabase(e,t.agentId);return n?matches(n):withExistingOpenClawStateDatabaseCurrentReadOnly(matches,{env:e.env,allowNativeRead:true})===true};const l=resolveSqliteInspectionSignal();const u=[];for(const t of e.held){l?.throwIfAborted();if(!(isReservedSystemAgentId(t.agentId)?o(t.path,resolveOpenClawAgentSqlitePath({agentId:t.agentId,env:e.env})):c.includes(t.agentId)&&s.some(e=>e.agentId===t.agentId&&o(e.path,t.path)))||!matchesReceipt(t))continue;try{const e=await inspectOwner(t.path,t.agentId);if(e)u.push({...t,producer:e})}catch(e){l?.throwIfAborted();n.push(`Agent ${t.agentId} remains held; could not verify its database ownership: ${formatErrorMessage(e)}`)}}if(u.length===0)return{changes:t,warnings:n,restored:r};const d=new Set(u);const assertCurrent=e=>{i.assertAdmission();if(!o.isCurrent()||[...d].some(t=>!matchesReceipt(t,e)))throw new Error(`Agent deletion recovery changed; preserved stores remain held. Rerun Doctor.`)};assertCurrent();const f=await backupDoctorSqliteDatabases({env:e.env,pendingDatabasePaths:u.map(e=>e.path),databasePaths:u.map(e=>e.path),authority:{assertCurrent},requireSnapshots:true,repair:{key:`published-missing-agent-deletion-journal`,validate:t=>{const n=executeSqliteQueryTakeFirstSync(t,getNodeSqliteKysely(t).selectFrom(`schema_meta`).select([`role`,`agent_id`]).where(`meta_key`,`=`,`primary`));if(n?.role===`global`){const n={db:t,path:resolveOpenClawStateSqlitePath(e.env)};if(u.some(e=>!readEligibleHolds(n,e.agentId).some(t=>t.agentId===e.agentId&&o(t.path,e.path))||readAgentDeletionJournalInDatabase(n,e.agentId)))throw new Error(`Recovery backup does not preserve the deletion reconstruction records.`)}else if(!u.some(e=>e.agentId===n?.agent_id&&isDeepStrictEqual(readVerifiedOwner(t,e.agentId),e.producer)))throw new Error(`Recovery backup does not preserve the verified agent ownership metadata.`)}}});t.push(...f.changes);n.push(...f.warnings);const p=f.snapshots??[];const m=p.find(t=>o(t.sourcePath,resolveOpenClawStateSqlitePath(e.env)));if(!m)throw new Error(`Agent restoration requires a verified shared-state and reconstruction-record backup.`);const{createAgent:h}=await import(`./agent-create-B5rc-g8Z.mjs`);let g=a.hash??null;for(const t of new Set(u.map(e=>e.agentId))){const i=u.filter(e=>e.agentId===t);assertCurrent();if(isReservedSystemAgentId(t)){for(const e of i)if(!isDeepStrictEqual(await inspectOwner(e.path,t),e.producer))throw new Error(`System agent ${t} ownership changed before recovery.`);runOpenClawStateWriteTransaction(e=>{assertCurrent(e);resolveAgentDeletionRecoveryHolds(e,t,i.map(e=>e.path))},{env:e.env})}else{const e=await h({name:t,expectedConfigHash:g,restorePaths:i.map(e=>e.path),beforePersistentApply:assertCurrent});if(e.status===`error`){n.push(`Agent ${t} remains held: ${e.message}`);continue}g=e.configHash??g}for(const a of i){if(withExistingOpenClawStateDatabaseCurrentReadOnly(e=>readAgentDeletionRecoveryHolds(e).some(e=>e.agentId===a.agentId&&o(e.path,a.path)),{env:e.env,allowNativeRead:true})!==false)throw new Error(`Agent ${t} restoration left ${a.path} held.`);d.delete(a);r.push(a);n.push(`Warning: Automatically restored agent ${t} database ${a.path}${isReservedSystemAgentId(t)?` after verifying reserved system-agent ownership`:` after verifying configured ownership and missing deletion history`}. Verified backup: ${p.find(e=>o(e.sourcePath,a.path)).path}; shared state and reconstruction records: ${m.path}.`)}}return{changes:t,warnings:n,restored:r}} //!src/commands/doctor-agent-deletion-journal.ts async function repairDoctorAgentDeletionJournal(e){const t=e.preflight.agentDatabaseMigrationDiscovery?.discovery;const n=[];const r=[];let i=false;if(!t)return{changes:n,warnings:[]};if(t.deletionJournal.status===`unavailable`&&t.deletionJournal.cause===`unreadable`&&!e.shouldRepair)return{changes:n,warnings:[sanitizeForLog(`${resolveOpenClawStateSqlitePath(e.env)}: ${t.deletionJournal.reason}. Stores remain held; restore verified deletion history, then rerun openclaw doctor --fix.`),...[...t.retainedTargets,...t.unverifiedTargets].map(({agentId:e,path:t})=>sanitizeForLog(`Held agent ${e} database ${t}; deletion history needs repair.`))]};const a=t.deletionJournal.status===`unavailable`&&t.deletionJournal.cause===`missing`;if(a&&t.unverifiedTargets.length===0&&t.failures.length===0&&prepareStateDatabaseInitialization(resolveOpenClawStateSqlitePath(e.env),e.env).kind===`fresh`)return{changes:n,warnings:[]};let o=t.unverifiedTargets.map(({agentId:e,path:t})=>({agentId:e,path:t}));if(a&&t.failures.length>0)return{changes:n,warnings:[`Agent deletion journal missing; stores remain held because their recovery inventory is incomplete. Repair the listed paths, then rerun openclaw doctor --fix.`,...t.failures.map(({path:e,reason:t})=>sanitizeForLog(`${e}: ${t}`))]};if(a&&e.preflight.agentDatabaseRecoveryConfigValid!==true)return{changes:n,warnings:[`Agent deletion journal missing; stores remain held because the ownership configuration could not be verified. Repair the configuration, then rerun openclaw doctor --fix.`]};if(e.shouldRepair){const s=await quarantineAgentDeletionJournal({inventory:[...t.targets,...t.retainedTargets,...o],configuredTargets:e.preflight.agentDatabaseMigrationDiscovery?.configuredAgentDatabaseTargets??[],env:e.env});if(s){i=!a&&s.warnings.length===0;r.push(...s.warnings.map(e=>sanitizeForLog(e)));o=s.held;n.push(a?`Reconstructed the missing agent deletion journal and recorded a Doctor receipt listing held stores.`:i?`Quarantined unusable agent deletion journal records and recorded a Doctor receipt listing held stores.`:`Preserved unusable agent deletion journal records in place and recorded a Doctor receipt listing held stores.`);n.push(...s.archives.map(e=>sanitizeForLog(`Saved deletion recovery receipt: ${e}`)))}const c=await restoreDoctorMissingJournalStores({env:e.env,held:o});n.push(...c.changes.map(sanitizeForLog));r.push(...c.warnings.map(sanitizeForLog));o=o.filter(e=>!c.restored.some(t=>t.agentId===e.agentId&&t.path===e.path))}if(o.length===0&&(!a||e.shouldRepair))return{changes:n,warnings:r};const s=await createConfigIO({env:e.env,observe:false,pluginValidation:`core-only`}).readConfigFileSnapshot();const c=process.platform===`win32`?quotePowerShellArg:quoteCliArg;return{changes:n,warnings:[...r,`Warning: Agent deletion journal ${a&&!e.shouldRepair?`missing`:i?`quarantined`:r.length>0?`unusable`:`reconstructed`}; ${o.length} store${o.length===1?``:`s`} held back. Updates can continue; held stores remain untouched.`,...o.map(t=>{if(isTransientSqliteBackupPath(t.path))return sanitizeForLog(`${t.path}: internal SQLite coordination artifact; preserved without agent restoration or deletion.`);if(isReservedSystemAgentId(t.agentId))return sanitizeForLog(`${t.path}: ${t.agentId} is a reserved system agent and cannot be added or deleted. Run ${formatCliCommand(`openclaw doctor --fix`,e.env)} to restore its canonical store after ownership, integrity, and backup verification; unverified stores remain untouched.`);const n=resolveAgentWorkspaceDir(s.sourceConfig,t.agentId,e.env);const r=listAgentIds(s.sourceConfig).includes(t.agentId)?resolveAgentDir(s.sourceConfig,t.agentId,e.env):path.dirname(t.path);const i=formatCliCommand(`openclaw agents add ${c(t.agentId)} --workspace ${c(n)} --agent-dir ${c(r)} --non-interactive`,e.env);return sanitizeForLog(`${t.path}: ${path.basename(t.path)===`openclaw-agent.sqlite`?`verify the workspace`:`restore the original session.store configuration for this database and verify the workspace`}, then run ${i} to abort deletion and restore; after restoration, run ${formatCliCommand(`openclaw agents delete ${c(t.agentId)} --force`,e.env)} to confirm deletion instead.`)}),...a&&!e.shouldRepair?[`Run ${formatCliCommand(`openclaw doctor --fix`,e.env)} to reconstruct the journal and restore verified configured stores automatically after verified backups. Other stores remain held.`]:[]]}}export{repairDoctorAgentDeletionJournal};