openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
7 lines • 9.71 kB
JavaScript
import{u as isStringArray}from"./record-coerce-BTbqdJ3-.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{n as normalizeAgentId}from"./agent-id-cOfqmfln.mjs";import"./session-key-BPgKfU2m.mjs";import{a as isSqliteCorruptionError}from"./sqlite-error-diagnostics-ASl1MXPN.mjs";import{a as executeSqliteQueryTakeFirstSync,i as executeSqliteQuerySync,s as getNodeSqliteKysely,v as expressionBuilder}from"./kysely-sync-R08Pt8qn.mjs";import{a as tableExists,o as tableHasColumn}from"./openclaw-state-db-schema-helpers-rYTimzjJ.mjs";import{r as resolveDatabasePath,s as resolveOpenClawStateSqlitePath}from"./openclaw-state-db.paths-CbgXfEg1.mjs";import{g as withExistingOpenClawStateDatabaseReadOnly,n as executeExistingOpenClawStateRead}from"./openclaw-state-db-readonly-Cd5_cxBs.mjs";import{o as runSqliteReadSnapshotSync}from"./sqlite-transaction-CON-dGDv.mjs";import{r as cloneEnvWithPlatformSemantics}from"./config-env-vars-DCDGIBtT.mjs";import{i as prepareOpenClawStateReadSource}from"./openclaw-state-worker-context-Dx8YjqO2.mjs";import{y as hasPreJournalStateSchema}from"./openclaw-state-db-BlgxYkYw.mjs";import{i as ensureAgentDeletionJournalPhaseSchema}from"./openclaw-state-db-schema-additive-DDOLEjcV.mjs";import{n as isSessionStoreTopologyChange,o as sessionChanges}from"./session-row-changes-21DJT-m_.mjs";import{s as readAgentDeletionRecoveryHolds}from"./agent-deletion-journal-recovery.kernel-DcfNqwh_.mjs";import{n as getAgentDeletionJournalStatus,s as loadAgentDeletionJournalStatus,u as seedAgentDeletionDiscovery}from"./agent-deletion-journal-status-WLzvY6ul.mjs";import{i as readRegisteredAgentDatabaseRows}from"./openclaw-agent-db-registry.read-BLUjVOoj.mjs";import{d as prepareOpenClawAgentDatabaseRegistrySnapshotRead,o as isAgentDatabaseRegistryChangedError,s as isOpenClawAgentDatabaseRegistryChange}from"./openclaw-agent-db-registry-listing-Bnnfy4SV.mjs";import path from"node:path";
//!src/templates/provenance-secondary-references.ts
const TEMPLATE_SECONDARY_REFERENCE_TABLES=[`template_package_refs`,`template_mcp_server_refs`,`template_cron_refs`];function readTemplateSecondaryReferenceTables(e,t){return TEMPLATE_SECONDARY_REFERENCE_TABLES.filter(n=>{if(!tableExists(e,n))return false;return Boolean(e.prepare(`SELECT 1 FROM ${n} WHERE agent_id = ? LIMIT 1`).get(t))})}
//!src/state/agent-deletion-journal-authority.worker.ts
function readAgentDeletionJournalAuthorityInDatabase(e,t){const n=executeSqliteQueryTakeFirstSync(e,getNodeSqliteKysely(e).selectFrom(`agent_deletion_journal`).select([`agent_id`,`operation_id`,`cleanup_completed`]).where(`agent_id`,`=`,normalizeAgentId(t)));if(!n)return;if(typeof n.operation_id!==`string`||!n.operation_id||n.cleanup_completed!==0&&n.cleanup_completed!==1)throw new Error(`Agent deletion journal authority is unreadable.`);return{agentId:n.agent_id,operationId:n.operation_id,cleanupCompleted:n.cleanup_completed===1}}function hasTemplateDeletionOwnership(e,t){const n=getNodeSqliteKysely(e.db);return[`template_installs`,`template_workspace_files`].some(r=>tableExists(e.db,r)&&executeSqliteQueryTakeFirstSync(e.db,n.selectFrom(r).select(`agent_id`).where(`agent_id`,`=`,t).limit(1))!==void 0)||readTemplateSecondaryReferenceTables(e.db,t).length>0}function retireAgentDeletionJournalInDatabase(e,t,n){ensureAgentDeletionJournalPhaseSchema(e.db);const r=executeSqliteQuerySync(e.db,getNodeSqliteKysely(e.db).updateTable(`agent_deletion_journal`).set({phase:`retiring`}).where(`agent_id`,`=`,normalizeAgentId(t)).where(`operation_id`,`=`,n).where(`cleanup_completed`,`=`,0)).numAffectedRows===1n;if(r)sessionChanges.emit({all:true,scope:`stores`},e.db);return r}
//!src/state/agent-deletion-journal.read.ts
var AgentDatabaseDeletionSnapshotChangedError=class extends Error{constructor(){super(`Agent database deletion snapshot changed during consumption.`);this.name=`AgentDatabaseDeletionSnapshotChangedError`}};function isAgentDatabaseDeletionSnapshotChangedError(e){return e instanceof AgentDatabaseDeletionSnapshotChangedError||isAgentDatabaseRegistryChangedError(e)}async function readAgentDeletionRecoveryHoldsInWorker(e={}){const t=resolveDatabasePath(e);return(await executeExistingOpenClawStateRead({...e,path:t},{type:`agentRecovery.holds`,input:{statePath:t}},{current:true}))?.held??[]}async function readAgentDeletionJournalForCreation(e,t={}){return(await executeExistingOpenClawStateRead(t,{type:`agentRecovery.creationJournal`,input:{agentId:normalizeAgentId(e)}},{current:true}))?.journal}function readAgentDeletionJournalStatusInDatabase(e,t){const n=getAgentDeletionJournalStatus(e,t);if(n)return n;if(!tableExists(e,`agent_deletion_journal`))return`absent`;const r=executeSqliteQueryTakeFirstSync(e,getNodeSqliteKysely(e).selectFrom(`agent_deletion_journal`).select(`cleanup_completed`).where(`agent_id`,`=`,normalizeAgentId(t)));return r?r.cleanup_completed===1?`complete`:`pending`:`absent`}async function readAgentDeletionJournalStatusInWorker(e,t={},n){n?.throwIfAborted();return loadAgentDeletionJournalStatus(resolveDatabasePath(t),e,async()=>{return(await executeExistingOpenClawStateRead(t,{type:`agentDeletionJournal.status`,agentId:normalizeAgentId(e)},{current:true,signal:n}))?.status??`absent`})}function parseAgentDeletionDatabasePaths(e){const t=JSON.parse(e);if(isStringArray(t))return t;throw new Error(`Invalid agent deletion database path journal.`)}function readRetainedAgentDeletionsFromDatabase(e,t,n=`maintenance`,r){let i=[];let a=false;let o;try{a=!tableExists(e,`agent_deletion_journal`);if(!a){const t=expressionBuilder();const a=t.and([t(`cleanup_completed`,`=`,1),t(`delete_files`,`=`,0)]);const s=n!==`runtime`?t.or([a,t(`cleanup_completed`,`=`,0)]):a;i=executeSqliteQuerySync(e,getNodeSqliteKysely(e).selectFrom(`agent_deletion_journal`).select([`agent_id`,`cleanup_completed`]).select(tableHasColumn(e,`agent_deletion_journal`,`phase`)?`phase`:t.lit(null).as(`phase`)).select([t.case().when(s).then(t.ref(`agent_dir`)).else(null).end().as(`agent_dir`),t.case().when(s).then(t.ref(`database_paths_json`)).else(`[]`).end().as(`database_paths_json`)]).$if(!r,e=>e.where(s)).orderBy(`agent_id`,`asc`)).rows.flatMap(t=>{r?.push({agentId:t.agent_id,status:t.cleanup_completed===1?`complete`:`pending`});if(t.agent_dir===null)return[];let i=[];try{i=parseAgentDeletionDatabasePaths(t.database_paths_json)}catch(e){if(n===`maintenance`)o??=formatErrorMessage(e)}const a={agentId:t.agent_id,agentDir:t.agent_dir,databasePaths:[path.join(t.agent_dir,`openclaw-agent.sqlite`),...i],cleanupCompleted:t.cleanup_completed===1};if(t.cleanup_completed===0&&t.phase==null&&hasTemplateDeletionOwnership({db:e},t.agent_id))a.manualTemplateRemoval=true;return a})}}catch(e){if(isSqliteCorruptionError(e))throw e;o=formatErrorMessage(e)}let s=[];try{if(tableExists(e,`migration_sources`))s=readAgentDeletionRecoveryHolds({db:e,path:t})}catch(e){if(n===`maintenance`||isSqliteCorruptionError(e))throw e}if(a&&s.length===0&&hasPreJournalStateSchema(e))return{status:`empty`};if(a||o!==void 0)return{status:`unavailable`,cause:a?`missing`:`unreadable`,reason:a?`deletion journal missing`:`deletion journal unreadable: ${o}`,...i.length||s.length?{known:{entries:i,held:s}}:{}};return i.length||s.length?{status:`present`,entries:i,held:s}:{status:`empty`}}function readAgentDatabaseDeletionSnapshot(e,t=`maintenance`){return withExistingOpenClawStateDatabaseReadOnly(({db:e,path:n})=>runSqliteReadSnapshotSync(e,()=>({retainedDeletions:readRetainedAgentDeletionsFromDatabase(e,n,t),registeredAgentDatabases:readRegisteredAgentDatabaseRows(e,n,false)}),{operationLabel:`agentDeletionJournal.snapshot`}),{env:e})}function prepareAgentDatabaseDeletionSnapshotRead(e={},t=`maintenance`,n){const r=cloneEnvWithPlatformSemantics(e.env??process.env);r.OPENCLAW_STATE_DIR=resolveStateDir(r);const i={env:r,path:path.resolve(e.path??resolveOpenClawStateSqlitePath(r))};const a=prepareOpenClawStateReadSource(i);const o=a.workerContext();const readSnapshot=async e=>{const assertReadCurrent=()=>{n?.throwIfAborted();e.maintenanceScope?.assertAdmission();e.admission.assertCurrent()};assertReadCurrent();const r=await executeExistingOpenClawStateRead(i,{type:`agentDatabaseDeletion.snapshot`,purpose:t},{context:e,current:true,signal:n});assertReadCurrent();if(t===`runtime-discovery`&&r)seedAgentDeletionDiscovery(i.path,r.snapshot.retainedDeletions);return{snapshot:r?.snapshot,assertCurrent:assertReadCurrent}};const read=()=>readSnapshot(o);return{read,async readWithCurrentAdmission(){return a.withCurrent(readSnapshot)},async withCurrentSnapshot(e){let t;let n;const r=sessionChanges.subscribeFacts(e=>{if(isSessionStoreTopologyChange(e)&&(!n||!isOpenClawAgentDatabaseRegistryChange(e)))t=true});try{for(;;){t=false;const{snapshot:r,assertCurrent:a}=await read();a();if(t)continue;n=prepareOpenClawAgentDatabaseRegistrySnapshotRead(i,e=>e.kind===`upsert`&&e.sources.every(e=>r?.registeredAgentDatabases.some(t=>t.agentId===e.agentId&&t.path===e.path&&t.schemaVersion===e.schemaVersion))).assertCurrent;return await e(r,()=>{a();if(t)throw new AgentDatabaseDeletionSnapshotChangedError;n?.()})}}finally{t=true;r()}}}}export{readAgentDeletionJournalForCreation as a,readAgentDeletionRecoveryHoldsInWorker as c,readAgentDeletionJournalAuthorityInDatabase as d,retireAgentDeletionJournalInDatabase as f,readAgentDatabaseDeletionSnapshot as i,readRetainedAgentDeletionsFromDatabase as l,parseAgentDeletionDatabasePaths as n,readAgentDeletionJournalStatusInDatabase as o,prepareAgentDatabaseDeletionSnapshotRead as r,readAgentDeletionJournalStatusInWorker as s,isAgentDatabaseDeletionSnapshotChangedError as t,hasTemplateDeletionOwnership as u};