UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1 lines • 45.3 kB
import{K as e,Lt as t,Tt as n,et as r,f as i,jt as a,mt as o,t as s,wt as c}from"./sqlite-readonly-subsystem-Bfq7Sewc.mjs";import{t as l}from"./sqlite-readonly-deferred-B75K7ut7.mjs";import{B as u,Et as d,Gt as f,K as p,Kt as m,Rt as h,Tt as g,Ut as _,an as v,kt as y,ln as ee,mn as b,o as x,qt as S,tt as C,ut as w}from"./sqlite-readonly-runtime-process-manifest-DDSkIpjb.mjs";import{_ as T,d as E,x as D,y as te}from"./sqlite-readonly-sqlite-snapshot-capacity-error-CpnKAwJy.mjs";import{Bt as O,En as ne,On as k,Tn as A,zt as re}from"./sqlite-readonly-sqlite-database-admission-Bj6bmeyX.mjs";import{u as ie}from"./sqlite-readonly-openclaw-state-db-async-lifecycle-BwAy3Dr9.mjs";import{r as ae,s as oe}from"./sqlite-readonly-openclaw-state-maintenance-context-BTKm0Xem.mjs";import{i as se}from"./sqlite-readonly-runtime-binary-CQkI442k.mjs";import{t as ce}from"./sqlite-readonly-runtime-worker-url-Ca-_reGi.mjs";import{i as j,n as le,r as ue,t as M}from"./sqlite-readonly-retained-operation-CV17ZGcz.mjs";import{t as de}from"./sqlite-readonly-errors-_ACXy9m3.mjs";import{r as fe}from"./sqlite-readonly-error-graph-internal-c5T0xDg9.mjs";import{Ct as pe,Q as me,a as he,c as ge,et as _e,f as ve,i as ye,it as N,l as be,n as xe,nt as P,o as F,r as I,rt as Se,s as L,t as Ce}from"./sqlite-readonly-location.worker.js";import{c as we,l as Te,o as R,s as Ee,u as De}from"./sqlite-readonly-pool-m9JiklDF.mjs";import{i as z,n as Oe,r as ke,t as Ae}from"./sqlite-readonly-spawn-diagnostics-ChQW81dO.mjs";import{c as je,d as Me,f as B,i as Ne,n as Pe,o as Fe,s as V}from"./sqlite-readonly-worker-task-pool-BzpvPJI8.mjs";import{c as H,l as Ie}from"./sqlite-readonly-worker-pool-sizing-DBZ7q5PT.mjs";import{n as U,r as W,t as Le}from"./sqlite-readonly-openclaw-state-worker-error-CRDBDn6B.mjs";import G from"node:path";import{serialize as Re}from"node:v8";import{randomInt as ze}from"node:crypto";import K,{realpathSync as Be,statSync as Ve}from"node:fs";import q from"node:fs/promises";import{tmpdir as He}from"node:os";import{MessageChannel as Ue,receiveMessageOnPort as We}from"node:worker_threads";import{isDeepStrictEqual as Ge}from"node:util";import{AsyncLocalStorage as Ke}from"node:async_hooks";import J from"node:child_process";import{channel as qe}from"node:diagnostics_channel";import{Socket as Je}from"node:net";function toStringifiedError(e){return e instanceof Error?e:Error(String(e))}const Ye=[`byte`,`kilo`,`mega`,`giga`,`tera`],Xe={iec:{base:1024,labels:[`B`,`KiB`,`MiB`,`GiB`,`TiB`]},"legacy-binary":{base:1024,labels:[`B`,`KB`,`MB`,`GB`,`TB`]}};function formatByteSize(e,t){let{base:r,labels:i}=Xe[t.style],a=Ye.indexOf(t.maxUnit),o=0,s=e;for(;s>=r&&o<a;)s/=r,o+=1;for(;;){let e=n(Ye[o],`byte-size unit`),c=n(i[o],`byte-size label`),l=typeof t.fractionDigits==`function`?t.fractionDigits(s,e):t.fractionDigits;if(l===null)return`${s}${t.separator}${c}`;let u=t.floorUnits?.includes(e)?Math.floor(s*10**l)/10**l:s;if(o<a&&Number(u.toFixed(l))>=r)s/=r,o+=1;else return`${u.toFixed(l)}${t.separator}${c}`}}function rawRoot(e){if(G.sep===`\\`&&/^\\\\[?.]\\UNC\\/i.test(e)){let t=G.parse(`\\\\${e.slice(8)}`).root;return e.slice(0,t.length+6)}return G.parse(e).root}function resolutionError(e,t){return Object.assign(/* @__PURE__ */ Error(`${e}: ${e===`ELOOP`?`too many symbolic links`:`not a directory`}, resolvePathPrefix ${p(t)}`),{code:e,syscall:`resolvePathPrefix`,path:t})}function*read(e){let t;return yield async()=>{t=await e()},t}function*resolvePrefix(e,t=!1){g(e);let n=u(e),r=rawRoot(n),i=n.slice(r.length).split(G.sep),a=i.length<=32,o=0,s=i.length,c=/* @__PURE__ */ new Set,l=0;for(;s>0;){let e=a?i.shift():i[o++];if(s--,e===``)continue;if(e===`.`||e===`..`){let n=r===rawRoot(r),i=e===`..`&&n?`.`:e,a=_(r),o=`${a}${a.endsWith(G.sep)?``:G.sep}${i}`;t?K.lstatSync(o,{bigint:!0}):yield*read(()=>q.lstat(o,{bigint:!0})),e===`..`&&!n&&(r=G.dirname(r));continue}let u=G.join(r,e),f;try{f=t?K.lstatSync(u,{bigint:!0}):yield*read(()=>q.lstat(u,{bigint:!0}))}catch(s){if(!d(s,`ENOENT`))throw s;return{absolutePath:n,existingPath:t?S.native(_(r)):yield*read(()=>m(_(r))),unresolvedSegments:a?[e,...i]:i.slice(o-1)}}if(!f.isSymbolicLink()){if(!f.isDirectory()&&s>0)throw resolutionError(`ENOTDIR`,n);r=u;continue}let p=a?i:i.slice(o),h=JSON.stringify([String(f.dev),String(f.ino),u,p]);if(l>=64||c.has(h))throw resolutionError(`ELOOP`,n);c.add(h),l++;let g=t?K.readlinkSync(u):yield*read(()=>q.readlink(u)),v=G.sep===`\\`?g.replaceAll(`/`,`\\`):g,y;if(G.isAbsolute(v)){let e=rawRoot(v);r=G.sep===`\\`&&e===`\\`?rawRoot(r):e,y=v.slice(e.length).split(G.sep)}else y=v.split(G.sep);y.length+p.length<=32?(i=p,i.unshift(...y)):i=y.concat(p),s=i.length,a=s<=32,o=0}return{absolutePath:n,existingPath:t?S.native(_(r)):yield*read(()=>m(_(r))),unresolvedSegments:[]}}function resolvePathPrefixSync(e){let t=resolvePrefix(e,!0).next();if(!t.done)throw Error(`Synchronous path prefix resolution yielded asynchronous IO`);return t.value}const Y=32768;function unavailable(){throw Error(`path suffix probe resources or cleanup authority are unavailable`)}function assertMutationPath(e){e.length>Y&&unavailable()}function suffixSegments(e,t){if(typeof e!=`string`)throw TypeError(`suffix must be a string`);if(e.length>8192)throw RangeError(`suffix exceeds 8192 code units`);if(e.includes(`\0`)||G.isAbsolute(e))throw TypeError(`suffix must be a relative path without NUL bytes`);let n=process.platform===`win32`,r=(n?e.replaceAll(`/`,`\\`):e).split(G.sep);if(r.length>t)throw RangeError(`suffix exceeds ${t} components`);if(r.some(e=>!e||e===`.`||e===`..`||n&&(e.includes(`:`)||/^[ .]+$/u.test(e)||h(e))))throw TypeError(`suffix must contain ordinary relative path components`);return r}function areAsciiCaseVariants(e,t){let fold=e=>e.replace(/[A-Z]/gu,e=>String.fromCharCode(e.charCodeAt(0)+32));return fold(e)===fold(t)}function forbiddenNames(e,t){let n=/* @__PURE__ */ new Set([e.toLowerCase(),t.toLowerCase()]),r=/* @__PURE__ */ new Set([e.toUpperCase(),t.toUpperCase()]);return e=>{let t=e.normalize(`NFC`);return n.has(t.toLowerCase())||r.has(t.toUpperCase())}}function*normalizationProbePairs(e,t,n,r){let i=/* @__PURE__ */ new Set,replaceAscii=(e,t)=>e.replace(/[A-Za-z]/gu,e=>{let n=e.toLowerCase(),r=t.get(n);return r?e===n?r:r.toUpperCase():e}),a=[...new Set(`${e}${t}`.toLowerCase().match(/[a-z]/gu)??[])].filter(n=>{let r=/* @__PURE__ */ new Map([[n,n===`z`?`y`:`z`]]);return areAsciiCaseVariants(replaceAscii(e,r).normalize(`NFC`),replaceAscii(t,r).normalize(`NFC`))});for(let o=0;o<24&&a.length>0;o++){let o=new Map(a.map(e=>[e,String.fromCharCode(97+ze(26))])),s=replaceAscii(e,o),c=replaceAscii(t,o);if(s.length>r||c.length>r||!areAsciiCaseVariants(s.normalize(`NFC`),c.normalize(`NFC`))||h(s)||h(c)||n(s)||n(c))continue;let l=`${s}\0${c}`;i.has(l)||(i.add(l),yield[s,c])}}function createPrivateProbeName(e){let t=``;for(let n=0;n<e;n++){let e=n===0?`bdefghijkmoqrstuvwxyz`:`abcdefghijklmnopqrstuvwxyz0123456789`;t+=e[ze(e.length)]}return t}function*asciiCaseProbePairs(e,t){for(let n of privateProbeNames(e,t))yield[n,`${n[0].toUpperCase()}${n.slice(1)}`]}function*privateProbeNames(e,t){let n=0;for(let r=0;r<96&&n<24;r++){let r=createPrivateProbeName(e);t(r)||(n++,yield r)}}function*prependPair(e,t){yield e,yield*t}var ProbeDirectories=class{requestedDirectory;root;created=[];cleanupComplete=!0;observations=0;mkdirAttempts=0;creations=0;maxObservations;maxMkdirAttempts;maxCreations;constructor(e,t){this.requestedDirectory=e;let n=Math.max(1,t/32);this.maxObservations=Math.min(32768,4096*n*n),this.maxMkdirAttempts=128*n,this.maxCreations=64*n,this.observe(1);let r=S.native(_(e));assertMutationPath(r),this.observe(2),this.root={path:r,identity:w(r)},this.assert(this.root)}reserveObservations(e){e>this.maxObservations-this.observations&&unavailable()}observe(e,t=!1){t||(this.reserveObservations(e),this.observations+=e)}assert(e,t=!1){if(this.observe(1,t),S.native(_(this.requestedDirectory))!==this.root.path)throw new ee(`path-mismatch`,`probe directory changed`);for(let n=e;n;n=n.parent)this.observe(2,t),C(n.path,n.identity)}create(e,t){(this.mkdirAttempts>=this.maxMkdirAttempts||this.creations>=this.maxCreations)&&unavailable();let n=G.join(e.path,t);assertMutationPath(n),this.assert(e),this.reserveObservations(2),this.mkdirAttempts++;try{K.mkdirSync(n)}catch(e){if(d(e,`EEXIST`))return;throw e}this.creations++,this.observe(2);let r={path:n,identity:w(n),parent:e};return this.created.push(r),this.assert(r),r}remove(e,t=!1){try{return this.assert(e,t),assertMutationPath(e.path),K.rmdirSync(e.path),!0}catch{return!1}}probe(e,t){for(let[n,r]of t){let t=G.join(e.path,r);assertMutationPath(t);let i=this.create(e,n);if(!i)continue;let a;this.observe(2);try{a=v(()=>K.lstatSync(t,{bigint:!0}))}catch(e){if(!d(e,`ENOENT`))throw e}if(this.assert(i),!a)return{aliases:!1,directory:i};if(a.isDirectory()&&!a.isSymbolicLink()&&b(i.identity,a))return{aliases:!0,directory:i};this.remove(i)||(this.cleanupComplete=!1,unavailable()),this.created.splice(this.created.indexOf(i),1)}}neutral(e,t,n){for(let r of privateProbeNames(t,n)){let t=this.create(e,r);if(t)return t}}cleanup(){for(let e=this.created.length-1;e>=0;e--)this.remove(this.created[e],!0)||(this.cleanupComplete=!1);try{this.assert(this.root,!0)}catch{this.cleanupComplete=!1}return this.cleanupComplete}};function observeSuffixes(e,t,n,r){let i,a;for(let o=0;o<t.length;o++){let s=t[o],c=n[o],l=s.normalize(`NFC`),u=c.normalize(`NFC`),d=areAsciiCaseVariants(l,u);if(l!==u&&!d&&!r(l,u))return!1;let f=s!==l||c!==u;if(l===u&&!f&&o===t.length-1)continue;let p=e();a??=p.root,i??=Math.max(G.join(p.root.path,t.join(G.sep)).length,G.join(p.root.path,n.join(G.sep)).length);let m=i-a.path.length-+!a.path.endsWith(G.sep),h=Math.max(1,Math.min(6,s.length,c.length)),g=forbiddenNames(l,u),_;if(l!==u){let e=a,t;if(d)t=asciiCaseProbePairs(h,g);else{let n=p.neutral(a,h,g);if(!n)return;e=n,t=[[s,c]]}let n=p.probe(e,t);if(!n)return;if(!n.aliases)return!1;_=n.directory}if(f){let e=normalizationProbePairs(s,c,g,m),t=e.next(),n,r=a;if(t.done){let e=p.neutral(a,h,g);if(!e)return;r=e,n=[[s,c]]}else n=prependPair(t.value,e);let i=p.probe(r,n);if(!i)return;if(!i.aliases)return!1;_??=i.directory}if(o<t.length-1){if(_??=p.neutral(a,h,g),!_)return;a=_}}return!0}function probePathSuffixAliasesSync(e){let t=e.directory;if(typeof t!=`string`)throw TypeError(`directory must be a string`);if(t.length>Y)throw RangeError(`directory exceeds 32768 code units`);if(t.includes(`\0`))throw TypeError(`directory must be a path without NUL bytes`);let n=f(t);if(n.length>Y)throw RangeError(`resolved directory exceeds 32768 code units`);let r=e.maxDepth,i=r===void 0?32:r;if(!Number.isSafeInteger(i)||i<0)throw RangeError(`maxDepth must be a non-negative safe integer`);let a=e.left,o=e.right,s=e.shouldProbeCaseVariants,c=suffixSegments(a,i),l=suffixSegments(o,i);if(c.length!==l.length)throw TypeError(`suffixes must have the same component count`);if(s!==void 0&&typeof s!=`function`)throw TypeError(`shouldProbeCaseVariants must be a function`);if(a===o)return!0;let u,shouldProbe=(e,t)=>{if(!s)return!0;try{let n=s(e,t);if(typeof n!=`boolean`)throw Promise.resolve(n).catch(()=>void 0),TypeError(`shouldProbeCaseVariants must return a boolean synchronously`);return n}catch(e){throw u={error:e},e}},d,p,m=!0;try{p=observeSuffixes(()=>d??=new ProbeDirectories(n,c.length),c,l,shouldProbe),d?.assert(d.root)}catch{if(p=void 0,u)throw u.error}finally{d&&(m=d.cleanup())}return m?p:void 0}function ok(e){return{ok:!0,value:e}}function err(e){return{ok:!1,error:e}}const Ze=/^[a-z0-9][a-z0-9_-]{0,63}$/i,Qe=/[^a-z0-9_-]+/g,$e=/^-+/,et=/-+$/;function normalizeAgentId(e){let t=normalizeAgentIdStrict(e);return t.ok?t.value:`main`}function normalizeAgentIdStrict(e){let t=(e??``).trim(),n=t.toLowerCase();if(Ze.test(t))return ok(n);let r=n.replace(Qe,`-`).replace($e,``).replace(et,``).slice(0,64);return r?ok(r):err(`unrepresentable`)}function isValidAgentId(e){let t=(e??``).trim();return!!t&&Ze.test(t)}const tt=`incognito-openclaw-agent.sqlite`,X=/* @__PURE__ */ new Map,nt=X.keys();function resolveOpenClawAgentSqlitePath(t){if(t.path!=null)return G.resolve(t.path);let n=normalizeAgentId(t.agentId),r=e(t.env??process.env),i=`${n}:${r}`,a=X.get(i);if(a!==void 0)return a;let o=G.resolve(r,`agents`,n,`agent`,`openclaw-agent.sqlite`);if(X.set(i,o),X.size>256){let e=nt.next();e.done||X.delete(e.value)}return o}function resolveIncognitoOpenClawAgentSqlitePath(e){return G.join(G.dirname(resolveOpenClawAgentSqlitePath(e)),tt)}function isIncognitoOpenClawAgentSqlitePath(e,t){let n=G.resolve(e);return G.basename(n)===`incognito-openclaw-agent.sqlite`&&n===resolveIncognitoOpenClawAgentSqlitePath(t)}const rt=/* @__PURE__ */ new Map;function shouldProbeUnicodeCaseVariants(e,t){let hasNonAscii=e=>e.split(``).some(e=>e.charCodeAt(0)>127);if(!hasNonAscii(e)&&!hasNonAscii(t))return!1;let n=e.toLowerCase()===t.toLowerCase();return e.toUpperCase()===t.toUpperCase()||n&&Array.from(e).length===Array.from(t).length}function areMissingSuffixAliases(e){if(e.left===e.right)return!0;let t=e.left.split(G.sep),n=e.right.split(G.sep);if(t.length!==n.length||[...t,...n].some(e=>!e||e===`.`||e===`..`))return!1;let r=[e.left,e.right].toSorted(),i=JSON.stringify([e.parentDevice,e.parentInode,e.parentRealPath,...r]),a=rt.get(i);if(a!==void 0)return a;let o,s;try{o=probePathSuffixAliasesSync({directory:e.parentRealPath,left:e.left,right:e.right,maxDepth:t.length,shouldProbeCaseVariants:shouldProbeUnicodeCaseVariants})}catch(e){s=e}if(o===void 0)throw Error(`Cannot determine whether database paths alias under ${JSON.stringify(e.parentRealPath)}: ${JSON.stringify(e.left)} and ${JSON.stringify(e.right)}. Check directory access and retry.`,{cause:s});return rt.set(i,o),o}function anchorDatabasePathWithoutNormalizing(e){let t=G.sep===`\\`?e.replaceAll(`/`,`\\`):e;if(G.isAbsolute(t))return t;if(G.sep===`\\`){let e=/^([A-Za-z]:)(.*)$/u.exec(t);if(e){let t=G.resolve(`${e[1]}.`);return e[2]?`${t}${t.endsWith(G.sep)?``:G.sep}${e[2]}`:t}}let n=process.cwd();return`${n}${n.endsWith(G.sep)?``:G.sep}${t}`}function resolveAgentDatabasePathIdentity(e){let t=anchorDatabasePathWithoutNormalizing(e);try{let e=Be.native(t),n=Ve(e,{bigint:!0});return{lexicalPath:t,realPath:e,device:n.dev.toString(),inode:n.ino.toString()}}catch(e){if(!d(e,`ENOENT`))throw e;let n=G.parse(t).root,r=resolvePathPrefixSync(n+t.slice(n.length).split(G.sep).filter(Boolean).join(G.sep)),i=r.existingPath,a=Ve(i,{bigint:!0});return{lexicalPath:t,parentDevice:a.dev.toString(),parentInode:a.ino.toString(),parentRealPath:i,unresolvedSuffix:r.unresolvedSegments.join(G.sep)}}}function areSameAgentDatabasePathIdentities(e,t){return e.lexicalPath===t.lexicalPath?!0:`realPath`in e?`realPath`in t&&(e.realPath===t.realPath||e.device===t.device&&e.inode===t.inode):!(`realPath`in t)&&e.parentDevice===t.parentDevice&&e.parentInode===t.parentInode&&areMissingSuffixAliases({left:e.unresolvedSuffix,right:t.unresolvedSuffix,parentDevice:e.parentDevice,parentInode:e.parentInode,parentRealPath:e.parentRealPath})}function createOpenClawAgentDatabasePathMatcher(e=[]){let t=new Map(e.map(e=>[e.lexicalPath,e])),resolveIdentity=e=>{let n=anchorDatabasePathWithoutNormalizing(e),r=t.get(n);if(r)return r;let i=resolveAgentDatabasePathIdentity(n);return t.set(n,i),i};return Object.assign((e,t)=>areSameAgentDatabasePathIdentities(resolveIdentity(e),resolveIdentity(t)),{capture(e){resolveIdentity(e)},observations:()=>[...t.values()],createIndex(){let e=/* @__PURE__ */ new Map,t=[],n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map;return a=>{let o=resolveIdentity(a),s=e.get(o.lexicalPath);if(s!==void 0)return s;let c;if(`realPath`in o){let e=`${o.device}:${o.inode}`,i=n.get(e),a=r.get(o.realPath);c=i===void 0?a:a===void 0?i:Math.min(i,a),c===void 0&&(c=t.push(o)-1,n.set(e,c),r.set(o.realPath,c))}else{let e=`${o.parentDevice}:${o.parentInode}`,n=i.get(e)??[];c=n.find(e=>areSameAgentDatabasePathIdentities(t[e],o)),c===void 0&&(c=t.push(o)-1,n.push(c),i.set(e,n))}let l=t[c].lexicalPath;return e.set(o.lexicalPath,l),l}},isCurrent(){for(let e of t.values()){let t=resolveAgentDatabasePathIdentity(e.lexicalPath);if(!Ge(e,t))return!1}return!0}})}function isSameOpenClawAgentDatabasePath(e,t){return areSameAgentDatabasePathIdentities(resolveAgentDatabasePathIdentity(e),resolveAgentDatabasePathIdentity(t))}function canonicalPathForRegistryBoundary(e){let t=resolveAgentDatabasePathIdentity(e);if(`realPath`in t)return t.realPath;let n=t.unresolvedSuffix.split(G.sep);return n.includes(`..`)?t.parentRealPath:G.join(t.parentRealPath,...n)}function isPersistentOpenClawAgentDatabasePath(t,n=process.env){let r=G.resolve(t),i=G.join(G.resolve(e(n)),`imports`);if(y(i,r))return!1;let a=canonicalPathForRegistryBoundary(t),o=canonicalPathForRegistryBoundary(e(n)),s=canonicalPathForRegistryBoundary(G.join(o,`imports`));return!y(s,a)}const it=/* @__PURE__ */ new Set([`--no-maglev`,`--maglev`,`--no-concurrent-sparkplug`,`--concurrent-sparkplug`]);function resolveForwardedNodeCompilerArgs(){return process.execArgv.filter(e=>it.has(e.replaceAll(`_`,`-`)))}const at=qe(`openclaw.memory.critical`);function createStateWorkerMemoryPressureSubscription(e,t){let n=!1,onPressure=e=>t(e===!0);return()=>{let t=e();t!==n&&(n=t,t?at.subscribe(onPressure):at.unsubscribe(onPressure))}}const ot={"startupMetadata.readCurrent":`retire-after-result`,"startupMetadata.rollbackRecoveryRequired":`retire-after-result`};function sqliteReadOnlyOperationRequiresProcessRetirement(e){return e in ot}const st=t(Symbol.for(`openclaw.agentCreationClaim`),()=>new Ke),Z=t(Symbol.for(`openclaw.agentCreationClaimResources`),()=>/* @__PURE__ */ new Map);function getActiveAgentCreationClaim(e,t){let n=st.getStore();if(n&&n.kind===`host`&&n.isActive()&&n.agentId===normalizeAgentId(e)&&n.statePath===G.resolve(t))return n}function reserveAgentCreationClaimAdmission(e,t,n){let r=getActiveAgentCreationClaim(t.agentId,ie(t.env??process.env));if(r)return Z.set(e,r),r.registerClose(async()=>{Z.get(e)===r&&(await n(),Z.delete(e))}),()=>{Z.delete(e)}}function releaseAgentCreationClaimHandle(e){Z.delete(e)}const ct=t(Symbol.for(`openclaw.agentDatabaseExecutionAdmissionClosedError`),()=>class extends Error{});t(Symbol.for(`openclaw.agentDatabaseSchemaAdmissionChangedError`),()=>class extends Error{constructor(){super(`Agent schema admission changed before publication; retry the operation`)}}),t(Symbol.for(`openclaw.agentDatabaseSchemaAdmissionInvalidError`),()=>class extends Error{constructor(){super(`Invalid agent schema admission receipt`)}});const lt=t(Symbol.for(`openclaw.agentDatabaseStartupPublicationError`),()=>class extends Error{constructor(e){super(de(e),{cause:e})}}),ut=t(Symbol.for(`openclaw.agentDeletionDatabaseCleanup`),()=>new Ke),dt=t(Symbol.for(`openclaw.agentDeletionDatabaseCleanupHandles`),()=>/* @__PURE__ */ new Map);t(Symbol.for(`openclaw.agentDeletionDatabaseCleanupExecutions`),()=>/* @__PURE__ */ new Map);function captureAgentDeletionResourceOwner(e){let t=ut.getStore();if(t?.ownsDatabase&&(e(t)||t.canonicalPath&&e({agentId:t.agentId,path:t.canonicalPath})))return t.assertCurrentHost(),t}function releaseAgentDeletionDatabaseCleanup(e){dt.delete(e)}const Q=t(Symbol.for(`openclaw.agentDatabaseAsyncResources`),()=>({active:/* @__PURE__ */ new Set,closing:/* @__PURE__ */ new Map,selections:/* @__PURE__ */ new Map}));function hasOpenClawAgentDatabaseAsyncResources(e){return e?[...Q.active,...Q.closing.keys()].some(t=>matchesAgentDatabaseClose(e,t)):Q.active.size>0||Q.closing.size>0}function registerAgentDatabaseResourceReleaseHandler(e){Q.onRelease=e}Ie(async(e,t)=>{let n=(await Promise.allSettled([.../* @__PURE__ */ new Set([...Q.active,...Q.closing.keys()])].filter(n=>!t?.has(G.resolve(n.path))&&e.some(e=>H(e,n.path))).map(e=>closeAgentDatabaseResource(e)))).flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(n.length>0)throw AggregateError(n,`Agent database resource cleanup failed`)});function matchesAgentDatabaseClose(e,t){return(e.path===void 0||e.path===t.path||t.ownership===`unresolved`&&H(t,e.path))&&(e.rootPath===void 0||y(e.rootPath,t.path)||t.ownership===`unresolved`&&H(t,e.rootPath))&&(e.agentId===void 0||t.ownership===`unresolved`||e.agentId===t.agentId)}function registerOpenClawAgentDatabaseAsyncResource(e,t){return registerAgentDatabaseResource({...e,ownership:`known`,agentId:normalizeAgentId(e.agentId)},t)}function registerOpenClawAgentDatabaseReadCandidateResource(e){return registerAgentDatabaseResource({...e,ownership:`unresolved`})}function registerAgentDatabaseResource(e,t){let n={...e,path:G.resolve(e.path)};n.cleanupOwner=captureAgentDeletionResourceOwner(e=>matchesAgentDatabaseClose(e,n)),assertAgentDatabaseResourceAdmission(n);let r=t&&n.ownership===`known`?reserveAgentCreationClaimAdmission(n,t,()=>closeAgentDatabaseResource(n)):void 0,unregister=()=>{Q.active.delete(n),r?.(),Q.onRelease?.(n)};return ae()?.own(unregister,`agent-resources`,()=>closeAgentDatabaseResource(n)),Q.active.add(n),unregister}function assertAgentDatabaseResourceAdmission(e){if([...Q.selections.keys()].some(t=>matchesAgentDatabaseClose(t,e))||[...Q.closing.keys()].some(t=>(t.path===e.path||t.ownership===`unresolved`&&H(t,e.path)||e.ownership===`unresolved`&&H(e,t.path))&&(t.ownership===`unresolved`||e.ownership===`unresolved`||t.agentId===e.agentId)))throw new ct(`Agent database resources are closing: ${e.path}`)}function closeAgentDatabaseResource(e,t){if(e.ownership===`known`&&e.closeSync){Q.closing.set(e,void 0);try{return e.revoke(),e.closeSync(),Q.active.delete(e),Q.closing.delete(e),Q.onRelease?.(e),Promise.resolve()}catch(n){t&&t(e.path,n);let r=Promise.reject(a(n,`Agent database cleanup failed`));return r.catch(()=>{}),r}}let n=Q.closing.get(e);return n||(n=Promise.resolve().then(()=>e.close()),Q.closing.set(e,n),n.then(()=>{Q.active.delete(e),Q.closing.delete(e),Q.onRelease?.(e)},()=>{Q.closing.set(e,void 0)}).catch(()=>{})),t&&n.catch(n=>t(e.path,n)).catch(()=>{}),e.revoke(),n}function revokeAgentDatabaseResources(e,t){let n=/* @__PURE__ */ new Set([...Q.active,...Q.closing.keys()]),r=[];for(let i of n)matchesAgentDatabaseClose(e,i)&&r.push(closeAgentDatabaseResource(i,t));return r}function isSameSqliteReadOnlyWorkerLaunch(e,t){let n=Object.keys(t.env);return e.runtimeGeneration===t.runtimeGeneration&&e.transport.kind===t.transport.kind&&(e.transport.kind===`native`||t.transport.kind===`broker`&&e.transport.owner===t.transport.owner)&&t.cwd===e.cwd&&n.length===Object.keys(e.env).length&&n.every(n=>t.env[n]===e.env[n])}function createSqliteReadOnlyWorkerSession(e){R();let t={...e.env},n=e.cwd,a=process.execPath,s=e.transport.kind===`broker`?{kind:`broker`,owner:e.transport.owner}:{kind:`native`},c={env:t,cwd:n,transport:s,runtimeGeneration:e.runtimeGeneration},u=[...e.argv],d={env:t,...s.kind===`native`&&n===r()?{}:{cwd:n},stdio:[`ignore`,`pipe`,`pipe`,`ipc`],windowsHide:!0},f=s.kind===`broker`?s.owner.spawn(a,u,d):J.spawn(a,u,d);Ae(a,f,e.pooledRead?`sqlite.scoped-read.${s.kind}`:`sqlite.session.${s.kind}`);let setIdle=e=>{if(s.kind!==`native`)return;let t=e?`unref`:`ref`;f[t](),f.channel?.[t]?.();for(let e of[f.stdout,f.stderr])e instanceof Je&&e[t]()},p=!1,m=0,h,g=``,_=0,v,{promise:y,resolve:ee}=l(),b=/* @__PURE__ */ new Map,x=y.then(async()=>{s.kind===`broker`&&f instanceof V&&!f.notStarted&&f.exitCode===null&&f.signalCode===null&&await s.owner.waitForCleanup();for(let e of b.values())e();b.clear()}),retire=e=>{setIdle(!1),p=!0,v&&e!==void 0&&(v.failure??=e),f.kill(`SIGKILL`)},sendMessage=e=>f.send(e,e=>{e&&retire(e)}),releasePending=t=>{if(v=void 0,h=void 0,t.cleanup(),e.pooledRead){for(let e of b.values())e();b.clear()}return t};e.retainLifetime!==!1&&T(x,()=>retire(/* @__PURE__ */ Error(`SQLite snapshot owner stopped`)));let S=!1,C=!1,w=!1;f.once(`spawn`,()=>{C=!0}),f.on(`error`,e=>retire(C?e:Object.assign(Error([[`EACCES`,`ENOENT`,`EPERM`].includes(e.code??``)?`SQLite read-only worker runtime binary not executable: ${a} (${e.code}, cwd ${n}). Check runtime execute permissions and access to the working directory`:`SQLite read-only worker failed to start (executable ${a}, cwd ${n})`,e.message].join(`: `),{cause:e}),{code:e.code,path:e.path})));let finishClose=async(e,t)=>{w=!0,p=!0;let n=v?.failure??I(`exited with ${t?`signal ${t}`:`code ${e}`}`,g),r=await Te({execPath:a,error:n,stderr:g,signal:t,started:S}).catch(toStringifiedError);if(v){let e=releasePending(v);e.reject(r??e.failure??n)}ee()};f.once(`close`,(e,t)=>{finishClose(e,t)});let captureOutput=(e,t)=>{_+=e.length,t&&(g=o(g+e.toString(`utf8`),-Ce)),_>1048576&&retire(I(`exceeded its output buffer`,g))},attachOutput=()=>{f.stdout?.on(`data`,e=>captureOutput(e,!1)),f.stderr?.on(`data`,e=>captureOutput(e,!0))},E=f instanceof V?f.ready().then(attachOutput).catch(retire):void 0;E||attachOutput(),f.on(`message`,t=>{if(S=!0,!p){if(!v||!t||typeof t!=`object`||Object.keys(t).length!==2||!(`id`in t)||t.id!==v.id||!(`result`in t))retire(I(`returned an unexpected response`,g));else try{let e;if(v.transfer&&`type`in t.result){let n=v.transfer.accept(t.result);if(`request`in n){sendMessage({id:v.id,transfer:n.request});return}e=n.value}else e=F({kind:`launched`,stdout:JSON.stringify(t.result),stderr:g,status:0},v.mode);releasePending(v).resolve(e)}catch(n){if(v&&e.retainOnOperationError&&he(v.mode)&&ye(t.result)&&!t.result.ok){releasePending(v).reject(n);return}retire(n)}}});let D={closed:x,isRetired(){return p},get notStarted(){return f instanceof V?f.notStarted:w&&!C},createNativeReplacement(){return i(()=>createSqliteReadOnlyWorkerSession({...e,env:t,cwd:n,argv:u,transport:{kind:`native`}}))},compatible(e){return!p&&isSameSqliteReadOnlyWorkerLaunch(c,e)},run(t,n){if(p)return Promise.reject(/* @__PURE__ */ Error(`SQLite read-only worker is closed`));if(n.mode===`auth-profile-rows`&&n.source===`canonical`&&!n.artifactPreserving){let e=G.resolve(t);b.has(e)||b.set(e,registerOpenClawAgentDatabaseReadCandidateResource({path:e,revoke:()=>retire(/* @__PURE__ */ Error(`Auth profile reader owner was revoked`)),close:()=>D.close()}))}return h=new Promise((r,i)=>{g=``,_=0;let abort=()=>retire(n.signal?.reason),a,o=++m;v={id:o,mode:n.mode,...n.mode===`auth-profile-rows`?{transfer:ge()}:n.mode===`operation`?{transfer:be(n.command.type)}:{},resolve:r,reject:i,cleanup:()=>{clearTimeout(a),n.signal?.removeEventListener(`abort`,abort)}},n.signal?.addEventListener(`abort`,abort,{once:!0}),n.signal?.aborted?abort():(async()=>{try{if(!e.deadlineOwnedByCaller()){let{timeoutMs:n,size:r}=await e.readBudget(t);if(p)return;a=setTimeout(()=>retire(e.timeoutError(t,n,r)),n)}if(E&&(await E,p))return;let r={id:o,args:e.requestArgs(t,n),...n.mode===`auth-profile-rows`||n.mode===`operation`?{[n.mode===`operation`?`operation`:`auth`]:{expectedIdentity:n.expectedIdentity,expectedBirthtime:n.expectedBirthtime,artifactPreserving:n.artifactPreserving,...n.mode===`operation`?{command:Re(n.command).toString(`base64`)}:{immutable:n.immutable,retainReader:!e.pooledRead&&n.source===`canonical`&&!n.artifactPreserving,schema:n.source===`canonical`&&!n.artifactPreserving?ve(t,n.expectedIdentity):void 0}}}:{}};if(n.mode===`operation`&&Buffer.byteLength(JSON.stringify(r))>1048576)throw Error(`SQLite read-only operation exceeded its request buffer`);sendMessage(r)}catch(e){retire(e)}})()})},setIdle,async close(){if(D.setIdle(!1),p){await x;return}p=!0;let t=setTimeout(()=>retire(),e.closeTimeoutMs);try{sendMessage(`close`)}catch(e){retire(e)}try{await x}finally{clearTimeout(t)}}};return e.runtimeGeneration?.retain(D,async()=>(await h?.catch(()=>void 0),()=>D.close())),D}const ft=s(`state/sqlite`);function trackSqliteRead(e){return Fe(`sqlite_read`,_e(e.mode===`operation`?e.command.type:e.mode),e.signal)}function createSqliteReadOnlyWorkerPool(e){let t=[],n=/* @__PURE__ */ new WeakMap,r=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new WeakSet,o=createStateWorkerMemoryPressureSubscription(()=>t.some(e=>e.idleSince!==void 0&&!e.session?.isRetired()),e=>{for(let n of t)n.session&&!n.leased&&!n.quarantined&&n.queued===0&&je(n.idleSince,e)&&retireIdleSlot(n)}),assertBrokerOpen=e=>{if(e.transport.kind===`broker`&&a.has(e.transport.owner))throw Error(`SQLite read-only worker broker is closing`)};async function closeSlot(e){let t=e.session;try{await t?.close(),e.session=void 0}catch(t){e.quarantined={error:t};for(let e of r)e();throw t}}async function selectScopedReadWorker(e,a){assertBrokerOpen(a);let o=e.mode===`operation`&&(e.command.type===`pageCache.begin`||e.command.type===`pageCache.step`),s=z.getStore();if(o){if(!s?.active)throw Error(`Database page-cache warm requires an active read-only worker scope`);let t=n.get(s);if(t){if(!isSameSqliteReadOnlyWorkerLaunch(t.launch,a))throw Error(`Database page-cache warm worker launch changed during its scope`);return t}if(e.command.type===`pageCache.step`)throw Error(`Database page-cache warm is no longer active`)}for(;;){assertBrokerOpen(a),e.signal?.throwIfAborted();let c=t.filter(e=>!e.leased&&!e.quarantined),l=c.find(e=>isSameSqliteReadOnlyWorkerLaunch(e.launch,a));if(!l&&t.length<4&&(l={launch:a,tail:Promise.resolve(),queued:0},t.push(l)),l??=c.find(e=>e.queued===0&&!e.session),l??=c.reduce((e,t)=>!e||t.queued<e.queued?t:e,void 0),l){if(o&&s){let e=l,t={started:!1};e.leased=t,n.set(s,e),s.releaseReadWorker=async()=>{try{t.started&&(await e.tail,await closeSlot(e))}finally{e.leased=void 0,n.delete(s),s.releaseReadWorker=void 0,!e.quarantined&&e.queued===0&&e.session&&!e.session.isRetired()&&(e.session.setIdle(!0),armScopedReadWorkerIdle(e));for(let e of r)e()}}}return l}if(t.every(e=>e.quarantined))throw AggregateError(t.map(e=>e.quarantined?.error),`SQLite read-only worker capacity is held by unconfirmed cleanup`);let u,d=i(()=>new Promise(e=>{u=e}));r.add(u);try{await x(d,e.signal,e=>e.reason)}finally{r.delete(u)}}}function retireIdleSlot(e){clearTimeout(e.idle),e.idleSince=void 0,o();let t=i(()=>closeSlot(e));return e.tail=t.catch(()=>{ft.warn(`Idle SQLite read-only worker cleanup failed`)}),t}function armScopedReadWorkerIdle(e){e.launch.transport.kind===`broker`&&a.has(e.launch.transport.owner)?retireIdleSlot(e):(e.idleSince=performance.now(),o(),e.idle=i(()=>setTimeout(()=>{retireIdleSlot(e)},6e4)),e.idle.unref())}return{run:async function(t,n,r,a=trackSqliteRead(n)){let s=n.mode===`operation`&&(n.command.type===`pageCache.begin`||n.command.type===`pageCache.step`),c;try{c=await selectScopedReadWorker(n,r),assertBrokerOpen(r)}catch(e){throw a.completed(),e}clearTimeout(c.idle),c.idleSince=void 0,o(),c.queued++;let l=c.tail,u=i(()=>x(l,n.signal,e=>e.reason)).then(async()=>{if(n.signal?.throwIfAborted(),c.quarantined)throw c.quarantined.error;if(a.started(),c.leased&&n.mode===`operation`&&n.command.type===`pageCache.begin`&&(c.leased.started=!0),(!isSameSqliteReadOnlyWorkerLaunch(c.launch,r)||c.session?.isRetired())&&await closeSlot(c),n.signal?.throwIfAborted(),c.launch=r,!c.session){c.session=e({...r,pooledRead:!0});let{closed:t}=c.session;i(()=>t.then(o,o))}let l=c.session;l.setIdle(!1);try{let e=await l.run(t,n);return n.signal?.throwIfAborted(),!s&&(n.mode===`operation`&&sqliteReadOnlyOperationRequiresProcessRetirement(n.command.type)||!re().explicitSqliteCloseReleasesNativeResources)&&await closeSlot(c),e}catch(e){try{await closeSlot(c)}catch(t){throw k([e,t],`SQLite read and child cleanup failed`,e)}throw e}}).finally(()=>{a.completed(),c.queued--,!c.leased&&!c.quarantined&&c.queued===0&&c.session&&!c.session.isRetired()&&(c.session?.setIdle(!0),armScopedReadWorkerIdle(c))});return c.tail=i(()=>Promise.allSettled([l,u]).then(()=>{})),u},async closeBroker(e){a.add(e);let n=await Promise.allSettled(t.filter(t=>t.launch.transport.kind===`broker`&&t.launch.transport.owner===e&&t.session&&t.queued===0&&!t.leased&&!t.quarantined).map(retireIdleSlot));fe(n,`SQLite read-only broker worker cleanup failed`)}}}const $=3e5,pt=s(`state/sqlite`);function resolveSqliteInspectionBudget(e,t,n){let r=c($+Math.ceil(40*Number(n??0)/33554432)*1e3,$),i=n===void 0?`unknown size`:formatByteSize(Number(n),{style:`iec`,maxUnit:`giga`,separator:` `,fractionDigits:n<1024n?0:1});return r>$&&pt.debug(`SQLite ${e} for ${t}: ${i}, budget ${r/1e3} seconds`),{timeoutMs:r,size:i}}function readSqliteInspectionBudget(e,t,n){let r=n;try{r??=K.statSync(t,{bigint:!0}).size;for(let e of[`-wal`,`-shm`,`-journal`])try{r+=K.statSync(t+e,{bigint:!0}).size}catch(e){if(!d(e,`ENOENT`))throw e}}catch{}return resolveSqliteInspectionBudget(e,t,r)}async function readSqliteInspectionBudgetAsync(e,t,n){let r=n;try{r??=(await K.promises.stat(t,{bigint:!0})).size;for(let e of[`-wal`,`-shm`,`-journal`])try{r+=(await K.promises.stat(t+e,{bigint:!0})).size}catch(e){if(!d(e,`ENOENT`))throw e}}catch{}return resolveSqliteInspectionBudget(e,t,r)}function sqliteInspectionTimeoutError(e,t,n,r){return/* @__PURE__ */ Error(`SQLite ${e} timed out after ${n/1e3} seconds (budget for ${r}) for ${t}. Stop the Gateway service and other OpenClaw processes using this database, then retry; if already stopped, check storage performance.`)}async function withSqliteReadOnlyWorkerScope(e,t){if(!t&&z.getStore()?.active)return e();let n=ke(t);try{return await n.run(e)}finally{await n.close()}}function isSqliteInspectionDeadlineOwnedByCaller(){return z.getStore()?.deadlineOwnedByCaller===!0}function runScopedSqliteInspection(e,t){let n=z.getStore();if(!n)return t(e);if(!n.active)return Promise.reject(new Oe);let r=t(e?AbortSignal.any([e,n.controller.signal]):n.controller.signal);return n.pending.add(r),r.then(()=>n.pending.delete(r),()=>n.pending.delete(r)),r}function sqliteReadOnlyWorkerArgv(e){let{moduleUrl:t,runtimeGeneration:n}=P(N(e[0]===`content-version`||e[0]===`file-generation`?`sqliteSourceRevision`:`sqliteReadOnly`));return{runtimeGeneration:n,argv:[...resolveForwardedNodeCompilerArgs(),...ce(t),se,...e]}}function captureSqliteReadOnlyWorkerLaunch(t,n){let i=n===void 0?void 0:De();return{runtimeGeneration:P(N(`sqliteReadOnly`)).runtimeGeneration,env:{...O(B(t)),OPENCLAW_STATE_DIR:e(t)},cwd:r()??He(),transport:i?{kind:`broker`,owner:i}:{kind:`native`}}}function createScopedSqliteReadOnlyWorker(e){let t=N(`sqliteReadOnly`);return i(()=>createSqliteReadOnlyWorkerSession({...e,argv:[...resolveForwardedNodeCompilerArgs(),...ce(Se(t,e.runtimeGeneration)),se,`session`],requestArgs:L,readBudget:e=>readSqliteInspectionBudgetAsync(`read-only snapshot`,e),deadlineOwnedByCaller:e.retainLifetime===!1?()=>!1:isSqliteInspectionDeadlineOwnedByCaller,timeoutError:(e,t,n)=>sqliteInspectionTimeoutError(`read-only snapshot`,e,t,n),closeTimeoutMs:$}))}async function runSqliteReadOnlyOperation(e,t,n){let r=structuredClone(t),i=await runSqliteReadOnlyWorker(e,{...n,mode:`operation`,command:r});return readOperationResult(r.type,i)}function readOperationResult(e,t){if(typeof t!=`object`||!(`operation`in t)||t.operation!==e)throw Error(`SQLite read-only worker returned a different operation`);return t.value}function runSqliteReadOnlyWorker(e,t){let n=(t.mode===`auth-profile-rows`||t.mode===`operation`)&&t.source===`canonical`&&pe(`agent`,e)?t.mode===`auth-profile-rows`&&oe(e)?{...t,artifactPreserving:!0,immutable:!0}:{...t,artifactPreserving:!0}:t;return runScopedSqliteInspection(n.signal,t=>{let r=z.getStore();if(!r)return runSqliteReadOnlyWorkerOnce(e,n);let i={...n,signal:t},a=n.mode===`sync`&&!r.busy;if(a&&(r.busy=!0),i.mode===`auth-profile-rows`||i.mode===`operation`){let t=captureSqliteReadOnlyWorkerLaunch(i.env,i.source);return mt.run(e,i,t)}return(async()=>{if(!a)return runSqliteReadOnlyWorkerOnce(e,i);try{let t=captureSqliteReadOnlyWorkerLaunch();return r.worker?.compatible(t)||(await r.worker?.close(),i.signal?.throwIfAborted(),r.worker=createScopedSqliteReadOnlyWorker(t)),await r.worker.run(e,i)}finally{r.busy=!1}})()})}const mt=createSqliteReadOnlyWorkerPool(createScopedSqliteReadOnlyWorker);function runSqliteReadOnlyWorkerOnce(e,t,n){if(t.mode===`auth-profile-rows`||t.mode===`operation`)return mt.run(e,t,captureSqliteReadOnlyWorkerLaunch(t.env,t.source));let{argv:r,runtimeGeneration:i}=sqliteReadOnlyWorkerArgv(L(e,t));return runOneShotSqliteInspection({pathname:e,operation:`read-only snapshot`,argv:r,runtimeGeneration:i,signal:t.signal,deadlineOwnedByCaller:n?.deadlineOwnedByCaller??isSqliteInspectionDeadlineOwnedByCaller(),env:n?.env,cwd:n?.cwd,stoppedFailure:`snapshot owner stopped`,read:e=>(t.signal?.throwIfAborted(),F(e,t.mode))})}function runOneShotSqliteInspection(e){R();let t=e.mode===`staging-sweep`?`snapshot staging`:e.pathname,n=O(e.env??B()),i=process.execPath,a=e.cwd??r(),o=!1,stop=()=>{o=!0},s=(async()=>{let{timeoutMs:s,size:c}=e.mode===`staging-sweep`?resolveSqliteInspectionBudget(e.operation,t,void 0):await readSqliteInspectionBudgetAsync(e.operation,t);if(e.signal?.throwIfAborted(),o)throw Error(e.stoppedFailure);return new Promise((l,u)=>{let d={kind:`launched`,stderr:``,stdout:``,status:null},f=!1,p=J.execFile(i,e.argv,{encoding:`utf8`,windowsHide:!0,env:n,...a===r()?{}:{cwd:a},maxBuffer:xe,timeout:e.deadlineOwnedByCaller?void 0:s,killSignal:`SIGKILL`},(n,r,i)=>{let a=n?.killed&&n.signal===`SIGKILL`&&n.code==null;d={kind:`launched`,status:p.exitCode,failure:n?o?e.stoppedFailure:a?sqliteInspectionTimeoutError(e.operation,t,s,c).message:`exited unsuccessfully: ${n.message}`:void 0,stderr:i,stdout:r,cause:n??void 0}}),m=we(p),abort=()=>{!o&&!f&&(o=!0,p.kill(`SIGKILL`))};stop=abort;let finishClose=async()=>{f=!0;try{let t=await m();if(t)throw t;l(e.read(d))}catch(e){u(e instanceof Error?e:Error(String(e)))}finally{e.signal?.removeEventListener(`abort`,abort)}};p.once(`close`,()=>{finishClose()}),e.signal?.addEventListener(`abort`,abort,{once:!0}),e.signal?.aborted&&abort()})})();if(e.runtimeGeneration){let t=s.then(()=>void 0,()=>void 0);e.runtimeGeneration.retain(t,()=>t)}return T(s,()=>stop())}function runSqliteReadOnlyWorkerSync(e,t,n=`sync`,r){R();let{timeoutMs:i,size:a}=readSqliteInspectionBudget(`read-only snapshot`,e),o=J.spawnSync(process.execPath,sqliteReadOnlyWorkerArgv(L(e,{mode:n,stagingRoot:t,expectedSourceIdentity:r})).argv,{encoding:`utf8`,windowsHide:!0,stdio:`pipe`,env:O(B()),maxBuffer:xe,timeout:i,killSignal:`SIGKILL`}),s=Ee({error:o.error,stderr:o.stderr,signal:o.signal,started:!!o.stdout});if(s)throw s;let c=o.error?{kind:`launch-failed`,error:Error(d(o.error,`ETIMEDOUT`)?sqliteInspectionTimeoutError(`read-only snapshot`,e,i,a).message:`SQLite read-only worker failed to start for ${e}: ${o.error.message}`,{cause:o.error})}:{kind:`launched`,stdout:o.stdout,stderr:o.stderr,status:o.status,failure:o.status===0?void 0:`exited with ${o.signal?`signal ${o.signal}`:`code ${o.status}`}`};return F(c,n)}function createSqliteReadOnlyNativeResourceConnection(e){let{port1:t,port2:n}=new Ue,r=!1,receive=n=>{let r;try{e.receive(n),r={id:n.id,ok:!0}}catch(e){let t=Le(e,{includeOrdinary:!0});if(!t)throw e;r={id:n.id,ok:!1,error:t}}t.postMessage(r)},fail=n=>{e.onFailure(n),t.close()};return t.on(`message`,e=>{try{receive(e)}catch(e){fail(e)}}),t.on(`messageerror`,fail),{port:n,service(){if(!r)for(;;){let e=We(t);if(!e)return;try{receive(e.message)}catch(e){throw fail(e),e}}},decodeCloseError(e){let t=/* @__PURE__ */ Error(`SQLite snapshot staging failed`);W(t,e);let n=U(t,{includeOrdinary:!0});return n instanceof AggregateError?n:new A(n.message,{cause:n})},dispose(){r=!0,t.removeAllListeners(),t.close(),n.close()}}}function decodeSqliteSnapshotStagingError(e){let t=/* @__PURE__ */ Error(`SQLite snapshot staging failed`);W(t,e);let n=U(t,{includeOrdinary:!0});return n.name===`SqliteSnapshotDirectoryBusyError`?new ne(n.message,{cause:n.cause}):n}function completed(){let e=M(()=>{});return e.resolve(void 0),e.operation}function createStagingOwner(e,t){let n=t.captureResource(N(`sqliteReadOnlyNativeResource`),`sqliteSnapshotNativeResource`,void 0,connectNativeResource),r=Pe({workerUrl:e,workerClass:`writer`,idleTimeoutMs:0,maxPendingTasks:128,maxPendingBytes:Me},{retainedTransport:!0,nativeSource:t,nativeResource:n,databaseAccess:`read-only`,decodeResourceError:e=>decodeSqliteSnapshotStagingError(e)}),i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o=0,s=/* @__PURE__ */ new Set,c=!1,l=0,u=!1,d,f;function connectNativeResource(){return createSqliteReadOnlyNativeResourceConnection({receive(e){let t=e.directory;if(e.type===`allocated`){let n=a.get(e.preparationId);if(!n)throw new A(`SQLite snapshot preparation custody is unavailable`);n.directories.add(t),retainDirectory(t,e.preparationId)}else if(e.type===`retire`){if(!i.has(t))throw new A(`SQLite snapshot native custody is unavailable`);te(t,{requireRequested:!0})}},onFailure(e){f??={error:e}}})}let serviceRequests=()=>{if(!c){c=!0;try{for(let e of s)e.service();for(let e of Array.from(a.values()))e.serviceClose()}finally{c=!1}}},closeWhenIdle=()=>d?.read().status===`pending`?d:l>0||i.size>0?completed():d=j(ue(r.startCloseResources(),()=>l>0||i.size>0?completed():r.startRotate()),()=>{f=void 0}),retainDirectory=(e,t)=>{let n=i.get(e);if(n)return n;let o,startRetire=()=>{if(o&&o.read().status!==`rejected`)return o;try{te(e)}catch(e){let t=M(()=>{});return t.reject(e),t.operation}return o=ue(r.startCloseResources(e),()=>{if(i.delete(e),t!==void 0){let n=a.get(t);n?.directories.delete(e),n?.releaseIfComplete()}return closeWhenIdle()})},s={directory:e,startRetire};return i.set(e,s),E(e,startRetire),s},p={start:(e,t)=>{if(u)throw Error(`SQLite snapshot staging owner is closing`);let n=++o,i=Buffer.byteLength(JSON.stringify({...e,preparationId:n})),c=e.type===`prepare`?new Ue:void 0,abort=()=>{c&&(c.port1.postMessage({type:`abort`}),me(`resource`,`to_worker`))},d=e.type===`prepare`&&c?{...e,preparationId:n,abortPort:c.port2}:{...e,preparationId:n};l++;let p,m={directories:/* @__PURE__ */ new Set,abort(){h.read().status===`pending`&&abort()},startClose,serviceClose:()=>p?.service(),releaseIfComplete(){v?.read().status!==`pending`&&m.directories.size===0&&a.delete(n)}};a.set(n,m);let h=r.startTask(()=>{if(f!==void 0)throw f.error;return t?.throwIfAborted(),t?.addEventListener(`abort`,abort,{once:!0}),d},{inputBytes:i,transferList:()=>c?[c.port2]:[]}),g,_=j(h,e=>{if(e.type===`failed`){let t=decodeSqliteSnapshotStagingError(e.error);throw e.cleanupFailure&&!(t instanceof AggregateError)?new A(String(t),{cause:t}):t}return e}),v=le(_,()=>g=le(h.release(),()=>(t?.removeEventListener(`abort`,abort),c?.port1.close(),c?.port2.close(),l--,closeWhenIdle())),(e,t)=>k([e,t],`SQLite snapshot staging failed`,e));function startClose(){if(p?.read().status===`pending`)return p;let e,t=!1,n=M(()=>{if(!(t||n.operation.read().status!==`pending`)){t=!0;try{if(serviceRequests(),v.service(),v.read().status===`pending`)return;e??=[...m.directories].map(e=>{let t={},r=D(e,e=>{t.cause=e});return r.result.then(()=>n.operation.service(),()=>n.operation.service()),[e,r,t]});for(let[t,n,r]of e){n.service();let e=n.read();if(e.status===`pending`)return;if(e.status===`rejected`)throw e.error;if(!e.value)throw new A(`SQLite staging preparation cleanup failed: ${t}`,r)}let t=g?.read();if(t?.status===`rejected`)throw t.error;m.releaseIfComplete(),n.resolve(void 0)}catch(e){n.reject(e)}finally{t=!1}}});return p=n.operation,v.result.then(()=>n.operation.service(),()=>n.operation.service()),n.operation.service(),n.operation}let finish=()=>{s.delete(v),m.releaseIfComplete()};return v.result.then(finish,finish),v.read().status===`pending`?s.add(v):finish(),{...v,service:serviceRequests,startClose}},retainDirectory};return t.retain(p,async()=>{u=!0;for(let e of a.values())e.abort();await Promise.allSettled([...s].map(e=>e.result));let e=Array.from(a.values()).map(e=>e.startClose()),t=(await Promise.allSettled(e.map(e=>e.result))).flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(t.length)throw k(t,`SQLite snapshot generation cleanup failed`,t[0]);await closeWhenIdle().result,await r.close()}),p}function captureSqliteSnapshotStagingOwner(){let{moduleUrl:e,runtimeGeneration:n}=P(N(`sqliteSnapshotStaging`)),r=Ne({runtimeGeneration:n}),a=t(Symbol.for(`openclaw.sqliteSnapshotStagingOwner`),()=>/* @__PURE__ */ new WeakMap),o=a.get(r);return o||(o=i(()=>createStagingOwner(e,r)),a.set(r,o)),o}export{isValidAgentId as A,tt as C,isSameOpenClawAgentDatabasePath as D,isPersistentOpenClawAgentDatabasePath as E,err as M,ok as N,resolveIncognitoOpenClawAgentSqlitePath as O,toStringifiedError as P,createStateWorkerMemoryPressureSubscription as S,isIncognitoOpenClawAgentSqlitePath as T,registerOpenClawAgentDatabaseReadCandidateResource as _,readSqliteInspectionBudget as a,lt as b,runSqliteReadOnlyWorkerOnce as c,withSqliteReadOnlyWorkerScope as d,assertAgentDatabaseResourceAdmission as f,registerOpenClawAgentDatabaseAsyncResource as g,registerAgentDatabaseResourceReleaseHandler as h,isSqliteInspectionDeadlineOwnedByCaller as i,normalizeAgentId as j,resolveOpenClawAgentSqlitePath as k,runSqliteReadOnlyWorkerSync as l,matchesAgentDatabaseClose as m,captureSqliteReadOnlyWorkerLaunch as n,runSqliteReadOnlyOperation as o,hasOpenClawAgentDatabaseAsyncResources as p,createScopedSqliteReadOnlyWorker as r,runSqliteReadOnlyWorker as s,captureSqliteSnapshotStagingOwner as t,sqliteInspectionTimeoutError as u,revokeAgentDatabaseResources as v,createOpenClawAgentDatabasePathMatcher as w,releaseAgentCreationClaimHandle as x,releaseAgentDeletionDatabaseCleanup as y};