UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

24 lines • 21.6 kB
import{t as __exportAll}from"./rolldown-runtime-Dhi_T53f.js";import{it as resolveGlobalSingleton,p as LruCache,z as runInDetachedAsyncContext}from"./paths--OfTlHNJ.js";import{f as AsyncContext,t as createSubsystemLogger}from"./subsystem-ClzPkrHG.js";import{S as releaseAgentCreationClaimHandle,b as releaseAgentDeletionDatabaseCleanup,g as registerAgentDatabaseResourceReleaseHandler,h as matchesAgentDatabaseClose,m as hasOpenClawAgentDatabaseAsyncResources,y as revokeAgentDatabaseResources}from"./sqlite-readonly-worker-CJyn3oRb.js";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.js";import{a as isAgentDatabaseStartupReadReady}from"./agent-database-admission-Cfotvjtp.js";import"./runtime-process-manifest-CzeI_ZiX.js";import"./async-work-scope-BmlBpc8q.js";import{D as openTrackedStateDatabase,E as closeTrackedStateDatabase,J as isExistingOpenClawStateSchema,K as assertOpenClawStateSchemaRepairAllowed,ct as assertSqliteIntegrity,g as assertStateDatabaseIntegrityOnce,o as openClawStateDatabaseCache,ot as createSqliteTerminalOpenLatch,st as SqliteRepairableForeignKeyError,v as adoptPeerPublishedStateSchemaVersion,y as createStateSchemaAdmission}from"./openclaw-state-db-cache-DjvCroXk.js";import"./runtime-binary-BWC3z4wd.js";import"./runtime-worker-url-C_8irENp.js";import{Fn as sqlPublicationAnchor,H as prepareSqliteDatabaseCleanClose,Kt as OPENCLAW_STATE_SCHEMA_SQL,Pn as isPostgresSqlConnection,h as assertNoActiveSqliteReaders,mt as deferSqlitePostCommitPublication,rt as revokeSqliteDatabaseAdmissionsForPath}from"./sqlite-worker-request-class-l9sdQxsj.js";import{At as disposeNodeSqliteDependents,Et as setSqliteBusyTimeout,Ht as getOpenClawDatabaseMaintenanceResourceScope,Ot as assertNodeSqliteDisposalAllowed,Ut as getOpenClawDatabaseMaintenanceScope,kt as clearNodeSqliteKyselyCacheForDatabase,o as resolveDatabasePath,q as admitSqliteSchema,u as resolveOpenClawStateSqlitePath}from"./openclaw-state-db-async-lifecycle-DFpGMybR.js";import{t as extractSqliteTableSchema}from"./sqlite-schema-sql-D2HdV_QG.js";import{I as withStateDatabaseSchemaMaintenance,M as assertOpenClawStateWriteAllowed,St as assertSupportedStateSchemaVersion,Z as mayShareAgentDatabaseFile,at as openExistingStatePostgresConnection,d as assertExistingOpenClawStateRuntimeSchema,dn as readOpenClawAgentDatabaseIdentity,it as isStatePostgres,l as runManagedStateTransaction,ln as agentDatabaseBorrowers,lt as withPostgresSchemaAdmissionRetry,nt as ensureStatePostgresFragment,qt as agentDatabaseMaintenanceAuthority,un as isOpenClawAgentDatabasePathCurrent,v as assertOpenClawStateDatabaseOwner,wt as requireStatePostgresPhysicalFacts,xt as admitStateSchemaFacts}from"./openclaw-agent-db-registry-listing-DQvRJUwf.js";import{a as runOpenClawStateWriteTransaction,l as ensureAgentDatabaseLeaseSchema,o as recoverOrphanTaskDeliveryRows,t as invalidateOpenClawAgentDatabaseValidation,u as createSqliteSchemaEnsurer}from"./agent-database-preparation-context-CdipnVPq.js";import"./errors-Bn-s0XYn.js";import{c as getCanonicalSqliteTableNames,g as runUpdateSqliteMigration,n as assertSqliteSchemaContains,s as getCanonicalSqliteNamedIndexNames}from"./sqlite-source-handle-gJa7vBkU.js";import"./sqlite-worker-operation-settlement-DUfe98Na.js";import{A as executeSqliteQueryTakeFirstSync,d as assertTransactionUsable,j as getNodeSqliteKysely,k as executeSqliteQuerySync,s as resolveAgentDatabaseIdleHandleTtlMs,u as withEngineStoreAdmission}from"./sqlite-schema-issues-Dicad9Gx.js";import"./worker-request-diagnostics-D8vk7d55.js";import{s as OPENCLAW_SQLITE_BUSY_TIMEOUT_MS}from"./openclaw-state-db-contract-lz-66XzZ.js";import"./worker-task-pool-D981bQaU.js";import"./pid-alive-b9rOSUDi.js";import"./sqlite-database-admission-turn-BOLzWM8u.js";import"./sqlite-worker-store-Cs92G7R4.js";import"./openclaw-state-worker-store-D_ezLkQm.js";import path from"node:path";import{stat}from"node:fs/promises";import fs,{statSync}from"node:fs";import{isDeepStrictEqual}from"node:util";import{createHash,randomUUID}from"node:crypto";import{AsyncLocalStorage}from"node:async_hooks";import{MessageChannel,MessagePort,isMainThread,receiveMessageOnPort,threadId}from"node:worker_threads";import{addAbortListener,setMaxListeners}from"node:events";import{channel}from"node:diagnostics_channel";import{performance as performance$1}from"node:perf_hooks"; //!src/process/gateway-work-admission-state.ts const currentRootWork=new AsyncContext(Symbol.for(`openclaw.gatewayWorkAdmissionState`));const reloadWaitingRoots=new AsyncContext(Symbol.for(`openclaw.gatewayReloadWaitingRoots`));const subscriptionRootWork=new AsyncContext(Symbol(`gatewaySubscriptionRootWork`));function createShutdownCleanupController(){const e=new AbortController;setMaxListeners(0,e.signal);return e}const GATEWAY_WORK_ADMISSION_STATE=resolveGlobalSingleton(Symbol.for(`openclaw.gatewayWorkAdmissionState`),()=>({restartDrainReason:void 0,restartDrainController:new AbortController,shutdownCleanupController:createShutdownCleanupController(),restartSignalPending:false,restartSignalGeneration:0,suspendPhase:`accepting`,suspendGeneration:0,activeRootWork:/* @__PURE__ */ new Set,rootWorkReleaseListeners:/* @__PURE__ */ new Set,suspendOpenWaiters:/* @__PURE__ */ new Set,suspendListeners:/* @__PURE__ */ new Set})); //!src/process/gateway-work-admission.ts const admissionLog=createSubsystemLogger(`gateway/admission`);function getGatewayShutdownCleanupSignal(){return GATEWAY_WORK_ADMISSION_STATE.shutdownCleanupController.signal} //!src/sessions/session-agent-work-admission.ts const sessionWorkAdmissionClosures=resolveGlobalSingleton(Symbol.for(`openclaw.sessionWorkAdmissionClosures`),()=>/* @__PURE__ */ new Set); //!src/state/openclaw-state-db-existing-write.ts function assertExistingOpenClawStateSchemaMetadata(e,t,n){const r=assertOpenClawStateDatabaseOwner(e,{pathname:t});if(n>=1&&r?.schema_version===n)return n;if(n>=1&&adoptPeerPublishedStateSchemaVersion(e,r))return 40;throw new Error(`Existing-state schema metadata is inconsistent.`)}function assertExistingOpenClawStateSchema(e,t,n,r,i=`full`){const a=assertExistingOpenClawStateSchemaMetadata(e,t,assertSupportedStateSchemaVersion(e,t));if(i===`quick`)assertSqliteIntegrity(e,t,{check:`quick`,tables:n===void 0?void 0:getCanonicalSqliteTableNames(n)});else assertStateDatabaseIntegrityOnce(e,t);if(n!==void 0)assertSqliteSchemaContains(e,t,n,r);return a}function runExistingOpenClawStateWriteTransaction(e,t,n){const r=prepareExistingOpenClawStateWriter(t,n);const write=()=>{const i=createExistingOpenClawStateWriter(r,n);try{return i.run(e,t)}finally{i.close()}};return n.recoverTaskDeliveryOrphans?withStateDatabaseSchemaMaintenance({databasePath:r.pathname},write):write()}function prepareExistingOpenClawStateWriter(e,t){if(e.database||e.readOnly)throw new Error(`Existing-state writes require their own tracked writable connection.`);const n=e.env??process.env;const r=resolveDatabasePath({path:e.path,env:n});isExistingOpenClawStateSchema(r);if(t.recoverTaskDeliveryOrphans)assertOpenClawStateSchemaRepairAllowed(r);const i=fs.lstatSync(r);if(!i.isFile())throw new Error(`Existing-state write requires a regular database file.`);return{env:n,pathname:r,original:i}}function createExistingOpenClawStateWriter({env:e,pathname:t,original:n},r){const assertSameFile=()=>{const e=fs.lstatSync(t);if(!e.isFile()||e.dev!==n.dev||e.ino!==n.ino)throw new Error(`Existing-state database generation changed.`)};assertSameFile();openClawStateDatabaseCache.assertOpenClawStateDatabaseFreshOpenAllowedAtPath(t,e);if(isStatePostgres())return createExistingPostgresStateWriter(t,r,assertSameFile);const i=openTrackedStateDatabase(t,{existingOnly:true,...r.recoverTaskDeliveryOrphans?{enableForeignKeyConstraints:false}:{}});const a=createStateSchemaAdmission(`state.subset:${createHash(`sha256`).update(JSON.stringify([r.schemaSql,r.schemaCompatibility,r.integrityCheck])).digest(`hex`)}`,e=>typeof e===`number`?e:void 0,r.integrityCheck===void 0?`process`:void 0);const o=r.initializeAdditiveSchema?createSqliteSchemaEnsurer(()=>r.schemaSql,{tables:getCanonicalSqliteTableNames(r.schemaSql),indexes:getCanonicalSqliteNamedIndexNames(r.schemaSql)}):void 0;let s=false;const close=()=>{s=true;clearNodeSqliteKyselyCacheForDatabase(i);closeTrackedStateDatabase(i)};return{run(e,n){if(s||!i.isOpen)throw new Error(`Existing-state writer is closed.`);if(n.database||n.readOnly)throw new Error(`Existing-state writes require their own tracked writable connection.`);const c=n.env??process.env;if(resolveDatabasePath({path:n.path,env:c})!==t)throw new Error(`Existing-state writer cannot change its database path.`);assertSameFile();const l=isExistingOpenClawStateSchema(t);const u=n.busyTimeoutMs??r.busyTimeoutMs??5e3;setSqliteBusyTimeout(i,u);admitStateSchemaFacts(i,t);if(!r.recoverTaskDeliveryOrphans&&r.integrityCheck===void 0)assertStateDatabaseIntegrityOnce(i,t);const write=()=>runManagedStateTransaction(i,()=>{assertSameFile();assertOpenClawStateWriteAllowed({database:i,databasePath:t,env:c});const n=a.get(i);const s=n===void 0;if(l)assertExistingOpenClawStateRuntimeSchema(i,t);const validate=()=>assertExistingOpenClawStateSchema(i,t,s&&r.initializeAdditiveSchema?void 0:r.schemaSql,r.schemaCompatibility,r.integrityCheck);let u;let d=[];if(r.recoverTaskDeliveryOrphans){try{validate()}catch(e){if(!(e instanceof SqliteRepairableForeignKeyError))throw e}d=recoverOrphanTaskDeliveryRows(i,t);u=validate()}else u=n??validate();if(s&&r.initializeAdditiveSchema){assertSqliteSchemaContains(i,t,r.schemaSql,{...r.schemaCompatibility,allowedMissingTables:getCanonicalSqliteTableNames(r.schemaSql)});admitSqliteSchema(i);o?.(i);assertSqliteSchemaContains(i,t,r.schemaSql,r.schemaCompatibility)}if(s){admitSqliteSchema(i);a.publish(i,u)}const f=e({db:i,path:t,recoveryChanges:d});assertSameFile();if(r.recoverTaskDeliveryOrphans)assertSqliteIntegrity(i,t);return f},{beginLockFailureReporting:r.beginLockFailureReporting,busyTimeoutMs:u,databaseLabel:t,operationLabel:r.operationLabel});return r.attributeUpdateWrite?runUpdateSqliteMigration(i,t,write,{close}):write()},assertSettled(){assertSameFile();assertTransactionUsable(i);if(i.isOpen&&i.isTransaction)throw new Error(`Existing-state writer retained an unsettled transaction`);if(i.isOpen)assertNoActiveSqliteReaders(i,`Existing-state writer`)},close}}function createExistingPostgresStateWriter(e,t,n){const r=withEngineStoreAdmission(()=>openExistingStatePostgresConnection(e));if(!r)throw new Error(`Existing PostgreSQL state writer requires its selected engine`);const{db:i}=r.database;const a=getCanonicalSqliteTableNames(t.schemaSql);return{run(r,o){if(!i.isOpen)throw new Error(`Existing-state writer is closed.`);if(o.database||o.readOnly)throw new Error(`Existing-state writes require their own tracked writable connection.`);const s=o.env??process.env;if(resolveDatabasePath({path:o.path,env:s})!==e)throw new Error(`Existing-state writer cannot change its database path.`);let c=false;return withEngineStoreAdmission(()=>withPostgresSchemaAdmissionRetry(i,()=>runManagedStateTransaction(i,()=>{n();assertOpenClawStateWriteAllowed({database:i,databasePath:e,env:s});const o=requireStatePostgresPhysicalFacts(i).catalog;for(const e of a)if(t.initializeAdditiveSchema)ensureStatePostgresFragment(i,e);else if(!o.some(t=>t.kind===`table`&&t.table===e))throw new Error(`Existing PostgreSQL state schema is missing ${e}`);c=true;const l=r({db:i,path:e,recoveryChanges:[]});n();return l},{databaseLabel:e,operationLabel:t.operationLabel,beginLockFailureReporting:t.beginLockFailureReporting}),()=>!c))},assertSettled(){n();assertTransactionUsable(i);if(!i.isOpen)throw new Error(`Existing-state writer retained a closed PostgreSQL connection`);if(i.isTransaction)throw new Error(`Existing-state writer retained an unsettled transaction`)},close(){r.close()}}} //!src/state/openclaw-agent-db-existing-write.ts const existingAgentLeaseSchema=[`schema_meta`,`state_leases`,`agent_database_leases`].map(e=>extractSqliteTableSchema(OPENCLAW_STATE_SCHEMA_SQL,e,{endMarker:`) STRICT;`,errorMessage:`Existing agent lease schema is unavailable.`})).join(` `);function withExistingAgentLeaseWrite(e,t,n){return runExistingOpenClawStateWriteTransaction(({db:t})=>{e.assertOwnedInTransaction(t);const r=n(t);e.assertOwnedInTransaction(t);return r},t,{operationLabel:`agent.database.maintenance.admission`,schemaSql:existingAgentLeaseSchema,integrityCheck:getOpenClawDatabaseMaintenanceScope()?.sqliteIntegrityCheck,schemaCompatibility:{allowedMissingColumns:[`agent_database_leases.provenance`]}})} //!src/state/openclaw-agent-db-lease.ts const log$1=createSubsystemLogger(`state/agent-db`);const closeReceipts=resolveGlobalSingleton(Symbol.for(`openclaw.agentDatabaseCloseReceipts`),()=>new LruCache(128),e=>e.clear());function readAgentDatabaseLeases(e,t){const n=getNodeSqliteKysely(e).selectFrom(`agent_database_leases`).selectAll();return executeSqliteQuerySync(e,t===void 0?n:n.where(`lease_id`,`=`,t)).rows}function releaseOpenClawAgentDatabaseLease(e,t={},n,r){const i=performance.now();const release=t=>{const a=getNodeSqliteKysely(t);const o=executeSqliteQueryTakeFirstSync(t,n===void 0?a.selectFrom(`agent_database_leases`).select([`path`,`agent_id`]).where(`lease_id`,`=`,e):a.deleteFrom(`agent_database_leases`).where(`lease_id`,`=`,e).returning([`path`,`agent_id`]));if(n===void 0){if(o)clearAgentDatabaseLeaseVerifications(t,o.path);executeSqliteQuerySync(t,a.deleteFrom(`agent_database_leases`).where(`lease_id`,`=`,e))}let s;let c;if(!o)s=`lease-not-held`;else if(typeof n!==`object`)s=n===`uncheckpointed`?`checkpoint-incomplete`:n??`close-unconfirmed`;else if(o.path!==n.path)s=`path-mismatch`;else{c=findAgentDatabasePathLease(t,n.path);s=c?`active-leases`:n.publishSeal()?`written`:`verification-missing`}const publish=()=>{const t=r?performance.now()-r.startedAt:0;const n=t>=500;const a=n?{totalMs:Math.round(t),walStopMs:Math.round(r?.walStopMs??0),checkpointMs:Math.round(r?.checkpointMs??0),nativeCloseMs:Math.round(r?.nativeCloseMs??0),leaseReleaseMs:Math.round(performance.now()-i)}:void 0;const l=a?createHash(`sha256`).update(o?.path??`unknown`).digest(`hex`).slice(0,16):void 0;if(o){const e=closeReceipts.get(o.path);if(!n&&e?.agentId===o.agent_id&&e.receipt===s&&e.blockingLeaseId===c?.lease_id)return;closeReceipts.set(o.path,{agentId:o.agent_id,receipt:s,blockingLeaseId:c?.lease_id})}log$1.info(`agent database clean-close receipt: ${s}; agent=${o?.agent_id??`unknown`}${c?`; blockingLeaseId=${c.lease_id}; ownerPid=${c.owner_pid}`:``}${a?`; db=${l}; thread=${threadId}; close=${JSON.stringify(a)}`:``}`,{agentId:o?.agent_id,path:o?.path,leaseId:e,receipt:s,pid:process.pid,threadId,...a?{close:a}:{},...s===`checkpoint-incomplete`&&r?.checkpoint?{checkpoint:r.checkpoint}:{},blockingLease:c&&{leaseId:c.lease_id,ownerPid:c.owner_pid,ownerStartTime:c.owner_start_time,path:c.path,openedAt:c.opened_at}})};if(!deferSqlitePostCommitPublication(t,publish))publish()};const a=agentDatabaseMaintenanceAuthority.getStore();const o=path.resolve(t.database?.path??t.path??resolveOpenClawStateSqlitePath(t.env));if(a?.databasePath===o)return withExistingAgentLeaseWrite(a.authority,t,release);withEngineStoreAdmission(()=>runOpenClawStateWriteTransaction(e=>{ensureAgentDatabaseLeaseSchema(e.db);release(e.db)},typeof n===`object`?{...t,initializationAgentPaths:[...t.initializationAgentPaths??[],n.path]}:t))}function agentDatabaseLeasePaths(e){const t=getNodeSqliteKysely(e);return executeSqliteQuerySync(e,t.selectFrom(`agent_database_leases`).select(`path`).distinct()).rows.map(e=>e.path)}function findAgentDatabasePathLease(e,t){return readAgentDatabaseLeases(e).find(e=>mayShareAgentDatabaseFile(e.path,t))}function clearAgentDatabaseLeaseVerifications(e,t){for(const n of/* @__PURE__ */ new Set([t,...agentDatabaseLeasePaths(e)]))if(mayShareAgentDatabaseFile(n,t)){invalidateOpenClawAgentDatabaseValidation(n);revokeSqliteDatabaseAdmissionsForPath(n)}} //!src/state/openclaw-agent-db-close.ts function createAgentDatabaseHandleCloser(e){return function closeCachedOpenClawAgentDatabase(t){try{var n=_usingCtx();const r=t.closeTiming??{startedAt:performance.now()};delete t.closeTiming;const i=e.leases.get(t.path);const a=!t.db.isOpen;const o=t.walMaintenance.health?.state===`error`;const s=isPostgresSqlConnection(t.db);const c=sqlPublicationAnchor(t.db);assertNodeSqliteDisposalAllowed(c);const l=n.u(!a&&!s?prepareSqliteDatabaseCleanClose(c):void 0);let u;let d;try{if(!a&&!s)setSqliteBusyTimeout(c,0);disposeNodeSqliteDependents(c);const n=performance.now();t.walMaintenance.close({checkpointMode:`TRUNCATE`});r.checkpointMs=performance.now()-n;const i=!e.failures.has(t.path)&&!o&&t.walMaintenance.health?.state!==`error`;const f=!a&&i&&isOpenClawAgentDatabasePathCurrent(t);r.checkpoint={alreadyClosed:a,pathCurrent:f,state:t.walMaintenance.health?.state,logFrames:t.walMaintenance.health?.logFrames,checkpointedFrames:t.walMaintenance.health?.checkpointedFrames};d=i&&(a||f);const p=performance.now();if(t.db.isOpen)t.db.close();if(s&&c.isOpen)c.close();r.nativeCloseMs=performance.now()-p;if(f&&!s){const{canonicalPath:e}=readOpenClawAgentDatabaseIdentity(t);const n=statSync(`${e}-wal`,{throwIfNoEntry:false})?.size??0;r.checkpoint.walBytes=n;if(l&&n===0)u={path:t.path,publishSeal:l.publish}}}catch(e){if(i){invalidateOpenClawAgentDatabaseValidation(t.path);revokeSqliteDatabaseAdmissionsForPath(t.path)}throw e}if(i){releaseOpenClawAgentDatabaseLease(i.leaseId,{env:i.env,initializationAgentPaths:[t.path]},u??(d?s?`postgres-closed`:`uncheckpointed`:void 0),r);e.leases.delete(t.path)}releaseAgentDeletionDatabaseCleanup(t);releaseAgentCreationClaimHandle(t);e.idleTimers.get(t.db)?.[Symbol.dispose]();e.idleTimers.delete(t.db)}catch(e){n.e=e}finally{n.d()}}} //!src/state/openclaw-agent-db-lifecycle.ts const agentDbLog=createSubsystemLogger(`state/agent-db`);const cache=resolveGlobalSingleton(Symbol.for(`openclaw.agentDatabaseLifecycle`),()=>({...agentDatabaseBorrowers,leases:/* @__PURE__ */ new Map,terminal:createSqliteTerminalOpenLatch({closeByPath:e=>closeOpenClawAgentDatabaseByPath(e)}),unregisterExitClose:null,pending:/* @__PURE__ */ new Map,activePending:/* @__PURE__ */ new Set,retainedCloses:/* @__PURE__ */ new Set}));agentDatabaseBorrowers.refreshIdleTimer=refreshAgentDatabaseIdleTimer;registerAgentDatabaseResourceReleaseHandler(e=>{if(!getGatewayShutdownCleanupSignal().aborted)return;for(const t of cache.databases.values())if(matchesAgentDatabaseClose({path:t.path},e))cache.idleTimers.get(t.db)?.refresh()});const closeCachedOpenClawAgentDatabase=createAgentDatabaseHandleCloser(cache);function logResourceCloseFailure(e,t){agentDbLog.warn(`Agent database resource close failed`,{path:e,error:t})}function unregisterUnusedAgentDatabaseExitClose(){if(cache.databases.size===0&&cache.retainedCloses.size===0){cache.unregisterExitClose?.();cache.unregisterExitClose=null}}function revokePendingAgentDatabaseOpen(e,t){for(const n of cache.activePending)if(n.path===e&&(t===void 0||n.agentId===t))n.controller.abort(/* @__PURE__ */ new Error(`Agent database open was revoked: ${e}`))}function refreshAgentDatabaseIdleTimer(e){const t=cache.idleTimers.get(e.db);if(t){t.refresh();return}const n=getGatewayShutdownCleanupSignal();const closeIdle=()=>{if(cache.databases.get(e.path)!==e){cache.idleTimers.get(e.db)?.[Symbol.dispose]();cache.idleTimers.delete(e.db);return}if(getOpenClawDatabaseMaintenanceResourceScope(e.db))return;if(e.db.isOpen&&cache.borrowers.get(e.db)?.size)return;if(e.db.isOpen&&e.db.isTransaction){r.refresh();return}if(n.aborted&&hasOpenClawAgentDatabaseAsyncResources({path:e.path}))return;try{closeCachedOpenClawAgentDatabase(e);cache.databases.delete(e.path);cache.failures.delete(e.path);unregisterUnusedAgentDatabaseExitClose()}catch(t){logResourceCloseFailure(e.path,t);r.refresh()}};const refresh=()=>{if(n.aborted)runInDetachedAsyncContext(()=>queueMicrotask(closeIdle));else r.refresh()};const r=runInDetachedAsyncContext(()=>setTimeout(closeIdle,resolveAgentDatabaseIdleHandleTtlMs()));const i=addAbortListener(n,refresh);r.unref();cache.idleTimers.set(e.db,{refresh,[Symbol.dispose](){clearTimeout(r);i[Symbol.dispose]()}})}function closeOpenClawAgentDatabaseByPath(e,t){const n=path.resolve(e);revokeAgentDatabaseResources({path:n,agentId:t},logResourceCloseFailure);revokePendingAgentDatabaseOpen(n,t);for(const e of cache.retainedCloses)if(e.path===n&&(t===void 0||e.agentId===t))e.close();const r=cache.databases.get(n);if(!r||t!==void 0&&r.agentId!==t)return false;closeCachedOpenClawAgentDatabase(r);cache.databases.delete(n);cache.failures.delete(n);unregisterUnusedAgentDatabaseExitClose();return true} //!src/state/openclaw-agent-execution-owner.ts const log=createSubsystemLogger(`state/agent-db`); //!src/state/openclaw-agent-write-admission.ts const reservationDiagnostics=channel(`openclaw.agent-database.reservation`); //!src/state/openclaw-agent-execution.ts var openclaw_agent_execution_exports=/* @__PURE__ */ __exportAll({getPendingOpenClawAgentDatabasePreparation:()=>getPendingOpenClawAgentDatabasePreparation});const executionState=resolveGlobalSingleton(Symbol.for(`openclaw.agentDatabaseExecutionOwners`),()=>({owners:/* @__PURE__ */ new Map,idle:/* @__PURE__ */ new Set}));const executions=executionState.owners;function getPendingOpenClawAgentDatabasePreparation(e,t=`write`){const n=executions.get(e)?.getPendingPreparation();return n&&t===`read`&&isAgentDatabaseStartupReadReady(e)?void 0:n}export{getGatewayShutdownCleanupSignal as n,openclaw_agent_execution_exports as t};