openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
3 lines • 41.1 kB
JavaScript
import{Mt as e,ft as t,l as n,t as r,u as i}from"./sqlite-readonly-subsystem-C-VJT-xk.mjs";import{t as a}from"./sqlite-readonly-deferred-B75K7ut7.mjs";import{$t as o,Bt as s,D as c,Dt as l,Ht as u,Kt as d,O as f,Tt as p,Wt as m,Yt as h,cn as g,dn as _,in as v,lt as y}from"./sqlite-readonly-runtime-process-manifest-CLhsN5hb.mjs";import{t as b}from"./sqlite-readonly-absolute-path-Cb1z8Zgx.mjs";import{G as x,Sn as ee,V as S,X as te,Z as C,g as ne,it as w,ln as T,qn as re,sn as E,tt as D,un as O,wt as k,z as ie}from"./sqlite-readonly-node-sqlite-u3RAlsBE.mjs";import{i as ae,n as A}from"./sqlite-readonly-openclaw-root-PLr-9gty.mjs";import{t as j}from"./sqlite-readonly-errors-bSzGfuz-.mjs";import{n as M}from"./sqlite-readonly-error-graph-internal-BvCeLnSw.mjs";import{i as oe}from"./sqlite-readonly-sqlite-transaction-CZJn2Fa5.mjs";import N from"node:path";import{setImmediate as P}from"node:timers/promises";import F from"node:fs";import{promisify as I}from"node:util";import{AsyncLocalStorage as se}from"node:async_hooks";import{performance as L}from"node:perf_hooks";var NativePolicyDirectoryMismatch=class extends g{constructor(e){super(`path-mismatch`,`staging directory pathname changed`,{cause:e})}};function nativePolicyDirectoryObserver(e,t,n){if(!e||process.platform===`win32`||process.versions.bun)return;let r=e.observeDirectoryFd;if(typeof r!=`function`)return;let i=o().mode,a=!1;return Object.assign(()=>{if(a)throw new NativePolicyDirectoryMismatch;if(o().mode!==i)return;let s;try{s=r.call(e,t,n)}catch(e){if(e?.code===`OBSERVATION_UNAVAILABLE`)return;throw e?.code===`OBSERVATION_REDIRECTED`?new g(`path-mismatch`,`staging directory pathname redirected`):e?.code===`path-mismatch`?new NativePolicyDirectoryMismatch(e instanceof Error?e:void 0):e}if(o().mode===i&&!(!s||!c(s.dev)||!c(s.ino)||typeof s.mode!=`bigint`||s.mode<0n||s.mode>4294967295n||typeof s.nlink!=`bigint`||s.nlink<0n||s.nlink>18446744073709551615n||typeof s.realPath!=`string`||s.realPath.includes(`\0`)||!N.isAbsolute(s.realPath))){if((s.mode&61440n)!=16384n||s.nlink===0n||s.realPath!==n)throw new NativePolicyDirectoryMismatch;return Object.freeze({canonicalPath:s.realPath,identity:Object.freeze({dev:f(s.dev),ino:f(s.ino),mode:s.mode,nlink:s.nlink})})}},{dispose(){a=!0}})}const ce=[`dev`,`mode`,`nlink`,`uid`,`gid`,`rdev`,`blksize`,`ino`,`size`,`blocks`],le=[`atime`,`mtime`,`ctime`,`birthtime`],R=/* @__PURE__ */ new WeakMap,z=/* @__PURE__ */ new WeakMap;function directoryReceiptIdentity(e){if(!e)throw new g(`path-mismatch`,`directory receipt identity is missing`);let t=_(e),n=z.get(t),r=t.dev,i=t.ino;if(n){let matches=(e,t)=>typeof e==`bigint`?e===t:e===Number(t);if(!matches(r,n.identity.dev)||!matches(i,n.identity.ino))throw new g(`path-mismatch`,`directory receipt identity changed`);return n.identity}let exact=e=>{if(typeof e!=`bigint`&&!Number.isSafeInteger(e)||process.platform===`win32`&&(e===0||e===0n))throw new g(`path-mismatch`,`directory receipt identity could not be verified`);return BigInt(e)};return Object.freeze({dev:exact(r),ino:exact(i)})}function snapshotDirectoryReceipt(e){let t=e?.path,n=e?.realPath,r=e?.identity;if(typeof t!=`string`||typeof n!=`string`||r==null)throw new g(`path-mismatch`,`directory receipt is incomplete`);s(t,`filesystem`),s(n,`filesystem`);let i=directoryReceiptIdentity(e.exactIdentity??r),a=R.get(e),matches=(e,t)=>typeof e==`bigint`?e===t:e===Number(t);if(a&&(!matches(r.dev,a.identity.dev)||!matches(r.ino,a.identity.ino)||t!==a.path||n!==a.realPath||i.dev!==a.identity.dev||i.ino!==a.identity.ino))throw new g(`path-mismatch`,`directory receipt changed before admission`);let o=a?.metadata??z.get(r)?.metadata??snapshotDirectoryMetadata(r,i);return Object.freeze({path:t,realPath:n,identity:i,metadata:o})}function snapshotDirectoryMetadata(e,t){let n={};for(let r of ce)n[r]=Number(r===`dev`||r===`ino`?t[r]:e[r]);for(let t of le)if(`atimeNs`in e){let r=e[`${t}Ns`],i=(r%1000000000n+1000000000n)%1000000000n;n[`${t}Ms`]=Number((r-i)/1000000000n)*1e3+Number(i)/1e6}else n[`${t}Ms`]=e[`${t}Ms`];return Object.freeze(n)}function directoryReceiptAuthority(e){return R.get(e)??snapshotDirectoryReceipt(e)}function ownDirectoryReceipt(e){return receiptFromAuthority(snapshotDirectoryReceipt(e))}function copyRetainedDirectoryReceipt(e){return receiptFromAuthority(directoryReceiptAuthority(e))}function receiptFromAuthority(e){let t={exactIdentity:e.identity,path:e.path,realPath:e.realPath,identity:Object.assign(Object.create(F.Stats.prototype),e.metadata)};return R.set(t,e),z.set(t.identity,e),t}function createDirectoryReceiptFromIdentity(e,t,n){let r=Object.freeze({dev:n.dev,ino:n.ino});return receiptFromAuthority(Object.freeze({path:e,realPath:t,identity:r,metadata:snapshotDirectoryMetadata(n,r)}))}function createDirectoryReceiptSync(e,t,n=d){s(e,`filesystem`,`${t} path uses a Windows filesystem namespace alias`);let r=m(e);s(r,`filesystem`,`${t} path uses a Windows filesystem namespace alias`);let i=y(r),a=n(u(r));return s(a,`filesystem`,`${t} real path uses a Windows filesystem namespace alias`),createDirectoryReceiptFromIdentity(r,a,i)}function assertDirectoryReceiptCurrentSync(e,t,n=d){let r=directoryReceiptAuthority(e);s(r.path,`filesystem`,`${t} path uses a Windows filesystem namespace alias`),s(r.realPath,`filesystem`,`${t} real path uses a Windows filesystem namespace alias`),y(r.path,r.identity);let i=n(u(r.path));if(s(i,`filesystem`,`${t} real path uses a Windows filesystem namespace alias`),i!==r.realPath)throw new g(`path-mismatch`,`${t} changed during durable directory operation: ${r.path}`)}const B=Symbol(`checked mutation directory observation`),V=/* @__PURE__ */ new WeakMap;function identity(e){return Object.freeze({dev:e.dev,ino:e.ino,mode:e.mode,nlink:e.nlink})}function sameIdentity(e,t,n=!1){return e.dev===t.dev&&e.ino===t.ino&&e.mode===t.mode&&(n||e.nlink===t.nlink)}function directoryMode(e){return(e&61440n)==16384n}function absent(e){try{return F.lstatSync(e,{throwIfNoEntry:!1})===void 0}catch(e){return l(e)&&e.code===`ENOENT`}}function missingMutationSegments(e){return e.missingSegments.length-e.missingOffset}function nextMissingMutationPath(e){let t=e.missingSegments[e.missingOffset];return t===void 0?void 0:N.join(e.ancestor,t)}function checkedMutationDirectory(e,t,n,r){if(!directoryMode(n.mode))throw TypeError(`mutation directory evidence must describe a real directory`);let i=Object.freeze({path:e,canonicalPath:t,identity:identity(n),[B]:!0});return r&&V.set(i,r),i}function checkedDirectory(e){return e[B]===!0&&N.isAbsolute(e.path)&&N.isAbsolute(e.canonicalPath)&&directoryMode(e.identity.mode)}function mutationObservationUsesDirectory(e,t){return checkedDirectory(t)&&e.ancestor===t.path&&e.canonicalAncestor===t.canonicalPath&&sameIdentity(e.entry,t.identity)&&sameIdentity(e.identity,t.identity)}function observeMutationPath(e){try{let t=e,n=[];for(;absent(t);){let e=N.dirname(t);if(e===t)return;n.push(N.basename(t)),t=e}n.reverse();let r=Object.freeze(n),i=v(()=>F.lstatSync(t,{bigint:!0})),a=d.native(t),o=a===t?i:v(()=>F.lstatSync(a,{bigint:!0}));if(o.isSymbolicLink()||r.length>0&&!o.isDirectory())return;let s=Object.freeze({path:e,ancestor:t,canonicalAncestor:a,canonicalPath:N.join(a,...r),entry:identity(i),identity:identity(o),missingSegments:r,missingOffset:0});return mutationObservationCurrent(s)?s:void 0}catch{return}}function mutationObservationCurrent(e){try{let t=v(()=>F.lstatSync(e.ancestor,{bigint:!0}));if(!sameIdentity(e.entry,t,t.isDirectory())||d.native(e.ancestor)!==e.canonicalAncestor)return!1;let n=e.canonicalAncestor===e.ancestor?t:v(()=>F.lstatSync(e.canonicalAncestor,{bigint:!0}));return sameIdentity(e.identity,n,n.isDirectory())&&(missingMutationSegments(e)===0||n.isDirectory()&&absent(nextMissingMutationPath(e)))}catch{return!1}}function mutationObservationsCurrent(e,t){let n=/* @__PURE__ */ new Map,groupFor=e=>{let t=n.get(e);return t||(t={observations:[],directories:[]},n.set(e,t)),t};try{for(let t of e)if(t.ancestor!==t.canonicalAncestor){if(!mutationObservationCurrent(t))return!1}else groupFor(t.ancestor).observations.push(t);for(let e of t){if(!checkedDirectory(e))return!1;groupFor(e.path).directories.push(e)}let current=(e,t)=>{let n=new Set(t.observations.flatMap(e=>{let t=nextMissingMutationPath(e);return t===void 0?[]:[t]}));if(t.directories.length&&![...n].every(absent))return!1;let r=t.directories.length?V.get(t.directories[0])?.():void 0,i=r?.identity??v(()=>F.lstatSync(e,{bigint:!0})),a=r?.canonicalPath??d.native(e),o=directoryMode(i.mode);return!t.observations.every(e=>a===e.canonicalAncestor&&sameIdentity(e.entry,i,o)&&sameIdentity(e.identity,i,o)&&(missingMutationSegments(e)===0||o))||!t.directories.every(e=>o&&sameIdentity(e.identity,i)&&a===e.canonicalPath)?!1:t.directories.length>0||[...n].every(absent)};for(let[e,t]of n)if(!t.directories.length&&!current(e,t))return!1;let r=/* @__PURE__ */ new Set;for(let e of t)if(!r.has(e.path)){if(!current(e.path,n.get(e.path)))return!1;r.add(e.path)}return!0}catch{return!1}}function advanceMutationObservation(e,t,n){let r=nextMissingMutationPath(e);if(r===void 0||r!==n.path)return e;if(checkedDirectory(t)&&checkedDirectory(n)&&e.ancestor===t.path&&e.canonicalAncestor===t.canonicalPath&&sameIdentity(e.entry,t.identity,!0)&&sameIdentity(e.identity,t.identity,!0)&&t.path===t.canonicalPath&&n.path===n.canonicalPath&&N.dirname(n.path)===t.path)return Object.freeze({...e,ancestor:n.path,canonicalAncestor:n.canonicalPath,entry:n.identity,identity:n.identity,missingOffset:e.missingOffset+1})}function exactIdentityMatches(e,t){return[`dev`,`ino`].every(n=>{let r=e[n];return(typeof r==`bigint`||Number.isSafeInteger(r))&&BigInt(r)===t[n]})}function describeStagedDirectory(e,t){let n=F.fstatSync(e,{bigint:!0});if(!n.isDirectory())throw new g(`not-file`,`staging parent must be a directory`);let r=Object.freeze({path:m(t),realPath:d(t),identity:Object.freeze({dev:n.dev,ino:n.ino})});return assertStagedDirectoryCurrent(r),r}function assertStagedDirectoryCurrent(e){let t=F.lstatSync(e.path,{bigint:!0});if(!t.isDirectory()||!exactIdentityMatches(e.identity,t)||d(e.path)!==e.realPath)throw new g(`path-mismatch`,`staging directory pathname changed`);return t}function assertNativeStagedDirectoryCurrent(e,t,n){if(typeof e.stagedDirectoryMatches==`function`&&n.path===n.realPath)try{if(!e.stagedDirectoryMatches(t,n.path,n.identity.dev,n.identity.ino))throw new g(`path-mismatch`,`staging directory pathname changed`);return}catch(e){if(e?.code!==`OBSERVATION_UNAVAILABLE`)throw e}assertStagedDirectoryCurrent(n)}function describeNativeStagedDirectory(e,t,n){let r=F.fstatSync(t,{bigint:!0});if(!r.isDirectory())throw new g(`not-file`,`staging parent must be a directory`);let i=m(n),a=Object.freeze({path:i,realPath:i,identity:Object.freeze({dev:r.dev,ino:r.ino})});return assertNativeStagedDirectoryCurrent(e,t,a),{directory:a,stat:r}}function sameDirectoryMetadata(e,t){return e.dev===t.dev&&e.ino===t.ino&&e.mode===t.mode&&e.nlink===t.nlink}function describePolicyStagedDirectory(e,t,n){let r=N.resolve(t),i=F.fstatSync(e,{bigint:!0});if(!i.isDirectory())throw new g(`not-file`,`staging parent must be a directory`);let a=nativePolicyDirectoryObserver(n,e,r),o=a?.();if(o){if(!sameDirectoryMetadata(i,o.identity))throw new NativePolicyDirectoryMismatch;let e=Object.freeze({path:r,realPath:o.canonicalPath,identity:Object.freeze({dev:i.dev,ino:i.ino})});return Object.freeze({directory:e,observation:checkedMutationDirectory(r,o.canonicalPath,o.identity,a),stat:i,observeCurrent:a,disposeObservation:a.dispose})}let s=y(r),c=N.resolve(d.native(r)),l=y(r,i);if(c!==r||!sameDirectoryMetadata(i,s)||!sameDirectoryMetadata(i,l)||N.resolve(d.native(r))!==c)throw new g(`path-mismatch`,`staging directory pathname changed`);let u=Object.freeze({path:r,realPath:c,identity:Object.freeze({dev:i.dev,ino:i.ino})});return Object.freeze({directory:u,observation:checkedMutationDirectory(r,c,l),stat:l})}function assertPolicyStagedDirectoryCurrent(e){let t=e.observeCurrent?.();if(t){if(!sameDirectoryMetadata(e.stat,t.identity)||t.canonicalPath!==e.directory.realPath)throw new g(`path-mismatch`,`staging directory pathname changed`);return e.stat}let n=y(e.directory.path,e.directory.identity);if(!sameDirectoryMetadata(e.stat,n)||N.resolve(d.native(e.directory.path))!==e.directory.realPath)throw new g(`path-mismatch`,`staging directory pathname changed`);return n}function refreshPolicyStagedDirectoryObservation(e){let t=e.observeCurrent?.();if(t){if(!exactIdentityMatches(e.directory.identity,t.identity)||t.canonicalPath!==e.directory.realPath)throw new g(`path-mismatch`,`staging directory pathname changed`);return checkedMutationDirectory(e.directory.path,t.canonicalPath,t.identity,e.observeCurrent)}let n=y(e.directory.path,e.directory.identity),r=N.resolve(d.native(e.directory.path));if(r!==e.directory.realPath)throw new g(`path-mismatch`,`staging directory pathname changed`);return checkedMutationDirectory(e.directory.path,r,n)}function openStagedDirectory(e){let t=typeof e==`string`?void 0:directoryReceiptAuthority(ownDirectoryReceipt(e)),n=m(typeof e==`string`?e:t.path),r=F.lstatSync(n,{bigint:!0});if(!r.isDirectory())throw new g(`not-file`,`staging parent must be a real directory`);if(t&&(!exactIdentityMatches(t.identity,r)||d(n)!==t.realPath))throw new g(`path-mismatch`,`stale staging directory receipt`);let i=F.openSync(n,F.constants.O_RDONLY|F.constants.O_DIRECTORY|F.constants.O_NOFOLLOW|F.constants.O_NONBLOCK);try{let e=describeStagedDirectory(i,n);if(!exactIdentityMatches(r,e.identity))throw new g(`path-mismatch`,`staging directory changed while opening`);return{fd:i,receipt:e}}catch(e){try{F.closeSync(i)}catch(t){throw AggregateError([e,t],`staging directory admission and close failed`)}throw e}}const H=e(Symbol.for(`openclaw.sessionControllerCleanupContext`),()=>({}));function runWithSessionControllerCleanup(e){return H.exit?H.exit(e):e()}const U=r(`gateway/scheduler`),ue={now:()=>Date.now(),monotonicNow:()=>performance.now(),arm:(e,t)=>{let r=setTimeout(()=>{n(`scheduler:wake`,()=>{e()})},t);return r.unref(),()=>clearTimeout(r)}};function nextMaintenanceSlot(e,t,n){return e+(Math.floor(Math.max(0,t-e)/n)+1)*n}var GatewayScheduler=class{constructor(e={}){this.jobs=/* @__PURE__ */ new Map,this.pending=/* @__PURE__ */ new Set,this.dispatching=!1,this.fenced=!1,this.controller=new AbortController,this.clock=e.clock??ue}get signal(){return this.controller.signal}now(){return this.clock.now()}get nextWakeAtMs(){let e=this.now(),t=this.clock.monotonicNow(),n=null;for(let r of this.jobs.values()){if(r.running)continue;let i=e+this.remaining(r,e,t);n=n===null?i:Math.min(n,i)}return n}scope(){let e=new AbortController,t={signal:AbortSignal.any([this.signal,e.signal]),jobs:/* @__PURE__ */ new Set},beginClose=()=>{e.abort(),M(e.signal.reason),M(t.signal.reason);for(let e of t.jobs)this.cancel(e)},close=()=>{beginClose();let e=[...t.jobs].flatMap(e=>e.running??[]);return e.length>0?Promise.all(e).then(()=>void 0):void 0};return{signal:t.signal,now:()=>this.now(),schedule:e=>this.scheduleOwned(e,t),beginClose,close,stop:async()=>{await close()}}}schedule(e){return this.scheduleOwned(e)}scheduleOwned(e,t){let n=`delayMs`in e,r=this.now(),i=n?r+e.delayMs:e.atMs,a=e.phase===`maintenance`?Math.max(r,Math.floor(i/1e4)*1e4):i;if(!Number.isFinite(a)||e.everyMs!==void 0&&(!Number.isFinite(e.everyMs)||e.everyMs<=0))throw Error(`Invalid Gateway schedule: ${e.id}`);let o=this.fenced||t?.signal.aborted===!0,s=o?void 0:this.jobs.get(e.id),c={id:e.id,diagnosticName:`scheduler:${e.id.startsWith(`maintenance:`)?e.id.split(`:`).slice(0,3).join(`:`):e.id.split(/[:/]/u,1)[0]}`,run:e.run,everyMs:e.everyMs,phase:e.phase,atMs:a,elapsedAtMs:e.phase!==`maintenance`&&(n||e.everyMs!==void 0)?this.clock.monotonicNow()+Math.max(0,a-r):void 0,context:ae(()=>runWithSessionControllerCleanup(()=>se.snapshot())),cancelled:o,owner:t};e.mode===`earliest`&&s&&!s.running&&(c.atMs=Math.min(c.atMs,s.atMs),e.phase!==`maintenance`&&s.elapsedAtMs!==void 0&&(c.elapsedAtMs=c.elapsedAtMs===void 0?s.elapsedAtMs:Math.min(c.elapsedAtMs,s.elapsedAtMs)));let cancel=()=>this.cancel(c);return o||(t?.jobs.add(c),this.jobs.set(c.id,c),s&&this.cancel(s),this.arm()),{get atMs(){return c.atMs},cancel,stop:async()=>{cancel(),await c.running}}}cancel(e){e.cancelled=!0,e.running||e.owner?.jobs.delete(e),this.jobs.get(e.id)===e&&(this.jobs.delete(e.id),this.arm())}fence(){this.fenced=!0,this.cancelTimer?.(),this.cancelTimer=void 0;for(let e of this.jobs.values())this.cancel(e);this.jobs.clear()}beginClose(){this.fence(),this.controller.abort(),M(this.controller.signal.reason)}async stop(){this.beginClose(),await Promise.all(this.pending)}remaining(e,t,n){let r=e.atMs-t;return e.elapsedAtMs===void 0?r:Math.min(r,e.elapsedAtMs-n)}arm(){if(this.fenced||this.dispatching)return;this.cancelTimer?.(),this.cancelTimer=void 0;let e=this.nextWakeAtMs;if(e!==null){let t=this.now(),n=Math.min(2147483647,Math.max(0,Math.ceil(e-t)));this.cancelTimer=i(()=>this.clock.arm(()=>this.wake(t+n),n))}}wake(e){if(this.cancelTimer=void 0,this.fenced)return;let t=this.now(),n=this.clock.monotonicNow(),r=[...this.jobs.values()].filter(e=>!e.running&&this.remaining(e,t,n)<=0).toSorted((e,r)=>this.remaining(e,t,n)-this.remaining(r,t,n)),i;t-e>6e4&&U.debug(`late wake by ${t-e}ms; coalescing ${r.length} due jobs`),this.dispatching=!0;try{for(let e of r){if(this.fenced||e.cancelled||e.owner?.signal.aborted||this.jobs.get(e.id)!==e)continue;e.everyMs===void 0&&this.jobs.delete(e.id);let t=this.run(e);t&&(i??=[]).push(t)}}finally{this.dispatching=!1,this.arm()}return i?Promise.all(i).then(()=>void 0):void 0}run(e){U[e.everyMs===void 0?`debug`:`trace`](`running ${e.id}`);let t=a(),r=new A;e.running=t.promise,this.pending.add(t.promise);let finish=()=>{e.running=void 0,this.pending.delete(t.promise),e.everyMs!==void 0&&!e.cancelled&&!this.fenced?e.phase===`maintenance`?(e.atMs=Math.floor(e.atMs/1e4)*1e4,e.atMs=nextMaintenanceSlot(e.atMs,this.now(),e.everyMs)):(e.atMs=this.now()+e.everyMs,e.elapsedAtMs=this.clock.monotonicNow()+e.everyMs):e.owner?.jobs.delete(e),t.resolve(),this.arm()},i;try{i=e.context(()=>n(e.diagnosticName,()=>r.run(e.run)))}catch(t){U.error(`${e.id} failed: ${String(t)}`)}if(!i&&!r.hasPendingWork)finish();else return Promise.resolve(i).catch(t=>U.error(`${e.id} failed: ${String(t)}`)).then(()=>A.runWhenAllIdle(()=>[r],()=>r.drain())).finally(finish),t.promise}};const W=BigInt(2**53-1);function readFiniteSqliteNumber(e){let t=typeof e==`bigint`?Number(e):e;return typeof t==`number`&&Number.isFinite(t)?t:void 0}function coerceRequiredSqliteNumber(e){return typeof e==`bigint`?Number(e):e}function normalizeSqliteNumber(e){return typeof e==`bigint`?e>W||e<-W?void 0:Number(e):typeof e==`number`?e:void 0}const de=e(Symbol.for(`openclaw.sqliteWalCheckpointListeners`),()=>/* @__PURE__ */ new Set);function observeSqliteWalCheckpointHealth(e,t){let{activeReaders:n,readerDiagnostics:r,...i}=t;if(t.state===`complete`)return i;let{activeReaders:a,...o}=ie(e);return{...i,activeReaders:[...(n??[]).filter(e=>e.threadId!==o.threadId),...a].toSorted((e,t)=>t.ageMs-e.ageMs).slice(0,8),readerDiagnostics:[...(r??[]).filter(e=>e.threadId!==o.threadId),o].slice(-8)}}function notifyCheckpoint(e,t){for(let n of de)try{n({databasePath:S(e),health:structuredClone(t.health),observedAtNs:t.observedAtNs,lastCompletedAtNs:t.lastCompletedAtNs})}catch{}}function sqliteFileBytes(e){try{return F.statSync(e).size}catch(e){if(p(e,`ENOENT`))return 0;throw e}}function readCheckpointResult(e){let[t,n,r]=Object.values(e??{}).map(e=>normalizeSqliteNumber(typeof e==`number`||typeof e==`bigint`?e:null));if(t===void 0||n===void 0||r===void 0)throw Error(`SQLite returned an invalid WAL checkpoint result`);return{busy:t,logFrames:n,checkpointedFrames:r}}function checkpoint(e,t){return e.prepare(`PRAGMA wal_checkpoint(${t});`).get()}var SqliteWalCheckpointBusyError=class extends Error{};function truncateSqliteWal(e,t){let n=checkpoint(e,`TRUNCATE`),r=readFiniteSqliteNumber(n?.busy??(n?Object.values(n)[0]:void 0));if(r===void 0)throw Error(`SQLite checkpoint returned an invalid result for ${t}.`);if(r!==0)throw new SqliteWalCheckpointBusyError(`SQLite checkpoint remained busy for ${t}. Stop OpenClaw and retry.`)}function createSqliteWalCheckpoint(e,t,n){let r,checkpointObservation=()=>({state:`error`,observedAtMs:Date.now(),walBytes:null,databaseBytes:null,logFrames:null,checkpointedFrames:null,lastCompletedAtMs:r?.health.lastCompletedAtMs??null,consecutiveBlocked:0,warning:!0}),recordCheckpointError=(e,n=checkpointObservation())=>{let i={...n,observedAtMs:Date.now(),state:`error`,consecutiveBlocked:0,warning:!0,error:j(e)};r={observedAtNs:process.hrtime.bigint(),lastCompletedAtNs:r?.lastCompletedAtNs,health:t.databasePath?observeSqliteWalCheckpointHealth(t.databasePath,i):i},t.databasePath&¬ifyCheckpoint(t.databasePath,r),t.onCheckpointError?.(e)},recordCheckpoint=(e,i,a)=>{let o=process.hrtime.bigint(),s=checkpointObservation(),c,l;try{let{busy:e,logFrames:a,checkpointedFrames:u}=readCheckpointResult(i);if(c=e!==0,s.logFrames=a,s.checkpointedFrames=u,s.state=c||u<a?`blocked`:`complete`,s.state===`complete`?s.lastCompletedAtMs=s.observedAtMs:s.consecutiveBlocked=(r?.health.consecutiveBlocked??0)+1,t.databasePath)try{s.databaseBytes=sqliteFileBytes(t.databasePath),s.walBytes=sqliteFileBytes(`${t.databasePath}-wal`)}catch(e){l=e,s.error=j(e)}s.warning=s.state===`blocked`&&(s.consecutiveBlocked>=2||s.walBytes!==null&&s.databaseBytes!==null&&s.walBytes>Math.max(2*s.databaseBytes,n)),r={observedAtNs:o,lastCompletedAtNs:s.state===`complete`?o:r?.lastCompletedAtNs,health:t.databasePath?observeSqliteWalCheckpointHealth(t.databasePath,s):s},t.databasePath&¬ifyCheckpoint(t.databasePath,r)}catch(e){return recordCheckpointError(e,s),!1}if(s.error!==void 0&&t.onCheckpointError?.(l),s.warning&&!a){let n=t.databaseLabel??`sqlite database`;t.onCheckpointError?.(/* @__PURE__ */ Error(`${n} WAL checkpoint ${e} ${c?`remained busy`:`blocked by a reader`}`))}return s.state===`complete`};return{adopt(e){if(r&&r.observedAtNs>=e.observedAtNs&&(r.lastCompletedAtNs??0n)>=(e.lastCompletedAtNs??0n))return;let n=(r?.lastCompletedAtNs??0n)>(e.lastCompletedAtNs??0n)?r:e;(!r||e.observedAtNs>r.observedAtNs)&&(r=structuredClone(e)),r.lastCompletedAtNs=n?.lastCompletedAtNs,r.health.lastCompletedAtMs=n?.health.lastCompletedAtMs??null,t.databasePath&&(r.health=observeSqliteWalCheckpointHealth(t.databasePath,r.health),notifyCheckpoint(t.databasePath,r))},checkpoint(t,n={}){try{return recordCheckpoint(t,checkpoint(e,t),n.quiet===!0)}catch(e){return recordCheckpointError(e),!1}},recordError:recordCheckpointError,inspectIdle(){let{busy:t,logFrames:n,checkpointedFrames:r}=readCheckpointResult(checkpoint(e,`PASSIVE`));return t===0&&n>=0&&r>=0&&r<=n},get health(){return r?structuredClone(r.health):void 0},get snapshot(){return r?structuredClone(r):void 0}}}function firstFailure(e,t){return e??{value:t}}function closeDescriptor(e,t){try{return F.closeSync(e),t}catch(e){return firstFailure(t,e)}}function probeTreeClone(e){let t=h(`probeTreeClone`);if(!t)return;let n=openStagedDirectory(b(e)),r,i;try{r=t.probeTreeClone(n.fd)??void 0}catch(e){i=firstFailure(i,e)}if(i=closeDescriptor(n.fd,i),i)throw i.value;return r}const fe=/\\([0-7]{3})/g;function decodeMountInfoPath(e){return e.replace(fe,(e,t)=>String.fromCharCode(Number.parseInt(t,8)))}const pe=/* @__PURE__ */ new Set([.../* @__PURE__ */ new Set([26985,20859,4283649346,4266872130]),16914839]),G=1e3,me=/* @__PURE__ */ new Set([`cifs`,`smbfs`,`smb2`,`smb3`]),he=/* @__PURE__ */ new Set([`virtiofs`,`fuse.virtiofs`,`9p`,`9p2000.l`]),ge=r(`infra/sqlite-wal`);let K=!1;function findExistingVolumePaths(e){let t=N.resolve(e);for(;;){let e;try{e=F.statSync(t)}catch{let e=N.dirname(t);if(e===t)return null;t=e;continue}let n=F.realpathSync(t);return{canonicalPath:e.isDirectory()?n:N.dirname(n),originalPath:e.isDirectory()?t:N.dirname(t)}}}function parseProcMountInfoEntries(e){let t=[];for(let n of e.split(`
`)){let e=n.indexOf(` - `);if(e===-1)continue;let r=n.slice(0,e).split(` `),i=n.slice(e+3).split(` `),a=r[4],o=i[0];a&&o&&t.push({mountPoint:decodeMountInfoPath(a),fsType:o,...i[1]?{source:decodeMountInfoPath(i[1])}:{}})}return t}function parseMountCommandEntries(e){let t=[];for(let n of e.split(`
`)){let e=/^(.+) on (.+) type ([^,\s)]+) \(/.exec(n)??/^(.+) on (.+) \(([^,\s)]+)/.exec(n);if(e){let[,n,r,i]=e;n&&r&&i&&t.push({source:n,mountPoint:r,fsType:i})}}return t}function readMountEntries(){try{return{ok:!0,value:parseProcMountInfoEntries(F.readFileSync(`/proc/self/mountinfo`,`utf8`))}}catch{}try{return{ok:!0,value:parseMountCommandEntries(String(process.getBuiltinModule(`node:child_process`).execFileSync(`mount`,[],{killSignal:`SIGKILL`,timeout:G})))}}catch(e){return p(e,`ETIMEDOUT`)?{ok:!1,error:`timeout`}:{ok:!0,value:[]}}}function isPathWithinMount(e,t){let n=N.resolve(e),r=N.resolve(t);return n===r||r===N.parse(r).root||n.startsWith(`${r}${N.sep}`)}function isSshfsMountSource(e){if(!e)return!1;let t=e.toLowerCase();return t===`sshfs`||t.startsWith(`sshfs#`)||t.startsWith(`sshfs@`)||/^(?:[^/\s:]+@)?[^/\s:]+:.*/u.test(e)}function resolveNetworkMountJournalPolicy(e){let t=e.fsType.toLowerCase();if(t.startsWith(`nfs`)||me.has(t))return`rollback`;if(t===`fuse.sshfs`||(t===`macfuse`||t===`osxfuse`)&&isSshfsMountSource(e.source))return`unsupported`}function resolveMountTypeJournalPolicy(e){let t=e.fsType.toLowerCase();return resolveNetworkMountJournalPolicy(e)??(he.has(t)||t.startsWith(`9p`)?`rollback`:`wal`)}function findMountEntry(e,t){return t.filter(t=>isPathWithinMount(e,t.mountPoint)).toSorted((e,t)=>t.mountPoint.length-e.mountPoint.length)[0]}function resolveMountEntryJournalPolicy(e,t){let n=findMountEntry(e,t);return n?resolveMountTypeJournalPolicy(n):`wal`}function isSqlitePathOnBtrfs(e){if(process.platform!==`linux`)return!1;let t=findExistingVolumePaths(e);if(!t)return!1;try{return F.statfsSync(t.canonicalPath).type===2435016766}catch{let e=readMountEntries();return e.ok&&findMountEntry(t.canonicalPath,e.value)?.fsType.toLowerCase()===`btrfs`}}function setSqliteDirectoryNoCow(e){if(!F.statSync(e).isDirectory())throw Error(`SQLite NOCOW target is not a directory: ${e}`);let t=process.getBuiltinModule(`node:child_process`).spawnSync(`chattr`,[`+C`,e],{encoding:`utf8`,killSignal:`SIGKILL`,timeout:G,maxBuffer:4096});if(t.error||t.status!==0)throw t.error??/* @__PURE__ */ Error(`chattr +C failed: ${t.stderr.trim()||t.signal||t.status}`)}function prepareSqliteDatabaseDirectory(e){if(!(process.platform!==`linux`||F.existsSync(e)))try{isSqlitePathOnBtrfs(e)&&setSqliteDirectoryNoCow(N.dirname(e))}catch(t){K||(K=!0,ge.warn(`Could not enable SQLite directory NOCOW; continuing with filesystem defaults`,{databasePath:e,error:t instanceof Error?t.message:String(t)}))}}function combineMountEntryJournalPolicies(e){let t=readMountEntries();if(!t.ok){let[t,n]=e;if(process.platform===`darwin`&&t===n)try{if(probeTreeClone(n)===`apfs`)return`wal`}catch{}return`rollback`}let n=new Set(e.map(e=>resolveMountEntryJournalPolicy(e,t.value)));return n.has(`unsupported`)?`unsupported`:n.has(`rollback`)?`rollback`:`wal`}function isWindowsUncPath(e){return/^\\\\\?\\UNC\\[^\\]+\\[^\\]+/i.test(e)||/^\\\\(?![?.]\\)[^\\]+\\[^\\]+/.test(e)}function isWindowsDrivePath(e){return/^[A-Za-z]:[\\/]/.test(e)||/^\\\\\?\\[A-Za-z]:[\\/]/i.test(e)}function resolvePathJournalPolicy(e){if(process.platform===`win32`){let t=N.win32.normalize(e);if(isWindowsUncPath(t))return`rollback`;if(isWindowsDrivePath(t))try{return isWindowsUncPath(N.win32.normalize(F.realpathSync.native(e)))?`rollback`:`wal`}catch{return`rollback`}}let t=findExistingVolumePaths(e);if(!t)return`wal`;let n=[t.originalPath,t.canonicalPath];try{if(pe.has(F.statfsSync(t.canonicalPath).type))return`rollback`}catch{}return combineMountEntryJournalPolicies(n)}const q=/* @__PURE__ */ new WeakMap;function createSqliteWalReclamationResult(){return{checkpointCompleted:!1,freePagesBefore:null,remainingFreePages:null,checkpointCalls:0,checkpointIncomplete:0,checkpointMs:0,checkpointMaxMs:0,queryMs:0,vacuumMs:0,vacuumPasses:0,vacuumPagesRequested:0}}function readSqliteFreePageCount(e,t){let n=t?L.now():0;try{return Number(e.prepare(`PRAGMA freelist_count`).get()?.freelist_count??0)}finally{t&&(t.queryMs+=L.now()-n)}}function reclaimSqliteWalFreePages(e,t,n){let r=createSqliteWalReclamationResult(),checkpoint=()=>{n.beforeMutation?.();let e=L.now();try{let e=n.checkpointMode??`TRUNCATE`,i=t(e);return r.checkpointCalls++,!i&&e===`TRUNCATE`&&(n.beforeMutation?.(),i=t(`PASSIVE`),r.checkpointCalls++),r.checkpointCompleted=i,r.checkpointIncomplete+=Number(!i),i}finally{let t=L.now()-e;r.checkpointMs+=t,r.checkpointMaxMs=Math.max(r.checkpointMaxMs,t)}};return n.maxPages===0&&n.checkpointMode===`PASSIVE`?(checkpoint(),r):T(e,0,()=>{if(!checkpoint()||n.maxPages===0)return r;let t=readSqliteFreePageCount(e,r);if(r.freePagesBefore=t,r.remainingFreePages=t,!Number.isSafeInteger(t)||t<=0)return r;let i=Math.min(q.get(e)??8,t,n.maxPages??512);if(!Number.isSafeInteger(i)||i<=0)throw Error(`SQLite page reclamation requires a positive integer page limit`);let a=L.now(),o=!1,s=!1;try{oe(e,()=>{o=!0,n.beforeMutation?.(),r.vacuumPasses++,r.vacuumPagesRequested+=i,e.exec(`PRAGMA incremental_vacuum(${i});`),n.onCommit?.()},{beginLockFailureReporting:`suppress`,busyTimeoutMs:0,operationLabel:`incremental-vacuum`}),s=!0}catch(e){if(o||!k(e))throw e;return r}finally{let t=L.now()-a;r.vacuumMs+=t,s&&q.set(e,Math.max(1,Math.min(512,i*2,Math.floor(i*25/Math.max(t,.001)))))}return n.afterCommit?.(),checkpoint()&&(r.remainingFreePages=readSqliteFreePageCount(e,r)),r})}const J=`/proc/self/fd`;async function readUnlessMissing(e,t=!1){try{return await e()}catch(e){if(t&&p(e,`EBADF`)||p(e,`ENOENT`))return;throw e}}function isSqliteWalSidecarSplitBrain(e,t){return e.nlink===0n||!t||e.dev!==t.dev||e.ino!==t.ino}async function detectSqliteWalSplitBrain(e){let t=await readUnlessMissing(()=>F.promises.readdir(J)),n=[`${e}-wal`,`${e}-shm`];for(let r of t??[]){let t=N.join(J,r),i=await readUnlessMissing(()=>F.promises.readlink(t));if(i===void 0)continue;let a=n.find(e=>i===e||i===`${e} (deleted)`);if(!a)continue;let o=await readUnlessMissing(()=>I(F.fstat)(Number(r),{bigint:!0}),!0);if(o===void 0||await readUnlessMissing(()=>F.promises.readlink(t))!==i)continue;let s=await readUnlessMissing(()=>F.promises.stat(a,{bigint:!0}));if(!isSqliteWalSidecarSplitBrain(o,s))continue;let c=await readUnlessMissing(()=>I(F.fstat)(Number(r),{bigint:!0}),!0);if(c&&c.dev===o.dev&&c.ino===o.ino&&await readUnlessMissing(()=>F.promises.readlink(t))===i)return{event:`sqlite_wal_sidecar_identity_mismatch`,databasePath:e,descriptorDevice:o.dev.toString(),descriptorInode:o.ino.toString(),sidecarPath:a,...s?{targetDevice:s.dev.toString(),targetInode:s.ino.toString()}:{}}}}function terminateForSqliteWalSplitBrain(e,t){try{F.writeSync(2,`${JSON.stringify({level:`fatal`,subsystem:`infra/sqlite-wal`,message:`SQLite WAL sidecar identity mismatch; terminating without SQLite cleanup`,...e,databaseLabel:t,pid:process.pid})}\n`)}catch{}try{process.kill(process.pid,`SIGKILL`)}finally{process.abort()}}const Y=e(Symbol.for(`openclaw.sqliteWalWriteAdmissions`),()=>/* @__PURE__ */ new WeakMap);function registerSqliteWalWorkerMaintenance(e,t,n){e.exec(`PRAGMA wal_autocheckpoint = 0;`);let r=Y.get(e)?.stopCheckpointTick;Y.set(e,{execute:t,cancel:n}),r?.()}function isSqliteWalWorkerMaintained(e){return Y.get(e)?.execute!==void 0}function cancelSqliteWalWriteAdmission(e){return Y.get(e)?.cancel?.()}function createSqliteWalMaintenanceScheduler(e,t,n,r,i,a,o){let s=Y.get(e);Y.set(e,{...s,stopCheckpointTick:o});let c;return()=>(c||=(async()=>{let i=a(),o=!1;for(;;){let a=n(i);if(!a||i===0&&Y.get(e)?.execute)return;a.continuation=o;let s,admitted=()=>{n(i)&&(s=t(a))},c=Y.get(e);c?.execute?(s=await c.execute(a),s?.checkpoint&&r(s.checkpoint)):c?.admit?await c.admit(admitted):admitted();let l=s?.reclaimedPages??0;if(i-=l,l<=0||i<=0)return;o=!0,await P()}})().catch(i).finally(()=>{c=void 0}),c)}const X=1e4,Z=67108864,_e=new Int32Array(new SharedArrayBuffer(4)),ve=r(`infra/sqlite-wal`),ye=new GatewayScheduler;let be=0;const Q={name:`sqlite-wal-completed-write-revision`,read:e=>e instanceof SharedArrayBuffer&&e.byteLength===Int32Array.BYTES_PER_ELEMENT?e:void 0};function sharedCompletedCheckpoint(e,t){let n=x(e,Q);return n||=(n=new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT),Atomics.store(new Int32Array(n),0,t-1|0),D(e,Q,n),x(e,Q)),n?new Int32Array(n):void 0}function enableIncrementalAutoVacuumForFreshDatabase(e){let t=e.location(),n=t?C(t,ne):void 0;n&&(n.userVersion>0||n.tables.size>0||n.views.size>0)||e.prepare(`PRAGMA page_count`).get()?.page_count===0&&e.exec(`PRAGMA auto_vacuum = INCREMENTAL;`)}function configureSqlitePreSchemaPragmas(e,t={}){t.busyTimeoutMs!==void 0&&O(e,t.busyTimeoutMs),enableIncrementalAutoVacuumForFreshDatabase(e)}function readJournalModeResult(e){if(!e||typeof e!=`object`)return null;let t=e,n=t.journal_mode??Object.values(t)[0];return typeof n==`string`?n.toLowerCase():null}function hasInMemoryMainDatabase(e){return e.prepare(`PRAGMA database_list;`).all().find(e=>e.name===`main`)?.file===``}function requireRollbackJournalMode(e,t){let n=readJournalModeResult(e.prepare(`PRAGMA journal_mode = DELETE;`).get());if(n!==`delete`){let e=t.databaseLabel??`sqlite database`,r=t.databasePath?` at ${t.databasePath}`:``;throw Error(`${e}${r} is on a network-backed volume but SQLite kept journal_mode=${n??`unknown`}; refusing to continue with WAL on network storage.`)}}function enableWalJournalMode(e,t,n){let r=L.now()+t,i=!1;try{for(;;)try{let t=readJournalModeResult(e.prepare(`PRAGMA journal_mode = WAL;`).get());if(t===`wal`)return!0;if(t===`memory`&&hasInMemoryMainDatabase(e))return!1;let r=n.databaseLabel??`sqlite database`,i=n.databasePath?` at ${n.databasePath}`:``;throw Error(`${r}${i} could not enable WAL; SQLite kept journal_mode=${t??`unknown`}.`)}catch(t){let n=Math.max(0,r-L.now());if(!k(t)||n<=0)throw t;i||=(O(e,0),!0),Atomics.wait(_e,0,0,Math.min(10,n))}}finally{i&&O(e,t)}}function enableMacosCheckpointFullfsync(e){if(process.platform===`darwin`)try{e.exec(`PRAGMA checkpoint_fullfsync = 1;`)}catch{}}function refuseUnsupportedFilesystem(e){let t=e.databaseLabel??`sqlite database`,n=e.databasePath?` at ${e.databasePath}`:``;throw Error(`${t}${n} is on SSHFS, which cannot safely coordinate SQLite writes across mounts; refusing to open the database.`)}function configureSqliteWalMaintenance(e,n={}){let r=n.busyTimeoutMs??0;n.busyTimeoutMs!==void 0&&O(e,n.busyTimeoutMs);let a=E(n.autoCheckpointPages??16384,`autoCheckpointPages`),o=E(n.checkpointIntervalMs??18e5,`checkpointIntervalMs`),s=Math.min(o,t),c=o>X?X:0,l=n.checkpointMode??`TRUNCATE`,u=n.checkpointMode??`PASSIVE`,d=n.databasePath?resolvePathJournalPolicy(n.databasePath):`wal`;if(d===`unsupported`&&refuseUnsupportedFilesystem(n),d===`rollback`&&requireRollbackJournalMode(e,n),d===`rollback`||!enableWalJournalMode(e,r,n))return{checkpoint:()=>!0,reclaimFreePages:(t={})=>reclaimSqliteWalFreePages(e,()=>!0,t),stop:async()=>{},close:()=>!0};enableMacosCheckpointFullfsync(e),e.exec(`PRAGMA wal_autocheckpoint = ${isSqliteWalWorkerMaintained(e)?0:a};`),e.exec(`PRAGMA journal_size_limit = ${Z};`);let f=process.platform===`linux`&&n.databasePath&&F.existsSync(n.databasePath)?F.realpathSync.native(n.databasePath):void 0,p=!1,m=!1,h=!!f,g=createSqliteWalCheckpoint(e,n,Z),_=g.checkpoint,runMaintenance=e=>{if(p||m)return!1;try{return n.runMaintenance?n.runMaintenance(e):e()}catch(e){return g.recordError(e),!1}},checkpoint=()=>runMaintenance(()=>_(l)),reclaimFreePages=(t={})=>{let n,r;if(runMaintenance(()=>{try{return n=reclaimSqliteWalFreePages(e,_,t),n.checkpointCompleted}catch(e){throw r={error:e},e}}),r)throw r.error;if(!n)throw Error(`SQLite page reclamation owner is unavailable`);return{...n,checkpoint:g.snapshot}},v=ye.scope(),y=`sqlite-wal:${++be}`,b=0,x,maintainPeriodic=(t,n,r)=>{if(p)return{reclaimedPages:0};t.checkpoint&&g.adopt(t.checkpoint);let i=0,a=t.maxPages===0,o=a&&t.checkpointMode===`PASSIVE`,s=o?w(e):void 0,c=s===void 0?void 0:sharedCompletedCheckpoint(e,s),l=c!==void 0&&Atomics.load(c,0)===s;if(s!==void 0&&(l||s===x&&g.health?.state===`complete`))return{reclaimedPages:0,checkpoint:g.health?.state===`complete`?g.snapshot:void 0};let runTickCheckpoint=e=>g.checkpoint(e,{quiet:a});return x=runMaintenance(()=>{let a;if(o)n?.(`transaction`),a=runTickCheckpoint(`PASSIVE`);else{let r=reclaimSqliteWalFreePages(e,runTickCheckpoint,{checkpointMode:t.checkpointMode,maxPages:t.maxPages,beforeMutation:()=>n?.(`transaction`),onCommit:()=>n?.(`commit`)});a=r.checkpointCompleted,a&&r.freePagesBefore!==null&&r.remainingFreePages!==null&&(i=Math.min(r.vacuumPagesRequested,r.freePagesBefore-r.remainingFreePages))}if(a&&t.checkpointMode===`PASSIVE`&&(g.health?.walBytes??0)>Z&&(n?.(`transaction`),T(e,0,()=>runTickCheckpoint(`TRUNCATE`))),a&&t.maxPages>0&&!t.continuation)try{r?.()}catch(e){if(!k(e))throw e}return a})&&g.health?.state===`complete`?s:void 0,c&&x!==void 0&&Atomics.store(c,0,x),{reclaimedPages:i,checkpoint:g.snapshot}},stopCheckpointTick,S=createSqliteWalMaintenanceScheduler(e,maintainPeriodic,e=>s>0&&!v.signal.aborted&&!p&&!m&&!n.isScheduledMaintenanceSuspended?.()?{maxPages:e,checkpointMode:u,checkpoint:g.snapshot}:void 0,g.adopt,e=>g.recordError(e),()=>{let e=b;return b=0,e},()=>stopCheckpointTick?.()),schedule=(e,t,n)=>i(()=>v.schedule({id:`${y}:${e}`,delayMs:t,everyMs:t,run:n}));if(s>0&&schedule(`periodic`,s,async()=>{if(f&&h){m=!0;let t=ee(e,()=>{throw Error(`SQLite WAL inspection is pending; await maintenance.stop() before close`)});try{let e;try{e=await detectSqliteWalSplitBrain(f)}catch(e){h=!1,ve.warn(`SQLite WAL split-brain detection disabled`,{databaseLabel:n.databaseLabel,databasePath:f,error:e instanceof Error?e.message:String(e)})}e&&(p=!0,v.beginClose(),terminateForSqliteWalSplitBrain(e,n.databaseLabel))}finally{t(),m=!1}if(v.signal.aborted)return}return b=512,S()}),c>0&&!isSqliteWalWorkerMaintained(e)){let t=!1,n,cancelTick=()=>{n?.cancel(),n=void 0},armTick=()=>{!t&&!n&&!v.signal.aborted&&!p&&(n=i(()=>v.schedule({id:`${y}:tick`,delayMs:c,run:runTick})))},runTick=async()=>{if(n=void 0,await S(),t)return;let r=w(e),i=r===void 0?void 0:sharedCompletedCheckpoint(e,r);i&&Atomics.load(i,0)===r?cancelTick():armTick()},r=u===`PASSIVE`?te(e,armTick):void 0;r?(stopCheckpointTick=()=>{t=!0,r(),cancelTick()},armTick()):stopCheckpointTick=schedule(`tick`,c,S).cancel}let beginClose=()=>(stopCheckpointTick?.(),i(()=>v.beginClose()),cancelSqliteWalWriteAdmission(e));return{get health(){return g.health},checkpoint,maintainPeriodic,reclaimFreePages,inspectIdle:()=>runMaintenance(g.inspectIdle)?`healthy`:`retire`,stop:async()=>{try{await beginClose()}finally{await i(()=>v.stop())}},close:t=>(beginClose(),p||isSqliteWalWorkerMaintained(e)?!1:runMaintenance(()=>_(t?.checkpointMode??l)))}}let $;function detachEmptySqliteExitGroup(e){e.pending.size>0||($===e&&($=void 0),process.removeListener(`exit`,e.dispatch))}function registerSqliteCacheExitClose(e){let t={close:e},n=$;if(!n||process.listeners(`exit`).at(-1)!==n.dispatch){let e=/* @__PURE__ */ new Set([t]),r={pending:e,dispatch:()=>{let t=[...e];e.clear(),detachEmptySqliteExitGroup(r);for(let e of t)try{e.close()}catch{}}};process.on(`exit`,r.dispatch),$=n=r}else n.pending.add(t);let r=n;return()=>{r.pending.delete(t),detachEmptySqliteExitGroup(r)}}function configureSqliteConnectionPragmas(e,t={}){let{foreignKeys:n,synchronous:r,...i}=t,a=configureSqliteWalMaintenance(e,i);try{return r&&e.exec(`PRAGMA synchronous = ${r};`),n&&e.exec(`PRAGMA foreign_keys = ON;`),a}catch(e){try{a.close()}catch(t){throw re([e,t],`SQLite connection pragma configuration and WAL maintenance cleanup both failed.`,e)}throw e}}export{createDirectoryReceiptSync as A,mutationObservationCurrent as C,observeMutationPath as D,nextMissingMutationPath as E,ownDirectoryReceipt as M,NativePolicyDirectoryMismatch as N,assertDirectoryReceiptCurrentSync as O,nativePolicyDirectoryObserver as P,missingMutationSegments as S,mutationObservationsCurrent as T,exactIdentityMatches as _,registerSqliteWalWorkerMaintenance as a,advanceMutationObservation as b,truncateSqliteWal as c,assertNativeStagedDirectoryCurrent as d,assertPolicyStagedDirectoryCurrent as f,describeStagedDirectory as g,describePolicyStagedDirectory as h,isSqliteWalWorkerMaintained as i,directoryReceiptAuthority as j,copyRetainedDirectoryReceipt as k,coerceRequiredSqliteNumber as l,describeNativeStagedDirectory as m,configureSqlitePreSchemaPragmas as n,createSqliteWalReclamationResult as o,assertStagedDirectoryCurrent as p,registerSqliteCacheExitClose as r,prepareSqliteDatabaseDirectory as s,configureSqliteConnectionPragmas as t,normalizeSqliteNumber as u,openStagedDirectory as v,mutationObservationUsesDirectory as w,checkedMutationDirectory as x,refreshPolicyStagedDirectoryObservation as y};