openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1 lines • 59.1 kB
JavaScript
import{F as e,V as t,ht as n,st as r}from"./openclaw-state-read-map-size-DJbMcZYM.mjs";import{o as i,v as a}from"./openclaw-state-read-home-dir-BQZX1pD2.mjs";import{Xt as o,an as s,c,o as l,on as u}from"./openclaw-state-read-sqlite-database-admission-Ck6VG7rE.mjs";import{r as d}from"./openclaw-state-read-src-BpoB6DKe.mjs";import{t as f}from"./openclaw-state-read-promise-like-3qqJObCs.mjs";import{a as p}from"./openclaw-state-read-tmp-openclaw-dir-C3Ynn93H.mjs";import{Z as m}from"./openclaw-state-read-logger-Ix7jXPG1.mjs";import{a as h,c as g,u as _}from"./openclaw-state-read-sqlite-lifecycle-errors-3AcFJUep.mjs";import{F as v,L as ee,R as y,_ as b,k as x,p as S,v as C,x as w}from"./openclaw-state-read-read-open-flags-CtNL1rJs.mjs";import{E as T,G as te,I as ne,M as re,ht as E,lt as ie,mt as ae}from"./openclaw-state-read-root-symlink-policy-AldRD6ik.mjs";import{t as oe}from"./openclaw-state-read-deferred-B75K7ut7.mjs";import{s as D}from"./openclaw-state-read-openclaw-state-db.paths-CFemYLpA.mjs";import{f as se,s as ce}from"./openclaw-state-read-openclaw-state-db-async-lifecycle-B_Y330HB.mjs";import{a as O}from"./openclaw-state-read-record-coerce-D1s3ReAs.mjs";import{t as le}from"./openclaw-state-read-runtime-process-entrypoints-ItwYqjQs.mjs";import{t as ue}from"./openclaw-state-read-runtime-worker-url-ClM3d-g2.mjs";import{c as k,t as de}from"./openclaw-state-read-sqlite-worker-request-class-Coonj2Xz.mjs";import{t as A}from"./openclaw-state-read-subsystem-DSi0tJn8.mjs";import{n as fe,t as pe}from"./openclaw-state-read-runtime-worker-generation-CoxNB-TF.mjs";import{a as me,b as he,i as ge,o as _e,s as j,t as ve}from"./openclaw-state-read-sqlite-snapshot-capacity-error-Df9fZtJA.mjs";import{t as ye}from"./openclaw-state-read-errors-D_saNBXy.mjs";import{b as be}from"./openclaw-state-read-sqlite-schema-facts-DxLfPKu-.mjs";import{_ as xe,a as Se,g as M,n as Ce,u as N}from"./openclaw-state-read-worker-request-diagnostics-CbvzxbuX.mjs";import{i as we}from"./openclaw-state-read-error-graph-internal-BY0i7Ouv.mjs";import{n as Te}from"./openclaw-state-read-execa-protocol-BrSZNRnu.mjs";import"./openclaw-state-read-context-D0V7bHDr.mjs";import{i as Ee,n as De,r as Oe,t as P}from"./openclaw-state-read-child-runtime-viability-CqVmSQzb.mjs";import{t as F}from"./openclaw-state-read-child-C4Er8s0x.mjs";import{t as ke}from"./openclaw-state-read-spawn-diagnostics-CpCgfk1o.mjs";import{n as I}from"./openclaw-state-read-agent-id-DmscQLD6.mjs";import{deserialize as Ae,serialize as je}from"node:v8";import L,{realpathSync as Me,statSync as Ne}from"node:fs";import R from"node:path";import{threadId as Pe}from"node:worker_threads";import z from"node:child_process";import B from"node:fs/promises";import{tmpdir as Fe}from"node:os";import{createHash as Ie,randomInt as Le}from"node:crypto";import{AsyncLocalStorage as V}from"node:async_hooks";import{isDeepStrictEqual as Re,toUSVString as ze}from"node:util";import{channel as Be}from"node:diagnostics_channel";import{Socket as Ve}from"node:net";function toStringifiedError(e){return e instanceof Error?e:Error(String(e))}const He=[`byte`,`kilo`,`mega`,`giga`,`tera`],Ue={iec:{base:1024,labels:[`B`,`KiB`,`MiB`,`GiB`,`TiB`]},"legacy-binary":{base:1024,labels:[`B`,`KB`,`MB`,`GB`,`TB`]}};function formatByteSize(t,n){let{base:r,labels:i}=Ue[n.style],a=He.indexOf(n.maxUnit),o=0,s=t;for(;s>=r&&o<a;)s/=r,o+=1;for(;;){let t=e(He[o],`byte-size unit`),c=e(i[o],`byte-size label`),l=typeof n.fractionDigits==`function`?n.fractionDigits(s,t):n.fractionDigits;if(l===null)return`${s}${n.separator}${c}`;let u=n.floorUnits?.includes(t)?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)}${n.separator}${c}`}}function rawRoot(e){if(R.sep===`\\`&&/^\\\\[?.]\\UNC\\/i.test(e)){let t=R.parse(`\\\\${e.slice(8)}`).root;return e.slice(0,t.length+6)}return R.parse(e).root}function resolutionError(e,t){return Object.assign(/* @__PURE__ */ Error(`${e}: ${e===`ELOOP`?`too many symbolic links`:`not a directory`}, resolvePathPrefix ${re(t)}`),{code:e,syscall:`resolvePathPrefix`,path:t})}function*read(e){let t;return yield async()=>{t=await e()},t}function*resolvePrefix(e,t=!1){b(e);let n=T(e),r=rawRoot(n),i=n.slice(r.length).split(R.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=v(r),o=`${a}${a.endsWith(R.sep)?``:R.sep}${i}`;t?L.lstatSync(o,{bigint:!0}):yield*read(()=>B.lstat(o,{bigint:!0})),e===`..`&&!n&&(r=R.dirname(r));continue}let u=R.join(r,e),d;try{d=t?L.lstatSync(u,{bigint:!0}):yield*read(()=>B.lstat(u,{bigint:!0}))}catch(s){if(!C(s,`ENOENT`))throw s;return{absolutePath:n,existingPath:t?E.native(v(r)):yield*read(()=>ae(v(r))),unresolvedSegments:a?[e,...i]:i.slice(o-1)}}if(!d.isSymbolicLink()){if(!d.isDirectory()&&s>0)throw resolutionError(`ENOTDIR`,n);r=u;continue}let f=a?i:i.slice(o),p=JSON.stringify([String(d.dev),String(d.ino),u,f]);if(l>=64||c.has(p))throw resolutionError(`ELOOP`,n);c.add(p),l++;let m=t?L.readlinkSync(u):yield*read(()=>B.readlink(u)),h=R.sep===`\\`?m.replaceAll(`/`,`\\`):m,g;if(R.isAbsolute(h)){let e=rawRoot(h);r=R.sep===`\\`&&e===`\\`?rawRoot(r):e,g=h.slice(e.length).split(R.sep)}else g=h.split(R.sep);g.length+f.length<=32?(i=f,i.unshift(...g)):i=g.concat(f),s=i.length,a=s<=32,o=0}return{absolutePath:n,existingPath:t?E.native(v(r)):yield*read(()=>ae(v(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 H=32768;function unavailable(){throw Error(`path suffix probe resources or cleanup authority are unavailable`)}function assertMutationPath(e){e.length>H&&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`)||R.isAbsolute(e))throw TypeError(`suffix must be a relative path without NUL bytes`);let n=process.platform===`win32`,r=(n?e.replaceAll(`/`,`\\`):e).split(R.sep);if(r.length>t)throw RangeError(`suffix exceeds ${t} components`);if(r.some(e=>!e||e===`.`||e===`..`||n&&(e.includes(`:`)||/^[ .]+$/u.test(e)||x(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+Le(26))])),s=replaceAscii(e,o),c=replaceAscii(t,o);if(s.length>r||c.length>r||!areAsciiCaseVariants(s.normalize(`NFC`),c.normalize(`NFC`))||x(s)||x(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[Le(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=E.native(v(e));assertMutationPath(r),this.observe(2),this.root={path:r,identity:te(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),E.native(v(this.requestedDirectory))!==this.root.path)throw new y(`path-mismatch`,`probe directory changed`);for(let n=e;n;n=n.parent)this.observe(2,t),ne(n.path,n.identity)}create(e,t){(this.mkdirAttempts>=this.maxMkdirAttempts||this.creations>=this.maxCreations)&&unavailable();let n=R.join(e.path,t);assertMutationPath(n),this.assert(e),this.reserveObservations(2),this.mkdirAttempts++;try{L.mkdirSync(n)}catch(e){if(C(e,`EEXIST`))return;throw e}this.creations++,this.observe(2);let r={path:n,identity:te(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),L.rmdirSync(e.path),!0}catch{return!1}}probe(e,t){for(let[n,r]of t){let t=R.join(e.path,r);assertMutationPath(t);let i=this.create(e,n);if(!i)continue;let a;this.observe(2);try{a=S(()=>L.lstatSync(t,{bigint:!0}))}catch(e){if(!C(e,`ENOENT`))throw e}if(this.assert(i),!a)return{aliases:!1,directory:i};if(a.isDirectory()&&!a.isSymbolicLink()&&ie(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(R.join(p.root.path,t.join(R.sep)).length,R.join(p.root.path,n.join(R.sep)).length);let m=i-a.path.length-+!a.path.endsWith(R.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>H)throw RangeError(`directory exceeds 32768 code units`);if(t.includes(`\0`))throw TypeError(`directory must be a path without NUL bytes`);let n=ee(t);if(n.length>H)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,f,p=!0;try{f=observeSuffixes(()=>d??=new ProbeDirectories(n,c.length),c,l,shouldProbe),d?.assert(d.root)}catch{if(f=void 0,u)throw u.error}finally{d&&(p=d.cleanup())}return p?f:void 0}const U=a(Symbol.for(`openclaw.artifactPreservingStateReads`),()=>new V),W=a(Symbol.for(`openclaw.liveStateReads`),()=>new V);function withLiveStateReads(e,t){return W.run(t?.startupConfig?`startup-config`:`runtime`,e)}function isLiveStateRead(){return W.getStore()!==void 0}function isStartupConfigStateRead(){return W.getStore()===`startup-config`}function withArtifactPreservingStateReads(e,t={}){if(isArtifactPreservingStateRead(`agent`))return e();let n={agentDatabases:t.agentDatabases===!0,readers:/* @__PURE__ */ new Set,privateRoots:/* @__PURE__ */ new Set,snapshots:/* @__PURE__ */ new Map},closeReaders=e=>{for(let t of n.readers)try{t()}catch(t){e.push(t)}},finish=(e,t=[])=>{closeReaders(t);for(let e of n.snapshots.values())try{if(!e.cleanup())throw new h(`SQLite inspection snapshot cleanup failed.`)}catch(e){t.push(e)}return _(t,`Artifact-preserving inspection and cleanup failed.`),e},finishAsync=async(e,t=[])=>{closeReaders(t);for(let e of n.snapshots.values())try{if(!await e.cleanupAsync())throw new h(`SQLite inspection snapshot cleanup failed.`)}catch(e){t.push(e)}return _(t,`Artifact-preserving inspection and cleanup failed.`),e},r;try{r=U.run(n,e)}catch(e){return finish(void 0,[e])}return f(r)?Promise.resolve(r).then(finishAsync,e=>finishAsync(void 0,[e])):finish(r)}function isArtifactPreservingStateRead(e=`shared`,t){let n=U.getStore();return!(!n||e!==`shared`&&!n.agentDatabases||t&&[...n.privateRoots].some(e=>w(e,t)))}const We=/* @__PURE__ */ new Set([`--no-maglev`,`--maglev`,`--no-concurrent-sparkplug`,`--concurrent-sparkplug`]);function resolveForwardedNodeCompilerArgs(){return process.execArgv.filter(e=>We.has(e.replaceAll(`_`,`-`)))}const Ge=Be(`openclaw.memory.critical`);function createStateWorkerMemoryPressureSubscription(e,t){let n=!1,onPressure=e=>t(e===!0);return()=>{let t=e();t!==n&&(n=t,t?Ge.subscribe(onPressure):Ge.unsubscribe(onPressure))}}const Ke={"startupMetadata.readCurrent":`retire-after-result`,"startupMetadata.rollbackRecoveryRequired":`retire-after-result`};function sqliteReadOnlyOperationRequiresProcessRetirement(e){return e in Ke}const qe=`incognito-openclaw-agent.sqlite`,G=/* @__PURE__ */ new Map,Je=G.keys();function resolveOpenClawAgentSqlitePath(e){if(e.path!=null)return R.resolve(e.path);let t=I(e.agentId),n=p(e.env??process.env),r=`${t}:${n}`,i=G.get(r);if(i!==void 0)return i;let a=R.resolve(n,`agents`,t,`agent`,`openclaw-agent.sqlite`);if(G.set(r,a),G.size>256){let e=Je.next();e.done||G.delete(e.value)}return a}function resolveIncognitoOpenClawAgentSqlitePath(e){return R.join(R.dirname(resolveOpenClawAgentSqlitePath(e)),qe)}function isIncognitoOpenClawAgentSqlitePath(e,t){let n=R.resolve(e);return R.basename(n)===`incognito-openclaw-agent.sqlite`&&n===resolveIncognitoOpenClawAgentSqlitePath(t)}function resolveExplicitIncognitoAgentSqliteTarget(e,t={}){if(!e||R.basename(e)!==`incognito-openclaw-agent.sqlite`)return;let n=R.resolve(e),r=I(t.agentId??R.basename(R.dirname(R.dirname(n)))),i=t.env??{OPENCLAW_STATE_DIR:R.resolve(n,`../../../..`)};if(!isIncognitoOpenClawAgentSqlitePath(n,{agentId:r,env:i}))throw Error(`Explicit incognito database target does not match its agent and state root`);return{agentId:r,env:i,path:n}}const K=/* @__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(R.sep),n=e.right.split(R.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=K.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 K.set(i,o),o}function anchorDatabasePathWithoutNormalizing(e){let t=R.sep===`\\`?e.replaceAll(`/`,`\\`):e;if(R.isAbsolute(t))return t;if(R.sep===`\\`){let e=/^([A-Za-z]:)(.*)$/u.exec(t);if(e){let t=R.resolve(`${e[1]}.`);return e[2]?`${t}${t.endsWith(R.sep)?``:R.sep}${e[2]}`:t}}let n=process.cwd();return`${n}${n.endsWith(R.sep)?``:R.sep}${t}`}function resolveAgentDatabasePathIdentity(e){let t=anchorDatabasePathWithoutNormalizing(e);try{let e=Me.native(t),n=Ne(e,{bigint:!0});return{lexicalPath:t,realPath:e,device:n.dev.toString(),inode:n.ino.toString()}}catch(e){if(!C(e,`ENOENT`))throw e;let n=R.parse(t).root,r=resolvePathPrefixSync(n+t.slice(n.length).split(R.sep).filter(Boolean).join(R.sep)),i=r.existingPath,a=Ne(i,{bigint:!0});return{lexicalPath:t,parentDevice:a.dev.toString(),parentInode:a.ino.toString(),parentRealPath:i,unresolvedSuffix:r.unresolvedSegments.join(R.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(!Re(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(R.sep);return n.includes(`..`)?t.parentRealPath:R.join(t.parentRealPath,...n)}function isPersistentOpenClawAgentDatabasePath(e,t=process.env){let n=R.resolve(e),r=R.join(R.resolve(p(t)),`imports`);if(w(r,n))return!1;let i=canonicalPathForRegistryBoundary(e),a=canonicalPathForRegistryBoundary(p(t)),o=canonicalPathForRegistryBoundary(R.join(a,`imports`));return!w(o,i)}const q=a(Symbol.for(`openclaw.agentCreationClaim`),()=>new V),J=a(Symbol.for(`openclaw.agentCreationClaimResources`),()=>/* @__PURE__ */ new Map);function getActiveAgentCreationClaim(e,t){let n=q.getStore();if(n&&n.kind===`host`&&n.isActive()&&n.agentId===I(e)&&n.statePath===R.resolve(t))return n}function resolveAgentCreationClaimAgentId(e,t){let n=q.getStore();return n&&n.kind===`worker`&&n.agentId===I(e)&&n.statePath===R.resolve(t)?(n.assertCurrent(),n.agentId):getActiveAgentCreationClaim(e,t)?.agentId}function captureAgentCreationClaim(e){let t=getActiveAgentCreationClaim(e.agentId,D(e.env??process.env));if(t)return{witness:{agentId:t.agentId,statePath:t.statePath},assertCurrent(){if(!t.isActive()||q.getStore()!==t)throw Error(`Agent database belongs to an active agent creation claim.`)}}}function reserveAgentCreationClaimAdmission(e,t,n){let r=getActiveAgentCreationClaim(t.agentId,D(t.env??process.env));if(r)return J.set(e,r),r.registerClose(async()=>{J.get(e)===r&&(await n(),J.delete(e))}),()=>{J.delete(e)}}function registerAgentCreationClaimHandle(e,t){let n=getActiveAgentCreationClaim(t.agentId,D(t.env??process.env));return n&&J.set(e,n),n}function assertAgentCreationClaimAccess(e,t){assertAgentCreationClaimCurrent(t);let n=J.get(e);if(n&&n!==getActiveAgentCreationClaim(t.agentId,D(t.env??process.env)))throw Error(`Agent database belongs to an active agent creation claim.`)}function assertAgentCreationClaimCurrent(e){let t=q.getStore();if(t&&t.kind===`host`&&!t.isActive()&&t.agentId===I(e.agentId)&&t.statePath===R.resolve(D(e.env??process.env)))throw Error(`Agent creation claim is no longer active.`)}function assertAgentCreationClaimAliases(e){let t=resolveOpenClawAgentSqlitePath(e);for(let n of J.keys())isSameOpenClawAgentDatabasePath(n.path,t)&&assertAgentCreationClaimAccess(n,e)}function releaseAgentCreationClaimHandle(e){J.delete(e)}const Ye=a(Symbol.for(`openclaw.agentDatabaseExecutionAdmissionClosedError`),()=>class extends Error{}),Xe=a(Symbol.for(`openclaw.agentDatabaseSchemaAdmissionChangedError`),()=>class extends Error{constructor(){super(`Agent schema admission changed before publication; retry the operation`)}}),Ze=a(Symbol.for(`openclaw.agentDatabaseSchemaAdmissionInvalidError`),()=>class extends Error{constructor(){super(`Invalid agent schema admission receipt`)}}),Qe=a(Symbol.for(`openclaw.agentDatabaseStartupPublicationError`),()=>class extends Error{constructor(e){super(ye(e),{cause:e})}}),$e=a(Symbol.for(`openclaw.agentDeletionDatabaseCleanup`),()=>new V),Y=a(Symbol.for(`openclaw.agentDeletionDatabaseCleanupHandles`),()=>/* @__PURE__ */ new Map),X=a(Symbol.for(`openclaw.agentDeletionDatabaseCleanupExecutions`),()=>/* @__PURE__ */ new Map);function getAgentDeletionDatabaseCleanup(e){let t=$e.getStore();if(!t)return;let n=resolveOpenClawAgentSqlitePath(e);if(t.agentId!==I(e.agentId)||t.path!==n&&t.canonicalPath!==n)return;let r=e.statePath??D(e.env??process.env);if(t.statePath!==R.resolve(r))throw Error(`Agent deletion database cleanup belongs to another state database.`);return t}function captureAgentDeletionResourceOwner(e){let t=$e.getStore();if(t?.ownsDatabase&&(e(t)||t.canonicalPath&&e({agentId:t.agentId,path:t.canonicalPath})))return t.assertCurrentHost(),t}function assertAgentDeletionDatabaseCleanupAccess(e,t){let n=getAgentDeletionDatabaseCleanup(t),r=Y.get(e);if(r&&r!==n)throw Error(`Agent database belongs to an active deletion cleanup.`);n?.assertCurrent()}function assertAgentDeletionCleanupAliases(e,t){let n=resolveOpenClawAgentSqlitePath(e);for(let r of Y.keys())t(r.path,n)&&assertAgentDeletionDatabaseCleanupAccess(r,e);for(let r of X.values())if(t(r.path,n)&&getAgentDeletionDatabaseCleanup(e)!==r)throw Error(`Agent database belongs to an active deletion cleanup.`)}function assertAgentDeletionExecutionCleanupAccess(e,t){let n=X.get(e),r=getAgentDeletionDatabaseCleanup(t);if(n&&n!==r)throw Error(`Agent database belongs to an active deletion cleanup.`);r?.assertCurrentHost()}function registerAgentDeletionExecutionCleanup(e,t,n){let r=getAgentDeletionDatabaseCleanup(t);r?.worker&&r.ownsDatabase&&(r.assertCurrentHost(),X.get(e)!==r&&(X.set(e,r),r.registerClose(async()=>{await n(),X.delete(e)})))}function registerAgentDeletionDatabaseCleanup(e,t){let n=getAgentDeletionDatabaseCleanup(t);if(n?.assertCurrent(),n?.ownsDatabase&&!n.workerOwned)return Y.set(e,n),n}function releaseAgentDeletionDatabaseCleanup(e){Y.delete(e)}const Z=a(Symbol.for(`openclaw.agentDatabaseAsyncResources`),()=>({active:/* @__PURE__ */ new Set,closing:/* @__PURE__ */ new Map,selections:/* @__PURE__ */ new Map}));function hasOpenClawAgentDatabaseAsyncResources(e){return e?[...Z.active,...Z.closing.keys()].some(t=>matchesAgentDatabaseClose(e,t)):Z.active.size>0||Z.closing.size>0}function registerAgentDatabaseResourceReleaseHandler(e){Z.onRelease=e}xe(async(e,t)=>{let n=(await Promise.allSettled([.../* @__PURE__ */ new Set([...Z.active,...Z.closing.keys()])].filter(n=>!t?.has(R.resolve(n.path))&&e.some(e=>M(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`&&M(t,e.path))&&(e.rootPath===void 0||w(e.rootPath,t.path)||t.ownership===`unresolved`&&M(t,e.rootPath))&&(e.agentId===void 0||t.ownership===`unresolved`||e.agentId===t.agentId)}function registerOpenClawAgentDatabaseAsyncResource(e,t){return registerAgentDatabaseResource({...e,ownership:`known`,agentId:I(e.agentId)},t)}function registerOpenClawAgentDatabaseSyncResource(e){return registerAgentDatabaseResource({...e,ownership:`known`,agentId:I(e.agentId),close:async()=>e.close(),closeSync:e.close})}function registerOpenClawAgentDatabaseReadCandidateResource(e){return registerAgentDatabaseResource({...e,ownership:`unresolved`})}function registerAgentDatabaseResource(e,t){let n={...e,path:R.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=()=>{Z.active.delete(n),r?.(),Z.onRelease?.(n)};return ce()?.own(unregister,`agent-resources`,()=>closeAgentDatabaseResource(n)),Z.active.add(n),unregister}function assertAgentDatabaseResourceAdmission(e){if([...Z.selections.keys()].some(t=>matchesAgentDatabaseClose(t,e))||[...Z.closing.keys()].some(t=>(t.path===e.path||t.ownership===`unresolved`&&M(t,e.path)||e.ownership===`unresolved`&&M(e,t.path))&&(t.ownership===`unresolved`||e.ownership===`unresolved`||t.agentId===e.agentId)))throw new Ye(`Agent database resources are closing: ${e.path}`)}function closeAgentDatabaseResource(e,t){if(e.ownership===`known`&&e.closeSync){Z.closing.set(e,void 0);try{return e.revoke(),e.closeSync(),Z.active.delete(e),Z.closing.delete(e),Z.onRelease?.(e),Promise.resolve()}catch(r){t&&t(e.path,r);let i=Promise.reject(n(r,`Agent database cleanup failed`));return i.catch(()=>{}),i}}let r=Z.closing.get(e);return r||(r=Promise.resolve().then(()=>e.close()),Z.closing.set(e,r),r.then(()=>{Z.active.delete(e),Z.closing.delete(e),Z.onRelease?.(e)},()=>{Z.closing.set(e,void 0)}).catch(()=>{})),t&&r.catch(n=>t(e.path,n)).catch(()=>{}),e.revoke(),r}function revokeAgentDatabaseResources(e,t){let n=/* @__PURE__ */ new Set([...Z.active,...Z.closing.keys()]),r=[];for(let i of n)matchesAgentDatabaseClose(e,i)&&r.push(closeAgentDatabaseResource(i,t));return r}async function drainAgentDatabaseResources(e,t,n){return withAgentDatabaseCloseFence(e,async()=>{let r=performance.now(),i=[.../* @__PURE__ */ new Set([...Z.active,...Z.closing.keys()])].filter(t=>matchesAgentDatabaseClose(e,t)&&(!n||t.cleanupOwner===n)),a=i.filter(e=>e.retireAfterResources);for(let e of a)Z.closing.has(e)||Z.closing.set(e,void 0),e.revoke();let o=await Promise.allSettled(i.filter(e=>!e.retireAfterResources).map(e=>closeAgentDatabaseResource(e))),s=performance.now(),c=o.flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(c.length>0)throw AggregateError(c,`Agent database resource drainage failed`);let l=await Promise.allSettled(a.map(e=>closeAgentDatabaseResource(e))),u=performance.now(),d=l.flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(d.length>0)throw AggregateError(d,`Agent database native retirement failed`);let f=await t(),p=performance.now()-r;if(p>=500&&e.path){let t=Ie(`sha256`).update(e.path).digest(`hex`).slice(0,16),n={totalMs:Math.round(p),resourceJoinMs:Math.round(s-r),workerJoinMs:Math.round(u-s),nativeOwnerMs:Math.round(p-(u-r))};A(`state/agent-db`).info(`agent database close settled: agent=${e.agentId??i.find(e=>e.ownership===`known`)?.agentId??`unknown`}; db=${t}; thread=${Pe}; close=${JSON.stringify(n)}`)}return f})}async function withAgentDatabaseCloseFence(e,t){let n={...e};Z.selections.set(n,void 0);try{let e=t([.../* @__PURE__ */ new Set([...Z.active,...Z.closing.keys()])].filter(e=>matchesAgentDatabaseClose(n,e)).map(e=>e.path));return Z.selections.set(n,e),await e}finally{Z.selections.delete(n)}}function captureSqliteAuthSchema(e,t){if(c(e)?.key!==t)return;let n=l(e,be,()=>void 0);if(!n)return;let kind=e=>n.tables.has(e)?`table`:n.views.has(e)||n.indexes.has(e)||n.triggers.has(e)?`other`:`missing`;return{userVersion:n.userVersion,store:kind(`auth_profile_store`),state:kind(`auth_profile_state`)}}function isJsonTransferField(e){return O(e)?e.kind===`object`||e.kind===`array`||e.kind===`end`||(e.kind===`key`||e.kind===`value`)&&(e.append===void 0||e.append===!0&&typeof e.value==`string`)&&(typeof e.value==`string`||e.kind===`value`&&(e.value===null||typeof e.value==`boolean`||typeof e.value==`number`)):!1}function createJsonFieldReceiver(){let e,t=!1,n=[],r,write=r=>{let i=n.at(-1);if(i){if(i.key===void 0)throw Error(`JSON field has no property key`);Object.defineProperty(i.container,i.key,{value:r,writable:!0,enumerable:!0,configurable:!0}),i.key=void 0}else{if(t)throw Error(`JSON transfer has more than one root`);e=r,t=!0}},flush=()=>{if(!r)return;let e=r.chunks.join(``);if(r.kind===`key`){let t=n.at(-1);if(!t||t.key!==void 0)throw Error(`JSON property key has no value or container`);t.key=e}else write(e);r=void 0};return{accept(e){if(!isJsonTransferField(e))throw Error(`Invalid JSON transfer field`);if(e.kind===`key`||e.kind===`value`){if(e.append){if(!r||r.kind!==e.kind||typeof e.value!=`string`)throw Error(`Invalid JSON string continuation`);r.chunks.push(e.value);return}flush(),typeof e.value==`string`?r={kind:e.kind,chunks:[e.value]}:write(e.value)}else if(flush(),e.kind===`end`){let e=n.pop();if(!e||e.key!==void 0)throw Error(`JSON container ended with an incomplete field`)}else{let t=e.kind===`array`?[]:{};write(t),n.push({container:t})}},finish(){if(flush(),n.length)throw Error(`JSON transfer ended with an incomplete container`);return e}}}function createSqliteWorkerTransferOwner(){let e=0,t,cleanup=e=>{let t=[];for(let[n,r]of[[`iteratorClosed`,()=>e.iterator.return?.()],[`cleaned`,()=>e.cleanup?.()]])if(!e[n])try{r(),e[n]=!0}catch(e){t.push(e)}_(t,`SQLite read transfer cleanup failed`)},cancel=()=>{t&&=(cleanup(t),void 0)},requireTransfer=e=>{if(!t||t.id!==e)throw Error(`SQLite read transfer is no longer active`);return t};return{start(n,r){if(t)throw Error(`The preceding SQLite read transfer was not released`);return t={id:++e,iterator:n,cleanup:r.cleanup,iteratorClosed:!1,cleaned:!1,counts:new Map(r.kinds.map(e=>[e,0])),sequence:0,finished:!1},{id:t.id,kinds:[...t.counts.keys()]}},next(e){let t=requireTransfer(e);if(t.finished)throw Error(`SQLite read transfer has already reached its end`);if(t.record&&t.record.offset===t.record.bytes.byteLength&&(t.record=void 0),!t.record){let n=t.iterator.next();if(n.done)return cleanup(t),t.finished=!0,{id:e,sequence:t.sequence++,done:!0,counts:[...t.counts]};let{kind:r}=n.value,i=t.counts.get(r);if(i===void 0)throw Error(`SQLite read transfer returned an unexpected record kind`);t.record={kind:r,bytes:`serialized`in n.value?n.value.serialized:je(n.value.value),offset:0},t.counts.set(r,i+1)}let n=t.record,r=n.offset,i=Math.min(n.bytes.byteLength,r+8388608);return n.offset=i,{id:e,sequence:t.sequence++,done:!1,kind:n.kind,recordBytes:n.bytes.byteLength,offset:r,recordDone:i===n.bytes.byteLength,bytes:new Uint8Array(n.bytes.subarray(r,i))}},end(e){if(!requireTransfer(e).finished)throw Error(`SQLite read transfer ended before its complete result`);cancel()},cancel,close:cancel}}function createSqliteWorkerTransferReceiver(e,t){let n=new Map(e.kinds.map(e=>[e,0])),r=0,i=!1,a;return{accept(o){try{if(i||o.id!==e.id||o.sequence!==r++)throw Error(`SQLite read transfer frame is out of order`);if(o.done){if(a||o.counts.length!==n.size||o.counts.some(([e,t])=>n.get(e)!==t)||new Set(o.counts.map(([e])=>e)).size!==n.size)throw Error(`SQLite read transfer ended with an incomplete result`);return i=!0,o.counts}let s=n.get(o.kind);if(s===void 0||!Number.isSafeInteger(o.recordBytes)||o.recordBytes<1||!Number.isSafeInteger(o.offset)||o.offset<0||o.bytes.byteLength<1||o.bytes.byteLength>8388608)throw Error(`SQLite read transfer returned an invalid frame`);if(!a){if(o.offset!==0)throw Error(`SQLite read transfer omitted the start of a record`);a={kind:o.kind,bytes:o.recordDone?o.bytes:new Uint8Array(o.recordBytes),offset:0}}let c=o.offset+o.bytes.byteLength;if(a.kind!==o.kind||a.bytes.byteLength!==o.recordBytes||a.offset!==o.offset||c>o.recordBytes||o.recordDone!==(c===o.recordBytes))throw Error(`SQLite read transfer returned a discontinuous record`);if(a.bytes!==o.bytes&&a.bytes.set(o.bytes,o.offset),a.offset=c,o.recordDone){let e=Ae(a.bytes),r=a.kind;a=void 0,t({kind:r,value:e}),n.set(r,s+1)}return}catch(e){throw a=void 0,i=!0,e}}}}function decodeFrame(e,t){if(e.done)return e;if(e.bytes.length>11184812)throw Error(`Invalid ${t} transfer bytes`);let n=Buffer.from(e.bytes,`base64`);if(n.toString(`base64`)!==e.bytes)throw Error(`Invalid ${t} transfer encoding`);return{...e,bytes:n}}function createSqliteReadOnlyTransferReceiver(e){let t,n,r=!1,i=!1;return{accept(a){if(i)throw Error(`Invalid ${e.label} transfer response`);if(a.type===`start`&&!t){let r=a.handle;if(!Number.isSafeInteger(r.id)||r.id<1||r.kinds.length!==e.kinds.length||r.kinds.some((t,n)=>t!==e.kinds[n]))throw Error(`Invalid ${e.label} transfer handle`);return n=r.id,t=createSqliteWorkerTransferReceiver({id:n,kinds:e.kinds},({kind:t,value:n})=>e.acceptRecord(t,n)),{request:{type:`next`,transferId:n}}}if(!t||n===void 0)throw Error(`${e.label.charAt(0).toUpperCase()}${e.label.slice(1)} transfer has not started`);if(a.type===`frame`&&!r){let i=decodeFrame(a.frame,e.label);if(!i.done&&e.maxRecordBytes&&i.recordBytes>e.maxRecordBytes)throw Error(`${e.label} transfer record exceeds its bound`);let o=t.accept(i);if(o){if(o.length!==e.kinds.length||o.some(([,e])=>e<1))throw Error(`Incomplete ${e.label} transfer result`);r=!0}return{request:{type:r?`end`:`next`,transferId:n}}}if(a.type===`complete`&&r)return i=!0,{value:e.readResult()};throw Error(`${e.label.charAt(0).toUpperCase()}${e.label.slice(1)} transfer response is out of order`)}}}function createSqliteAuthTransferReceiver(){let e=createJsonFieldReceiver();return createSqliteReadOnlyTransferReceiver({kinds:[`fields`],label:`auth profile`,maxRecordBytes:65536,acceptRecord(t,n){if(!Array.isArray(n))throw Error(`Invalid auth profile field batch`);for(let t of n)e.accept(t)},readResult(){let t=e.finish();if(!O(t)||!(`store`in t)||!(`state`in t)||typeof t.cacheable!=`boolean`)throw Error(`Invalid auth profile transfer rows`);return{store:t.store,state:t.state,cacheable:t.cacheable}}})}function createSqliteOperationTransferReceiver(e){let t;return createSqliteReadOnlyTransferReceiver({kinds:[`result`],label:`SQLite operation`,acceptRecord(n,r){if(t||!O(r)||r.operation!==e||!(`value`in r))throw Error(`SQLite read-only worker returned a different or duplicate operation`);t={operation:e,value:r.value}},readResult(){if(!t)throw Error(`SQLite read-only worker returned no operation`);return t}})}const et=1048576;function isSqliteSnapshotStagingMode(e){return e===`staging-create`||e===`staging-create-legacy`||e===`staging-reconcile`||e===`staging-retire`}var SqliteReadOnlyInspectionContentionError=class extends Error{};function sqliteReadOnlyWorkerRequestArgs(e,t){let n=[t.mode,R.resolve(e)];if(t.mode===`task-delivery-recovery`)return[...n,R.resolve(t.recoveryDirectory),R.resolve(t.sourcePath)];let r=t.stagingRoot&&R.resolve(t.stagingRoot);if(t.mode===`private-fork`)return[...n,r??``,JSON.stringify(t.family)];let i=t.mode===`auth-profile-rows`||t.mode===`operation`?void 0:t.expectedSourceIdentity;if(i!==void 0){if(t.mode!==`sync`&&t.mode!==`staged-sync`&&t.mode!==`metadata`)throw Error(`SQLite source identity is supported only for sync or metadata snapshots`);n.push(r??``,JSON.stringify(o(i)))}else r&&n.push(r);return n}function isSqliteReadOnlyWorkerResult(e){return!e||typeof e!=`object`||Array.isArray(e)?!1:`ok`in e&&e.ok===!1&&`message`in e&&typeof e.message==`string`?Object.keys(e).length===2||Object.keys(e).length===3&&`errcode`in e&&typeof e.errcode==`number`&&Number.isInteger(e.errcode)&&e.errcode>=0&&e.errcode<=2147483647:Object.keys(e).length!==2||!(`ok`in e)?!1:e.ok===!0&&`engine`in e&&O(e.engine)&&(e.engine.engine===`sqlite`||e.engine.engine===`postgres`&&typeof e.engine.storeId==`string`&&typeof e.engine.namespace==`string`)||e.ok===!0&&`reclamation`in e&&O(e.reclamation)&&[e.reclamation.removed,e.reclamation.bytes,e.reclamation.skipped].every(e=>typeof e==`number`&&Number.isFinite(e)&&e>=0)||e.ok===!0&&`hasExistingData`in e&&typeof e.hasExistingData==`boolean`||e.ok===!0&&`location`in e&&typeof e.location==`string`||e.ok===!0&&`contentVersion`in e&&typeof e.contentVersion==`string`&&/^(?:[a-f0-9]{64})?$/.test(e.contentVersion)||e.ok===!0&&`generation`in e&&typeof e.generation==`string`||e.ok===!0&&`taskDeliveryRecovery`in e&&O(e.taskDeliveryRecovery)&&Object.keys(e.taskDeliveryRecovery).length===2&&typeof e.taskDeliveryRecovery.count==`number`&&Number.isSafeInteger(e.taskDeliveryRecovery.count)&&e.taskDeliveryRecovery.count>0&&typeof e.taskDeliveryRecovery.payloadSha256==`string`&&/^[a-f0-9]{64}$/u.test(e.taskDeliveryRecovery.payloadSha256)}function createSqliteReadOnlyWorkerError(e,t,n){let r=ze(m(t.trim(),-4e3));return Error(`SQLite read-only worker ${e}${r?`\nstderr (tail): ${r}`:``}`,n)}function parseSqliteReadOnlyWorkerResult(e,t){if(!e.trim())throw createSqliteReadOnlyWorkerError(`returned no JSON result`,t);let n;try{n=JSON.parse(e)}catch{throw createSqliteReadOnlyWorkerError(`returned invalid JSON`,t)}if(!isSqliteReadOnlyWorkerResult(n))throw createSqliteReadOnlyWorkerError(`returned an invalid result`,t);return n}function readSqliteReadOnlyWorkerValue(e,t){if(e.kind===`launch-failed`)throw e.error;let n;try{n=parseSqliteReadOnlyWorkerResult(e.stdout,e.stderr)}catch(t){throw e.failure?createSqliteReadOnlyWorkerError(e.failure,e.stderr,{cause:e.cause}):t}if(e.status!==0||e.failure||!n.ok){let r=!n.ok&&(e.status===0||e.status===1)&&n.message.startsWith(`SQLite snapshot capacity unavailable: `),i=n.ok?e.failure??`exited with code ${e.status}`:r?n.message.slice(38):n.message,a=!n.ok&&i.startsWith(`Retryable SQLite inspection contention: `),o=a?i.slice(40):i,s=e.failure===void 0&&!n.ok&&(t===`staging-create`||t===`staging-create-legacy`)&&o.startsWith(`SQLite snapshot directory creation refused: `),c=createSqliteReadOnlyWorkerError(s?o.slice(44):o,e.stderr,{cause:e.cause});if(n.ok||n.errcode===void 0||t!==`backup-engine`&&t!==`backup-engine-preserving`&&t!==`state-sqlite-populated`||e.status!==0&&e.status!==1||Object.assign(c,{errcode:n.errcode}),r)throw new ve(c.message,{cause:e.cause});if(a){let e=new SqliteReadOnlyInspectionContentionError(c.message);throw s?ge(e):e}throw c}if((t===`sync`||t===`private-fork`||t===`async`||t===`staged-sync`||t===`staged-async`||t===`metadata`||t===`consolidated`||isSqliteSnapshotStagingMode(t))&&`location`in n)return n.location;if(t===`staging-sweep`&&`reclamation`in n)return n.reclamation;if((t===`backup-engine`||t===`backup-engine-preserving`)&&`engine`in n)return n.engine;if(t===`state-sqlite-populated`&&`hasExistingData`in n)return n.hasExistingData;if(t===`content-version`&&`contentVersion`in n)return n.contentVersion;if((t===`file-generation`||t===`update-generation`)&&`generation`in n)return n.generation;if(t===`task-delivery-recovery`&&`taskDeliveryRecovery`in n)return n.taskDeliveryRecovery;throw createSqliteReadOnlyWorkerError(`returned a result for a different operation`,e.stderr)}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){P();let n={...e.env},r=e.cwd,a=process.execPath,o=e.transport.kind===`broker`?{kind:`broker`,owner:e.transport.owner}:{kind:`native`},s={env:n,cwd:r,transport:o,runtimeGeneration:e.runtimeGeneration},c=[...e.argv],l={env:n,...o.kind===`native`&&r===i()?{}:{cwd:r},stdio:[`ignore`,`pipe`,`pipe`,`ipc`],windowsHide:!0},u=o.kind===`broker`?o.owner.spawn(a,c,l):z.spawn(a,c,l);ke(a,u,e.pooledRead?`sqlite.scoped-read.${o.kind}`:`sqlite.session.${o.kind}`);let setIdle=e=>{if(o.kind!==`native`)return;let t=e?`unref`:`ref`;u[t](),u.channel?.[t]?.();for(let e of[u.stdout,u.stderr])e instanceof Ve&&e[t]()},d=!1,f=0,p,h=``,g=0,_,{promise:v,resolve:ee}=oe(),y=/* @__PURE__ */ new Map,b=v.then(async()=>{o.kind===`broker`&&u instanceof F&&!u.notStarted&&u.exitCode===null&&u.signalCode===null&&await o.owner.waitForCleanup();for(let e of y.values())e();y.clear()}),retire=e=>{setIdle(!1),d=!0,_&&e!==void 0&&(_.failure??=e),u.kill(`SIGKILL`)},sendMessage=e=>u.send(e,e=>{e&&retire(e)}),releasePending=t=>{if(_=void 0,p=void 0,t.cleanup(),e.pooledRead){for(let e of y.values())e();y.clear()}return t};e.retainLifetime!==!1&&he(b,()=>retire(/* @__PURE__ */ Error(`SQLite snapshot owner stopped`)));let x=!1,S=!1,C=!1;u.once(`spawn`,()=>{S=!0}),u.on(`error`,e=>retire(S?e:Object.assign(Error([[`EACCES`,`ENOENT`,`EPERM`].includes(e.code??``)?`SQLite read-only worker runtime binary not executable: ${a} (${e.code}, cwd ${r}). Check runtime execute permissions and access to the working directory`:`SQLite read-only worker failed to start (executable ${a}, cwd ${r})`,e.message].join(`: `),{cause:e}),{code:e.code,path:e.path})));let finishClose=async(e,t)=>{C=!0,d=!0;let n=_?.failure??createSqliteReadOnlyWorkerError(`exited with ${t?`signal ${t}`:`code ${e}`}`,h),r=await Ee({execPath:a,error:n,stderr:h,signal:t,started:x}).catch(toStringifiedError);if(_){let e=releasePending(_);e.reject(r??e.failure??n)}ee()};u.once(`close`,(e,t)=>{finishClose(e,t)});let captureOutput=(e,t)=>{g+=e.length,t&&(h=m(h+e.toString(`utf8`),-4e3)),g>1048576&&retire(createSqliteReadOnlyWorkerError(`exceeded its output buffer`,h))},attachOutput=()=>{u.stdout?.on(`data`,e=>captureOutput(e,!1)),u.stderr?.on(`data`,e=>captureOutput(e,!0))},w=u instanceof F?u.ready().then(attachOutput).catch(retire):void 0;w||attachOutput(),u.on(`message`,t=>{if(x=!0,!d){if(!_||!t||typeof t!=`object`||Object.keys(t).length!==2||!(`id`in t)||t.id!==_.id||!(`result`in t))retire(createSqliteReadOnlyWorkerError(`returned an unexpected response`,h));else try{let e;if(_.transfer&&`type`in t.result){let n=_.transfer.accept(t.result);if(`request`in n){sendMessage({id:_.id,transfer:n.request});return}e=n.value}else e=readSqliteReadOnlyWorkerValue({kind:`launched`,stdout:JSON.stringify(t.result),stderr:h,status:0},_.mode);releasePending(_).resolve(e)}catch(n){if(_&&e.retainOnOperationError&&isSqliteSnapshotStagingMode(_.mode)&&isSqliteReadOnlyWorkerResult(t.result)&&!t.result.ok){releasePending(_).reject(n);return}retire(n)}}});let T={closed:b,isRetired(){return d},get notStarted(){return u instanceof F?u.notStarted:C&&!S},createNativeReplacement(){return t(()=>createSqliteReadOnlyWorkerSession({...e,env:n,cwd:r,argv:c,transport:{kind:`native`}}))},compatible(e){return!d&&isSameSqliteReadOnlyWorkerLaunch(s,e)},run(t,n){if(d)return Promise.reject(/* @__PURE__ */ Error(`SQLite read-only worker is closed`));if(n.mode===`auth-profile-rows`&&n.source===`canonical`&&!n.artifactPreserving){let e=R.resolve(t);y.has(e)||y.set(e,registerOpenClawAgentDatabaseReadCandidateResource({path:e,revoke:()=>retire(/* @__PURE__ */ Error(`Auth profile reader owner was revoked`)),close:()=>T.close()}))}return p=new Promise((r,i)=>{h=``,g=0;let abort=()=>retire(n.signal?.reason),a,o=++f;_={id:o,mode:n.mode,...n.mode===`auth-profile-rows`?{transfer:createSqliteAuthTransferReceiver()}:n.mode===`operation`?{transfer:createSqliteOperationTransferReceiver(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(d)return;a=setTimeout(()=>retire(e.timeoutError(t,n,r)),n)}if(w&&(await w,d))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:je(n.command).toString(`base64`)}:{immutable:n.immutable,retainReader:!e.pooledRead&&n.source===`canonical`&&!n.artifactPreserving,schema:n.source===`canonical`&&!n.artifactPreserving?captureSqliteAuthSchema(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(T.setIdle(!1),d){await b;return}d=!0;let t=setTimeout(()=>retire(),e.closeTimeoutMs);try{sendMessage(`close`)}catch(e){retire(e)}try{await b}finally{clearTimeout(t)}}};return e.runtimeGeneration?.retain(T,async()=>(await p?.catch(()=>void 0),()=>T.close())),T}const tt=A(`state/sqlite`);function trackSqliteRead(e){return Ce(`sqlite_read`,de(e.mode===`operation`?e.command.type:e.mode),e.signal)}function createSqliteReadOnlyWorkerPool(e){let n=[],r=/* @__PURE__ */ new WeakMap,i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new WeakSet,o=createStateWorkerMemoryPressureSubscription(()=>n.some(e=>e.idleSince!==void 0&&!e.session?.isRetired()),e=>{for(let t of n)t.session&&!t.leased&&!t.quarantined&&t.queued===0&&Se(t.idleSince,e)&&retireIdleSlot(t)}),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 i)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=j.getStore();if(o){if(!s?.active)throw Error(`Database page-cache warm requires an active read-only worker scope`);let t=r.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=n.filter(e=>!e.leased&&!e.quarantined),l=c.find(e=>isSameSqliteReadOnlyWorkerLaunch(e.launch,a));if(!l&&n.length<4&&(l={launch:a,tail:Promise.resolve(),queued:0},n.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,r.set(s,e),s.releaseReadWorker=async()=>{try{t.started&&(await e.tail,await closeSlot(e))}finally{e.leased=void 0,r.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 i)e()}}}return l}if(n.every(e=>e.quarantined))throw AggregateError(n.map(e=>e.quarantined?.error),`SQLite read-only worker capacity is held by unconfirmed cleanup`);let u,f=t(()=>new Promise(e=>{u=e}));i.add(u);try{await d(f,e.signal,e=>e.reason)}finally{i.delete(u)}}}function retireIdleSlot(e){clearTimeout(e.idle),e.idleSince=void 0,o();let n=t(()=>closeSlot(e));return e.tail=n.catch(()=>{tt.warn(`Idle SQLite read-only worker cleanup failed`)}),n}function armScopedReadWorkerIdle(e){e.launch.transport.kind===`broker`&&a.has(e.launch.transport.owner)?retireIdleSlot(e):(e.idleSince=performance.now(),o(),e.idle=t(()=>setTimeout(()=>{retireIdleSlot(e)},6e4)),e.idle.unref())}return{run:async function(n,r,i,a=trackSqliteRead(r)){let c=r.mode===`operation`&&(r.command.type===`pageCache.begin`||r.command.type===`pageCache.step`),l;try{l=await selectScopedReadWorker(r,i),assertBrokerOpen(i)}catch(e){throw a.completed(),e}clearTimeout(l.idle),l.idleSince=void 0,o(),l.queued++;let u=l.tail,f=t(()=>d(u,r.signal,e=>e.reason)).then(async()=>{if(r.signal?.throwIfAborted(),l.quarantined)throw l.quarantined.error;if(a.started(),l.leased&&r.mode===`operation`&&r.command.type===`pageCache.begin`&&(l.leased.started=!0),(!isSameSqliteReadOnlyWorkerLaunch(l.launch,i)||l.session?.isRetired())&&await closeSlot(l),r.signal?.throwIfAborted(),l.launch=i,!l.session){l.session=e({...i,pooledRead:!0});let{closed:n}=l.session;t(()=>n.then(o,o))}let u=l.session;u.setIdle(!1);try{let e=await u.run(n,r);return r.signal?.throwIfAborted(),!c&&(r.mode===`operation`&&sqliteReadOnlyOperationRequiresProcessRetirement(r.command.type)||!s().explicitSqliteCloseReleasesNativeResources)&&await closeSlot(l),e}catch(e){try{await closeSlot(l)}catch(t){throw g([e,t],`SQLite read and child cleanup failed`,e)}throw e}}).finally(()=>{a.completed(),l.queued--,!l.leased&&!l.quarantined&&l.queued===0&&l.session&&!l.session.isRetired()&&(l.session?.setIdle(!0),armScopedReadWorkerIdle(l))});return l.tail=t(()=>Promise.allSettled([u,f]).then(()=>{})),f},async closeBroker(e){a.add(e);let t=await Promise.allSettled(n.filter(t=>t.launch.transport.kind===`broker`&&t.launch.transport.owner===e&&t.session&&t.queued===0&&!t.leased&&!t.quarantined).map(retireIdleSlot));we(t,`SQLite read-only broker worker cleanup failed`)}}}const Q=3e5,nt=A(`state/sqlite`);function resolveSqliteInspectionBudget(e,t,n){let i=r(Q+Math.ceil(40*Number(n??0)/33554432)*1e3,Q),a=n===void 0?`unknown size`:formatByteSize(Number(n),{style:`iec`,maxUnit:`giga`,separator:` `,fractionDigits:n<1024n?0:1});return i>Q&&nt.debug(`SQLite ${e} for ${t}: ${a}, budget ${i/1e3} seconds`),{timeoutMs:i,size:a}}function readSqliteInspectionBudget(e,t,n){let r=n;try{r??=L.statSync(t,{bigint:!0}).size;for(let e of[`-wal`,`-shm`,`-journal`])try{r+=L.statSync(t+e,{bigint:!0}).size}catch(e){if(!C(e,`ENOENT`))throw e}}catch{}return resolveSqliteInspectionBudget(e,t,r)}async function readSqliteInspectionBudgetAsync(e,t,n){let r=n;try{r??=(await L.promises.stat(t,{bigint:!0})).size;for(let e of[`-wal`,`-shm`,`-journal`])try{r+=(await L.promises.stat(t+e,{bigint:!0})).size}catch(e){if(!C(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&&j.getStore()?.active)return e();let n=_e(t);try{return await n.run(e)}finally{await n.close()}}function isSqliteInspectionDeadlineOwnedByCaller(){return j.getStore()?.deadlineOwnedByCaller===!0}function runScopedSqliteInspection(e,t){let n=j.getStore();if(!n)return t(e);if(!n.active)return Promise.reject(new me);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}=pe(k(e[0]===`content-version`||e[0]===`file-generation`?`sqliteSourceRevision`:`sqliteReadOnly`));return{runtimeGeneration:n,argv:[...resolveForwardedNodeCompilerArgs(),...ue(t),le,...e]}}function captureSqliteReadOnlyWorkerLaunch(e,t){let n=t===void 0?void 0:Te();return{runtimeGeneration:pe(k(`sqliteReadOnly`)).runtimeGeneration,env:{...u(N(e)),OPENCLAW_STATE_DIR:p(e)},cwd:i()??Fe(),transport:n?{kind:`broker`,owner:n}:{kind:`native`}}}function createScopedSqliteReadOnlyWorker(e){let n=k(`sqliteReadOnly`);return t(()=>createSqliteReadOnlyWorkerSession({...e,argv:[...resolveForwardedNodeCompilerArgs(),...ue(fe(n,e.runtimeGeneration)),le,`session`],requestArgs:sqliteReadOnlyWorkerRequestArgs,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:Q}))}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`&&isArtifactPreservingStateRead(`agent`,e)?t.mode===`auth-profile-rows`&&se(e)?{...t,artifactPreserving:!0,immutable:!0}:{...t,artifactPreserving:!0}:t;return runScopedSqliteInspection(n.signal,t=>{let r=j.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 $.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 $=createSqliteReadOnlyWorkerPool(createScopedSqliteReadOnlyWorker);function runSqliteReadOnlyWorkerOnce(e,t,n){if(t.mode===`auth-profile-rows`||t.mode===`operation`)return $.run(e,t,captureSqliteReadOnlyWorkerLaunch(t.env,t.source));let{argv:r,runtimeGeneration:i}=sqliteReadOnlyWorkerArgv(sqliteReadOnlyWorkerRequestArgs(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(),readSqliteReadOnlyWorkerValue(e,t.mode))})}function runOneShotSqliteInspection(e){P();let t=e.mode===`staging-sweep`?`snapshot staging`:e.pathname,n=u(e.env??N()),r=process.execPath,a=e.cwd??i(),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=z.execFile(r,e.argv,{encoding:`utf8`,windowsHide:!0,env:n,...a===i()?{}:{cwd:a},maxBuffer:et,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=Oe(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 he(s,()=>stop())}function runSqliteReadOnlyWorkerSync(e,t,n=`sync`,r){P();let{timeoutMs:i,size:a}=readSqliteInspectionBudget(`read-only snapshot`,e),o=z.spawnSync(process.execPath,sqliteReadOnlyWorkerArgv(sqliteReadOnlyWorkerRequestArgs(e,{mode:n,stagingRoot:t,expectedSourceIdentity:r})).argv,{encoding:`utf8`,windowsHide:!0,stdio:`pipe`,env:u(N()),maxBuffer:et,timeout:i,killSignal:`SIGKILL`}),s=De({error:o.error,stderr:o.stderr,signal:o.signal,started:!!o.stdout});if(s)throw s;return readSqliteReadOnlyWorkerValue(o.error?{kind:`launch-failed`,error:Error(C(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}`}`},n)}export{isStartupConfigStateRead as $,Xe as A,resolveAgentCreationClaimAgentId as B,assertAgentDeletionDatabaseCleanupAccess as C,registerAgentDeletionExecutionCleanup as D,registerAgentDeletionDatabaseCleanup as E,assertAgentCreationClaimCurrent as F,isSameOpenClawAgentDatabasePath as G,createOpenClawAgentDatabasePathMatcher as H,captureAgentCreationClaim as I,resolveOpenClawAgentSqlitePath as J,resolveExplicitIncognitoAgentSqliteTarget as K,registerAgentCreationClaimHandle as L,Qe as M,assertAgentCreationClaimAccess as N,releaseAgentDeletionDatabaseCleanup as O,assertAgentCreationClaimAliases as P,isLiveStateRead as Q,releaseAgentCreationClaimHandle as R,assertAgentDeletionCleanupAliases as S,getAgentDeletionDatabaseCleanup as T,isIncognitoOpenClawAgentSqlitePath as U,qe as V,isPersistentOpenClawAgentDatabasePath as W,U as X,createStateWorkerMemoryPressureSubscription as Y,isArtifactPreservingStateRead as Z,registerAgentDatabaseResourceReleaseHandler as _,runSqliteReadOnlyOperation as a,registerOpenClawAgentDatabaseSyncResource as b,runSqliteReadOnlyWorkerSync as c,createSqliteWorkerTransferOwner as d,withArtifactPreservingStateReads as et,createSqliteWorkerTransferReceiver as f,matchesAgentDatabaseClose as g,hasOpenClawAgentDatabaseAsyncResources as h,readSqliteInspectionBudget as i,Ze as j,Ye as k,sqliteInspectionTimeoutError as l,drainAgentDatabaseResources as m,createScopedSqliteReadOnlyWorker as n,resolvePathPrefixSync as nt,runSqliteReadOnlyWorker as o,assertAgentDatabaseResourceAdmission as p,resolveIncognitoOpenClawAgentSqlitePath as q,isSqliteInspectionDeadlineOwnedByCaller as r,toStringifiedError as rt,runSqliteReadOnlyWorkerOnce as s,captureSqliteReadOnlyWorkerLaunch as t,withLiveStateReads as tt,withSqliteReadOnlyWorkerScope as u,registerOpenClawAgentDatabaseAsyncResource as v,assertAgentDeletionExecutionCleanupAccess as w,revokeAgentDatabaseResources as x,registerOpenClawAgentDatabaseReadCandidateResource as y,reserveAgentCreationClaimAdmission as z};