UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1 lines • 30 kB
import{n as e}from"./openclaw-state-read-rolldown-runtime-C7TU3oOp.mjs";import{Cn as t,gt as n,t as r,wn as i,xt as a}from"./openclaw-state-read-subsystem-Dwoo5bcz.mjs";import{Bt as o,Nt as s,U as c,Vt as l,at as u,it as d,jt as f,tt as p}from"./openclaw-state-read-sqlite-database-admission-CrkztOzk.mjs";import{Pt as m,a as h,r as g}from"./openclaw-state-read-src-RL5xtYG2.mjs";import{O as _,c as v,u as y}from"./openclaw-state-read-openclaw-state-db-cache-DyomEqgV.mjs";import{C as b,f as x}from"./openclaw-state-read-sqlite-post-commit-CsXPYVOo.mjs";import{t as S}from"./openclaw-state-read-deferred-B75K7ut7.mjs";import{C}from"./openclaw-state-read-sqlite-private-snapshot-fork-B2lPOtW3.mjs";import{A as w,B as T,F as E,H as D,I as O,N as k,O as A,S as j,Y as M,Z as N,a as P,et as F,j as I,w as L}from"./openclaw-state-read-sqlite-readonly-worker-D6FdUovN.mjs";import{s as R}from"./openclaw-state-read-openclaw-state-db.paths-7XLpcdiq.mjs";import{c as z,f as B,p as V,u as H}from"./openclaw-state-read-runtime-worker-generation-DIZIqsAo.mjs";import{l as U}from"./openclaw-state-read-gateway-lock-payload-BrJys_8Q.mjs";import{m as W,u as ee}from"./openclaw-state-read-sqlite-wal-write-admission-BvF6tHCz.mjs";import"./openclaw-state-read-sqlite-worker-operation-settlement-DOkqmUGd.mjs";import{a as G}from"./openclaw-state-read-runtime-binary-BjmkF9EB.mjs";import{r as K}from"./openclaw-state-read-runtime-worker-url-C8NPtAdy.mjs";import{f as te}from"./openclaw-state-read-worker-cpu-CbvwBMyE.mjs";import{t as ne}from"./openclaw-state-read-errors-D4PLrhBz.mjs";import{n as re}from"./openclaw-state-read-error-graph-internal-Cj78mC_c.mjs";import{i as ie,n as ae,u as q}from"./openclaw-state-read-sqlite-worker-operation-admission-DdAi_0af.mjs";import{n as oe}from"./openclaw-state-read-sqlite-handle-lifecycle-uqyIC6ii.mjs";import{n as se}from"./openclaw-state-read-agent-id-DmscQLD6.mjs";import"./openclaw-state-read-session-key-H2_GWFw8.mjs";import{o as ce,s as le}from"./openclaw-state-read-openclaw-state-db-readonly-Bv32Owin.mjs";import{A as ue,E as de,M as fe,T as pe,j as me}from"./openclaw-state-read-openclaw-agent-db-engine-CmBIEYKS.mjs";import{a as he,i as ge}from"./openclaw-state-read-openclaw-agent-db-identity-EXR5NQy4.mjs";import{s as _e,t as ve}from"./openclaw-state-read-openclaw-agent-db-registry-listing-BSp1z3ZT.mjs";import{c as ye,f as be,l as J,o as Y,r as X}from"./openclaw-state-read-openclaw-agent-db-validation-cache-CA862sC1.mjs";import"./openclaw-state-read-backoff-B79CSFak.mjs";import{_ as xe,n as Z,x as Se}from"./openclaw-state-read-openclaw-agent-write-admission-Cuy_tnWd.mjs";import{a as Ce,c as Q,i as we,t as Te}from"./openclaw-state-read-sqlite-worker-store-IQvL052n.mjs";import{t as Ee}from"./openclaw-state-read-openclaw-state-worker-store-Co6iNMIO.mjs";import De from"node:path";import{MessagePort as Oe}from"node:worker_threads";import{readFile as ke,stat as $}from"node:fs/promises";import{randomUUID as Ae}from"node:crypto";import{AsyncLocalStorage as je}from"node:async_hooks";import{isDeepStrictEqual as Me}from"node:util";import{addAbortListener as Ne}from"node:events";const Pe=t(Symbol.for(`openclaw.sessionWorkAdmissionClosures`),()=>/* @__PURE__ */ new Set);function agentWorkAdmissionIdentity(e){return{agentId:se(e.agentId),statePath:l(e.statePath??R(e.env??process.env)).canonicalPath}}function assertAgentSessionWriteAdmission(e,t=e.agentId){let n=I(e);if(n){n.assertCurrentHost();return}if(Pe.size===0)return;let r=agentWorkAdmissionIdentity({agentId:t,env:e.env}),i=[...Pe].find(e=>e.identities.length===0&&matchesAgentWorkAdmission(e.agent,r));if(i)throw i.reason}function matchesAgentWorkAdmission(e,t){return!!(e&&t&&e.agentId===t.agentId&&e.statePath===t.statePath)}function captureAgentDeletionCleanupAdmission(e,t,n){let r=I(e);if(!r?.worker)return;let i=r.worker;return r.assertCurrentHost(),{guard:i.guard,assertCurrent:r.assertCurrentHost,authorize(e){let o=e.facts;if(e.stage!==`prepare`||!a(o)||o.kind!==`agent-deletion-current`&&o.kind!==`agent-deletion-lease`)return!1;if(n(),r.assertCurrentHost(),!Me(o.guard,i.guard))throw Error(`Agent deletion request differs from its live cleanup owner`);if(o.kind===`agent-deletion-lease`){if(!(o.port instanceof Oe))throw Error(`Agent deletion lost its lease admission handoff port`);let e=i.lease.createAdmission(t);try{o.port.postMessage(e.admission.port,[e.admission.port]),te(`admission`,`to_worker`),t.settled.then(()=>e.admission.finish())}catch(t){throw e.admission.finish(),t}finally{o.port.close()}}return!0}}}async function cleanupRetiredAgentDatabaseLease(e){e.assertOwned(),await e.stopped,e.assertOwned();let t=e.readOpenRefused?.()===!0;if(e.closed?.())return;let n=await o(e.lease.sharedStatePath);if(n.key!==e.lease.sharedStateIdentity)throw Error(`Retired agent cleanup cannot adopt a replacement shared database`);e.assertOwned(),t||J(e.lease.path);let r={environment:e.context.environment,existingSchemaPath:e.context.existingSchemaPath,stateIntegrity:e.context.stateIntegrity},i=await Ee(e.lease.sharedStatePath,r,()=>e.assertOwned(),n,e.context.maintenanceScope).catch(t=>{throw t instanceof Error&&(t.message+=` (leaseId=${e.lease.leaseId}, path=${e.lease.path})`,t.stack=`${t.name}: ${t.message}\n${t.stack??``}`),t});if(!i)throw Error(`Retired agent cleanup lost its original shared database`);let a=[];try{await Q(i,n=>n.execute({type:`agentDatabases.releaseExitedLease`,input:{...e.lease,outcome:t?`refused-before-open`:`unknown`}}),r,()=>e.assertOwned(),()=>({nativeLocations:[e.lease.sharedStatePath],admission:ie((t,n)=>{e.assertOwned(),t.stage===`prepare`&&t.facts===`agent-integrity-invalidated`&&J(e.lease.path),n()})}))}catch(e){a.push(e)}try{await i.close()}catch(e){a.push(e)}b(a,`Retired agent lease cleanup and Worker close failed`)}function readAgentDatabaseClosedReceipt(e,t,n){if(e&&t&&n&&e.incarnation===t.incarnation&&e.identity.key===`file:${t.physicalIdentity}`&&e.identity.canonicalPath===t.nativeLocation)return{receipt:e,identity:t,lease:n}}async function publishAgentDatabaseCloseCheckpoint(e,t,n){let r=t?.receipt.checkpoint;if(!t||!r)return;let{receipt:i,identity:a,lease:o}=t;try{n();let[t,s,c]=await Promise.all([$(e,{bigint:!0}),$(a.nativeLocation,{bigint:!0}),$(o.sharedStatePath,{bigint:!0})]);f(t,{key:i.identity.key}),f(s,{key:i.identity.key}),f(c,{key:o.sharedStateIdentity}),n(),C(e,r)}catch{}}async function closeAgentDatabaseNativeGeneration(e){let{pathname:t,context:n,processOwner:r,opening:i,readOpenedStore:a,assertCleanupOwned:o}=e,s=[];try{(await r?.prepareAccess())?.()}catch(e){r?.signal.aborted&&s.push(e)}let c=!1;if(i)try{await i.then(async e=>{await e?.close(),c=e!==void 0},()=>a()?.close()??Te(t))}catch(e){s.push(e)}let l=e.readRetirement();if(s.length===0&&!r?.signal.aborted&&l.stopped&&l.lease)try{await cleanupRetiredAgentDatabaseLease({context:n,stopped:l.stopped,assertOwned:o,lease:l.lease,readOpenRefused:l.readOpenRefused,closed:()=>c?l.closed:void 0})}catch(e){s.push(e)}r?.signal.aborted&&l.stopped?await finishAgentDatabaseRetirementAfterOwnershipLoss(t,n.admission.databasePath,l.stopped,s):(b(s,`Agent native close and lease cleanup failed`),await publishAgentDatabaseCloseCheckpoint(t,l.closed,o))}async function finishAgentDatabaseRetirementAfterOwnershipLoss(e,t,n,a){await n,J(e);let o=W(t),s=await ke(o,`utf8`).then(e=>{let t=U(e);return t?{pid:t.pid,role:t.role}:`unrecognized lock contents`},e=>m(e,`ENOENT`)?`lock removed`:`lock unreadable`);r(`state/agent-db`).warn(`Agent database native handle retired after state ownership loss; lease cleanup deferred to recovery`,{path:e,lockPath:o,replacement:s,errors:a.map(e=>i(e))})}function createSharedAgentDatabasePreparation(e){let t=/* @__PURE__ */ new Set,n,r=/* @__PURE__ */ new Set,i=[];return{source:{assertCurrent(){e();let t;for(let e of r)try{e.assertCurrent();return}catch(e){t??={error:e}}throw t?t.error:new E(`Agent database preparation has no current caller`)},onRegistryChange(e){i.push(e);for(let t of r)t.notify(e)},createAdmission:e=>()=>({nativeLocations:e.nativeLocations,admission:ie((t,n)=>{if(e.authorize(t),!n())throw Error(`Agent database shared opening admission expired`)},e.attachment)})},retain(){let e=S();return t.add(e.promise),()=>{t.delete(e.promise),e.resolve()}},beginNativeOpen(){let e=S();return n=e.promise,()=>{n=void 0,e.resolve()}},getPendingNativeOpen:()=>n,getPendingPreparation:()=>{if(t.size!==0)return(async()=>{for(;t.size>0;)await Promise.all(t)})()},follow(e,t){let n=je.snapshot(),a,notify=t=>{try{n(()=>e.onRegistryChange?.(t))}catch(e){a={error:e}}};for(let e of i)notify(e);let o={notify,assertCurrent:()=>n(t)};return r.add(o),{assertPublished(){if(a)throw a.error},release(){r.delete(o)}}}}}function createAgentDatabaseNativeGeneration(e,t,n,r,i,o,c,u,d,f,m,h,_=!1,y){let b=je.snapshot(),x=_?P():void 0,S=x?new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)):void 0,cancelStartup=()=>{S&&(Atomics.store(S,0,1),Atomics.notify(S,0))},C=x&&Ne(x,cancelStartup),w={leaseId:Ae(),agentId:e,databasePath:t,stateDatabasePath:n.admission.databasePath,environment:n.environment,...u?{expectedIdentity:u}:{},...m?{creatingIdentity:m}:{},...h?{creationClaim:h}:{}},T=new q,D,k,A,j,M,N,F,I,L,R,z,B=!1,V,H=createSharedAgentDatabasePreparation(()=>assertCurrent()),onNativeLost=e=>{V??=e,T.retire(),z&&J(t),B&&f(e)},assertCurrent=()=>{if(o(),k&&!we(k))throw V??new p(`Database unavailable. Check history, then retry.`,`unavailable`);if(!T.open)throw Error(`Agent native generation is retiring`)},admission=(r,o,c)=>f=>{let p=o?X({agentId:e,path:t}):void 0;o&&(o.nativeSettlement=f.settled);let h=de(e,{env:n.environment}),g=[t,...F?[F.nativeLocation]:[],n.admission.databasePath,n.admission.identity.canonicalPath],assertSourceCurrent=e=>{r.assertCurrent(),assertCurrent(),c?.(e)},_=captureAgentDeletionCleanupAdmission({agentId:e,path:t,env:n.environment},f,assertSourceCurrent),observeNative=e=>{let n=e.facts;if(e.stage===`prepare`&&a(n)&&n.kind===`agent-registration-committed`){let e=n.registration;if(!o||!z||!a(e))throw Error(`Agent registration commit differs from its admitted native owner`);o.recordCommitted({agentId:w.agentId,agentPath:t,stateDatabasePath:z.sharedStatePath,stateDatabaseIdentity:z.sharedStateIdentity})}},authorizeNative=r=>{let i=r.facts;if(!_?.authorize(r)){if(assertCurrent(),_?.assertCurrent(),r.stage===`prepare`&&a(i)&&i.kind===`agent-startup-fts`){if(assertSourceCurrent(),!h||!z||i.message!==void 0&&typeof i.message!=`string`)throw Error(`FTS repair requires live Gateway startup admission`);me([u?.physicalIdentity??t,u?.birthtime].join(`:`),n.admission.databasePath,i.message)}else if((!F||m)&&c?.(),r.stage===`prepare`&&a(i)&&i.kind===`agent-registration-start`){if(assertSourceCurrent(),!o||!z)throw Error(`Agent registration start differs from its admitted native owner`);o.begin()}else if(r.stage===`prepare`&&a(i)&&i.kind===`shared-owner`){if(!(i.validationPort instanceof Oe))throw Error(`Agent worker lost its validation handoff port`);try{assertSourceCurrent(),v(n.admission);let r=i.lease;if(!a(r)||r.ownerStartTime!==null&&typeof r.ownerStartTime!=`number`)throw Error(`Agent worker lease differs from its captured native owner`);z={leaseId:w.leaseId,agentId:w.agentId,path:t,ownerPid:process.pid,ownerStartTime:r.ownerStartTime,sharedStatePath:n.admission.databasePath,sharedStateIdentity:n.admission.identity.key},p=X({agentId:e,path:t});let o={integrityRevoked:ye(t),validation:Y({agentId:e,path:t})};i.validationPort.postMessage(o,[]),te(`admission`,`to_worker`)}finally{i.validationPort.close()}}else if(r.stage===`prepare`&&a(i)&&(i.kind===`agent-open-resume`||i.kind===`agent-validation-start`)){if(assertSourceCurrent(),!z)throw Error(`Agent open notice differs from its captured native lease`);i.kind===`agent-validation-start`&&(p=X({agentId:e,path:t}))}else if(r.stage!==`open`){let e=a(i)?i.identity:void 0;if(!a(e)||e.kind!==`file`||typeof e.physicalIdentity!=`string`||typeof e.birthtime!=`string`||typeof e.incarnation!=`string`||typeof e.nativeLocation!=`string`||F&&!Me(e,F))throw Error(`Agent database operation belongs to another native owner`);let n=F??Object.freeze({kind:`file`,physicalIdentity:e.physicalIdentity,birthtime:e.birthtime,incarnation:e.incarnation,nativeLocation:e.nativeLocation});if(u&&(n.physicalIdentity!==u.physicalIdentity||u.birthtime!==void 0&&n.birthtime!==u.birthtime))throw Error(`Agent database operation differs from its expected physical file`);return F||s(t,`file:${n.physicalIdentity}`,n.birthtime),d({kind:`file`,physicalIdentity:n.physicalIdentity,birthtime:n.birthtime,nativeLocation:n.nativeLocation}),h?.(a(i)?i.agentDeletionJournalPresent:void 0),F??=n,F}}},y=r.createAdmission({attachment:{kind:`agent-execution`,startupJournal:h!==void 0,...S?{startupCancellation:S}:{},..._?{deletion:_.guard}:{}},nativeLocations:g,assertCurrent,authorize(n){if(n.stage===`prepare`&&a(n.facts)&&n.facts.kind===`agent-registration-committed`)return;let r=authorizeNative(n);n.stage===`open`&&o&&(assertSourceCurrent(),!F&&!u&&l(t).key.startsWith(`path:`)&&(!z&&Y({agentId:e,path:t})&&J(t),o.begin())),n.stage===`prepare`&&r&&p&&a(n.facts)&&n.facts.validation!==void 0&&(assertSourceCurrent(r),p(r.physicalIdentity,n.facts.validation),p=void 0),assertSourceCurrent(r)}})(f);return B&&F&&!m&&!o&&ae(y.admission,{logical:i,native:T.state,physicalIdentity:F.physicalIdentity,incarnation:F.incarnation,...F.birthtime===void 0?{}:{birthtime:F.birthtime}}),y.admission.observeRequests(observeNative),y},captureOpeningAdmission=(...e)=>t=>{let n=admission(...e)(t);return M={admission:n.admission,settled:t.settled},n},captureRegistration=r=>{let i=F??u;return ve({agentId:e,agentPath:t,capturedIdentity:i?{key:`file:${i.physicalIdentity}`,canonicalPath:i.nativeLocation,birthtime:i.birthtime}:m??y,admission:n.admission,assertPublicationCurrent:n.assertPublicationCurrent,onRegistryChange:r.onRegistryChange})},open=(r,i,a=!1,o)=>{if(assertCurrent(),r.assertCurrent(),i?.(),!D){let s=H.retain(),c=H.beginNativeOpen();D=(async()=>{let s=u!==void 0;be(e,t,u);let l=a||s?captureRegistration(s?H.source:r):void 0,openStore=async()=>{k=await Ce({moduleUrl:K(G.agentDatabaseExecution),databasePath:t,input:w,existingOnly:s||!a},{startupPreparation:_,stateContext:n,stateDatabasePath:n.admission.databasePath,assertCurrent:s?assertCurrent:()=>{assertCurrent(),r.assertCurrent(),i?.(),o?.throwIfAborted()},signal:s?void 0:o,createAdmission:captureOpeningAdmission(s?H.source:r,l,s?void 0:i),onNativeStopped:(e,t,n)=>{I=e,L=t,R=n},onNativeLost});let e=k;return c(),e&&s&&!F&&await b(()=>Q(e,e=>e.execute({type:`database.prepareWrite`,input:void 0}),void 0,assertCurrent,captureOpeningAdmission(H.source,l))),k},d=l?await _e(l,openStore):await openStore();if(d)try{return assertCurrent(),B||=F!==void 0,d}catch(e){try{await d.close()}catch(t){throw AggregateError([e,t],`Agent open and cleanup failed`,{cause:t})}throw e instanceof E&&(j=e),e}})().catch(async e=>{if(A=e instanceof O||j!==void 0&&e===j?`open-refused`:`native`,M){let{admission:t,settled:n}=M,r=await n;t.failure!==void 0&&t.failureSource!==`protocol`&&e===t.failure&&r.kind!==`unknown`&&!t.committed&&t.cleanupFailures.length===0&&(A=`open-refused`)}throw e}).finally(()=>{M=void 0,j=void 0,c(),s()})}let s=D;return s.then(e=>(!e&&D===s&&(D=void 0),!e&&a&&!u?open(r,i,!0,o):e))};async function run(n,r,i,a=!1,o){let assertOperationCurrent=()=>{assertCurrent(),n.assertCurrent(),i?.(),o?.throwIfAborted()},s=B?void 0:H.retain(),c=s?H.follow(n,assertOperationCurrent):void 0,l;try{let r=B?k:await g(open(n,i,a,o),o,e=>e.reason);if(c?.assertPublished(),assertOperationCurrent(),!r){if(a&&u)throw Error(`Captured agent database file disappeared before writable preparation`);return}let s=a?Y({agentId:e,path:t})?.schema:void 0;if(!F||a&&B&&(!s||Atomics.load(new Int32Array(s.valid),0)!==1)){let e=captureRegistration(n);await _e(e,async()=>{await Q(r,e=>e.execute({type:`database.prepareWrite`,input:void 0},{signal:o}),void 0,assertOperationCurrent,admission(n,e,i)),assertCurrent(),n.assertCurrent()}),B=!0}l=r}finally{c?.release(),s?.()}return Q(l,r,void 0,assertOperationCurrent,admission(n,void 0,i))}return{failure:()=>A??(k&&!we(k)?B?`lost`:`native`:void 0),isPrepared(){return assertCurrent(),B},getPendingNativeOpen:H.getPendingNativeOpen,getPendingPreparation:H.getPendingPreparation,captureClaim(e){assertCurrent();let t=F;if(!t)throw Error(`Agent database generation has not been admitted`);return{identity:t.physicalIdentity,incarnation:t.incarnation,assertCurrent(){e(),assertCurrent()}}},run,close(){return T.retire(),cancelStartup(),C?.[Symbol.dispose](),N??=closeAgentDatabaseNativeGeneration({pathname:t,context:n,processOwner:r,opening:D,readOpenedStore:()=>k,assertCleanupOwned:c,readRetirement:()=>({stopped:I,lease:z,readOpenRefused:R,closed:readAgentDatabaseClosedReceipt(L?.(),F,z)})}).catch(e=>{throw N=void 0,e}),N}}}function toAgentExecutionConstraints(e){return e.key.startsWith(`file:`)?{expectedIdentity:{kind:`file`,physicalIdentity:e.key.slice(5),nativeLocation:e.canonicalPath,birthtime:e.birthtime}}:{expectedCreationIdentity:e}}function assertAgentDatabaseExecutionSharedState(e,t){let n=process.platform===`win32`?_(e.env??process.env):e.env;if(t!==ce(R(n)).admission.identity.key)throw Error(`Agent database execution belongs to another shared-state database; drain its existing resources before changing the state directory.`)}function supportsAgentDatabaseExecutionScope(e){let t=I(e);return(H()||z()?.ownsSchemaMaintenance!==!0&&!xe())&&(!t||t.worker!==void 0)}function supportsOpenClawAgentDatabaseExecution(e){return!M(F(e),e)&&supportsAgentDatabaseExecutionScope(e)}function captureNativeAgentDatabaseExecutionIdentity(e,t,n,r){r();let i=he(e),assertCurrent=()=>{if(r(),e.agentId!==t||Z.databases.get(e.path)!==e||he(e)!==i||i.canonicalPath!==n||!ge(e))throw Error(`Agent execution cannot adopt a different native database owner`)};return assertCurrent(),{fileIdentity:{kind:`file`,physicalIdentity:i.identity,birthtime:i.birthtime,nativeLocation:i.canonicalPath},assertCurrent}}function assertAgentDatabaseExecutionCreationIdentity(e,t,n,r){let i=t.key.startsWith(`path:`);if(r||i&&(Z.databases.has(e)||Z.pending.has(e))||!i&&(!t.key.startsWith(`file:`)||typeof t.birthtime!=`string`)||n?.key!==t.key||n.canonicalPath!==t.canonicalPath||n.birthtime!==t.birthtime)throw Error(`Agent creation no longer owns its originally observed target`)}function assertBorrowedAgentDatabaseFileIdentity({borrowedPath:e,identity:t,creatingTarget:n,fileIdentity:r,expectedIdentity:i,nativeIdentity:a,observedIdentity:o}){if(!r){let r=o??l(e);if(r.canonicalPath!==t.canonicalPath||n?.key.startsWith(`file:`)&&(r.key!==n.key||r.birthtime!==n.birthtime))throw Error(`Agent database borrower changed its originally observed target`)}if(r&&i&&(r.physicalIdentity!==i.physicalIdentity||r.birthtime!==void 0&&i.birthtime!==void 0&&r.birthtime!==i.birthtime))throw Error(`Agent database borrower belongs to another physical file`);let s=r??i,c=r?.birthtime??i?.birthtime;if(s&&a&&(a.physicalIdentity!==s.physicalIdentity||c!==void 0&&a.birthtime!==c))throw Error(`Agent database borrower belongs to another physical file`)}function assertAgentDatabaseBorrowTarget(e,t,n){if(t){if(!n)s(e,`file:`+t.physicalIdentity,t.birthtime);else if(n.key!==`file:`+t.physicalIdentity||t.birthtime!==void 0&&n.birthtime!==t.birthtime)throw Error(`Agent database borrower belongs to another physical file`)}}function createAgentDatabaseAcceptedWork(){let e=/* @__PURE__ */ new Map,t=/* @__PURE__ */ new Set;return{pending:e,onTerminal:e=>(t.add(e),()=>t.delete(e)),reportTerminal:n=>{if(t.size===0)return;let r=n instanceof Error?n:Error(ne(n)),i=[...t];t.clear(),Promise.resolve().then(async()=>{await Promise.allSettled(e.keys()),x(i,r)})},settleBorrower:t=>Promise.allSettled([...e].flatMap(([e,n])=>n.borrower===t?[e]:[])),cancelReadAdmissions:t=>{for(let n of e.values())(t===void 0||n.borrower===t)&&n.queuedReadAbort?.abort(new E(`Agent database read admission is closed`))},closeAccepted:async t=>{let n=[...e].flatMap(([e,t])=>t.queuedReadAbort?[e]:[]),r=t();await Promise.allSettled([r,...n]),await r}}}const Fe=r(`state/agent-db`);function createAgentDatabaseExecution(e,t,r){let i=r.owners,{agentId:a,pathname:o,identity:l,initialIdentity:f,expectedCreationIdentity:p}=t,m=le({env:e.env}),_={agentId:a,path:o,env:m.environment},v=I(_),b=v?.ownsDatabase?v:void 0,x=D(e),C=/* @__PURE__ */ new Map,T=pe(a,{env:m.environment}),O=new q,A=0,M=createAgentDatabaseAcceptedWork(),N=p,P=0,F,R,z,H,U,W,G,acceptFileIdentity=e=>{if(R&&(R.physicalIdentity!==e.physicalIdentity||R.birthtime!==e.birthtime))throw Error(`Agent database execution belongs to another physical file`);R??=Object.freeze({...e})},clearIdleTimer=()=>{clearTimeout(G),G=void 0},reportCleanupFailure=e=>{try{Fe.warn(`Agent database cleanup failed: ${ne(e)}`)}catch{}},finishRetirement=()=>{O.retire(),i.get(o)===K&&(unregisterAgent(),W?.())},assertCurrent=()=>{if(!O.open||i.get(o)!==K||!supportsAgentDatabaseExecutionScope(_))throw new E(`Agent database execution admission is closed`);w(K,_),m.admission.assertCurrent(),T(),x?.assertCurrent()},closeNative=e=>{if(e&&F!==e)return Promise.resolve();if(clearIdleTimer(),z)return z;let t=F;if(!t)return Promise.resolve();let n=t.close().then(()=>{F===t&&(F=void 0,H=void 0,r.idle.delete(K))},e=>{throw re(e),H={error:e},e}).finally(()=>{z===n&&(z=void 0)});return z=n,n};function createGeneration(e,t,n){let r=createAgentDatabaseNativeGeneration(a,l.canonicalPath,m,e,O.state,assertCurrent,()=>{if(i.get(o)!==K||F!==r||!z)throw Error(`Agent cleanup no longer owns its original execution reference`)},t??R??toAgentExecutionConstraints(l).expectedIdentity,acceptFileIdentity,M.reportTerminal,R?void 0:N??n,x?.witness,fe(a,{env:m.environment},()=>closeNative(r)),l);return r}async function run(e,t,n,r,i=!1,s=!1,l,f,p){let _=Z.pending.get(o);if(_){if(l&&!R)throw Error(`Agent creation cannot adopt another pending opener`);if(_.agentId!==a)throw Error(`Agent database ${o} is opening for ${_.agentId}`);await _.promise,_.controller.signal.throwIfAborted(),n()}let v=F?.getPendingNativeOpen();if(v&&(await g(v,f,e=>e.reason),n()),z&&(await z,n()),(H||F?.failure())&&(await closeNative(),assertCurrent(),e.assertCurrent(),n(),f?.throwIfAborted()),!F){let t=await ee(m.admission);assertCurrent(),e.assertCurrent(),n(),f?.throwIfAborted(),F??=createGeneration(t,r,l)}let y=F,b=!1;try{let r=await y.run(e,e=>(b=!0,t(e)),n,s,f);return F===y&&!z&&(y.failure()||!R&&!y.getPendingPreparation())&&await closeNative(y).catch(reportCleanupFailure),r}catch(a){let o=y.failure(),m=!b&&c(a);if(F===y&&(o||i))try{o===`native`&&!m&&!z?(M.reportTerminal(a),await K.close()):await closeNative(y)}catch(e){reportCleanupFailure(e);let t=a instanceof Error?a:Error(String(a)),n=Object.assign(Error(t.message,{cause:AggregateError([a,e],`Agent operation and cleanup failed`,{cause:a})}),{name:t.name});throw d(a,`outcome-unknown`)?u(n,a):n}if(m){let o=p??performance.now()+2e3;p===void 0&&Fe.warn(`Agent database execution admission delayed by SQLite lock contention; retrying before execution.`);let c=o-performance.now();if(c>0){if(await h(Math.min(25,c),f),assertCurrent(),e.assertCurrent(),n(),performance.now()>=o)throw a;return run(e,t,n,r,i,s,l,f,o)}}throw a}}let releaseBorrower=async e=>{if(e&&--P===0&&!R&&!z&&!H&&(F&&await closeNative(F).catch(reportCleanupFailure),!P&&!F&&!z&&!H&&(N=void 0)),--A,A!==0||!O.open||H||b)return;let t=Se(),canRetain=()=>F&&R&&!z&&!t.aborted;try{for(let e of r.idle){if(!canRetain()||r.idle.size<4)break;if(A!==0||!O.open||r.idle.has(K))return;await e.closeIdle()}}catch(e){reportCleanupFailure(e)}if(A===0&&O.open&&!r.idle.has(K)){if(canRetain()&&r.idle.size<4){r.idle.add(K);let e=n(()=>setTimeout(()=>{G===e&&r.idle.has(K)&&K.closeIdle().catch(reportCleanupFailure)},oe()));G=e,e.unref()}else await K.closeIdle().catch(reportCleanupFailure)}},retainBorrower=e=>(assertCurrent(),A+=1,clearIdleTimer(),!z&&!H&&r.idle.delete(K),e&&(N??=e,P+=1),()=>releaseBorrower(e)),K={kind:`file`,agentId:a,get sharedDatabaseKey(){return m.admission.identity.key},get creationIdentity(){return N},getPendingPreparation:()=>F?.getPendingPreparation(),retain:()=>retainBorrower(N),borrow(e,t,n,r,i){let c=I({..._,path:e}),d=t?Object.freeze({...t}):void 0,f=n?Object.freeze({...n}):void 0;assertAgentDatabaseBorrowTarget(e,R,i);let assertReferenceCurrent=t=>{assertCurrent(),assertBorrowedAgentDatabaseFileIdentity({borrowedPath:e,identity:l,creatingTarget:f,fileIdentity:R,expectedIdentity:d,nativeIdentity:t,observedIdentity:i})};if(assertReferenceCurrent(),f&&!N&&!R&&F)throw Error(`Agent creation cannot capture another pending native opener`);retainAlias(e),r!==void 0&&retainAlias(De.resolve(r)),B(C.get(o));let p=retainBorrower(f),assertCreationReference=e=>{if(f&&!R&&!e)throw Error(`Originally observed agent target requires creating admission first`);if(P&&!R&&(!e||!f))throw Error(`Originally observed agent target requires its captured creating reference`)},m=new q,h,g=Symbol(`agent database borrower`),assertBorrowed=()=>{if(!m.open)throw Error(`Agent database execution reference is released`);c?.assertCurrentHost(),assertReferenceCurrent()},captureGenerationClaim=()=>{if(assertBorrowed(),!F)throw Error(`Agent database execution has no admitted generation`);return F.captureClaim(assertBorrowed)},v={agentId:a,path:e,onTerminal:M.onTerminal,get fileIdentity(){return assertBorrowed(),R},async adoptNativeDatabase(e){let t=(async()=>{let t=captureNativeAgentDatabaseExecutionIdentity(e,a,l.canonicalPath,assertBorrowed);F&&!R&&(await closeNative(F),t.assertCurrent()),assertReferenceCurrent(t.fileIdentity),acceptFileIdentity(t.fileIdentity)})();M.pending.set(t,{borrower:g});try{await t}finally{M.pending.delete(t)}},assertCurrent:assertBorrowed,captureGenerationClaim,capturePreparedGenerationClaim(){if(Z.pending.has(o)||z||H||F?.failure()||!F?.isPrepared())assertBorrowed();else return captureGenerationClaim()},async prepare(e,t){assertBorrowed(),assertCreationReference(!0);let n=run(e,async()=>void 0,e=>{assertReferenceCurrent(e),assertCreationReference(!0)},d,!1,!0,f,t);M.pending.set(n,{borrower:g}),n.finally(()=>M.pending.delete(n)).catch(()=>void 0),await n},async runExisting(e,t,n){let r=m.open?F:void 0,i=S();M.pending.set(i.promise,{borrower:g});try{assertBorrowed(),assertCreationReference(!1);let execute=()=>run(e,t,e=>{assertReferenceCurrent(e),assertCreationReference(!1)},d,n?.retireNativeOnFailure);if(n?.withAdmission){let e=new AbortController;return M.pending.set(i.promise,{borrower:g,queuedReadAbort:e}),await n.withAdmission(execute,e.signal)}return await execute()}catch(e){let t=n?.retireNativeOnFailure===!0;if(r&&F===r&&R)try{s(R.nativeLocation,`file:${R.physicalIdentity}`,R.birthtime)}catch{t=!0}if(t&&r)try{await closeNative(r)}catch(t){throw u(AggregateError([e,t],`Agent execution refusal and native cleanup failed`,{cause:e}),e)}throw e}finally{M.pending.delete(i.promise),i.resolve()}},release(){return m.retire(),M.cancelReadAdmissions(g),h??=(async()=>{await M.settleBorrower(g),await p()})()}};return c?.registerClose(()=>v.release()),v},async closeIdle(){Se().aborted&&r.idle.has(K)||(await closeNative(),A===0&&!F&&finishRetirement())},async retireForCleanup(){if(!b){for(;M.pending.size>0;)await Promise.allSettled(M.pending.keys());await K.close()}},close(){return O.close(),M.cancelReadAdmissions(),U??=(async()=>{await closeNative(),finishRetirement()})().catch(e=>{throw U=void 0,O.reopen(),e}),U}},revoke=()=>{O.revoke(),M.cancelReadAdmissions(),clearIdleTimer(),M.reportTerminal(new E(`Agent database execution admission revoked`))},unregisterAgent=()=>{for(let[e,t]of C)i.get(e)===K&&i.delete(e),t();C.clear()},retainAlias=t=>{if(C.has(t))return;let register=()=>L({agentId:a,path:t,revoke,close:()=>M.closeAccepted(()=>K.close()),retireAfterResources:!0},e),n=C.size===0?register():V(register);C.set(t,n),i.set(t,K)};try{return retainAlias(o),retainAlias(l.canonicalPath),k(K,_,()=>j({path:o,agentId:a},async()=>{},b)),W=y({admission:m.admission,close:async()=>{M.reportTerminal(new E(`Agent database state admission closed`)),await M.closeAccepted(()=>K.close())}}),K.borrow(o,f,p,t.requestedPath,t.observedIdentity)}catch(e){throw O.retire(),unregisterAgent(),W?.(),e}}var Ie=/* @__PURE__ */ e({captureOpenClawAgentDatabaseExecution:()=>captureOpenClawAgentDatabaseExecution,getPendingOpenClawAgentDatabasePreparation:()=>getPendingOpenClawAgentDatabasePreparation,supportsOpenClawAgentDatabaseExecution:()=>supportsOpenClawAgentDatabaseExecution});const Le=t(Symbol.for(`openclaw.agentDatabaseExecutionOwners`),()=>({owners:/* @__PURE__ */ new Map,idle:/* @__PURE__ */ new Set})),Re=Le.owners;function getPendingOpenClawAgentDatabasePreparation(e,t=`write`){let n=Re.get(e)?.getPendingPreparation();return n&&t===`read`&&ue(e)?void 0:n}function captureOpenClawAgentDatabaseExecution(e,t={},n=!1){return captureAgentDatabaseExecution(e,t,n)}function captureAgentDatabaseExecution(e,t,n,r){assertAgentSessionWriteAdmission(e),A(e,N);let i=se(e.agentId),a=F(e);if(T(e),!supportsOpenClawAgentDatabaseExecution(e))throw Error(`This agent database scope still requires its existing native owner`);let o=Re.get(a),s=t.expectedCreationIdentity?Object.freeze({...t.expectedCreationIdentity}):void 0;if(!o||s){let c=r??l(a);if(o??=Re.get(c.canonicalPath),s&&assertAgentDatabaseExecutionCreationIdentity(a,s,s.key.startsWith(`path:`)&&o?o.creationIdentity??c:c,t.expectedIdentity),!o)return createAgentDatabaseExecution(e,{agentId:i,pathname:a,identity:c,initialIdentity:t.expectedIdentity,expectedCreationIdentity:s??(n&&c.key.startsWith(`path:`)?c:void 0),requestedPath:t.requestedPath,observedIdentity:r},Le)}if(o.agentId!==i)throw Error(`OpenClaw agent database ${a} is already open for agent ${o.agentId}; requested agent ${i}.`);return assertAgentDatabaseExecutionSharedState(e,o.sharedDatabaseKey),w(o,e),o.borrow(a,t.expectedIdentity,s??(n?o.creationIdentity:void 0),t.requestedPath,r)}export{Ie as t};