UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

50 lines • 30.1 kB
import{l as resolveGlobalSingleton}from"./string-coerce-BBqv4GXj.mjs";import{d as markSqliteInspectionOperation,p as readSqliteInspectionOperation,v as withSqliteInspectionOperation}from"./sql-connection-D2qSU3Um.mjs";import{t as hasErrnoCode}from"./errno-DUBt6SQQ.mjs";import{l as groupPluginRecords}from"./redact-LQdRaLFO.mjs";import{t as resolveStateDir}from"./state-dir-C22DK7p0.mjs";import{i as resolveRequiredOsHomeDir}from"./home-dir-C2A7IM0a.mjs";import{a as root,r as FsSafeError$1}from"./utils-CfSlIBx_.mjs";import{c as resolvePreferredOpenClawTmpDir}from"./subsystem-BMw5Czn-.mjs";import{t as isPromiseLike}from"./promise-like-OKzBwzLG.mjs";import{t as assertDatabaseFileIdentity}from"./sqlite-worker-identity-gGA4fE_R.mjs";import{a as SqliteSnapshotCleanupError}from"./sqlite-lifecycle-errors-BKA8AtC6.mjs";import{Q as requireNodeSqlite,nt as createSqliteTableContract,tt as createSqliteIndexContract}from"./sqlite-database-admission-BikxIIFA.mjs";import"./sqlite-schema-facts-x2rWNNBl.mjs";import{a as normalizeSchemaSql,c as quoteSqliteIdentifier}from"./sqlite-schema-sql-D2HdV_QG.mjs";import{a as resolveSqliteFilesystemPath,t as openNodeSqliteDatabase}from"./node-sqlite-CX_zY7OF.mjs";import{A as hasSqliteSnapshotCapacityCode,M as markPrivateDirectoryCreationRefused,b as SQLITE_SNAPSHOT_PREFIX,c as discardPreparedCopyPayload,f as registerSnapshotTempDirectory,g as retainSnapshotWork,j as isPrivateDirectoryCreationRefused,k as SqliteSnapshotCapacityError,l as preparationCleanupError,m as removeTempDirectoryAsync,o as cleanupFailedSnapshotPreparation,p as removeTempDirectory,u as publishPreparedCopy,x as acquireSqliteSnapshotToken}from"./sqlite-readonly-worker-context-Nl3i9Fck.mjs";import fsSync from"node:fs";import path from"node:path";import{createHash,randomUUID}from"node:crypto";import{copyRootFileSync,createDirectorySync,createFileSync,readFileWindowFullySync,sameFileContentsSync,sameFileIdentity}from"@openclaw/fs-safe/advanced";import{FsSafeError}from"@openclaw/fs-safe/errors";import fsPromises from"node:fs/promises";import{threadId}from"node:worker_threads"; //!src/infra/sqlite-backup.ts async function backupNodeSqliteDatabase(e,t,n){const r=setInterval(()=>{},100);try{const r=await requireNodeSqlite().backup(e,resolveSqliteFilesystemPath(t),{progress:n});n?.({totalPages:r,remainingPages:0});return r}finally{clearInterval(r)}} //!src/infra/sqlite-file-copy.ts async function copySqliteFile(e,t,n,r={}){const{beforeByteCopy:i,clone:a=`auto`}=r;const o=await root(path.dirname(e));const s=await root(path.dirname(t));let c;const copy=r=>s.copyIn(path.basename(t),{relativePath:path.basename(e),root:{stat:e=>o.stat(e),open:async(t,r)=>{const i=await o.open(t,r);try{if(!sameFileIdentity(n,await i.handle.stat({bigint:true})))throw new Error(`SQLite copy source changed: ${e}`);return i}catch(e){await i.handle.close();throw e}}}},{clone:r,...i?{maxBytes:Number(n.size)}:{},sourceHardlinks:`allow`,overwrite:false,mode:384,durable:true,onDestinationPublished:e=>{c=e}});if(i&&a===`auto`)try{await copy(`always`)}catch(e){if(c||!(e instanceof FsSafeError$1)||!(e.code===`unsupported-platform`||e.code===`helper-unavailable`&&e.message===`native file cloning is unavailable`))throw e;await i(Number(n.size));await copy(`never`)}else{await i?.(Number(n.size));await copy(a)}if(!c)throw new Error(`SQLite copy was not published: ${t}`);return c} //!src/infra/windows-private-directory.ts function createPrivateWindowsDirectory(e){let t=false;try{createDirectorySync(path.resolve(e),{private:true,assertBeforeMutation(){t=true}})}catch(e){if(!t||e instanceof FsSafeError&&e.code===`already-exists`)throw markPrivateDirectoryCreationRefused(e);throw e}} //!src/infra/sqlite-private-directory.ts const SQLITE_DIRECTORY_MODE=448;function resolvePrivateSqliteSnapshotStagingRoot(e=process.env){try{return resolveSnapshotStagingRoot(e)}catch(e){if(e instanceof Error&&hasSqliteSnapshotCapacityCode(e))throw new SqliteSnapshotCapacityError(`SQLite snapshot staging root is unavailable: ${e.message}; free disk space/quota`,{cause:e});throw e}}function resolveSnapshotStagingRoot(e){const t=e.OPENCLAW_UPDATE_IN_PROGRESS===`1`?e.TMPDIR?.trim():void 0;if(t&&path.isAbsolute(t))return resolvePreferredOpenClawTmpDir({preferredDir:path.join(t,`openclaw`),tmpdir:()=>t});const n=process.platform===`win32`?e.LOCALAPPDATA?.trim():void 0;const r=process.platform===`win32`?`AppData/Local`:`.cache`;const i=process.platform===`darwin`?`Library/Caches`:r;const a=[e.XDG_CACHE_HOME?.trim(),n].find(e=>e&&path.isAbsolute(e))??path.join(resolveRequiredOsHomeDir(e),i);const o=resolveStateDir(e);const s=createHash(`sha256`).update(o).digest(`hex`).slice(0,24);fsSync.mkdirSync(a,{recursive:true,mode:SQLITE_DIRECTORY_MODE});const c=resolvePreferredOpenClawTmpDir({preferredDir:path.join(a,`openclaw`),tmpdir:()=>a});const[l=``,...u]=path.relative(c,o).split(path.sep);const d=u.length>0&&/^sqlite-[a-f0-9]{24}$/u.test(l)?l:`sqlite-${s}`;const f=path.join(c,d);fsSync.mkdirSync(f,{recursive:true,mode:SQLITE_DIRECTORY_MODE});const p=fsSync.lstatSync(f);if(!p.isDirectory()||process.getuid&&p.uid!==process.getuid()||process.platform!==`win32`&&(p.mode&63)!==0)throw new Error(`SQLite snapshot namespace must be a private user-owned directory`);return f}function createPrivateSqliteTempDirectorySync(e,t){if(process.platform!==`win32`)try{return fsSync.mkdtempSync(path.join(e,t))}catch(e){throw markPrivateDirectoryCreationRefused(e)}const n=path.join(e,`${t}${randomUUID()}`);createPrivateWindowsDirectory(n);return n} //!src/infra/disk-space.ts function finiteNonNegativeNumber(e){const t=Number(e);return Number.isFinite(t)&&t>=0?t:null}function findExistingDiskSpacePath(e){let t=path.resolve(e);while(true)try{return fsSync.statSync(t).isDirectory()?t:path.dirname(t)}catch{const e=path.dirname(t);if(e===t)return null;t=e}}function tryReadDiskSpace(e){const t=findExistingDiskSpacePath(e);if(!t)return null;try{const n=fsSync.statfsSync(t);const r=finiteNonNegativeNumber(n.bsize);const i=finiteNonNegativeNumber(n.bavail);if(r===null||i===null)return null;const a=finiteNonNegativeNumber(n.blocks);return{targetPath:e,checkedPath:t,availableBytes:r*i,totalBytes:a===null?null:r*a}}catch{return null}}function formatDiskSpaceBytes(e){const t=e/1048576;const n=Math.max(0,Math.round(t));if(n<1024)return`${n} MiB`;const r=t/1024;return`${r.toFixed(r<10?1:0)} GiB`} //!src/infra/sqlite-schema-catalog.ts function readSqliteImageSizeBytes(e){return Number(e.prepare(`PRAGMA page_count;`).get()?.page_count)*Number(e.prepare(`PRAGMA page_size;`).get()?.page_size)}function createSqliteTableContractReader(e,t=[],n=[]){let r;let i;const a=/* @__PURE__ */ new Set;const readCatalog=(o=[])=>{if(!r){const i=[...n,...o];r=readSqliteSchemaCatalog(e,{viewNames:t,virtualTableNames:i});for(const e of r.tables)if(e.sql&&/^CREATE VIRTUAL TABLE /iu.test(e.sql)&&!i.includes(e.name))a.add(e.name)}else for(const t of o){if(!a.has(t))continue;const n=readSqliteColumnCatalog(e,t);r={...r,tables:r.tables.map(e=>e.name===t?{...e,columns:n}:e)};a.delete(t);i=void 0}return r};return Object.assign(e=>{const t=readCatalog([e]);return(i??=sqliteSchemaContractFromCatalog(t)).get(e)},{readCatalog:(n,r)=>n.every(e=>t.includes(e))?readCatalog(r):readSqliteSchemaCatalog(e,{viewNames:n,virtualTableNames:r}),readView:n=>{return(t.includes(n)?readCatalog().views:readSqliteSchemaCatalog(e,{viewNames:[n],virtualTableNames:[]}).views).find(e=>e.name===n)}})}function sqliteSchemaContractFromCatalog(e){return new Map(e.tables.map(e=>[e.name,createSqliteTableContract(e.name,e,{schema:`main`,name:e.name,strict:e.strict,wr:e.withoutRowid},e.indexes.map(e=>createSqliteIndexContract(e,e.sql,e.terms)).toSorted(compareJson),e.triggers,e.columns,e.foreignKeys)]))}function readSqliteSchemaCatalog(e,t={}){const n=e.prepare(`SELECT type, name, tbl_name, sql FROM main.sqlite_schema ORDER BY name`).all();const r=n.filter(e=>e.type===`table`&&!e.name.startsWith(`sqlite_`));const i=n.filter(e=>e.type===`view`&&(!t.viewNames||t.viewNames.includes(e.name)));if(r.length===0&&i.length===0)return{tables:[],views:[]};const a=e.prepare(`PRAGMA table_list`).all();const o=a.filter(e=>e.schema===`main`&&e.type===`virtual`&&t.virtualTableNames&&!t.virtualTableNames.includes(e.name)).map(e=>e.name);const s=a.some(e=>[`pragma_index_list`,`pragma_index_xinfo`,`pragma_table_xinfo`,`pragma_foreign_key_list`].includes(e.name.toLowerCase()));let c;let l;if(!s){c=/* @__PURE__ */ new Map;l=/* @__PURE__ */ new Map;const t=e.prepare(` SELECT t.name AS table_name, i.seq AS index_seq, i.name AS index_name, i.origin, i.partial, i."unique", x.seqno, x.cid, x.name, x."desc", x.coll, x."key" FROM main.sqlite_schema AS t CROSS JOIN pragma_index_list(t.name, 'main') AS i LEFT JOIN pragma_index_xinfo(i.name, 'main') AS x ON 1 = 1 WHERE t.type = 'table' AND substr(t.name, 1, 7) <> 'sqlite_' ORDER BY t.name, i.seq, x.seqno `).all();for(const e of t){const t=c.get(e.table_name)??[];if(t.at(-1)?.index_seq!==e.index_seq){t.push({table_name:e.table_name,index_seq:e.index_seq,name:e.index_name,origin:e.origin,partial:e.partial,unique:e.unique});c.set(e.table_name,t)}if(e.seqno!==null){const t=l.get(e.table_name)??[];t.push({table_name:e.table_name,index_seq:e.index_seq,seqno:e.seqno,cid:e.cid,name:e.name,desc:e.desc,coll:e.coll,key:e.key});l.set(e.table_name,t)}}}const u=!t.viewNames?`t.type IN ('table', 'view')`:t.viewNames.length>0?`t.type = 'table' OR (t.type = 'view' AND t.name IN (${t.viewNames.map(()=>`?`).join(`, `)}))`:`t.type = 'table'`;const d=o.length?`AND t.name NOT IN (${o.map(()=>`?`).join(`, `)})`:``;const f=s?void 0:groupPluginRecords(e.prepare(` SELECT t.name AS table_name, x.cid, x.name, x.type, x."notnull", x.dflt_value, x.pk, x.hidden FROM main.sqlite_schema AS t CROSS JOIN pragma_table_xinfo(t.name, 'main') AS x WHERE (${u}) AND substr(t.name, 1, 7) <> 'sqlite_' ${d} ORDER BY t.name, x.cid `).all(...t.viewNames??[],...o),e=>e.table_name);const p=s?void 0:groupPluginRecords(e.prepare(` SELECT t.name AS table_name, f.id, f.seq, f."table", f."from", f."to", f.on_update, f.on_delete, f."match" FROM main.sqlite_schema AS t CROSS JOIN pragma_foreign_key_list(t.name, 'main') AS f WHERE t.type = 'table' AND substr(t.name, 1, 7) <> 'sqlite_' ORDER BY t.name, f.id, f.seq `).all(),e=>e.table_name);const m=groupPluginRecords(n.filter(e=>e.type===`trigger`),e=>e.tbl_name);const h=new Map(n.filter(e=>e.type===`index`).map(e=>[e.name,e.sql]));const normalizedRow=e=>({name:e.name,sql:normalizeSchemaSql(e.sql)});const readColumns=t=>o.includes(t)?[]:f?(f.get(t)??[]).map(({table_name:e,...t})=>t):readSqliteColumnCatalog(e,t);const readTriggers=e=>(m.get(e)??[]).map(normalizedRow);return{tables:r.map(t=>{const n=a.find(e=>e.schema===`main`&&e.name===t.name);if(!n)throw new Error(`Could not inspect SQLite table options for ${t.name}.`);const r=c?c.get(t.name)??[]:e.prepare(`PRAGMA main.index_list(${quoteSqliteIdentifier(t.name)})`).all().map(({name:e,origin:t,partial:n,unique:r,seq:i})=>({name:e,origin:t,partial:n,unique:r,index_seq:i}));const i=groupPluginRecords(l?.get(t.name)??[],e=>e.index_seq);return{name:t.name,sql:normalizeSchemaSql(t.sql),strict:n.strict,withoutRowid:n.wr,columns:readColumns(t.name),foreignKeys:p?(p.get(t.name)??[]).map(({table_name:e,...t})=>t):e.prepare(`PRAGMA main.foreign_key_list(${quoteSqliteIdentifier(t.name)})`).all(),indexes:r.map(t=>({name:t.name,origin:t.origin,partial:t.partial,unique:t.unique,sql:normalizeSchemaSql(h.get(t.name)??null),terms:l?(i.get(t.index_seq)??[]).map(({table_name:e,index_seq:t,...n})=>n):e.prepare(`PRAGMA main.index_xinfo(${quoteSqliteIdentifier(t.name)})`).all()})).toSorted((e,t)=>e.name.localeCompare(t.name)),triggers:readTriggers(t.name)}}),views:i.map(e=>({name:e.name,sql:normalizeSchemaSql(e.sql),columns:readColumns(e.name),triggers:readTriggers(e.name)}))}}function readSqliteColumnCatalog(e,t){return e.prepare(`PRAGMA main.table_xinfo(${quoteSqliteIdentifier(t)})`).all()}function compareJson(e,t){return JSON.stringify(e).localeCompare(JSON.stringify(t))} //!src/infra/sqlite-snapshot-policy.ts const MAX_SNAPSHOT_ATTEMPTS=10;const SQLITE_SOURCE_READ_BUSY_TIMEOUT_MS=3e4;const SNAPSHOT_RETRY_BASE_MS=10;const SNAPSHOT_RETRY_MAX_MS=80;function sqliteSnapshotSourceFileSize(e){try{const t=fsSync.statSync(e);return t.isFile()?t.size:0}catch(e){if(hasErrnoCode(e,`ENOENT`))return 0;throw e}}function assertSqliteSnapshotSpace(e,t){const n=typeof e===`string`?[``,`-wal`,`-journal`].reduce((t,n)=>t+sqliteSnapshotSourceFileSize(e+n),0):readSqliteImageSizeBytes(e);const r=tryReadDiskSpace(t);if(r&&r.availableBytes<n)throw Object.assign(/* @__PURE__ */ new Error(`SQLite read-only snapshot needs ${formatDiskSpaceBytes(n)} (${n} bytes) near ${t}, but only ${formatDiskSpaceBytes(r.availableBytes)} (${r.availableBytes} bytes) is available. Free disk space before retrying.`),{code:`ENOSPC`})}function waitForSnapshotRetrySync(e){if(e+1>=10)return;const t=Math.min(SNAPSHOT_RETRY_MAX_MS,SNAPSHOT_RETRY_BASE_MS*2**e);if(t>0)Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)} //!src/infra/sqlite-snapshot-staging.ts function acquireSqliteSnapshotReadToken(e){return acquireSqliteSnapshotToken(e,`read`)}function sqliteSnapshotStagingError(e,t,n=false,r){markSqliteInspectionOperation(t,`snapshot`);let i=n;let a=false;let o=false;let s;for(let n=0,r=t;n<8&&r instanceof Error;n+=1){o||=r instanceof AggregateError||r instanceof SqliteSnapshotCleanupError;const{errcode:t,path:n}=r;a||=hasSqliteSnapshotCapacityCode(r);if(a||typeof t===`number`&&[13,778,1034,1290].includes(t)||`${n??``}${path.sep}`.startsWith(`${e}${path.sep}`)){i=true;if(typeof t===`number`)s=t}r=r.cause}if(!i)return t;const c=a?`free disk space/quota`:`check filesystem health and write permissions`;let l=``;if(a&&r)try{const t=sqliteSnapshotSourceFileSize(r)+sqliteSnapshotSourceFileSize(`${r}-wal`)+sqliteSnapshotSourceFileSize(`${r}-journal`);const n=tryReadDiskSpace(e)?.availableBytes;const i=fsSync.existsSync(`${r}-wal`)&&fsSync.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{}const u=process.env.OPENCLAW_UPDATE_IN_PROGRESS===`1`?`TMPDIR`:`XDG_CACHE_HOME`;const d=`${t instanceof Error?t.message:String(t)}${s!==void 0?` (SQLite errcode=${s})`:``}; snapshot staging root ${n?e:path.dirname(e)}${l}: ${c} or set ${u} to a writable filesystem`;const f=a&&!o&&readSqliteInspectionOperation(t)!==`source`?new SqliteSnapshotCapacityError(d,{cause:t}):new Error(d,{cause:t});return isPrivateDirectoryCreationRefused(t)?markPrivateDirectoryCreationRefused(f):f}async function createSqliteSnapshotStagingDirectory(e=resolvePrivateSqliteSnapshotStagingRoot(),t=false,n,r=false){n?.throwIfAborted();try{return await allocateSqliteSnapshotStagingDirectory(e,t,n,r)}catch(e){if(e instanceof SqliteSnapshotCleanupError||r&&e instanceof AggregateError)throw e;n?.throwIfAborted();markSqliteInspectionOperation(e,`snapshot`);throw e}}async function allocateSqliteSnapshotStagingDirectory(e=resolvePrivateSqliteSnapshotStagingRoot(),t=false,n,r=false){n?.throwIfAborted();if(r){const r=new AbortController;return retainSnapshotWork((async()=>{const{allocateWorkerOwnedSqliteSnapshotDirectory:i}=await import(`./sqlite-snapshot-staging-allocation-VHNyVILB.mjs`);n?.throwIfAborted();r.signal.throwIfAborted();const a=await i(e,t,n?AbortSignal.any([n,r.signal]):r.signal);registerSnapshotTempDirectory(a.directory);if(n?.aborted||r.signal.aborted){if(!await removeTempDirectoryAsync(a.directory))throw new SqliteSnapshotCleanupError(`SQLite snapshot cleanup failed: ${a.directory}`);n?.throwIfAborted();r.signal.throwIfAborted()}return a.directory})(),()=>r.abort(/* @__PURE__ */ new Error(`SQLite snapshot allocation stopped`)))}return createSqliteSnapshotStagingDirectorySync(e,t)}function createSqliteSnapshotStagingDirectorySync(e=resolvePrivateSqliteSnapshotStagingRoot(),t=false){const n=createSqliteSnapshotStagingTokenSync(e,t);registerSnapshotTempDirectory(n.directory,n.release);return n.directory}function createSqliteSnapshotStagingTokenSync(e=resolvePrivateSqliteSnapshotStagingRoot(),t=false){let n;try{try{n=createPrivateSqliteTempDirectorySync(e,t?`openclaw-sqlite-readonly-${process.pid}-`:SQLITE_SNAPSHOT_PREFIX)}catch(t){throw sqliteSnapshotStagingError(e,t,true)}return{directory:n,release:acquireSqliteSnapshotToken(n,`create`)}}catch(e){if(n)removeTempDirectory(n);throw e}} //!src/infra/sqlite-wal-checksum.ts const SQLITE_WAL_MAGIC_LE=931071618;const SQLITE_WAL_MAGIC_BE=931071619;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]} //!src/infra/sqlite-snapshot-wal-prefix.ts const WAL_HEADER_BYTES=32;const WAL_FRAME_HEADER_BYTES=24;const COPY_BUFFER_BYTES=1048576;function readWalGeneration(e){const t=Buffer.alloc(WAL_HEADER_BYTES);if(readFileWindowFullySync(e,t,0)!==t.length)return;const n=t.readUInt32BE(0);if(n!==931071618&&n!==931071619)return;const r=n===931071618?`LE`:`BE`;const i=t.readUInt32BE(8);const[a,o]=sqliteWalChecksum(t.subarray(0,24),r);if(i<512||i>65536||(i&i-1)!==0||t.readUInt32BE(24)!==a||t.readUInt32BE(28)!==o)return;return{header:t,byteOrder:r,frameBytes:WAL_FRAME_HEADER_BYTES+i}}function copyCommittedWalFrames(e,t,n,r){const{header:i,byteOrder:a,frameBytes:o}=n;if(readWalGeneration(e)?.header.equals(i)!==true)return false;const s=i.subarray(16,24);let c=[i.readUInt32BE(24),i.readUInt32BE(28)];writeFully(t,i,0);let l=WAL_HEADER_BYTES;const u=Math.max(1,Math.floor(COPY_BUFFER_BYTES/o));const d=Buffer.allocUnsafe(u*o);for(let n=WAL_HEADER_BYTES;n<r;){const i=d.subarray(0,Math.min(d.length,r-n));const u=readFileWindowFullySync(e,i,n);let f=0;let p=true;for(let e=0;e+o<=u;e+=o){const t=i.subarray(e,e+o);if(t.readUInt32BE(0)===0||!t.subarray(8,16).equals(s)){p=false;break}const r=sqliteWalChecksum(t.subarray(WAL_FRAME_HEADER_BYTES),a,sqliteWalChecksum(t.subarray(0,8),a,c));if(t.readUInt32BE(16)!==r[0]||t.readUInt32BE(20)!==r[1]){p=false;break}c=r;f=e+o;if(t.readUInt32BE(4)!==0)l=n+f}if(f>0)writeFully(t,i.subarray(0,f),n);if(!p||f<i.length)break;n+=f}fsSync.ftruncateSync(t,l);fsSync.fsyncSync(t);return l}function writeFully(e,t,n){for(let r=0;r<t.length;){const i=fsSync.writeSync(e,t,r,t.length-r,n+r);if(i<=0)throw new Error(`SQLite WAL snapshot write made no progress`);r+=i}}function matchesCapturedWalPrefix(e,t,n){const r=fsSync.openSync(t,`r`);try{const t=fsSync.fstatSync(r);if(!t.isFile()||t.size!==n)return false;const i=Buffer.allocUnsafe(Math.min(COPY_BUFFER_BYTES,n));const a=Buffer.allocUnsafe(i.length);for(let t=0;t<n;t+=i.length){const o=Math.min(i.length,n-t);const s=i.subarray(0,o);const c=a.subarray(0,o);if(readFileWindowFullySync(e,s,t)!==o||readFileWindowFullySync(r,c,t)!==o||!s.equals(c))return false}return true}finally{fsSync.closeSync(r)}}function prepareSqliteWalPrefixCopy(e,t,n){const r=readWalGeneration(e);if(!r)return;return()=>{const i=fsSync.fstatSync(e).size;if(!Number.isSafeInteger(i)||i<WAL_HEADER_BYTES)return false;const a=fsSync.openSync(t,`wx`,384);let o;try{o=copyCommittedWalFrames(e,a,r,i)}finally{fsSync.closeSync(a)}return o!==false&&n()&&matchesCapturedWalPrefix(e,t,o)&&readWalGeneration(e)?.header.equals(r.header)===true}} //!src/infra/sqlite-readonly-location.ts const SQLITE_HEADER_BYTES=20;const SQLITE_READONLY_RESULT_CODE=8;const SQLITE_RESULT_CODE_MASK=255;const SQLITE_JOURNAL_MAGIC=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 fsSync.statSync(e,{bigint:true})}catch(e){if(e.code===`ENOENT`)return;throw e}}function readSourceSidecars(e){return{journal:Boolean(statIfPresent(`${e}-journal`)),shm:Boolean(statIfPresent(`${e}-shm`)),wal:Boolean(statIfPresent(`${e}-wal`))}}function openPinnedFile(e,t){let n;try{n=fsSync.openSync(e,`r`)}catch(e){if(e.code===`ENOENT`)throw new SqliteSourceChangedError(`source-disappeared`);throw e}try{const r=fsSync.fstatSync(n,{bigint:true});if(t)assertDatabaseFileIdentity(r,t);const i=statIfPresent(e);if(!r.isFile()||!i?.isFile()||!sameFileIdentity(r,i))throw new SqliteSourceChangedError(`source-identity-changed`);return{descriptor:n,identity:r,pathname:e}}catch(e){fsSync.closeSync(n);throw e}}function readSourceJournalMode(e,t){const n=openPinnedFile(e,t);try{const e=Buffer.alloc(SQLITE_HEADER_BYTES);const t=fsSync.readSync(n.descriptor,e,0,e.length,0);assertPinnedIdentityUnchanged(n);if(t===0)return`empty`;if(t!==e.length||e.subarray(0,16).toString(`utf8`)!==`SQLite format 3\0`)return`unknown`;return e[18]===2||e[19]===2?`wal`:`rollback`}finally{fsSync.closeSync(n.descriptor)}}function assertPinnedIdentityUnchanged(e){const t=fsSync.fstatSync(e.descriptor,{bigint:true});const n=statIfPresent(e.pathname);if(!t.isFile()||!n?.isFile()||!sameFileIdentity(e.identity,t)||!sameFileIdentity(e.identity,n))throw new SqliteSourceChangedError(`source-identity-changed`)}function sourceMatchesCopy(e,t,n){const r=openPinnedFile(e,n);try{const e=fsSync.openSync(t,`r`);try{if(!fsSync.fstatSync(e).isFile())return false;const t=sameFileContentsSync(r.descriptor,e);assertPinnedIdentityUnchanged(r);return t}finally{fsSync.closeSync(e)}}finally{fsSync.closeSync(r.descriptor)}}function assertExpectedSidecars(e,t){const 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){const e=t;if(typeof e.errcode===`number`&&(e.errcode&SQLITE_RESULT_CODE_MASK)===SQLITE_READONLY_RESULT_CODE)return true;t=e.cause}return false}function rollbackJournalReferencesSuperJournal(e){const t=fsSync.openSync(e,`r`);try{const e=fsSync.fstatSync(t).size;if(e<16)return false;const n=Buffer.allocUnsafe(16);if(fsSync.readSync(t,n,0,n.length,e-n.length)!==n.length)return false;const r=n.readUInt32BE(0);return r>0&&r<=e-20&&n.subarray(8).equals(SQLITE_JOURNAL_MAGIC)}finally{fsSync.closeSync(t)}}function syncPrivateSnapshot(e){const t=fsSync.openSync(e,`r+`);try{fsSync.fsyncSync(t)}finally{fsSync.closeSync(t)}}function recoverPrivateJournalCopy(e){if(rollbackJournalReferencesSuperJournal(`${e}-journal`))throw new Error(`SQLite hot rollback journal references a super-journal and cannot be recovered privately: ${e}`);const t=openNodeSqliteDatabase(e);try{t.exec(`PRAGMA busy_timeout = 30000; PRAGMA trusted_schema = OFF;`);t.prepare(`PRAGMA schema_version;`).get()}finally{t.close()}fsSync.rmSync(`${e}-journal`,{force:true});syncPrivateSnapshot(e)}function*createStableReadOnlyCopyInTempDirectory(e,t,n,r=n?path.dirname(n):resolvePrivateSqliteSnapshotStagingRoot(),i,a){let o=n;try{o??=createSqliteSnapshotStagingDirectorySync(r);assertSqliteSnapshotSpace(e,o);const n=path.join(o,`database.sqlite.partial`);if(process.platform!==`win32`)fsSync.chmodSync(o,448);if(readSourceJournalMode(e,i)!==t)throw new SqliteSourceChangedError(`journal-mode-changed`);const s=readSourceSidecars(e);let c=false;if(t===`wal`&&s.wal&&!s.journal){const t=openPinnedFile(`${e}-wal`);try{const r=prepareSqliteWalPrefixCopy(t.descriptor,`${n}-wal`,()=>sourceMatchesCopy(e,n,i));if(r)yield{sourcePath:e,targetPath:n,expectedSourceIdentity:i};const a=r?.();assertPinnedIdentityUnchanged(t);if(a===false)throw new SqliteSourceChangedError(`wal-copy-unstable`);c=a===true}finally{fsSync.closeSync(t.descriptor)}}const l=[...s.journal?[`-journal`]:[],...s.wal?[`-wal`]:[]];if(c)assertExpectedSidecars(e,s);else if(l.length>0){for(const t of l)yield{sourcePath:`${e}${t}`,targetPath:`${n}${t}`};yield{sourcePath:e,targetPath:n,expectedSourceIdentity:i};if(!sourceMatchesCopy(e,n,i))throw new SqliteSourceChangedError(`main-changed-during-copy`);for(const t of l)if(!sourceMatchesCopy(`${e}${t}`,`${n}${t}`))throw new SqliteSourceChangedError(t===`-wal`?`wal-changed-during-copy`:`rollback-journal-changed-during-copy`);assertExpectedSidecars(e,s)}else{yield{sourcePath:e,targetPath:n,expectedSourceIdentity:i};assertExpectedSidecars(e,s);const t=a!==void 0||sourceMatchesCopy(e,n,i);assertExpectedSidecars(e,s);if(!t)throw new SqliteSourceChangedError(`main-changed-during-copy`)}if(readSourceJournalMode(e,i)!==t)throw new SqliteSourceChangedError(`journal-mode-changed`);if(a&&(s.journal||s.wal&&fsSync.statSync(`${n}-wal`).size!==0))throw new SqliteSourceChangedError(`recovery-data-appeared`);if(s.journal)recoverPrivateJournalCopy(n);return publishPreparedCopy(o,a)}catch(t){const r=o?sqliteSnapshotStagingError(o,t,false,e):t;if(o&&n===void 0){const e=[r];if(!removeTempDirectory(o,t=>e.push(t)))throw preparationCleanupError(e,`SQLite snapshot preparation`)}throw r}}async function copyPreparedLocation(e){let t=e.next();while(!t.done){try{const{sourcePath:e,targetPath:n,expectedSourceIdentity:r}=t.value;const i=openPinnedFile(e,r);try{await copySqliteFile(e,n,i.identity,{clone:`never`})}finally{try{assertPinnedIdentityUnchanged(i)}finally{fsSync.closeSync(i.descriptor)}}}catch(n){t=e.throw(n);continue}t=e.next()}return t.value}async function createOnlineReadOnlyBackup(e,t,n,r){const i=typeof t===`object`?t.directory:await createSqliteSnapshotStagingDirectory(t,false,n);const a=path.join(i,`database.sqlite.partial`);try{if(process.platform!==`win32`)fsSync.chmodSync(i,448);const t=withSqliteInspectionOperation(`source`,()=>openNodeSqliteDatabase(e,{readOnly:true}));try{t.exec(`PRAGMA busy_timeout = ${SQLITE_SOURCE_READ_BUSY_TIMEOUT_MS}; PRAGMA trusted_schema = OFF; BEGIN;`);t.prepare(`PRAGMA schema_version;`).get();assertSqliteSnapshotSpace(t,i);await retainSnapshotWork(backupNodeSqliteDatabase(t,a,r));t.exec(`ROLLBACK;`)}finally{if(t.isOpen)t.close()}syncPrivateSnapshot(a);return publishPreparedCopy(i)}catch(n){const r=sqliteSnapshotStagingError(i,n,false,e);return cleanupFailedSnapshotPreparation(i,r,`SQLite online backup`,typeof t===`object`)}}function*prepareArtifactPreservingCopy(e,t,n,r){const i=fsSync.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`)discardPreparedCopyPayload(t.directory,n);if(!(n instanceof SqliteSourceChangedError))throw n;if(e+1>=10)throw new SqliteSourceChangedError(n.reason,{cause:n,attempts:10});waitForSnapshotRetrySync(e)}}const LIVE_WRITER_CHANGES=/* @__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)||!LIVE_WRITER_CHANGES.has(r.reason))throw r;const i=fsSync.realpathSync.native(e);const a=openPinnedFile(i,n);try{const e=readSourceSidecars(i);if(readSourceJournalMode(i,n)!==`wal`||!e.wal||!e.shm||e.journal)throw r;const o=await createOnlineReadOnlyBackup(i,t);try{assertPinnedIdentityUnchanged(a)}catch(e){o.cleanup();throw e}return o}finally{fsSync.closeSync(a.descriptor)}}}async function prepareSqliteReadOnlyLocationFromOwnedDatabase(e,t,n,r){const assertReady=()=>{n?.throwIfAborted();t();if(!e.isOpen||e.isTransaction)throw new Error(`SQLite inspection requires an open owner outside a transaction`)};assertReady();const i=await createSqliteSnapshotStagingDirectory(void 0,false,n,r===`async`);try{assertReady();assertSqliteSnapshotSpace(e,i);const r=path.join(i,`database.sqlite.partial`);await retainSnapshotWork(backupNodeSqliteDatabase(e,r));n?.throwIfAborted();t();return publishPreparedCopy(i)}catch(e){const t=[e];if(!await removeTempDirectoryAsync(i,e=>t.push(e))&&r===`async`)throw preparationCleanupError(t,`Owned SQLite snapshot preparation`);throw e}} //!src/infra/database-engine/admission-scope.ts const processRole=resolveGlobalSingleton(Symbol.for(`openclaw.databaseProcessRole`),()=>({}));function getDatabaseProcessRole(){return processRole.role}let admissionDepth=0;function withEngineStoreAdmission(e){admissionDepth+=1;try{const t=e();if(isPromiseLike(t))throw new Error(`Database engine admission must remain synchronous`);return t}finally{admissionDepth-=1}}function assertEngineStoreExecutionAllowed(){if(threadId===0&&admissionDepth===0&&processRole.role!==`cli-oneshot`)throw new Error(`PostgreSQL connections must run in a worker; only synchronous admission, migrations, and CLI one-shots may run on the main thread`)} //!src/infra/sqlite-handle-lifecycle.ts const SQLITE_IDLE_HANDLE_TTL_MS=18e5;const SQLITE_CLI_AGENT_IDLE_HANDLE_TTL_MS=3e4;function resolveAgentDatabaseIdleHandleTtlMs(){return getDatabaseProcessRole()===`cli-oneshot`?SQLITE_CLI_AGENT_IDLE_HANDLE_TTL_MS:SQLITE_IDLE_HANDLE_TTL_MS}export{createPrivateSqliteTempDirectorySync as _,withEngineStoreAdmission as a,prepareSqliteReadOnlyCopyInProcess as c,readSourceSidecars as d,acquireSqliteSnapshotReadToken as f,sqliteSchemaContractFromCatalog as g,createSqliteTableContractReader as h,getDatabaseProcessRole as i,prepareSqliteReadOnlyLocationFromOwnedDatabase as l,createSqliteSnapshotStagingDirectorySync as m,resolveAgentDatabaseIdleHandleTtlMs as n,SqliteSourceChangedError as o,createSqliteSnapshotStagingDirectory as p,assertEngineStoreExecutionAllowed as r,isSqliteReadOnlyError as s,SQLITE_IDLE_HANDLE_TTL_MS as t,readSourceJournalMode as u,resolvePrivateSqliteSnapshotStagingRoot as v};