UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

7 lines • 19.6 kB
import{l as isRecord,u as isStringArray}from"./record-coerce-BTbqdJ3-.mjs";import{r as isPathInside}from"./path-guards-DGttsOJI.mjs";import{n as normalizeAgentId}from"./agent-id-cOfqmfln.mjs";import"./session-key-BPgKfU2m.mjs";import{g as isReservedSystemAgentId}from"./agent-roster-4XrgUgPK.mjs";import{n as createOpenClawAgentDatabasePathMatcher}from"./openclaw-agent-db.paths-SkzMsgQ0.mjs";import{N as normalizeAgentDirRegistryPath}from"./agent-scope-config-CG9CFpGX.mjs";import{n as isPostgresSqlConnection}from"./sql-connection-nx8lLUJM.mjs";import{a as isSqliteCorruptionError}from"./sqlite-error-diagnostics-ASl1MXPN.mjs";import{a as executeSqliteQueryTakeFirstSync,i as executeSqliteQuerySync,s as getNodeSqliteKysely}from"./kysely-sync-R08Pt8qn.mjs";import{D as requireNativeDatabaseFile}from"./sqlite-schema-facts-CWOeTpUB.mjs";import{a as resolveOpenClawRegisteredAgentDatabasePath,i as resolveOpenClawAgentDatabaseStoredPath}from"./openclaw-state-db.paths-CbgXfEg1.mjs";import{n as executeExistingOpenClawStateRead}from"./openclaw-state-db-readonly-Cd5_cxBs.mjs";import{M as resolveAgentCreationClaimAgentId,g as getAgentDeletionDatabaseCleanup}from"./openclaw-agent-db-resources-KCMTIo4b.mjs";import{s as observeSqliteWorkerAdmissionFinish}from"./sqlite-worker-operation-settlement-Cl93BzUc.mjs";import{i as observeSqliteWorkerCommittedFacts}from"./sqlite-worker-operation-admission-BZvXBQev.mjs";import{a as resolveSqliteDatabaseFilePaths}from"./sqlite-files-731tEtYd.mjs";import{r as captureOpenClawStateWorkerContext}from"./openclaw-state-worker-context-Dx8YjqO2.mjs";import{i as ensureAgentDeletionJournalPhaseSchema,t as assertAgentDeletionJournalAvailable,x as reconstructAgentDeletionJournalSchema}from"./openclaw-state-db-schema-additive-DDOLEjcV.mjs";import{o as sessionChanges}from"./session-row-changes-21DJT-m_.mjs";import{r as createStateDomainPublication}from"./state-domain-publication-DEIaO2Mq.mjs";import{a as recordLegacyMigrationReceipt}from"./state-migrations.receipts-DhYgpkdJ.mjs";import{l as readRetainedAgentDeletionsFromDatabase,n as parseAgentDeletionDatabasePaths,u as hasTemplateDeletionOwnership}from"./agent-deletion-journal.read-DL01GJPw.mjs";import{n as withAgentProvenancePublication}from"./agent-provenance-publication-C5U_xqxD.mjs";import{a as decodeHolds,c as readReport,i as assertAgentDeletionRecoveryHoldsMatch,n as AGENT_DELETION_RECOVERY_SOURCE_KEY,s as readAgentDeletionRecoveryHolds,t as AGENT_DELETION_RECONSTRUCTION_DESCRIPTION}from"./agent-deletion-journal-recovery.kernel-DcfNqwh_.mjs";import{a as invalidateAgentDeletionDiscovery,d as updateAgentDeletionDiscovery,l as publishAgentDeletionJournalStatus,t as getAgentDeletionDiscovery}from"./agent-deletion-journal-status-WLzvY6ul.mjs";import{t as deleteAgentProvenanceForAgent}from"./agent-provenance-DgTm-0eu.mjs";import path from"node:path";import{randomUUID}from"node:crypto"; //!src/state/agent-deletion-journal-publication.ts const agentDeletionJournalPublication=createStateDomainPublication({domain:`agent-deletion-journal`,keyOf:e=>e.agentId,isValue:e=>isRecord(e)&&typeof e.agentId===`string`&&typeof e.operationId===`string`&&typeof e.cleanupCompleted===`boolean`});function observeAgentDeletionJournal(e,t){const n=normalizeAgentId(e);let r=false;let i=false;let a;return{release:agentDeletionJournalPublication.subscribeFacts(e=>{if(e.kind===`committed`&&e.receipt.source.identity===t.admission.identity.key){const t=e.receipt.facts.get(n);if(!t||t.kind===`unchanged`)return;r=true;i=t.kind!==`unknown`;a=t.kind===`postimage`?t.value:void 0}else if(e.kind===`unknown`&&e.identity===t.admission.identity.key){r=true;i=false}}),seed(e){if(!r){a=e&&{agentId:e.agentId,operationId:e.operationId,cleanupCompleted:e.cleanupCompleted};i=true}},assertCurrent(e){t.admission.assertCurrent();if(!i||!a||a.operationId!==e||a.cleanupCompleted)throw new Error(`Agent ${n} deletion no longer owns database cleanup.`)}}}function withAgentDeletionJournalPublication(e,t){return n=>{const r=withAgentProvenancePublication(e,t)(n);const i=agentDeletionJournalPublication.begin({identity:t.admission.identity.key,assertCurrent:t.assertPublicationCurrent??t.admission.assertCurrent});observeSqliteWorkerCommittedFacts(r.admission,({facts:e})=>{if(isRecord(e)&&e.journalAuthority!==void 0)i.committed(e.journalAuthority)});observeSqliteWorkerAdmissionFinish(r.admission,()=>{const e=r.admission.settlement;i.finish(e?.kind===`completed`,true)});return r}} //!src/state/agent-deletion-journal-recovery.ts const JOURNAL_TABLE=`agent_deletion_journal`;function assertAgentDeletionRecoveryAllowsMutation(e,t){assertAgentDeletionJournalAvailable(e.db);const n=createOpenClawAgentDatabasePathMatcher();const r=readAgentDeletionRecoveryHolds(e).find(e=>n(e.path,t));if(r)throw new Error(`Agent database ${r.path} is held after deletion journal reconstruction. Run openclaw doctor --fix for explicit restoration guidance before repairing agent ${r.agentId}.`)}function reconstructAgentDeletionJournal(e,t,n=Date.now()){const r=e.db;if(isPostgresSqlConnection(r))requireNativeDatabaseFile(`postgres`,`repair`);if(!e.db.isTransaction)throw new Error(`Agent deletion journal reconstruction requires a shared-state transaction.`);const i=readReport(e);if(!reconstructAgentDeletionJournalSchema(r,e.path))return decodeHolds(e,i?.held??[]);return recordAgentDeletionRecoveryHolds(e,t,{now:n,missingJournal:t.filter(t=>!i?.held.some(n=>n.agentId===normalizeAgentId(t.agentId)&&n.path===resolveOpenClawAgentDatabaseStoredPath(e.path,t.path)))})}function recordAgentDeletionRecoveryHolds(e,t,{now:n=Date.now(),description:r=AGENT_DELETION_RECONSTRUCTION_DESCRIPTION,missingJournal:i=[],excludeMissingJournal:a=[]}={}){if(!e.db.isTransaction)throw new Error(`Agent deletion recovery requires a shared-state transaction.`);const o=readReport(e);const encode=t=>({agentId:normalizeAgentId(t.agentId),path:resolveOpenClawAgentDatabaseStoredPath(e.path,t.path)});const key=e=>JSON.stringify([e.agentId,e.path]);const s=/* @__PURE__ */ new Map;for(const e of[...o?.held??[],...t.filter(e=>!isReservedSystemAgentId(e.agentId)).map(encode)])s.set(key(e),e);const c=/* @__PURE__ */ new Map;for(const e of[...o?.missingJournal??[],...i.map(encode)])if(s.has(key(e)))c.set(key(e),e);for(const e of a.map(encode))c.delete(key(e));const l={...o,description:r,held:[...s.values()],missingJournal:[...c.values()]};recordLegacyMigrationReceipt(e.db,{sourceKey:AGENT_DELETION_RECOVERY_SOURCE_KEY,migrationKind:AGENT_DELETION_RECOVERY_SOURCE_KEY,sourcePath:e.path,targetTable:JOURNAL_TABLE,sourceSha256:null,sourceSizeBytes:null,sourceRecordCount:null,runId:`${AGENT_DELETION_RECOVERY_SOURCE_KEY}:${randomUUID()}`,now:n,reportJson:JSON.stringify(l),upsert:true});invalidateAgentDeletionDiscovery(e.db);sessionChanges.emit({all:true,scope:`stores`},e.db);return decodeHolds(e,l.held)}function resolveAgentDeletionRecoveryHolds(e,t,n,r){if(!e.db.isTransaction)throw new Error(`Agent deletion recovery resolution requires a shared-state transaction.`);const i=readReport(e);if(r)assertAgentDeletionRecoveryHoldsMatch(decodeHolds(e,i?.held??[]),r);if(!i)return 0;const a=normalizeAgentId(t);const o=new Set(n.map(t=>resolveOpenClawAgentDatabaseStoredPath(e.path,t)));const s=i.held.filter(e=>e.agentId!==a||!o.has(e.path));const c=i.missingJournal?.filter(e=>e.agentId!==a||!o.has(e.path));const l=i.held.length-s.length;if(l>0){executeSqliteQuerySync(e.db,getNodeSqliteKysely(e.db).updateTable(`migration_sources`).set({report_json:JSON.stringify({...i,held:s,missingJournal:c})}).where(`source_key`,`=`,AGENT_DELETION_RECOVERY_SOURCE_KEY));invalidateAgentDeletionDiscovery(e.db);sessionChanges.emit({all:true,scope:`stores`},e.db)}return l} //!src/state/agent-deletion-journal.ts function prepareDeletionDiscovery(e){return getAgentDeletionDiscovery(e.db)??readRetainedAgentDeletionsFromDatabase(e.db,e.path,`runtime-discovery`)}function publishDeletingAgent(e,t,n){updateAgentDeletionDiscovery(e.db,t,n.agentId,()=>({agentId:n.agentId,agentDir:n.agentDir,databasePaths:[path.join(n.agentDir,`openclaw-agent.sqlite`),...n.databasePaths],cleanupCompleted:false}));agentDeletionJournalPublication.stagePostimages(e.db,[{agentId:n.agentId,operationId:n.operationId,cleanupCompleted:n.cleanupCompleted}])}var AgentDatabaseDeletionRefusedError=class extends Error{};function assertAgentDeletionIdentityClaimAllowed(e,t){if(t&&normalizeAgentId(e)===normalizeAgentId(t))throw new AgentDatabaseDeletionRefusedError(`OpenClaw agent database is unavailable while agent ${normalizeAgentId(t)} is deleted.`)}function readAgentDeletionPathFenceRows(e,t=`runtime`,n){if(t===`maintenance`)assertAgentDeletionJournalAvailable(e);try{const r=getNodeSqliteKysely(e);let i=true;let a=r.selectFrom(`agent_deletion_journal`).selectAll();if(n!==void 0)a=a.where(`agent_id`,`=`,normalizeAgentId(n));const o=executeSqliteQuerySync(e,a).rows.map(e=>{let n=[];let r=[];try{n=parseAgentDeletionDatabasePaths(e.database_paths_json);r=parseCleanupPaths(e.cleanup_paths_json)}catch(e){if(t===`maintenance`)throw e;i=false}return Object.assign(e,{databasePaths:n,cleanupPaths:r})});return{known:i,rows:o}}catch(e){if(t===`maintenance`||isSqliteCorruptionError(e))throw e;return{known:false,rows:[]}}}function prepareAgentDeletionPathFence(e,t={},n=e.fenceAgentId?`maintenance`:`runtime`){const r=t.env??process.env;return{env:r,purpose:n,claimAgentId:normalizeAgentId(e.agentId),claimPath:path.resolve(e.path),...e.fenceAgentId?{fenceAgentId:normalizeAgentId(e.fenceAgentId)}:{},targetPaths:resolveSqliteDatabaseFilePaths(e.path).map(e=>normalizeAgentDirRegistryPath(e,r))}}function assertAgentDeletionPathFence(e,t){const n=e.db;const{rows:r,known:i}=readAgentDeletionPathFenceRows(n,t.purpose);if(!i&&r.length===0)return;const a=t.fenceAgentId?void 0:getAgentDeletionDatabaseCleanup({agentId:t.claimAgentId,path:t.claimPath,statePath:e.path});a?.assertCurrent();const o=a?.assertJournal(e.path,r.map(e=>({agentId:e.agent_id,operationId:e.operation_id,cleanupCompleted:e.cleanup_completed===1})));const s=t.fenceAgentId?void 0:resolveAgentCreationClaimAgentId(t.claimAgentId,e.path);for(const e of r){if(t.fenceAgentId&&t.fenceAgentId!==e.agent_id)continue;if(e.agent_id===o)continue;if(e.cleanup_completed===1&&e.agent_id===s)continue;if(e.phase===`draining`&&e.cleanup_completed!==1&&e.agent_id===t.claimAgentId&&!t.fenceAgentId)continue;assertAgentDeletionIdentityClaimAllowed(t.claimAgentId,e.agent_id);if(e.cleanup_completed===1)continue;const n=[...[e.agent_dir,e.workspace_dir,e.sessions_dir,...e.databasePaths].map(e=>({path:e,canonicalPath:normalizeAgentDirRegistryPath(e,t.env)})),...e.cleanupPaths.map(e=>({path:e.path,canonicalPath:normalizeAgentDirRegistryPath(e.canonicalPath,t.env)}))];for(const r of n){const n=t.targetPaths.find(e=>e===r.canonicalPath||isPathInside(r.canonicalPath,e));if(n)throw new AgentDatabaseDeletionRefusedError(`OpenClaw agent database ${n} is unavailable while agent ${e.agent_id} deletion owns ${r.path}.`)}}}function fromRow(e){if(e.phase!=null&&e.phase!==`draining`&&e.phase!==`retiring`)throw new Error(`Invalid agent deletion journal phase.`);return{agentId:e.agent_id,operationId:e.operation_id,phase:e.phase===`draining`?`draining`:`retiring`,agentDir:e.agent_dir,workspaceDir:e.workspace_dir,sessionsDir:e.sessions_dir,databasePaths:e.databasePaths??parseAgentDeletionDatabasePaths(e.database_paths_json),cleanupPaths:e.cleanupPaths??parseCleanupPaths(e.cleanup_paths_json),createdAt:e.created_at,cleanupCompleted:e.cleanup_completed===1,deleteFiles:e.delete_files===1}}function parseCleanupPaths(e){const t=JSON.parse(e);if(!Array.isArray(t)||!t.every(e=>isRecord(e)&&typeof e.path===`string`&&typeof e.canonicalPath===`string`&&typeof e.parentPath===`string`&&(e.kind===`target`||e.kind===`symlink`)&&(e.dev===null||typeof e.dev===`number`&&Number.isInteger(e.dev)||typeof e.dev===`string`&&/^(0|-?[1-9][0-9]*)$/u.test(e.dev))&&(e.ino===null||typeof e.ino===`number`&&Number.isInteger(e.ino)||typeof e.ino===`string`&&/^(0|-?[1-9][0-9]*)$/u.test(e.ino))&&typeof e.coversDescendants===`boolean`&&typeof e.done===`boolean`&&(e.note===void 0||typeof e.note===`string`)&&isStringArray(e.sourcePaths)))throw new Error(`Invalid agent deletion cleanup path journal.`);return t}function readAgentDeletionJournalInDatabase(e,t,n=`maintenance`){const r=readAgentDeletionPathFenceRows(e.db,n,t).rows[0];return r?fromRow(r):void 0}function listPendingAgentDeletionJournalsInDatabase(e){const t=[];const n=[];for(const r of readAgentDeletionPathFenceRows(e.db).rows){if(r.cleanup_completed===1)continue;if(r.phase==null&&hasTemplateDeletionOwnership(e,r.agent_id))n.push(r.agent_id);else t.push(fromRow(r))}return{entries:t,manualTemplateAgentIds:n}}function beginAgentDeletionJournalInDatabase(e,t,n=false,r){const i={...t,phase:t.phase??`retiring`,agentId:normalizeAgentId(t.agentId),databasePaths:[...new Set((t.databasePaths??[]).map(e=>path.resolve(e)))],cleanupPaths:t.cleanupPaths??[]};sessionChanges.emit({all:true,scope:`stores`},e.db);ensureAgentDeletionJournalPhaseSchema(e.db);const a=prepareDeletionDiscovery(e);const o=getNodeSqliteKysely(e.db);const s=executeSqliteQueryTakeFirstSync(e.db,o.selectFrom(`agent_deletion_journal`).selectAll().where(`agent_id`,`=`,i.agentId));if(r!==void 0){if(!s||s.operation_id!==r||s.cleanup_completed!==0)throw new Error(`Agent ${i.agentId} deletion changed before recovery.`);if(s.phase==null&&hasTemplateDeletionOwnership(e,i.agentId))throw new Error(`Agent ${i.agentId} deletion requires its Template removal owner.`)}const c=executeSqliteQuerySync(e.db,o.selectFrom(`agent_databases`).select(`path`).where(`agent_id`,`=`,i.agentId)).rows.flatMap(t=>resolveSqliteDatabaseFilePaths(resolveOpenClawRegisteredAgentDatabasePath(e.path,t.path)));const l=s&&fromRow(s);if(n&&l)i.deleteFiles=l.deleteFiles;const u=[...new Set([...l?.databasePaths??[],...i.databasePaths,...c].map(e=>path.resolve(e)))];const d=l?.cleanupPaths??i.cleanupPaths;if(l){executeSqliteQuerySync(e.db,o.updateTable(`agent_deletion_journal`).set({operation_id:i.operationId,database_paths_json:JSON.stringify(u),cleanup_paths_json:JSON.stringify(d),cleanup_completed:0,delete_files:i.deleteFiles?1:0}).where(`agent_id`,`=`,i.agentId));publishAgentDeletionJournalStatus(e.db,i.agentId,`pending`);const t={previousEntry:l,entry:{...l,operationId:i.operationId,databasePaths:u,cleanupPaths:d,cleanupCompleted:false,deleteFiles:i.deleteFiles}};publishDeletingAgent(e,a,t.entry);return t}const f=Date.now();executeSqliteQuerySync(e.db,o.insertInto(`agent_deletion_journal`).values({agent_id:i.agentId,operation_id:i.operationId,phase:t.phase??null,agent_dir:i.agentDir,workspace_dir:i.workspaceDir,sessions_dir:i.sessionsDir,database_paths_json:JSON.stringify(u),cleanup_paths_json:JSON.stringify(d),created_at:f,cleanup_completed:0,delete_files:i.deleteFiles?1:0}));publishAgentDeletionJournalStatus(e.db,i.agentId,`pending`);const p={entry:{...i,databasePaths:u,cleanupPaths:d,createdAt:f,cleanupCompleted:false}};publishDeletingAgent(e,a,p.entry);return p}function updateAgentDeletionJournalPathsInDatabase(e,t,n,...r){const[i,a]=r;const o=prepareDeletionDiscovery(e);assertAgentDeletionJournalAvailable(e.db);const s=getNodeSqliteKysely(e.db);const c=executeSqliteQuerySync(e.db,s.updateTable(`agent_deletion_journal`).set({[i]:JSON.stringify(a)}).where(`agent_id`,`=`,t).where(`operation_id`,`=`,n).where(`cleanup_completed`,`=`,0));const l=Number(c.numAffectedRows??0)>0;if(l){if(i===`database_paths_json`)updateAgentDeletionDiscovery(e.db,o,t,e=>e&&{...e,databasePaths:[path.join(e.agentDir,`openclaw-agent.sqlite`),...a]});sessionChanges.emit({all:true,scope:`stores`},e.db)}return l}function handoffAgentDeletionJournalInDatabase(e,t,n,r){assertAgentDeletionJournalAvailable(e.db);const i=getNodeSqliteKysely(e.db);const a=executeSqliteQuerySync(e.db,i.updateTable(`agent_deletion_journal`).set({operation_id:r}).where(`agent_id`,`=`,normalizeAgentId(t)).where(`operation_id`,`=`,n).where(`cleanup_completed`,`=`,0)).numAffectedRows===1n;if(a){agentDeletionJournalPublication.stagePostimages(e.db,[{agentId:normalizeAgentId(t),operationId:r,cleanupCompleted:false}]);sessionChanges.emit({all:true,scope:`stores`},e.db)}return a}function completeAgentDeletionJournalInDatabase(e,t,n){const r=normalizeAgentId(t);ensureAgentDeletionJournalPhaseSchema(e.db);const i=prepareDeletionDiscovery(e);const a=getNodeSqliteKysely(e.db);const o=executeSqliteQueryTakeFirstSync(e.db,a.updateTable(`agent_deletion_journal`).set({cleanup_completed:1}).where(`agent_id`,`=`,r).where(`operation_id`,`=`,n).where(e=>e.or([e(`phase`,`is`,null),e(`phase`,`=`,`retiring`)])).returning([`database_paths_json`,`delete_files`]));if(o){updateAgentDeletionDiscovery(e.db,i,r,e=>o.delete_files===1?void 0:e&&{...e,cleanupCompleted:true});publishAgentDeletionJournalStatus(e.db,r,`complete`);agentDeletionJournalPublication.stagePostimages(e.db,[{agentId:r,operationId:n,cleanupCompleted:true}]);resolveAgentDeletionRecoveryHolds(e,r,parseAgentDeletionDatabasePaths(o.database_paths_json));deleteAgentProvenanceForAgent(e.db,r);sessionChanges.emit({all:true,scope:`stores`},e.db)}return o!==void 0}function deleteAgentDeletionJournalInDatabase(e,t,n,r){const i=prepareDeletionDiscovery(e);const a=normalizeAgentId(t);assertAgentDeletionJournalAvailable(e.db);const o=getNodeSqliteKysely(e.db).deleteFrom(`agent_deletion_journal`).where(`agent_id`,`=`,a).where(`operation_id`,`=`,n);const s=executeSqliteQuerySync(e.db,r?o.where(`cleanup_completed`,`=`,1):o);const c=Number(s.numAffectedRows??0)>0;if(c){updateAgentDeletionDiscovery(e.db,i,a,()=>void 0);publishAgentDeletionJournalStatus(e.db,a,`absent`);agentDeletionJournalPublication.stageDeletions(e.db,[a]);sessionChanges.emit({all:true,scope:`stores`},e.db)}return c}async function readAgentDeletionJournalAsync(e,t={}){const n=captureOpenClawStateWorkerContext({...t,path:t.database?.path??t.path});const{runOpenClawStateWorkerOperation:r}=await import(`./openclaw-state-worker-store-DM1orX5Z.mjs`);const i=await r(n,t=>t.execute({type:`agentDeletion.read`,input:{agentId:normalizeAgentId(e)}}),{existingOnly:true});n.admission.assertCurrent();return i}async function listPendingAgentDeletionJournalsAsync(e={}){const t=await executeExistingOpenClawStateRead(e,{type:`agentRecovery.pendingDeletions`,input:void 0},{current:true});return{entries:t?.entries??[],manualTemplateAgentIds:t?.manualTemplateAgentIds??[]}}async function assertNoAgentDatabaseLeasesAsync(e,t={}){const n=captureOpenClawStateWorkerContext({...t,path:t.database?.path??t.path});const{executeOpenClawStateWorker:r}=await import(`./openclaw-state-worker-store-DM1orX5Z.mjs`);await r(n,{type:`agentDeletion.assertNoDatabaseLeasesUnowned`,input:{agentId:normalizeAgentId(e)}})}export{recordAgentDeletionRecoveryHolds as _,completeAgentDeletionJournalInDatabase as a,observeAgentDeletionJournal as b,listPendingAgentDeletionJournalsAsync as c,prepareAgentDeletionPathFence as d,readAgentDeletionJournalAsync as f,reconstructAgentDeletionJournal as g,assertAgentDeletionRecoveryAllowsMutation as h,beginAgentDeletionJournalInDatabase as i,listPendingAgentDeletionJournalsInDatabase as l,updateAgentDeletionJournalPathsInDatabase as m,assertAgentDeletionPathFence as n,deleteAgentDeletionJournalInDatabase as o,readAgentDeletionJournalInDatabase as p,assertNoAgentDatabaseLeasesAsync as r,handoffAgentDeletionJournalInDatabase as s,AgentDatabaseDeletionRefusedError as t,parseCleanupPaths as u,resolveAgentDeletionRecoveryHolds as v,withAgentDeletionJournalPublication as x,agentDeletionJournalPublication as y};