UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

21 lines • 26.7 kB
import{o as e}from"./transcript-record-coerce-eN4p5mcq.mjs";import{i as t}from"./transcript-global-singleton-DIJgobpU.mjs";import{M as n}from"./transcript-plugin-instance-invocation-7pP9ZY8b.mjs";import"./transcript-worker-cpu-DTToyx8O.mjs";import{_ as r,o as i,s as a,x as o}from"./transcript-sqlite-database-admission-Cro6ZHgY.mjs";import{n as s}from"./transcript-path-guards-DYqTo0Vr.mjs";import{f as c,l,t as u}from"./transcript-sqlite-worker-identity-C2ykgpDo.mjs";import{a as d,i as f,n as p}from"./transcript-runtime-worker-process-generation-D9EadN9J.mjs";import{n as m,t as h}from"./transcript-subsystem-er2pCebD.mjs";import{A as g,D as _,E as v,G as ee,H as te,J as y,M as b,R as x,S,T as C,U as w,V as T,W as E,_ as ne,j as re,p as ie,q as ae,w as D,x as O,z as k}from"./transcript-sqlite-table-layout-migration-6FYoXQ_h.mjs";import{r as A}from"./transcript-path-existence-DsAt-_G2.mjs";import{y as j}from"./transcript-openclaw-state-worker-error-DM4pmO7c.mjs";import{h as M}from"./transcript-sqlite-post-commit-BDZjIt2B.mjs";import{o as N}from"./transcript-openclaw-state-db-contract-DiFTYPe3.mjs";import{c as P}from"./transcript-openclaw-state-db.paths-DYRyvCKa.mjs";import{n as F,t as I}from"./transcript-artifact-preserving-state-reads-BHzs8nJG.mjs";import{i as L}from"./transcript-sqlite-transaction-BxeoS_ke.mjs";import{st as R}from"./transcript-openclaw-agent-db-schema-read-0j86l7zG.mjs";import{n as z}from"./transcript-crypto-digest-1BMQKHCD.mjs";import{r as B,t as V}from"./transcript-node-sqlite-dPq0UNII.mjs";import H from"node:path";import{AsyncLocalStorage as U}from"node:async_hooks";import"node:crypto";import W,{existsSync as G,mkdirSync as oe}from"node:fs";import{sameFileIdentity as se}from"@openclaw/fs-safe/advanced";const K=[``,`-wal`,`-shm`,`-journal`],ce=K.slice(1);Buffer.from([0,5,22,7]);const le=h(`state/sqlite`);var SqliteOrphanedSidecarsError=class extends Error{constructor(e,t,n){super(`SQLite database is missing at ${e}, and orphaned sidecars could not be copied: ${t.join(`, `)}. Refusing to open because SQLite could delete orphan WAL or journal state. Preserve the sidecar bytes, restore the main database, and pair it with the matching sidecar before retrying.`,{cause:n}),this.name=`SqliteOrphanedSidecarsError`}};function resolveSqliteDatabaseFilePaths(e){return K.map(t=>`${e}${t}`)}function findMatchingOrphanedSidecarCopy(e,t){let n=H.dirname(e),r=`${H.basename(e)}.orphaned-`,i=W.readdirSync(n,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.startsWith(r)).map(e=>H.join(n,e.name)).filter(e=>W.statSync(e).size===t);if(i.length===0)return;let a=z(e);for(let e of i)if(z(e)===a)return e}function copyOrphanedSidecar(e,t){let n=`${e}.orphaned-${t}`;for(let t=0;;t+=1){let r=t===0?n:`${n}-${t}`;try{return W.copyFileSync(e,r,W.constants.COPYFILE_EXCL),r}catch(e){if(e.code!==`EEXIST`)throw e}}}function quarantineOrphanedSqliteSidecars(e){if(W.existsSync(e))return;let t=[{path:`${e}-wal`,minimumBytes:32},{path:`${e}-journal`,minimumBytes:0}].flatMap(e=>{let t=W.statSync(e.path,{throwIfNoEntry:!1});return t?.isFile()===!0&&t.size>e.minimumBytes?[{path:e.path,size:t.size}]:[]});if(t.length===0)return;let n=Date.now(),r=[];try{for(let e of t){if(findMatchingOrphanedSidecarCopy(e.path,e.size))continue;let t=copyOrphanedSidecar(e.path,n);r.push({quarantinePath:t,sourcePath:e.path})}}catch(n){throw new SqliteOrphanedSidecarsError(e,t.map(e=>e.path),n)}if(r.length===0)return;let i=r.map(({sourcePath:e,quarantinePath:t})=>`${e} -> ${t}`);le.warn(`SQLite database is missing at ${e}; copied orphaned sidecars: ${i.join(`, `)}. Committed frames could not be applied because the main database is missing. The bytes are preserved. Recovery requires restoring the main database and pairing it with the quarantined file.`,{databasePath:e,copiedSidecars:r})}function buildUpdateRehearsalPathEnv(e){return{HOME:e,USERPROFILE:e,TMPDIR:e,TMP:e,TEMP:e,XDG_CONFIG_HOME:H.join(e,`config`),XDG_CACHE_HOME:H.join(e,`cache`),XDG_DATA_HOME:H.join(e,`data`),XDG_STATE_HOME:H.join(e,`state`),OPENCLAW_HOME:e,OPENCLAW_STATE_DIR:e,OPENCLAW_CONFIG_PATH:H.join(e,`openclaw.json`),OPENCLAW_WORKSPACE_DIR:H.join(e,`workspace`),OPENCLAW_SKIP_CHANNELS:`1`,OPENCLAW_SKIP_PROVIDERS:`1`,OPENCLAW_SKIP_CRON:`1`,OPENCLAW_SKIP_GMAIL_WATCHER:`1`,OPENCLAW_SKIP_CANVAS_HOST:`1`,OPENCLAW_SKIP_BROWSER_CONTROL_SERVER:`1`,OPENCLAW_SKIP_STARTUP_MODEL_PREWARM:`1`,OPENCLAW_NO_AUTO_UPDATE:`1`,NODE_DISABLE_COMPILE_CACHE:`1`}}function projectUpdateRehearsalDatabaseConfig(t,n){if(!e(t)||!e(t.database)||!resolveUpdateRehearsalRoot(n))return t;let{engine:r,families:i}=t.database;return r===`postgres`||e(i)&&Object.values(i).some(t=>e(t)&&t.engine===`postgres`)?{...t,database:{engine:`sqlite`}}:t}function resolveUpdateRehearsalRoot(e){let t=e.OPENCLAW_STATE_DIR;if(t&&H.isAbsolute(t)&&[`0`,`1`].includes(e.OPENCLAW_UPDATE_IN_PROGRESS??``)&&!Object.entries(buildUpdateRehearsalPathEnv(t)).some(([t,n])=>e[t]!==n)&&e.OPENCLAW_SERVICE_REPAIR_POLICY===`external`&&e.OPENCLAW_UPDATE_PARENT_ALLOWS_GATEWAY_SERVICE_REPAIR===`0`&&e.OPENCLAW_UPDATE_PARENT_ALLOWS_GATEWAY_ACTIVATION===`0`&&!e.OPENCLAW_COMPATIBILITY_HOST_VERSION)return H.resolve(t)}function isUpdateRehearsalReadOnlyPath(e,t){let n=resolveUpdateRehearsalRoot(t);if(!n)return!1;let r=H.resolve(e);return!s(n,r)||!s(A(n),A(r))}function isUpdateRehearsalPrivateDatabase(e,t){return resolveUpdateRehearsalRoot(t)!==void 0&&resolveSqliteDatabaseFilePaths(e).every(e=>!isUpdateRehearsalReadOnlyPath(e,t))}function readSqliteIntegrityFileIdentity(e,t){return sqliteIntegrityFileIdentity(e,W.statSync(e,{bigint:!0}),t)}async function readSqliteIntegrityFileIdentityAsync(e,t,n){let r=await W.promises.stat(e,{bigint:!0});return n&&u(r,n),sqliteIntegrityFileIdentity(e,r,t)}function sqliteIntegrityFileIdentity(e,t,n){if(!t.isFile()||n&&!se(n,t))throw Error(`SQLite source changed during integrity admission: ${e}`);return{dev:t.dev,ino:t.ino,size:t.size}}function sameFileFingerprint(e,t){return e.dev===t.dev&&e.ino===t.ino&&ae(e,t)&&e.sha256===t.sha256}function sameOptionalFileFingerprint(e,t){return e===void 0?t===void 0:t!==void 0&&sameFileFingerprint(e,t)}function sameSqliteFileGeneration(e,t){return sameFileFingerprint(e.database,t.database)&&sameOptionalFileFingerprint(e.journal,t.journal)&&sameOptionalFileFingerprint(e.wal?.size===0n?void 0:e.wal,t.wal?.size===0n?void 0:t.wal)}function parseFileFingerprint(t){if(!e(t))throw Error(`SQLite file fingerprint must be an object`);for(let e of[`birthtimeNs`,`ctimeNs`,`dev`,`ino`,`mtimeNs`,`size`])if(typeof t[e]!=`string`||!/^-?\d+$/u.test(t[e]))throw Error(`SQLite file fingerprint ${e} is invalid`);if(typeof t.sha256!=`string`||!/^[a-f0-9]{64}$/u.test(t.sha256))throw Error(`SQLite file fingerprint sha256 is invalid`);return{birthtimeNs:BigInt(t.birthtimeNs),ctimeNs:BigInt(t.ctimeNs),dev:BigInt(t.dev),ino:BigInt(t.ino),mtimeNs:BigInt(t.mtimeNs),sha256:t.sha256,size:BigInt(t.size)}}function parseSqliteFileGeneration(t){let n=JSON.parse(t);if(!e(n))throw Error(`SQLite file generation must be an object`);return{database:parseFileFingerprint(n.database),...n.journal===void 0?{}:{journal:parseFileFingerprint(n.journal)},...n.wal===void 0?{}:{wal:parseFileFingerprint(n.wal)}}}function readSqliteFileGenerationSync(e){return parseSqliteFileGeneration(b(e,void 0,`file-generation`))}const q=t(Symbol.for(`openclaw.sqliteSnapshotFlights`),()=>({unscoped:/* @__PURE__ */ new Map,scoped:/* @__PURE__ */ new WeakMap}));function completed$1(e){let t=p(()=>{});return t.resolve(e),t.operation}function serviceWhenSettled(e,t){e.result.then(t,t)}function createFlight(e,t,n){let r,i=!1,a=!1,o,s,c,l=p(()=>{if(!(a||l.operation.read().status!==`pending`)){a=!0;try{i||(i=!0,r=n(d.controller.signal,e=>c=e),serviceWhenSettled(r.operation,serviceFlight)),r.operation.service();let e=r.operation.read();e.status===`fulfilled`?l.resolve(e.value):e.status===`rejected`&&l.reject(e.error)}catch(e){l.reject(e)}finally{a=!1}}}),u=p(()=>{l.operation.service();let n=l.operation.read();if(n.status!==`pending`&&u.operation.read().status===`pending`){if(e.get(t)===d&&e.delete(t),n.status===`rejected`)u.reject(c??n.error);else if(d.references>0)u.resolve(n.value);else{o||(o=releaseSnapshot(d,n.value),serviceWhenSettled(o,()=>u.operation.service())),o.service();let e=o.read();e.status===`fulfilled`?e.value?u.resolve(n.value):u.reject(new M(`SQLite orphan snapshot cleanup did not complete`)):e.status===`rejected`&&u.reject(e.error)}}});function serviceFlight(){l.operation.service();for(let e of d.listeners)e();u.operation.service()}let d={controller:new AbortController,references:0,listeners:/* @__PURE__ */ new Set,production:l.operation,settled:u.operation,closeProducer(){return s??=r?.startClose?.()??completed$1(void 0),s}};return ee(u.operation.result,()=>{d.controller.abort(/* @__PURE__ */ Error(`SQLite snapshot owner stopped`)),serviceFlight()}),d}function releaseSnapshot(e,t){return f(t.startCleanup(),t=>t?d(e.closeProducer(),()=>!0):completed$1(!1))}function leaseFlight(e,t){let n=!1,r,releaseReference=()=>(n||(n=!0,e.references--),e.references===0),startCleanup=()=>(r??=!n&&releaseReference()?releaseSnapshot(e,t):completed$1(!0),r);return{location:t.location,cleanupRoot:t.cleanupRoot,privateFamily:t.privateFamily,cleanup(){if(n){let e=r?.read();return!e||e.status===`fulfilled`&&e.value}if(e.references>1)return releaseReference(),!0;let i=t.cleanup();return i&&releaseReference(),i},cleanupAsync:()=>startCleanup().result,startCleanup}}function startSnapshotFlight(e,t,n,r,i){r?.throwIfAborted();let a=`${c(e).key}:${t}`,o=q.unscoped;if(i?.scope){let e=q.scoped.get(i.scope);e||(e=/* @__PURE__ */ new Map,q.scoped.set(i.scope,e)),o=e}let s=o.get(a);s||(s=createFlight(o,a,n),o.set(a,s));let l=s;l.references++;let u=!1,f=!1,m,h=p(()=>{if(h.operation.read().status===`pending`){if(u||r?.aborted){if(f||(f=!0,l.references--),l.references===0&&(l.controller.abort(r?.reason),o.get(a)===l&&o.delete(a),l.settled.service(),l.settled.read().status===`pending`))return;h.reject(r?.reason??/* @__PURE__ */ Error(`SQLite snapshot preparation closed`))}else{l.production.service();let e=l.production.read();if(e.status===`pending`)return;e.status===`fulfilled`?h.resolve(leaseFlight(l,e.value)):(l.references--,h.reject(e.error))}r?.removeEventListener(`abort`,service),l.listeners.delete(service),l.settled.service()}}),service=()=>h.operation.service();return serviceWhenSettled(l.settled,service),l.listeners.add(service),r?.addEventListener(`abort`,service,{once:!0}),queueMicrotask(service),{...h.operation,startClose(){u=!0,h.operation.service();let e=h.operation.read();return m??=e.status===`fulfilled`?d(e.value.startCleanup(),e=>{if(!e)throw new M(`SQLite snapshot lease cleanup did not complete`)}):l.references===0?l.closeProducer():completed$1(void 0),m}}}function startAwaitedSnapshotWork(e){let t=p(()=>{});return Promise.resolve().then(e).then(t.resolve,t.reject),t.operation}async function prepareSingleFlightSqliteSnapshot(e,t,n,r,i){return startSnapshotFlight(e,t,(e,t)=>({operation:startAwaitedSnapshotWork(async()=>{let r=await n(e,t);return{...r,startCleanup:()=>startAwaitedSnapshotWork(()=>r.cleanupAsync())}})}),r,i).result}function startSingleFlightSqliteSnapshot(e,t,n,r,i){return startSnapshotFlight(e,t,(e,t)=>{let r=n(e,t);return{operation:r,startClose:()=>r.startClose()}},r,i)}const J=t(Symbol.for(`openclaw.sqliteLiveSnapshotOwners`),()=>/* @__PURE__ */ new Map);function registerLiveSqliteSnapshotOwner(e){let t=c(e.databasePath),n={assertCurrent:e.assertCurrent,database:e.database};return J.set(t.key,n),()=>{J.get(t.key)===n&&J.delete(t.key)}}function prepareSqliteSnapshotFromLiveOwner(e,t){t?.throwIfAborted();let n=c(e),r=J.get(n.key);if(r)return r.assertCurrent(),prepareSingleFlightSqliteSnapshot(n.canonicalPath,`live-owner:openclaw-state`,e=>ne(r.database,r.assertCurrent,e),t)}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=W.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(W.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}const Y=t(Symbol.for(`openclaw.sqliteReusableSnapshots`),()=>/* @__PURE__ */ new Map),X=t(Symbol.for(`openclaw.sqliteReusableSnapshotScopes`),()=>({depth:0,retiring:/* @__PURE__ */ new Set}));function isSqliteSnapshotReuseActive(){return X.depth>0}function completed(e){let t=p(()=>{});return t.resolve(e),t.operation}function readSource(e){try{let t=W.statSync(e,{bigint:!0,throwIfNoEntry:!1});if(!t?.isFile()||W.statSync(`${e}-journal`,{throwIfNoEntry:!1}))return;let n=W.statSync(`${e}-wal`,{bigint:!0,throwIfNoEntry:!1}),r=n&&n.size>0n?n:void 0;return{fingerprint:[`${t.dev}:${t.ino}:${t.size}:${t.mtimeNs}:${t.ctimeNs}`,r?`${r.dev}:${r.ino}:${r.size}:${r.mtimeNs}`:`none`].join(`|`),main:t,newestMs:Math.max(Number(t.mtimeMs),Number(r?.mtimeMs??0)),quiescentMs:[t,r].some(e=>e&&e.mtimeNs%1000000000n==0n)?2e3:50}}catch{return}}function canonicalKey(e){try{return W.realpathSync.native(e)}catch{return}}function retire(e,t){Y.get(e)===t&&Y.delete(e),t.retired=!0,t.leases===0&&settleRetirement(t.retire)}function settleRetirement(e){let t=new Promise(t=>{t(e())}).catch(reportRetirementFailure).finally(()=>X.retiring.delete(t));X.retiring.add(t)}function reportRetirementFailure(e){m({subsystem:`infra/sqlite-snapshot`}).warn({error:String(e)},`Retiring a reusable SQLite snapshot failed.`)}function lend(e,t){t.leases+=1;let n=!1,release=()=>(n||(n=!0,--t.leases,t.leases===0&&t.retired&&retire(e,t)),!0);return{location:t.location,cleanupRoot:t.cleanupRoot,privateFamily:t.privateFamily,cleanup:release,cleanupAsync:async()=>release(),startCleanup:()=>completed(release())}}function leaseReusableSqliteSnapshot(e,t,n={}){let r=canonicalKey(e),i=r?Y.get(r):void 0;if(r&&i){if(readSource(r)?.fingerprint!==i.fingerprint||!W.existsSync(i.location))retire(r,i);else if(!i.logicalOnly||n.logicalReader){if(t)try{u(i.main,t)}catch{return}return lend(r,i)}}}function captureReusableSqliteSource(e){let t=X.depth>0?canonicalKey(e):void 0,n=t?readSource(t):void 0;return n&&Date.now()-n.newestMs>=n.quiescentMs?n:void 0}function captureFamily(e){try{return captureSqlitePrivateSnapshotFamily(e.location,e.cleanupRoot??H.dirname(e.location))}catch{return}}const Z=t(Symbol.for(`openclaw.sqliteReusableSnapshotSources`),()=>/* @__PURE__ */ new Map);function bindReusableSqliteSource(e,t){t&&Z.set(e,t)}function publishBoundReusableSqliteSnapshot(e,t,n){let r=canonicalKey(e)??H.resolve(e),i=Y.get(r),a=Z.get(t.location)??(i?.location===t.location?i:void 0);return Z.delete(t.location),a?publishReusableSqliteSnapshot(e,a,t,n):t}function publishReusableSqliteSnapshot(e,t,n,r,i={}){let a=canonicalKey(e)??H.resolve(e),o=Y.get(a);if(o?.location===n.location&&o.fingerprint===t.fingerprint)return settleRetirement(r),lend(a,o);o&&retire(a,o);let s={...t,logicalOnly:i.logicalOnly===!0,location:n.location,cleanupRoot:n.cleanupRoot,privateFamily:n.privateFamily??captureFamily(n),leases:0,retired:!1,retire:r};return Y.set(a,s),lend(a,s)}function createLeasedSqliteSnapshotPreparation(e){return{...completed(e),startClose:()=>d(e.startCleanup(),()=>void 0)}}function findArtifactSnapshot(e,t){let n=e.snapshots.get(t.canonicalPath);if(n&&(n.sourceIdentity.key!==t.key||n.sourceIdentity.birthtime!==t.birthtime))throw Error(`SQLite database file identity changed during inspection`);return n}function retainArtifactSnapshot(e,t,n){let r=E(t.cleanupRoot??H.dirname(t.location));e.privateRoots.add(t.cleanupRoot??H.dirname(t.location));let i={...t,sourceIdentity:n,cleanup:()=>(r(),t.cleanup()),cleanupAsync:()=>(r(),t.cleanupAsync())};return e.snapshots.set(n.canonicalPath,i),i}function assertCustodiedSourceUnchanged(e,t){let n=W.statSync(e,{bigint:!0,throwIfNoEntry:!1});if(!n||n.ino!==t.ino||n.size!==t.size||n.mtimeNs!==t.mtimeNs||R(e)===void 0)throw Error(`SQLite source changed during in-place inspection: ${e}`)}function openSqliteReadOnlyDatabase(e,t={}){let n=I.getStore();if(!n||!F(`agent`,e))return V(e,{...t,readOnly:!0});let r=c(e),i=findArtifactSnapshot(n,r),a=i?void 0:R(r.canonicalPath);i||a||isUpdateRehearsalPrivateDatabase(e,process.env)||(i=retainArtifactSnapshot(n,prepareSqliteReadOnlyLocationSync(e),r));let o=i?E(i.cleanupRoot??H.dirname(i.location)):void 0,s={},close=()=>{s.close?.(),o?.(),n.readers.delete(close)};n.readers.add(close);let l=i?.location??(a?B(r.canonicalPath):e),u=V(l,{...t,readOnly:!0}),d=u.close.bind(u);return s.close=()=>{u.isOpen&&(d(),a&&assertCustodiedSourceUnchanged(r.canonicalPath,a))},u.close=close,u}async function prepareSqliteReadOnlyLocation(e,t={}){let r=x(t.signal),i=t.preserveSourceArtifacts===!0||F(`agent`,e);try{if(r?.throwIfAborted(),!i&&t.allowLiveOwner!==!1){let t=prepareSqliteSnapshotFromLiveOwner(e,r);if(t)return await t}r?.throwIfAborted();let a=t.reuse===!0&&i,o=a?leaseReusableSqliteSnapshot(e,t.expectedSourceIdentity):void 0;if(o)return o;let s=t.requireCleanup??t.signal!==void 0,c=prepareSingleFlightSqliteSnapshot(e,`${i?`worker-sync`:`worker-async`}:${s?`strict`:`best-effort`}:sync-token${t.expectedSourceIdentity?`:${JSON.stringify(t.expectedSourceIdentity)}`:``}`,async(r,o)=>{let c,l=a?captureReusableSqliteSource(e):void 0;try{r.throwIfAborted(),c=await O(void 0,!1,r),r.throwIfAborted();let n=await g(e,{mode:i?`sync`:`async`,signal:r,stagingRoot:c,expectedSourceIdentity:t.expectedSourceIdentity});r.throwIfAborted(),bindReusableSqliteSource(n,l);let o=k(n,c,s);return a&&(o.privateFamily=captureFamily(o)),o}catch(e){if(c&&!await w(c)){let t=new M(`${n(e)}; SQLite snapshot cleanup failed: ${c}`,{cause:e});throw o?.(t),t}throw e instanceof M?(o(e),e):(r.throwIfAborted(),e)}},r,t.shared===!1?{scope:{}}:void 0);return a?c.then(t=>publishBoundReusableSqliteSnapshot(e,t,()=>t.cleanup())):c}catch(e){throw r?.throwIfAborted(),e}}function startSqliteReadOnlyLocationAsync(e,t={}){let n=x(t.signal);n?.throwIfAborted();let r=H.resolve(e),i=t.preserveSourceArtifacts===!0||F(`agent`,r),a=t.expectedSourceIdentity===void 0?void 0:l(t.expectedSourceIdentity);if(a&&!i)throw Error(`SQLite source identity requires artifact-preserving preparation`);let o=t.reuse&&i?leaseReusableSqliteSnapshot(r,a):void 0;if(o)return createLeasedSqliteSnapshotPreparation(o);let s=t.signal!==void 0,{env:c,cwd:u}=C(),f=D(),p=_(),m=ie(),h=U.snapshot();return startSingleFlightSqliteSnapshot(r,`${i?`worker-sync`:`worker-async`}:${s?`strict`:`best-effort`}:async-token${a?`:${JSON.stringify(a)}`:``}`,e=>h(()=>{let t=m.start({type:`prepare`,root:f,pathname:r,allowLegacyWorker:!1,preserveSourceArtifacts:i,expectedSourceIdentity:a,deadlineOwnedByCaller:p,launch:{env:c,cwd:u,transport:{kind:`native`}}},e);return{...d(t,e=>{if(e.type!==`prepared`)throw Error(`SQLite snapshot producer returned an allocation without its prepared location`);let t=k(e.location,e.directory,s);return t.privateFamily=i?captureSqlitePrivateSnapshotFamily(e.location,e.directory):void 0,t}),startClose:()=>t.startClose()}}),n,{scope:m})}async function prepareSqliteReadOnlyLocationAwaited(e,t){let n=x(t.signal),r=H.resolve(e),i=l(t.expectedSourceIdentity);return(t.reuse?leaseReusableSqliteSnapshot(r,i):void 0)||(t.reuse&&!t.allowLiveOwner&&isSqliteSnapshotReuseActive()?prepareSqliteReadOnlyLocation(r,{preserveSourceArtifacts:!0,signal:n,requireCleanup:!0,reuse:!0,expectedSourceIdentity:i}):prepareSingleFlightSqliteSnapshot(r,`worker-${t.allowLiveOwner?`metadata`:`sync`}:strict:awaited-token:${JSON.stringify(i)}`,async(e,n)=>{let a=t.allowLiveOwner;return useAwaitedSnapshotWorker(e,n,async(t,n)=>{let o={mode:a?`metadata`:`sync`,stagingRoot:n,expectedSourceIdentity:i,signal:e},s=a?await re(r,o):await t.run(r,o);if(typeof s!=`string`)throw Error(`SQLite snapshot preparation returned an invalid location`);return e.throwIfAborted(),k(s,n,!0)})},n))}async function useAwaitedSnapshotWorker(e,t,n){e.throwIfAborted();let r=C(),i=v({...r,retainOnOperationError:!0}),a,o,retire=()=>{if(o&&o.read().status!==`rejected`)return o;let e=p(()=>{});return o=e.operation,(async()=>{if(a){let e=i.isRetired();e&&(await i.close(),i=v(r)),await i.run(a,{mode:e?`staging-reconcile`:`staging-retire`})}await i.close(),await i.closed,a&&await W.promises.rm(a,{recursive:!0,force:!0,maxRetries:3,retryDelay:20})})().then(e.resolve,e.reject),o};try{let t=await i.run(D(),{mode:`staging-create`,signal:e});if(typeof t!=`string`)throw Error(`SQLite snapshot allocation returned an invalid directory`);a=t,T(a,retire),e.throwIfAborted();let r=await n(i,a);return e.throwIfAborted(),r}catch(e){try{if(a){if(!await w(a))throw new M(`SQLite snapshot cleanup failed: ${a}`)}else await i.close(),await i.closed}catch(n){let r=AggregateError([e,n],`SQLite snapshot preparation and cleanup failed`);throw t?.(r),r}throw e}}function prepareSqliteReadOnlyLocationSync(e,t,r={}){let i=r.reuse?leaseReusableSqliteSnapshot(e,t):void 0;if(i)return i;let a=r.reuse?captureReusableSqliteSource(e):void 0,o=S();try{let n=k(b(e,o,`sync`,t),o);return a?publishReusableSqliteSnapshot(e,a,n,()=>n.cleanup()):n}catch(e){throw te(o)?e:new M(`${n(e)}; SQLite snapshot cleanup failed: ${o}`,{cause:e})}}const Q=5e3,$={name:`openclaw.quarantine.schema`,lifetime:`process`,schemaDependent:!0,read(e){if(typeof e==`object`&&e&&`version`in e&&typeof e.version==`number`)return{version:e.version}}};function quarantineDecisionAdmission(e){return{name:`openclaw.quarantine.decision:${H.resolve(e)}`,lifetime:`process`,read:e=>e===null||isQuarantineDecision(e)?e:void 0}}function isQuarantineDecision(t){return e(t)&&(t.kind===`agent`||t.kind===`state`)&&typeof t.reason==`string`&&typeof t.quarantinedAt==`number`&&(t.verifiedGenerationJson===null||typeof t.verifiedGenerationJson==`string`)}function configureQuarantineWriter(e,t){e.exec(` PRAGMA journal_mode = DELETE; PRAGMA synchronous = FULL; `);let n=readQuarantineSchemaVersion(e,t);n!==2&&(n===1?L(e,()=>e.exec(` ALTER TABLE quarantined_databases ADD COLUMN verified_generation TEXT; PRAGMA user_version = 2; `)):n!==2&&L(e,()=>e.exec(` CREATE TABLE IF NOT EXISTS quarantined_databases ( path TEXT NOT NULL PRIMARY KEY, kind TEXT NOT NULL, reason TEXT NOT NULL, quarantined_at INTEGER NOT NULL, writer_app_version TEXT, verified_generation TEXT ) STRICT; PRAGMA user_version = 2; `)),e.exec(`CREATE TABLE IF NOT EXISTS agent_integrity_verifications ( path TEXT NOT NULL PRIMARY KEY, dev TEXT NOT NULL, ino TEXT NOT NULL, app_version TEXT NOT NULL, verified_at INTEGER NOT NULL, clean_close INTEGER NOT NULL CHECK (clean_close IN (0, 1)) ) STRICT;`),o(e,$,{version:2}))}function readQuarantineSchemaVersion(e,t,n=!1){let r=n?void 0:a(e,$);if(r)return r.version;let i=e.prepare(`PRAGMA user_version`).get()?.user_version;if(typeof i!=`number`||!Number.isInteger(i))throw Error(`OpenClaw quarantine store ${t} has an invalid schema version.`);if(i>2)throw Error(`OpenClaw quarantine store ${t} uses newer schema version ${i}.`);return i!==0&&o(e,$,{version:i}),i}function withQuarantineWriter(e,t){let n=P(e),r=G(n),i=H.dirname(n);oe(i,{recursive:!0,mode:448}),y(i,448);let a=V(n,{timeout:Q}),o=!1;try{r||y(n,384),configureQuarantineWriter(a,n);let e=t(a);return o=!0,e}finally{a.isOpen&&a.close(),(o||!r)&&y(n,384)}}function ensureOpenClawQuarantineStore(e){G(P(e))||withQuarantineWriter(e,()=>{})}function readOpenClawDatabaseQuarantine(e,t={}){let n=P(t.env??process.env);t.refreshIdentity&&r(n);let load=()=>readPersistedQuarantineDecision(e,n,t.fresh)??null,a=t.fresh?load():i(n,quarantineDecisionAdmission(e),load);return a?resolveQuarantineDecision(a,e,n):void 0}function readPersistedQuarantineDecision(e,t,n=!1){if(!G(t))return;let r=openSqliteReadOnlyDatabase(t,{timeout:Q}),i;try{i={value:readQuarantineDecision(r,e,t,n)}}catch(e){i={error:e}}try{r.close()}catch(n){let r,a=`error`in i?i.error:void 0;if(`value`in i&&i.value)try{r=resolveQuarantineDecision(i.value,e,t)}catch(e){a=e}throw new j(a===void 0?[n]:[a,n],r)}if(`error`in i)throw i.error;return i.value}function readQuarantineDecision(e,t,n,r=!1){let i=readQuarantineSchemaVersion(e,n,r);if(i===0)return;let a=i>=2?`, verified_generation`:``,o=e.prepare(`SELECT kind, reason, quarantined_at${a} FROM quarantined_databases WHERE path = ? LIMIT 1`).get(H.resolve(t));if(!o)return;let s=i>=2?o.verified_generation:void 0;if(o.kind!==`agent`&&o.kind!==`state`||typeof o.reason!=`string`||typeof o.quarantined_at!=`number`||!Number.isInteger(o.quarantined_at)||s!=null&&typeof s!=`string`)throw Error(`OpenClaw quarantine store ${n} contains an invalid row.`);return{kind:o.kind,quarantinedAt:o.quarantined_at,reason:o.reason,verifiedGenerationJson:typeof s==`string`?s:null}}function resolveQuarantineDecision(e,t,n){if(e.verifiedGenerationJson!==null){let r;try{r=parseSqliteFileGeneration(e.verifiedGenerationJson)}catch{throw Error(`OpenClaw quarantine store ${n} contains an invalid row.`)}try{let e=readSqliteFileGenerationSync(H.resolve(t));if(!sameSqliteFileGeneration(r,e))return}catch{return}}return{kind:e.kind,quarantinedAt:e.quarantinedAt,reason:e.reason}}function readOpenClawDatabaseQuarantineFailure(e,t,n={}){let r,i;try{r=readOpenClawDatabaseQuarantine(t,n)}catch(e){if(!(e instanceof j))return;if(!e.quarantine)throw e;r=e.quarantine,i=e}if(!r)return;let a=/* @__PURE__ */ Error(`OpenClaw ${e} database ${t} is quarantined after integrity verification failed: ${r.reason??`unknown integrity error`}. Restore the database from a backup or repair it, then run openclaw doctor --fix to clear the quarantine. See ${N}.`);return a.name=`SqliteIntegrityError`,i&&(a.cause=i),a}export{resolveUpdateRehearsalRoot as _,prepareSqliteReadOnlyLocationAwaited as a,resolveSqliteDatabaseFilePaths as b,captureReusableSqliteSource as c,publishReusableSqliteSnapshot as d,registerLiveSqliteSnapshotOwner as f,projectUpdateRehearsalDatabaseConfig as g,isUpdateRehearsalPrivateDatabase as h,prepareSqliteReadOnlyLocation as i,isSqliteSnapshotReuseActive as l,readSqliteIntegrityFileIdentityAsync as m,readOpenClawDatabaseQuarantineFailure as n,prepareSqliteReadOnlyLocationSync as o,readSqliteIntegrityFileIdentity as p,openSqliteReadOnlyDatabase as r,startSqliteReadOnlyLocationAsync as s,ensureOpenClawQuarantineStore as t,leaseReusableSqliteSnapshot as u,ce as v,quarantineOrphanedSqliteSidecars as y};