openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
3 lines • 54.6 kB
JavaScript
import{Cn as e,Dn as t,Ht as n,a as r,gt as i,mn as a,pt as o,t as s,un as c}from"./openclaw-state-read-subsystem-Dwoo5bcz.mjs";import{$ as l,J as u,K as d,U as f,dt as p,f as m,jt as h,o as g,p as _,v,w as y}from"./openclaw-state-read-sqlite-database-admission-CrkztOzk.mjs";import{At as b,Ct as x,Dt as S,N as C,Pt as w,Zt as T,an as E,c as ee,fn as te,g as ne,kt as re,nn as D,nt as O,pn as k,st as ie,tt as A,y as ae}from"./openclaw-state-read-src-RL5xtYG2.mjs";import{u as oe,v as j,x as se}from"./openclaw-state-read-sqlite-post-commit-CsXPYVOo.mjs";import{t as ce}from"./openclaw-state-read-deferred-B75K7ut7.mjs";import{a as M,d as le,f as N,i as ue,l as de,o as fe,p as pe,s as me,t as P,u as he}from"./openclaw-state-read-fs-safe-DruirEvq.mjs";import{o as ge,s as _e}from"./openclaw-state-read-sidecar-lock-DBl8LBF5.mjs";import{n as F}from"./openclaw-state-read-positional-read-zdUE4ydg.mjs";import{Ct as ve,_ as ye,_t as I,dt as be,ft as xe,g as Se,gt as Ce,h as we,ht as Te,lt as Ee,pt as L,v as R,wt as De,yt as z}from"./openclaw-state-read-sqlite-readonly-worker-D6FdUovN.mjs";import"./openclaw-state-read-openclaw-state-db-contract-vqwNsqc6.mjs";import{n as Oe,r as B,s as ke,t as Ae}from"./openclaw-state-read-sqlite-wal-write-admission-BvF6tHCz.mjs";import{d as je}from"./openclaw-state-read-kysely-sync-cache-state-C7JSbWq6.mjs";import{a as V,i as Me,t as Ne}from"./openclaw-state-read-sqlite-busy-timeout-B0rAL9T0.mjs";import{t as Pe}from"./openclaw-state-read-errors-D4PLrhBz.mjs";import{i as Fe,s as Ie}from"./openclaw-state-read-sqlite-reader-lifecycle-CcWh6s9c.mjs";import{b as H,o as U}from"./openclaw-state-read-sqlite-schema-facts-Dtolu7-X.mjs";import{a as Le,n as W,o as Re}from"./openclaw-state-read-node-sqlite-B_Qn1gsS.mjs";import{n as G}from"./openclaw-state-read-error-graph-internal-Cj78mC_c.mjs";import{o as ze,t as Be}from"./openclaw-state-read-openclaw-state-db-schema-helpers-QFZd8aJI.mjs";import{c as Ve,o as He}from"./openclaw-state-read-openclaw-root-CbFTRFFl.mjs";import{n as Ue,r as We}from"./openclaw-state-read-sqlite-number-5mfxKD9j.mjs";import{i as Ge}from"./openclaw-state-read-sqlite-transaction-Bt-IwVhZ.mjs";import"./openclaw-state-read-sqlite-user-version-B2KxorOy.mjs";import K from"node:fs";import q from"node:path";import"node:fs/promises";import{randomUUID as Ke}from"node:crypto";import{AsyncLocalStorage as qe}from"node:async_hooks";import{promisify as Je}from"node:util";import{performance as J}from"node:perf_hooks";function admitUncachedCopyPath(e,t=!1,n){if(!q.isAbsolute(e.rootPath)||!q.isAbsolute(e.absolutePath))throw new k(`invalid-path`,`copy roots and paths must be absolute`);let r=n??O(D.native(e.rootPath),`native`,{bigint:!0}),i=n?.realPath,resolve=()=>{let n=t?ae({...e,rootCanonicalPath:i,absolutePath:q.dirname(e.absolutePath),boundaryLabel:`copy parent`,rejectSymlinks:!0,rejectFinalSymlink:!0}):void 0,r=ae({...e,rootCanonicalPath:i,boundaryLabel:`copy`,rejectSymlinks:!t,rejectFinalSymlink:!t,policy:t?ne.unlinkTarget:void 0});if(n&&q.dirname(r.canonicalPath)!==n.canonicalPath)throw new k(`path-mismatch`,`copy destination parent changed`);return r},a=resolve(),o=O(q.dirname(a.canonicalPath),`native`,{bigint:!0}),assertCurrent=()=>{A(r),A(o);let e=resolve();if(e.rootCanonicalPath!==r.realPath||e.canonicalPath!==a.canonicalPath)throw new k(`path-mismatch`,`copy path changed during operation`);A(r),A(o)};return assertCurrent(),{path:a.canonicalPath,parent:o,assertCurrent,rootCanonicalPath:void 0}}function createCopyPathAdmissionCache(){let e=/* @__PURE__ */ new Map,t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,assertParent=({root:e,parent:t,chain:n})=>{A(e);for(let e of n)e!==t&&ie(e.dir,{dev:BigInt(e.stat.dev),ino:BigInt(e.stat.ino)});t!==e&&A(t),A(e)};return{admit:(r,i=!1)=>{if(process.platform===`win32`&&(!/^[a-z]:\\/iu.test(r.rootPath)||T(r.rootPath,`filesystem`)||T(r.absolutePath,`filesystem`)||r.absolutePath.slice(3).split(`\\`).some(e=>/[. ]$/u.test(e)||e.includes(`~`)))||!q.isAbsolute(r.rootPath)||!q.isAbsolute(r.absolutePath)||r.rootPath.includes(`\0`)||r.absolutePath.includes(`\0`)||q.resolve(r.rootPath)!==r.rootPath||q.resolve(r.absolutePath)!==r.absolutePath||!r.absolutePath.startsWith(r.rootPath.endsWith(q.sep)?r.rootPath:`${r.rootPath}${q.sep}`))return admitUncachedCopyPath(r,i);let a=e.get(r.rootPath);if(!a){let t=D.native(r.rootPath);if(t!==r.rootPath)return admitUncachedCopyPath(r,i);a=O(t,`native`,{bigint:!0}),e.set(r.rootPath,a)}A(a);let o=q.dirname(r.absolutePath),s=t.get(r.rootPath),c=s?.get(o);if(!c){let e=admitUncachedCopyPath(r,i,a),l=[],u=r.rootPath,d=q.relative(r.rootPath,o);for(let e of d?d.split(q.sep):[]){u=q.join(u,e);let t=n.get(u);t||(t=O(u,`native`,{bigint:!0}),n.set(u,t)),l.push(t)}if(c={root:a,parent:l.at(-1)??a,chain:l},assertParent(c),e.path!==r.absolutePath||e.parent.realPath!==o||!b(e.parent.stat,c.parent.stat))throw new k(`path-mismatch`,`copy path changed during admission`);s??=/* @__PURE__ */ new Map,s.set(o,c),t.set(r.rootPath,s)}let l=c,assertCurrent=()=>{if(assertParent(l),!i&&K.lstatSync(r.absolutePath,{throwIfNoEntry:!1})?.isSymbolicLink())throw admitUncachedCopyPath(r,i),new k(`symlink`,`symlink not allowed`)};return assertCurrent(),{path:r.absolutePath,parent:l.parent,assertCurrent,rootCanonicalPath:l.root.realPath}},clear(){e.clear(),t.clear(),n.clear()}}}function copyError(e){if(e instanceof k)return e;let t=e?.code;return new k(t===`EEXIST`?`already-exists`:t===`ENOENT`?`not-found`:t===`too-large`?`too-large`:[`ENOTSUP`,`EOPNOTSUPP`,`ENOSYS`,`EXDEV`,`EINVAL`].includes(t??``)?`unsupported-platform`:`helper-failed`,`guarded synchronous file copy failed`,{cause:e})}function copyRootFileSync(e){return copyRootFileWithAdmissionSync(e,createCopyPathAdmissionCache())}function copyRootFileWithAdmissionSync(e,t){let n=e.source,r={rootPath:n.rootPath,absolutePath:n.absolutePath},i=e.destination,a={rootPath:i.rootPath,absolutePath:i.absolutePath},o=e.expectedSourceIdentity,s=o===void 0?void 0:re(o),c=s&&{dev:s.dev,ino:s.ino},l=pe(e.clone,`never`),u=S(e.maxBytes),d=e.mode,f=e.preserveSourceMode,p=e.sourceHardlinks??`reject`;if(d!==void 0&&(!Number.isInteger(d)||d<0||d>511))throw new k(`invalid-path`,`copy mode must be an integer from 0 to 0o777`);if(p!==`allow`&&p!==`reject`)throw new k(`invalid-path`,`invalid copy source hardlink policy`);let m,h,g,_=!1,v,y,b=process.platform===`win32`?E():E(`copyFileExclusiveSync`,`removeStagedFile`),w=process.platform!==`win32`&&b?.copyFileExclusiveSync&&b.removeStagedFile?b.copyFileExclusiveSync.bind(b):void 0;try{let e=t.admit(r);if(v=t.admit(a,!0),C(a.absolutePath),K.lstatSync(v.path,{throwIfNoEntry:!1}))throw new k(`already-exists`,`copy destination already exists`);let n=ee({...r,rootRealPath:e.rootCanonicalPath,boundaryLabel:`copy source`,maxBytes:u,rejectHardlinks:p!==`allow`});if(!n.ok)throw n.error??new k(`helper-failed`,`copy source admission failed`);m=N(n.fd);let i=x(()=>K.fstatSync(n.fd,{bigint:!0}),c),verifySource=()=>{e.assertCurrent();for(let t of[()=>K.fstatSync(n.fd,{bigint:!0}),()=>M(e.path,void 0)]){let e=x(t,i);if(!e.isFile())throw new k(`not-file`,`copy source must be a regular file`);if(p!==`allow`&&e.nlink>1n)throw new k(`hardlink`,`copy source must not be hardlinked`)}},o=d??(f?Number(i.mode&511n):384&~process.umask()),s;if(verifySource(),v.assertCurrent(),w){let e=te(b),t=ue(v.parent.realPath);g=N(t.fd),_=!0,x(()=>K.fstatSync(t.fd,{bigint:!0}),{dev:BigInt(v.parent.stat.dev),ino:BigInt(v.parent.stat.ino)}),v.assertCurrent();try{s=w(n.fd,t.fd,q.basename(v.path),l,u!==void 0&&Number.isFinite(u)?u:void 0)}catch(e){throw _e(e,v.path),e}h=N(s.fd,e)}else{if(l===`always`)throw new k(`unsupported-platform`,`synchronous native file cloning is unavailable`);h=de(v.path,{mode:384,assertBeforeMutation:v.assertCurrent},he(v.parent))}y=x(()=>K.fstatSync(h.fd,{bigint:!0}));let verifyTarget=()=>{v.assertCurrent();let e=x(()=>K.fstatSync(h.fd,{bigint:!0}),y),t=x(()=>M(v.path,void 0),y);if(!e.isFile()||e.nlink!==1n||!t.isFile()||t.nlink!==1n)throw new k(`path-mismatch`,`copy destination changed`);return e};if(verifyTarget(),s?.errorCode)throw copyError(Object.assign(Error(s.errorMessage),{code:s.errorCode}));let S=s?s.method:`copy`;if(S!==`clone`&&S!==`copy-file-range`&&S!==`copy`)throw new k(`helper-failed`,`native copy returned an unknown method`);s||fe(n.fd,h.fd,{maxBytes:u}),verifySource();let T=verifyTarget();if(u!==void 0&&Number.isFinite(u)&&T.size>BigInt(u))throw new k(`too-large`,`copy exceeds maxBytes`);return K.fchmodSync(h.fd,o),verifySource(),verifyTarget(),m.close(),_=!1,g?.close(),Object.freeze({...h,path:v.path,bytes:Number(T.size),method:S,identity:Object.freeze({dev:y.dev,ino:y.ino}),sourceIdentity:Object.freeze({dev:i.dev,ino:i.ino})})}catch(e){let t=copyError(e),n=[];if(h&&v)try{if(_){if(b.removeStagedFile(g.fd,q.basename(v.path),h.fd)===`preserved`)throw new k(`path-mismatch`,`copy cleanup preserved a replacement`)}else y&&le(v.path,y,v.assertCurrent)}catch(e){n.push(e)}for(let e of[h,m,g])try{e?.close()}catch(e){n.push(e)}throw n.length?new k(t.code,t.message,{cause:AggregateError([t,...n],`copy and cleanup failed`),details:{path:v?.path,cleanup:`failed`}}):t}}function sameFileContentsSync(e,t,n={}){let r=S(n.maxBytes)??1/0,i=Math.min(r,2**53-1),tooLarge=()=>new k(`too-large`,`file comparison exceeds ${i} bytes`);for(let n of[e,t]){let e=K.fstatSync(n,{bigint:!0});if(!e.isFile())throw new k(`not-file`,`file comparison requires regular-file descriptors`);if(e.size>BigInt(i))throw tooLarge()}let a=Buffer.allocUnsafe(Math.min(1048576,Math.max(1,i))),o=Buffer.allocUnsafe(a.length),s=0;for(;;){let n=Math.min(a.length,i-s);if(n===0){let n=K.readSync(e,a,0,1,s),r=K.readSync(t,o,0,1,s);if(n!==0||r!==0)throw tooLarge();return!0}let r=F(e,a.subarray(0,n),s),c=F(t,o.subarray(0,n),s);if(r!==c||!a.subarray(0,r).equals(o.subarray(0,c)))return!1;if(r<n)return!0;s+=r}}const Ye=e(Symbol.for(`openclaw.sessionControllerCleanupContext`),()=>({}));function runWithSessionControllerCleanup(e){return Ye.exit?Ye.exit(e):e()}const Y=s(`gateway/scheduler`),Xe={now:()=>Date.now(),monotonicNow:()=>performance.now(),arm:(e,t)=>{let n=setTimeout(()=>{o(`scheduler:wake`,()=>{e()})},t);return n.unref(),()=>clearTimeout(n)}};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??Xe}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(),G(e.signal.reason),G(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:Ve(()=>runWithSessionControllerCleanup(()=>qe.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(),G(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&&Y.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){Y[e.everyMs===void 0?`debug`:`trace`](`running ${e.id}`);let t=ce(),n=new He;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()},r;try{r=e.context(()=>o(e.diagnosticName,()=>n.run(e.run)))}catch(t){Y.error(`${e.id} failed: ${String(t)}`)}if(!r&&!n.hasPendingWork)finish();else return Promise.resolve(r).catch(t=>Y.error(`${e.id} failed: ${String(t)}`)).then(()=>He.runWhenAllIdle(()=>[n],()=>n.drain())).finally(finish),t.promise}};const Ze=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}=Fe(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 Ze)try{n({databasePath:Ie(e),health:structuredClone(t.health),observedAtNs:t.observedAtNs,lastCompletedAtNs:t.lastCompletedAtNs})}catch{}}function publishSqliteWalCheckpointObservation(e,t){let n={health:observeSqliteWalCheckpointHealth(e,t.health),observedAtNs:t.observedAtNs,lastCompletedAtNs:t.lastCompletedAtNs};return notifyCheckpoint(e,n),n}function sqliteFileBytes(e){try{return K.statSync(e).size}catch(e){if(w(e,`ENOENT`))return 0;throw e}}function readCheckpointResult(e){let[t,n,r]=Object.values(e??{}).map(e=>Ue(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=We(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:Pe(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=Pe(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 K.closeSync(e),t}catch(e){return firstFailure(t,e)}}function probeTreeClone(e){let t=E(`probeTreeClone`);if(!t)return;let n=ue(ge(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 Qe=/\\([0-7]{3})/g;function decodeMountInfoPath(e){return e.replace(Qe,(e,t)=>String.fromCharCode(Number.parseInt(t,8)))}const $e=/* @__PURE__ */ new Set([.../* @__PURE__ */ new Set([26985,20859,4283649346,4266872130]),16914839]),et=1e3,tt=/* @__PURE__ */ new Set([`cifs`,`smbfs`,`smb2`,`smb3`]),nt=/* @__PURE__ */ new Set([`virtiofs`,`fuse.virtiofs`,`9p`,`9p2000.l`]),rt=s(`infra/sqlite-wal`);let it=!1;function findExistingVolumePaths(e){let t=q.resolve(e);for(;;){let e;try{e=K.statSync(t)}catch{let e=q.dirname(t);if(e===t)return null;t=e;continue}let n=K.realpathSync(t);return{canonicalPath:e.isDirectory()?n:q.dirname(n),originalPath:e.isDirectory()?t:q.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(K.readFileSync(`/proc/self/mountinfo`,`utf8`))}}catch{}try{return{ok:!0,value:parseMountCommandEntries(String(process.getBuiltinModule(`node:child_process`).execFileSync(`mount`,[],{killSignal:`SIGKILL`,timeout:et})))}}catch(e){return w(e,`ETIMEDOUT`)?{ok:!1,error:`timeout`}:{ok:!0,value:[]}}}function isPathWithinMount(e,t){let n=q.resolve(e),r=q.resolve(t);return n===r||r===q.parse(r).root||n.startsWith(`${r}${q.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`)||tt.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)??(nt.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 K.statfsSync(t.canonicalPath).type===2435016766}catch{let e=readMountEntries();return e.ok&&findMountEntry(t.canonicalPath,e.value)?.fsType.toLowerCase()===`btrfs`}}function setSqliteDirectoryNoCow(e){if(!K.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:et,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`||K.existsSync(e)))try{isSqlitePathOnBtrfs(e)&&setSqliteDirectoryNoCow(q.dirname(e))}catch(t){it||(it=!0,rt.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=q.win32.normalize(e);if(isWindowsUncPath(t))return`rollback`;if(isWindowsDrivePath(t))try{return isWindowsUncPath(q.win32.normalize(K.realpathSync.native(e)))?`rollback`:`wal`}catch{return`rollback`}}let t=findExistingVolumePaths(e);if(!t)return`wal`;let n=[t.originalPath,t.canonicalPath];try{if($e.has(K.statfsSync(t.canonicalPath).type))return`rollback`}catch{}return combineMountEntryJournalPolicies(n)}const at=/* @__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?J.now():0;try{return Number(e.prepare(`PRAGMA freelist_count`).get()?.freelist_count??0)}finally{t&&(t.queryMs+=J.now()-n)}}function reclaimSqliteWalFreePages(e,t,n){let r=createSqliteWalReclamationResult(),checkpoint=()=>{n.beforeMutation?.();let e=J.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=J.now()-e;r.checkpointMs+=t,r.checkpointMaxMs=Math.max(r.checkpointMaxMs,t)}};return n.maxPages===0&&n.checkpointMode===`PASSIVE`?(checkpoint(),r):Me(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(at.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=J.now(),o=!1,s=!1;try{Ge(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||!f(e))throw e;return r}finally{let t=J.now()-a;r.vacuumMs+=t,s&&at.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 ot=`/proc/self/fd`;async function readUnlessMissing(e,t=!1){try{return await e()}catch(e){if(t&&w(e,`EBADF`)||w(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(()=>K.promises.readdir(ot)),n=[`${e}-wal`,`${e}-shm`];for(let r of t??[]){let t=q.join(ot,r),i=await readUnlessMissing(()=>K.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(()=>Je(K.fstat)(Number(r),{bigint:!0}),!0);if(o===void 0||await readUnlessMissing(()=>K.promises.readlink(t))!==i)continue;let s=await readUnlessMissing(()=>K.promises.stat(a,{bigint:!0}));if(!isSqliteWalSidecarSplitBrain(o,s))continue;let c=await readUnlessMissing(()=>Je(K.fstat)(Number(r),{bigint:!0}),!0);if(c&&c.dev===o.dev&&c.ino===o.ino&&await readUnlessMissing(()=>K.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{K.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 st=1e4,X=67108864,ct=new Int32Array(new SharedArrayBuffer(4)),lt=s(`infra/sqlite-wal`),ut=new GatewayScheduler;let dt=0;const Z={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=g(e,Z);return n||=(n=new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT),Atomics.store(new Int32Array(n),0,t-1|0),v(e,Z,n),g(e,Z)),n?new Int32Array(n):void 0}function enableIncrementalAutoVacuumForFreshDatabase(e){let t=e.location(),n=t?_(t,H):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&&V(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=J.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-J.now());if(!f(t)||n<=0)throw t;i||=(V(e,0),!0),Atomics.wait(ct,0,0,Math.min(10,n))}}finally{i&&V(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,t={}){let r=t.busyTimeoutMs??0;t.busyTimeoutMs!==void 0&&V(e,t.busyTimeoutMs);let a=Ne(t.autoCheckpointPages??16384,`autoCheckpointPages`),o=Ne(t.checkpointIntervalMs??18e5,`checkpointIntervalMs`),s=Math.min(o,n),c=o>st?st:0,l=t.checkpointMode??`TRUNCATE`,u=t.checkpointMode??`PASSIVE`,d=t.databasePath?resolvePathJournalPolicy(t.databasePath):`wal`;if(d===`unsupported`&&refuseUnsupportedFilesystem(t),d===`rollback`&&requireRollbackJournalMode(e,t),d===`rollback`||!enableWalJournalMode(e,r,t))return{checkpoint:()=>!0,reclaimFreePages:(t={})=>reclaimSqliteWalFreePages(e,()=>!0,t),stop:async()=>{},close:()=>!0};enableMacosCheckpointFullfsync(e),e.exec(`PRAGMA wal_autocheckpoint = ${B(e)?0:a};`),e.exec(`PRAGMA journal_size_limit = ${X};`);let p=process.platform===`linux`&&t.databasePath&&K.existsSync(t.databasePath)?K.realpathSync.native(t.databasePath):void 0,h=!1,g=!1,_=!!p,v=createSqliteWalCheckpoint(e,t,X),b=v.checkpoint,runMaintenance=e=>{if(h||g)return!1;try{return t.runMaintenance?t.runMaintenance(e):e()}catch(e){return v.recordError(e),!1}},checkpoint=()=>runMaintenance(()=>b(l)),reclaimFreePages=(t={})=>{let n,r;if(runMaintenance(()=>{try{return n=reclaimSqliteWalFreePages(e,b,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:v.snapshot}},x=ut.scope(),S=`sqlite-wal:${++dt}`,C=0,w,maintainPeriodic=(t,n,r)=>{if(h)return{reclaimedPages:0};t.checkpoint&&v.adopt(t.checkpoint);let i=0,a=t.maxPages===0,o=a&&t.checkpointMode===`PASSIVE`,s=o?y(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===w&&v.health?.state===`complete`))return{reclaimedPages:0,checkpoint:v.health?.state===`complete`?v.snapshot:void 0};let runTickCheckpoint=e=>v.checkpoint(e,{quiet:a});return w=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`&&(v.health?.walBytes??0)>X&&(n?.(`transaction`),Me(e,0,()=>runTickCheckpoint(`TRUNCATE`))),a&&t.maxPages>0&&!t.continuation)try{r?.()}catch(e){if(!f(e))throw e}return a})&&v.health?.state===`complete`?s:void 0,c&&w!==void 0&&Atomics.store(c,0,w),{reclaimedPages:i,checkpoint:v.snapshot}},stopCheckpointTick,T=Oe(e,maintainPeriodic,e=>s>0&&!x.signal.aborted&&!h&&!g&&!t.isScheduledMaintenanceSuspended?.()?{maxPages:e,checkpointMode:u,checkpoint:v.snapshot}:void 0,v.adopt,e=>v.recordError(e),()=>{let e=C;return C=0,e},()=>stopCheckpointTick?.()),schedule=(e,t,n)=>i(()=>x.schedule({id:`${S}:${e}`,delayMs:t,everyMs:t,run:n}));if(s>0&&schedule(`periodic`,s,async()=>{if(p&&_){g=!0;let n=je(e,()=>{throw Error(`SQLite WAL inspection is pending; await maintenance.stop() before close`)});try{let e;try{e=await detectSqliteWalSplitBrain(p)}catch(e){_=!1,lt.warn(`SQLite WAL split-brain detection disabled`,{databaseLabel:t.databaseLabel,databasePath:p,error:e instanceof Error?e.message:String(e)})}e&&(h=!0,x.beginClose(),terminateForSqliteWalSplitBrain(e,t.databaseLabel))}finally{n(),g=!1}if(x.signal.aborted)return}return C=512,T()}),c>0&&!B(e)){let t=!1,n,cancelTick=()=>{n?.cancel(),n=void 0},armTick=()=>{!t&&!n&&!x.signal.aborted&&!h&&(n=i(()=>x.schedule({id:`${S}:tick`,delayMs:c,run:runTick})))},runTick=async()=>{if(n=void 0,await T(),t)return;let r=y(e),i=r===void 0?void 0:sharedCompletedCheckpoint(e,r);i&&Atomics.load(i,0)===r?cancelTick():armTick()},r=u===`PASSIVE`?m(e,armTick):void 0;r?(stopCheckpointTick=()=>{t=!0,r(),cancelTick()},armTick()):stopCheckpointTick=schedule(`tick`,c,T).cancel}let beginClose=()=>(stopCheckpointTick?.(),i(()=>x.beginClose()),Ae(e));return{get health(){return v.health},checkpoint,maintainPeriodic,reclaimFreePages,inspectIdle:()=>runMaintenance(v.inspectIdle)?`healthy`:`retire`,stop:async()=>{try{await beginClose()}finally{await i(()=>x.stop())}},close:t=>(beginClose(),h||B(e)?!1:runMaintenance(()=>b(t?.checkpointMode??l)))}}let Q;function detachEmptySqliteExitGroup(e){e.pending.size>0||(Q===e&&(Q=void 0),process.removeListener(`exit`,e.dispatch))}function registerSqliteCacheExitClose(e){let t={close:e},n=Q;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),Q=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 se([e,t],`SQLite connection pragma configuration and WAL maintenance cleanup both failed.`,e)}throw e}}async function backupNodeSqliteDatabase(e,t,n){let r=setInterval(()=>{},100);try{let r=await p().backup(e,Re(t),{progress:n});return n?.({totalPages:r,remainingPages:0}),r}finally{clearInterval(r)}}async function copySqliteFile(e,t,n,r){let i=await P(q.dirname(e)),a=await P(q.dirname(t)),o,copy=s=>a.copyIn(q.basename(t),{relativePath:q.basename(e),root:{stat:e=>i.stat(e),open:async(t,r)=>{let a=await i.open(t,r);try{if(!b(n,await a.handle.stat({bigint:!0})))throw Error(`SQLite copy source changed: ${e}`);return a}catch(e){throw await a.handle.close(),e}}}},{clone:s,...r?{maxBytes:Number(n.size)}:{},sourceHardlinks:`allow`,overwrite:!1,mode:384,durable:!0,onDestinationPublished:e=>{o=e}});if(r)try{await copy(`always`)}catch(e){if(o||!(e instanceof k)||!(e.code===`unsupported-platform`||e.code===`helper-unavailable`&&e.message===`native file cloning is unavailable`))throw e;await r(Number(n.size)),await copy(`never`)}else await copy(`auto`);if(!o)throw Error(`SQLite copy was not published: ${t}`);return o}function createPrivateWindowsDirectory(e){let t=!1;try{me(q.resolve(e),{private:!0,assertBeforeMutation(){t=!0}})}catch(e){throw!t||e instanceof k&&e.code===`already-exists`?R(e):e}}function resolvePrivateSqliteSnapshotStagingRoot(e=process.env){try{return resolveSnapshotStagingRoot(e)}catch(e){throw e instanceof Error&&Se(e)?new we(`SQLite snapshot staging root is unavailable: ${e.message}; free disk space/quota`,{cause:e}):e}}function resolveSnapshotStagingRoot(e){let t=e.OPENCLAW_UPDATE_IN_PROGRESS===`1`?e.TMPDIR?.trim():void 0;if(t&&q.isAbsolute(t))return r({preferredDir:q.join(t,`openclaw`),tmpdir:()=>t});let n=process.platform===`win32`?e.LOCALAPPDATA?.trim():void 0,i=process.platform===`win32`?`AppData/Local`:`.cache`,a=process.platform===`darwin`?`Library/Caches`:i,o=[e.XDG_CACHE_HOME?.trim(),n].find(e=>e&&q.isAbsolute(e))??q.join(c(e),a);return r({preferredDir:q.join(o,`openclaw`),tmpdir:()=>o})}function createPrivateSqliteTempDirectorySync(e,t){if(process.platform!==`win32`)try{return K.mkdtempSync(q.join(e,t))}catch(e){throw R(e)}let n=q.join(e,`${t}${Ke()}`);return createPrivateWindowsDirectory(n),n}const $={name:`agent.schema-metadata`,lifetime:`process`,schemaDependent:!0,read(e){if(!(typeof e!=`object`||!e||!(`agentId`in e)||e.agentId!==null&&typeof e.agentId!=`string`||!(`role`in e)||e.role!==null&&typeof e.role!=`string`||!(`schemaVersion`in e)||e.schemaVersion!==null&&typeof e.schemaVersion!=`number`))return{agentId:e.agentId,role:e.role,schemaVersion:e.schemaVersion}}};function schemaMetadataKey(e){return{name:`agent.schema-metadata:${e}`,read:$.read}}function publishAgentSchemaMetadata(e,t){v(e,$,t);let n=U(e);n&&v(e,schemaMetadataKey(n.admissionId),t)}function readExistingAgentSchemaMeta(e){let t=U(e),n=t&&g(e,schemaMetadataKey(t.admissionId));if(n)return n;let r=!t||g(e,H)?.admissionId===t.admissionId?g(e,$):void 0;if(r)return t&&v(e,schemaMetadataKey(t.admissionId),r),r;if(!ze(e,`schema_meta`))return null;let i;try{i=e.prepare(`SELECT role, schema_version, agent_id FROM schema_meta WHERE meta_key = 'primary'`).get()}catch(t){throw Be(e,`schema_meta`,[`meta_key`,`role`,`schema_version`,`agent_id`],t)}if(!i)return null;let o={agentId:a(i.agent_id),role:typeof i.role==`string`?i.role:null,schemaVersion:typeof i.schema_version==`number`?i.schema_version:null},s=t&&U(e)===t;return oe(e)||s&&g(e,H)?.admissionId===t.admissionId?publishAgentSchemaMetadata(e,o):s&&v(e,schemaMetadataKey(t.admissionId),o),o}function sqliteSnapshotSourceFileSize(e){try{let t=K.statSync(e);return t.isFile()?t.size:0}catch(e){if(w(e,`ENOENT`))return 0;throw e}}function waitForSnapshotRetrySync(e){if(e+1>=10)return;let t=Math.min(80,10*2**e);t>0&&Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function finiteNonNegativeNumber(e){let t=Number(e);return Number.isFinite(t)&&t>=0?t:null}function findExistingDiskSpacePath(e){let t=q.resolve(e);for(;;)try{return K.statSync(t).isDirectory()?t:q.dirname(t)}catch{let e=q.dirname(t);if(e===t)return null;t=e}}function tryReadDiskSpace(e){let t=findExistingDiskSpacePath(e);if(!t)return null;try{let n=K.statfsSync(t),r=finiteNonNegativeNumber(n.bsize),i=finiteNonNegativeNumber(n.bavail);if(r===null||i===null)return null;let a=finiteNonNegativeNumber(n.blocks);return{targetPath:e,checkedPath:t,availableBytes:r*i,totalBytes:a===null?null:r*a}}catch{return null}}function acquireSqliteSnapshotReadToken(e){return De(e,`read`)}function sqliteSnapshotStagingError(e,t,n=!1,r){d(t,`snapshot`);let i=n,a=!1,o=!1,s;for(let n=0,r=t;n<8&&r instanceof Error;n+=1){o||=r instanceof AggregateError||r instanceof j;let{errcode:t,path:n}=r;a||=Se(r),(a||typeof t==`number`&&[13,778,1034,1290].includes(t)||`${n??``}${q.sep}`.startsWith(`${e}${q.sep}`))&&(i=!0,typeof t==`number`&&(s=t)),r=r.cause}if(!i)return t;let c=a?`free disk space/quota`:`check filesystem health and write permissions`,l=``;if(a&&r)try{let t=sqliteSnapshotSourceFileSize(r)+sqliteSnapshotSourceFileSize(`${r}-wal`)+sqliteSnapshotSourceFileSize(`${r}-journal`),n=tryReadDiskSpace(e)?.availableBytes,i=K.existsSync(`${r}-wal`)&&K.existsSync(`${r}-shm`);l=`; estimated ${t} bytes needed; ${n===void 0?`available bytes unknown`:`${n} bytes available`}; source ${i?`has live WAL sidecars`:`has no live WAL sidecars`}`}catch{}let f=process.env.OPENCLAW_UPDATE_IN_PROGRESS===`1`?`TMPDIR`:`XDG_CACHE_HOME`,p=`${t instanceof Error?t.message:String(t)}${s===void 0?``:` (SQLite errcode=${s})`}; snapshot staging root ${n?e:q.dirname(e)}${l}: ${c} or set ${f} to a writable filesystem`,m=a&&!o&&u(t)!==`source`?new we(p,{cause:t}):Error(p,{cause:t});return ye(t)?R(m):m}async function createSqliteSnapshotStagingDirectory(e=resolvePrivateSqliteSnapshotStagingRoot(),t=!1,n,r=!1){n?.throwIfAborted();try{return await allocateSqliteSnapshotStagingDirectory(e,t,n,r)}catch(e){throw e instanceof j||r&&e instanceof AggregateError||(n?.throwIfAborted(),d(e,`snapshot`)),e}}async function allocateSqliteSnapshotStagingDirectory(e=resolvePrivateSqliteSnapshotStagingRoot(),t=!1,n,r=!1){if(n?.throwIfAborted(),r){let r=new AbortController;return z((async()=>{let{allocateWorkerOwnedSqliteSnapshotDirectory:i}=await import(`./openclaw-state-read-sqlite-snapshot-staging-allocation-DLGwexTK.mjs`);n?.throwIfAborted(),r.signal.throwIfAborted();let a=await i(e,t,n?AbortSignal.any([n,r.signal]):r.signal);if(Te(a.directory),n?.aborted||r.signal.aborted){if(!await I(a.directory))throw new j(`SQLite snapshot cleanup failed: ${a.directory}`);n?.throwIfAborted(),r.signal.throwIfAborted()}return a.directory})(),()=>r.abort(/* @__PURE__ */ Error(`SQLite snapshot allocation stopped`)))}return createSqliteSnapshotStagingDirectorySync(e,t)}function createSqliteSnapshotStagingDirectorySync(e=resolvePrivateSqliteSnapshotStagingRoot(),t=!1){let n=createSqliteSnapshotStagingTokenSync(e,t);return Te(n.directory,n.release),n.directory}function createSqliteSnapshotStagingTokenSync(e=resolvePrivateSqliteSnapshotStagingRoot(),t=!1){let n;try{try{n=createPrivateSqliteTempDirectorySync(e,t?`openclaw-sqlite-readonly-${process.pid}-`:ve)}catch(t){throw sqliteSnapshotStagingError(e,t,!0)}return{directory:n,release:De(n,`create`)}}catch(e){throw n&&Ce(n),e}}function readUint32(e,t,n){return n===`LE`?e.readUInt32LE(t):e.readUInt32BE(t)}function sqliteWalChecksum(e,t,n=[0,0]){let[r,i]=n;for(let n=0;n<e.length;n+=8)r=r+readUint32(e,n,t)+i>>>0,i=i+readUint32(e,n+4,t)+r>>>0;return[r,i]}const ft=1048576;function readWalGeneration(e){let t=Buffer.alloc(32);if(F(e,t,0)!==t.length)return;let n=t.readUInt32BE(0);if(n!==931071618&&n!==931071619)return;let r=n===931071618?`LE`:`BE`,i=t.readUInt32BE(8),[a,o]=sqliteWalChecksum(t.subarray(0,24),r);if(!(i<512||i>65536||i&i-1||t.readUInt32BE(24)!==a||t.readUInt32BE(28)!==o))return{header:t,byteOrder:r,frameBytes:24+i}}function copyCommittedWalFrames(e,t,n,r){let{header:i,byteOrder:a,frameBytes:o}=n;if(readWalGeneration(e)?.header.equals(i)!==!0)return!1;let s=i.subarray(16,24),c=[i.readUInt32BE(24),i.readUInt32BE(28)];writeFully(t,i,0);let l=32,u=Math.max(1,Math.floor(ft/o)),d=Buffer.allocUnsafe(u*o);for(let n=32;n<r;){let i=d.subarray(0,Math.min(d.length,r-n)),u=F(e,i,n),f=0,p=!0;for(let e=0;e+o<=u;e+=o){let t=i.subarray(e,e+o);if(t.readUInt32BE(0)===0||!t.subarray(8,16).equals(s)){p=!1;break}let r=sqliteWalChecksum(t.subarray(24),a,sqliteWalChecksum(t.subarray(0,8),a,c));if(t.readUInt32BE(16)!==r[0]||t.readUInt32BE(20)!==r[1]){p=!1;break}c=r,f=e+o,t.readUInt32BE(4)!==0&&(l=n+f)}if(f>0&&writeFully(t,i.subarray(0,f),n),!p||f<i.length)break;n+=f}return K.ftruncateSync(t,l),K.fsyncSync(t),l}function writeFully(e,t,n){for(let r=0;r<t.length;){let i=K.writeSync(e,t,r,t.length-r,n+r);if(i<=0)throw Error(`SQLite WAL snapshot write made no progress`);r+=i}}function matchesCapturedWalPrefix(e,t,n){let r=K.openSync(t,`r`);try{let t=K.fstatSync(r);if(!t.isFile()||t.size!==n)return!1;let i=Buffer.allocUnsafe(Math.min(ft,n)),a=Buffer.allocUnsafe(i.length);for(let t=0;t<n;t+=i.length){let o=Math.min(i.length,n-t),s=i.subarray(0,o),c=a.subarray(0,o);if(F(e,s,t)!==o||F(r,c,t)!==o||!s.equals(c))return!1}return!0}finally{K.closeSync(r)}}function prepareSqliteWalPrefixCopy(e,t,n){let r=readWalGeneration(e);if(r)return()=>{let i=K.fstatSync(e).size;if(!Number.isSafeInteger(i)||i<32)return!1;let a=K.openSync(t,`wx`,384),o;try{o=copyCommittedWalFrames(e,a,r,i)}finally{K.closeSync(a)}return o!==!1&&n()&&matchesCapturedWalPrefix(e,t,o)&&readWalGeneration(e)?.header.equals(r.header)===!0}}const pt=/* @__PURE__ */ new Set;function withSqliteSourceReadDatabase(e,t,n,r={}){ke(e);let i=l(t,()=>W(r.readOnlyShm?Le(e):e,{readOnly:!0,timeout:r.timeout}));try{return ke(e),n(i)}finally{try{i.close()}finally{i.isOpen&&pt.add(i)}}}const mt=Buffer.from([217,213,5,249,32,161,99,215]);var SqliteSourceChangedError=class extends Error{constructor(e,t){super(t?.attempts?`SQLite source did not stabilize (reason=${e}, attempts=${t.attempts}) after ${t.attempts} read-only inspection attempts. Wait a moment for write activity to settle, then retry the inspection`:`SQLite source changed during read-only inspection (reason=${e})`,t),this.reason=e}};function statIfPresent(e){try{return K.statSync(e,{bigint:!0})}catch(e){if(e.code===`ENOENT`)return;throw e}}function readSourceSidecars(e){return{journal:!!statIfPresent(`${e}-journal`),shm:!!statIfPresent(`${e}-shm`),wal:!!statIfPresent(`${e}-wal`)}}function openPinnedFile(e,t){let n;try{n=K.openSync(e,`r`)}catch(e){throw e.code===`ENOENT`?new SqliteSourceChangedError(`source-disappeared`):e}try{let r=K.fstatSync(n,{bigint:!0});t&&h(r,t);let i=statIfPresent(e);if(!r.isFile()||!i?.isFile()||!b(r,i))throw new SqliteSourceChangedError(`source-identity-changed`);return{descriptor:n,identity:r,pathname:e}}catch(e){throw K.closeSync(n),e}}function readSourceJournalMode(e,t){let n=openPinnedFile(e,t);try{let e=Buffer.alloc(20),t=K.readSync(n.descriptor,e,0,e.length,0);return assertPinnedIdentityUnchanged(n),t===0?`empty`:t!==e.length||e.subarray(0,16).toString(`utf8`)!==`SQLite format 3\0`?`unknown`:e[18]===2||e[19]===2?`wal`:`rollback`}finally{K.closeSync(n.descriptor)}}function assertPinnedIdentityUnchanged(e){let t=K.fstatSync(e.descriptor,{bigint:!0}),n=statIfPresent(e.pathname);if(!t.isFile()||!n?.isFile()||!b(e.identity,t)||!b(e.identity,n))throw new SqliteSourceChangedError(`source-identity-changed`)}function copySourceFile(e,n,r){let i=openPinnedFile(e,r);try{let r;try{r=K.realpathSync.native(e)}catch(e){throw t(e)===`ENOENT`?new SqliteSourceChangedError(`source-disappeared`,{cause:e}):e}let a=copyRootFileSync({source:{rootPath:q.dirname(r),absolutePath:r},destination:{rootPath:q.dirname(n),absolutePath:n},expectedSourceIdentity:i.identity,sourceHardlinks:`allow`,clone:`auto`,mode:384});try{K.fsyncSync(a.fd),assertPinnedIdentityUnchanged(i)}finally{a.close()}}finally{K.closeSync(i.descriptor)}}function sourceMatchesCopy(e,t,n){let r=openPinnedFile(e,n);try{let e=K.openSync(t,`r`);try{if(!K.fstatSync(e).isFile())return!1;let t=sameFileContentsSync(r.descriptor,e);return assertPinnedIdentityUnchanged(r),t}finally{K.closeSync(e)}}finally{K.closeSync(r.descriptor)}}function assertExpectedSidecars(e,t){let n=readSourceSidecars(e);if(n.journal!==t.journal||n.wal!==t.wal)throw new SqliteSourceChangedError(`journal-state-changed`)}function isSqliteReadOnlyError(e){let t=e;for(let e=0;e<8&&t&&typeof t==`object`;e+=1){let e=t;if(typeof e.errcode==`number`&&(e.errcode&255)==8)return!0;t=e.cause}return!1}function rollbackJournalReferencesSuperJournal(e){let t=K.openSync(e,`r`);try{let e=K.fstatSync(t).size;if(e<16)return!1;let n=Buffer.allocUnsafe(16);if(K.readSync(t,n,0,n.length,e-n.length)!==n.length)return!1;let r=n.readUInt32BE(0);return r>0&&r<=e-20&&n.subarray(8).equals(mt)}finally{K.closeSync(t)}}function syncPrivateSnapshot(e){let t=K.openSync(e,`r+`);try{K.fsyncSync(t)}finally{K.closeSync(t)}}function recoverPrivateJournalCopy(e){if(rollbackJournalReferencesSuperJournal(`${e}-journal`))throw Error(`SQLite hot rollback journal references a super-journal and cannot be recovered privately: ${e}`);let t=W(e);try{t.exec(`PRAGMA busy_timeout = 30000; PRAGMA trusted_schema = OFF;`),t.prepare(`PRAGMA schema_version;`).get()}finally{t.close()}K.rmSync(`${e}-journal`,{force:!0}),syncPrivateSnapshot(e)}function*createStableReadOnlyCopyInTempDirectory(e,t,n,r=n?q.dirname(n):resolvePrivateSqliteSnapshotStagingRoot(),i,a){let o=n;try{o??=createSqliteSnapshotStagingDirectorySync(r);let n=q.join(o,`database.sqlite.partial`),s=q.join(o,`first`);if(process.platform!==`win32`&&K.chmodSync(o,448),readSourceJournalMode(e,i)!==t)throw new SqliteSourceChangedError(`journal-mode-changed`);let c=readSourceSidecars(e),l=!1;if(t===`wal`&&c.wal&&!c.journal){let t=openPinnedFile(`${e}-wal`);try{let r=prepareSqliteWalPrefixCopy(t.descriptor,`${n}-wal`,()=>sourceMatchesCopy(e,n,i));r&&(yield{sourcePath:e,targetPath:n,expectedSourceIdentity:i});let a=r?.();if(assertPinnedIdentityUnchanged(t),a===!1)throw new SqliteSourceChangedError(`wal-copy-unstable`);l=a===!0}finally{K.closeSync(t.descriptor)}}let u=[...c.journal?[`-journal`]:[],...c.wal?[`-wal`]:[]];if(l)assertExpectedSidecars(e,c);else if(u.length>0){for(let t of u)yield{sourcePath:`${e}${t}`,targetPath:`${n}${t}`};if(yield{sourcePath:e,targetPath:n,expectedSourceIdentity:i},!sourceMatchesCopy(e,n,i))throw new SqliteSourceChangedError(`main-changed-during-copy`);for(let t of u)if(!sourceMatchesCopy(`${e}${t}`,`${n}${t}`))throw new SqliteSourceChangedError(t===`-wal`?`wal-changed-during-copy`:`rollback-journal-changed-during-copy`);assertExpectedSidecars(e,c)}else{yield{sourcePath:e,targetPath:s,expectedSourceIdentity:i},assertExpectedSidecars(e,c);let t=a!==void 0||sourceMatchesCopy(e,s,i);if(assertExpectedSidecars(e,c),!t)throw new SqliteSourceChangedError(`main-changed-during-copy`);K.rmSync(n,{force:!0}),K.renameSync(s,n)}if(readSourceJournalMode(e,i)!==t)throw new SqliteSourceChangedError(`journal-mode-changed`);if(a&&(c.journal||c.wal&&K.statSync(`${n}-wal`).size!==0))throw new SqliteSourceChangedError(`recovery-data-appeared`);return c.journal&&recoverPrivateJournalCopy(n),L(o,a)}catch(t){let r=o?sqliteSnapshotStagingError(o,t,!1,e):t;if(o&&n===void 0){let e=[r];if(!Ce(o,t=>e.push(t)))throw xe(e,`SQLite snapshot preparation`)}throw r}}function copyPreparedLocationSync(e){let t=e.next();for(;!t.done;){try{let{sourcePath:e,targetPath:n,expectedSourceIdentity:r}=t.value;copySourceFile(e,n,r)}catch(n){t=e.throw(n);continue}t=e.next()}return t.value}async function copyPreparedLocation(e){let t=e.next();for(;!t.done;){try{let{sourcePath:e,targetPath:n,expectedSourceIdentity:r}=t.value,i=openPinnedFile(e,r);try{await copySqliteFile(e,n,i.identity)}finally{try{assertPinnedIdentityUnchanged(i)}finally{K.closeSync(i.descriptor)}}}catch(n){t=e.throw(n);continue}t=e.next()}return t.value}async function createOnlineReadOnlyBackup(e,t,n,r){let i=typeof t==`object`?t.directory:await createSqliteSnapshotStagingDirectory(t,!1,n),a=q.join(i,`database.sqlite.partial`);try{process.platform!==`win32`&&K.chmodSync(i,448);let t=l(`source`,()=>W(e,{readOnly:!0}));try{t.exec(`PRAGMA busy_timeout = 30000; PRAGMA trusted_schema = OFF; BEGIN;`),t.prepare(`PRAGMA schema_version;`).get(),await z(backupNodeSqliteDatabase(t,a,r)),t.exec(`ROLLBACK;`)}finally{t.isOpen&&t.close()}let n=W(a);try{n.exec(`PRAGMA journal_mode = DELETE;`)}finally{n.close()}return syncPrivateSnapshot(a),L(i)}catch(n){let r=sqliteSnapshotStagingError(i,n,!1,e);return Ee(i,r,`SQLite online backup`,typeof t==`object`)}}function*prepareArtifactPreservingCopy(e,t,n,r){let i=K.realpathSync.native(e);for(let e=0;;e+=1)try{return yield*createStableReadOnlyCopyInTempDirectory(i,readSourceJournalMode(i,n),typeof t==`object`?t.directory:void 0,typeof t==`string`?t:void 0,n,r)}catch(n){if(typeof t==`object`&&be(t.directory,n),!(n instanceof SqliteSourceChangedError))throw n;if(e+1>=10)throw new SqliteSourceChangedError(n.reason,{cause:n,attempts:10});waitForSnapshotRetrySync(e)}}function prepareSqliteReadOnlyLocationSyncInProcess(e,t,n,r){return copyPreparedLocationSync(prepareArtifactPreservingCopy(e,t,n,r))}const ht=/* @__PURE__ */ new Set([`wal-copy-unstable`,`main-changed-during-copy`,`wal-changed-during-copy`]);async function prepareSqliteReadOnlyCopyInProcess(e,t,n){try{return await copyPreparedLocation(prepareArtifactPreservingCopy(e,t,n))}catch(r){if(!(r instanceof SqliteSourceChangedError)||!ht.has(r.reason))throw r;let i=K.realpathSync.native(e),a=openPinnedFile(i,n);try{let e=readSourceSidecars(i);if(readSourceJournalMode(i,n)!==`wal`||!e.wal||!e.shm||e.journal)throw r;let o=await createOnlineReadOnlyBackup(i,t);try{assertPinnedIdentityUnchanged(a)}catch(e){throw o.cleanup(),e}return o}finally{K.closeSync(a.descriptor)}}}async function prepareSqliteReadOnlyLocationFromOwnedDatabase(e,t,n,r){let assertReady=()=>{if(n?.throwIfAborted(),t(),!e.isOpen||e.isTransaction)throw Error(`SQLite inspection requires an open owner outside a transaction`)};assertReady();let i=await createSqliteSnapshotStagingDirectory(void 0,!1,n,r===`async`);try{assertReady();let r=q.join(i,`database.sqlite.partial`);return await z(backupNodeSqliteDatabase(e,r)),n?.throwIfAborted(),t(),L(i)}catch(e){let t=[e];throw!await I(i,e=>t.push(e))&&r===`async`?xe(t,`Owned SQLite snapshot preparation`):e}}function fingerprint(e){return[e.dev,e.ino,e.birthtimeNs,e.ctimeNs,e.mtimeNs,e.size].join(`:`)}function walFingerprint(e){return[e.dev,e.ino,e.mtimeNs,e.size].join(`:`)}function readFile$1(e){let t=K.lstatSync(e,{bigint:!0,throwIfNoEntry:!1});if(t){if(!t.isFile()||t.nlink!==1n)throw Error(`Private SQLite snapshot must be an independent regular file: ${e}`);return t}}function captureSqlitePrivateSnapshotFamily(e,t){if(K.lstatSync(`${e}-journal`,{throwIfNoEntry:!1}))return;let n=readFile$1(e),r=readFile$1(`${e}-wal`);return n?{root:t,main:fingerprint(n),wal:r&&r.size>32n?walFingerprint(r):null}:void 0}export{publishSqliteWalCheckpointObservation as C,prepareSqliteDatabaseDirectory as S,resolvePrivateSqliteSnapshotStagingRoot as _,prepareSqliteReadOnlyLocationFromOwnedDatabase as a,registerSqliteCacheExitClose as b,readSourceSidecars as c,createSqliteSnapshotStagingDirectory as d,createSqliteSnapshotStagingDirectorySync as f,createPrivateSqliteTempDirectorySync as g,readExistingAgentSchemaMeta as h,prepareSqliteReadOnlyCopyInProcess as i,withSqliteSourceReadDatabase as l,publishAgentSchemaMetadata as m,SqliteSourceChangedError as n,prepareSqliteReadOnlyLocationSyncInProcess as o,$ as p,isSqliteReadOnlyError as r,readSourceJournalMode as s,captureSqlitePrivateSnapshotFamily as t,acquireSqliteSnapshotReadToken as u,configureSqliteConnectionPragmas as v,truncateSqliteWal as w,createSqliteWalReclamationResult as x,configureSqlitePreSchemaPragmas as y};