UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1 lines • 10.1 kB
import{L as e,R as t,d as n,f as r,in as i,l as a,o,s,t as c,u as l}from"./session-transcript-reconcile.worker-openclaw-state-db-cache-BwXc4xzw.mjs";import{It as u,Mt as d,t as f}from"./session-transcript-reconcile.worker-subsystem-BUNaGCPF.mjs";import{A as p,On as m,U as h,_ as g,i as _,or as v,p as y}from"./session-transcript-reconcile.worker-worker-task-pool-iygKQQAw.mjs";import{$ as b,T as x,c as S,n as C}from"./session-transcript-reconcile.worker-sqlite-snapshot-staging-owner-By9qNyNO.mjs";import{t as w}from"./session-transcript-reconcile.worker-src-N0n_HcqU.mjs";import{a as T,c as E,i as D,n as O,o as k,r as A,s as j,t as M}from"./session-transcript-reconcile.worker.js";import{AsyncLocalStorage as N}from"node:async_hooks";import{isDeepStrictEqual as P}from"node:util";function assertOpenClawStateWorkerActorPath(e){if(s.getKnownOpenClawStateDatabaseIdentity(e.databasePath)?.key!==e.key)throw new b(`Shared-state worker opening path changed`)}function runWithCapturedWorkerContext(e,t){let n=e.maintenanceScope,run=()=>n?n.run(()=>n.track(t())):t();return e.runInCapturedSchemaScope?e.runInCapturedSchemaScope(run):run()}function runWithOpenClawStateWorkerStore(e,t,n,r,i,a){let{admission:o}=t,s=O(e);return j(e,e=>n(a?{execute:(t,n)=>e.execute(t,{...n,signal:n?.signal?AbortSignal.any([a,n.signal]):a})}:e),t,e=>{o.assertCurrent(),assertOpenClawStateWorkerActorPath(s),r?.(e)},i)}function assertOpenClawStateWorkerSchemaContext(n){if(t(n.admission.databasePath),e()!==n.existingSchemaPath)throw Error(`Shared-state worker schema context does not match its caller`)}function captureOpenClawStateWorkerOpeningGuard(e){let t=e.admission,n=t.identity,r=N.bind(()=>t.assertCurrent()),assertCurrent=()=>{if(!r)throw Error(`Shared-state worker opening admission is closed`);r()};return{assertCurrent,createAdmission:()=>{let e=!1;return{nativeLocations:[t.databasePath],databaseIdentity:{databasePath:t.databasePath,key:n.key,birthtime:n.birthtime},admission:_((t,n)=>{if(e||t.stage!==`open`)throw Error(`Shared-state worker open admission requested out of order`);if(assertCurrent(),!n())throw Error(`Shared-state worker open admission expired`);e=!0})}},async run(e){try{return await e()}finally{r=void 0}}}}const F=f(`state/worker`);function createSharedStateWorkerOwner(){let e=p(`sharedStateStore`),t=/* @__PURE__ */ new Set,o=/* @__PURE__ */ new Set,s=/* @__PURE__ */ new Map,c=x(()=>t.size>0||s.size>0||o.size>0,retireIdleWorkers),matches=(e,t)=>t===void 0||e.context.admission.identity.key===t.key,hasActiveActorOperations=e=>[...o].some(t=>e.actor?t.actor===e.actor:t===e),clearIdleRetirement=e=>{e.idleSince=void 0,clearTimeout(e.idleTimer),e.idleTimer=void 0},hasPendingCleanup=e=>e.cleanup?.pending??(!e.context.maintenanceScope&&A(e.context.admission.databasePath)),retire=e=>{clearIdleRetirement(e),t.delete(e);let n=s.get(e);if(n||(n={},s.set(e,n)),c(),n.pending)return n.pending;let r=e.store?e.store.close():e.opening.then(e=>e?.close(),()=>e.cleanup?e.cleanup.close():e.context.maintenanceScope?void 0:M(e.context.admission.databasePath));n.pending=r;let settled=()=>{n.pending=void 0,hasPendingCleanup(e)||s.delete(e),c()};return r.then(settled,settled),r},scheduleIdleRetirement=e=>{if(e.activeOperations!==0||e.idleTimer||e.context.maintenanceScope||!e.store||!t.has(e))return;e.idleSince=performance.now();let n=d(()=>setTimeout(()=>{e.idleTimer===n&&e.activeOperations===0&&t.has(e)&&(e.idleTimer=void 0,retire(e).catch(t=>{F.warn(`Idle shared-state worker retirement failed`,{path:e.context.admission.databasePath,error:t})}))},i));e.idleTimer=n,n.unref?.()},retireAfterFailure=async(e,t,n)=>{try{await retire(e)}catch(e){throw AggregateError([t,e],`Shared-state worker ${n} and cleanup failed`,{cause:e})}throw t},retainOperation=(e,n)=>{let r=[...t].find(t=>t.store===e);if(!r)throw Error(`Shared-state worker operation lost its actor owner`);clearIdleRetirement(r),r.activeOperations+=1,o.add(r),n&&(r.nativeLostListeners.add(n),D(e)||n());let i=!1;return()=>{if(!i){if(i=!0,n&&r.nativeLostListeners.delete(n),--r.activeOperations,r.activeOperations===0&&o.delete(r),c(),t.has(r)&&!D(e)&&!hasActiveActorOperations(r)){let e=r.actor?retireActor(r.actor):retire(r);return e.catch(e=>{F.warn(`Shared-state worker retirement failed`,{path:r.context.admission.databasePath,error:e})}),e}scheduleIdleRetirement(r)}}},retireActor=e=>{let n=k(e);for(let n of/* @__PURE__ */ new Set([...t,...s.keys()]))n.actor===e&&retire(n);return n};async function close(e){for(let n of t.values())matches(n,e)&&retire(n);let n=(await Promise.allSettled([...s.keys()].filter(t=>matches(t,e)).map(retire))).flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(c(),n.length)throw AggregateError(n,`Failed to close shared-state SQLite workers`)}n({phase:`after-resources`,close}),r(e=>{if(e.kind!==`opened`){if(!e.identity)return;close(e.identity).catch(t=>{F.warn(`Shared-state worker retirement failed`,{path:e.path,error:t})})}});function retireIdleWorkers(e){for(let n of t)y(n.idleSince,e)&&d(()=>retireIdle(n))?.catch(e=>{F.warn(`Idle shared-state worker retirement failed`,{path:n.context.admission.databasePath,error:e})})}let retireIdle=e=>e.idleTimer&&e.store&&t.has(e)&&!e.context.maintenanceScope&&!hasActiveActorOperations(e)?retire(e):void 0;return{close,retainOperation,async openCleanup(n,r,i,a,c){let l={...a};if(i(),!l.key.startsWith(`file:`))return;let assertCurrent=()=>{i();for(let e of o)if(matches(e,l)&&e.store&&!D(e.store))throw new v(`Shared-state cleanup is waiting for accepted operations to settle`,`unavailable`)};assertCurrent();for(let e of/* @__PURE__ */ new Set([...t,...s.keys()]))(t.has(e)||s.has(e))&&matches(e,l)&&e.store&&!D(e.store)&&(assertCurrent(),await(e.actor?retireActor(e.actor):retire(e)),assertCurrent());return T({...g(e),databasePath:n,existingOnly:!0,admission:{identity:l.key,birthtime:l.birthtime,assertCurrent}},r,assertCurrent,{cleanupAccess:c&&{assertDatabaseAccess:c.assertCleanupDatabaseAccess}})},async open(n,r={}){let{existingOnly:i=!1,assertCurrent:o,signal:l}=r,{admission:u}=n,wait=e=>w(e,l),f=g(e),assertAdmission=()=>{l?.throwIfAborted(),u.assertCurrent(),o?.()};assertAdmission(),assertOpenClawStateWorkerSchemaContext(n);for(let e of/* @__PURE__ */ new Set([...t,...s.keys()]))if(matches(e,u.identity)&&t.has(e)&&(e.context.existingSchemaPath!==n.existingSchemaPath||!P(e.context.gatewayServiceInstallation,n.gatewayServiceInstallation)||e.source.moduleUrl.href!==f.moduleUrl.href)){if(hasActiveActorOperations(e))throw Error(`Shared-state worker policy changed while its actor is in use; close its leases first`);await wait(e.actor?retireActor(e.actor):retire(e)),assertAdmission()}for(let[e,t]of s)if(matches(e,u.identity)&&e.context.maintenanceScope===n.maintenanceScope){if(hasActiveActorOperations(e))throw Error(`Shared-state worker is retiring while its actor is in use; close its leases first`);if(!t.pending){if(!hasPendingCleanup(e)){s.delete(e),c();continue}throw Error(`Shared-state SQLite cleanup is pending; close the database before reopening`)}try{await wait(t.pending)}catch(n){if(s.get(e)===t)throw n}assertAdmission()}assertAdmission();let p=[...t].find(e=>matches(e,u.identity)&&e.context.maintenanceScope===n.maintenanceScope&&e.context.existingSchemaPath===n.existingSchemaPath&&P(e.context.gatewayServiceInstallation,n.gatewayServiceInstallation)),_=!p;if(!p){let e=captureOpenClawStateWorkerOpeningGuard(n),r=/* @__PURE__ */ new Set,open=()=>e.run(()=>T({...f,databasePath:u.databasePath,existingOnly:i},n,e.assertCurrent,{maintenanceScope:n.maintenanceScope,...i&&u.identity.key.startsWith(`file:`)?{createAdmission:e.createAdmission}:{},retireIdle:retireIdle.bind(void 0,a),retainCleanup:e=>{a.cleanup=e},onNativeLost:m.bind(void 0,r,void 0,void 0)})),a={source:f,context:n,existingOnly:i,nativeLostListeners:r,activeOperations:0,opening:Promise.resolve(void 0)};a.opening=n.maintenanceScope?open():d(open),p=a,a.opening=a.opening.then(e=>(e?(a.store=e,a.actor=O(e),scheduleIdleRetirement(a)):(t.delete(a),c()),e)),t.add(p),c(),n.maintenanceScope?.own(p,`shared-resources`,()=>retire(a)),p.opening.catch(()=>{t.delete(a),hasPendingCleanup(a)&&!s.has(a)&&s.set(a,{}),c()})}let v=await(_?p.opening:wait(p.opening));try{u.assertCurrent()}catch(e){return retireAfterFailure(p,e,`admission`)}if(l?.throwIfAborted(),o?.(),!v)return!i&&p.existingOnly?this.open(n,{...r,existingOnly:!1}):void 0;if(!t.has(p))return this.open(n,r);if(clearIdleRetirement(p),!D(v)&&!hasActiveActorOperations(p))return await wait(p.actor?retireActor(p.actor):retire(p)),this.open(n,r);try{p.bound||(a(p.context.admission,O(v).identity),p.bound=!0),u!==p.context.admission&&h(u.databasePath,u.identity)}catch(e){return retireAfterFailure(p,e,`binding`)}return p.actor&&assertOpenClawStateWorkerActorPath(p.actor),t.delete(p),t.add(p),v}}}function getOpenClawStateWorkerOwner(){return c(),u(Symbol.for(`openclaw.sharedStateWorkerOwner`),createSharedStateWorkerOwner)}async function executeOpenClawStateWorker(e,t){let n=await runOpenClawStateWorkerOperation(e,e=>e.execute(t));return e.admission.assertCurrent(),n}async function runOpenClawStateWorkerOperation(e,t,n){return E(()=>runWithCapturedWorkerContext(e,async()=>{try{n?.signal?.throwIfAborted(),e.admission.assertCurrent(),n?.assertCurrent?.();let r=await o(e,n?.signal);if(r)throw r;e.admission.assertCurrent(),n?.assertCurrent?.();let i=await getOpenClawStateWorkerOwner().open(e,n);if(!i){if(n?.signal?.throwIfAborted(),e.admission.assertCurrent(),n?.existingOnly)return;throw Error(`Canonical shared-state worker did not open its database`)}let a=getOpenClawStateWorkerOwner().retainOperation(i);try{return n?.signal?.throwIfAborted(),e.admission.assertCurrent(),n?.assertCurrent?.(),await runWithOpenClawStateWorkerStore(i,e,t,n?.assertCurrent,n?.createAdmission,n?.signal)}finally{a()}}catch(t){let n=C(t),r=S(n,e.admission.databasePath);if(r&&!s.getOpenClawStateDatabaseRecordedFailure(e.admission.databasePath)){try{e.admission.assertCurrent()}catch{throw n}l(e.admission.databasePath,r)}throw n}}))}export{executeOpenClawStateWorker,runOpenClawStateWorkerOperation};