UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

11 lines • 32.8 kB
import{Et as e,mt as t,v as n}from"./disk-budget.worker-subsystem-9qP7ka6r.mjs";import{Bt as r,Ci as i,Dn as a,Gi as o,Gt as s,It as c,Jt as l,Kt as u,Mn as d,Nn as f,Ot as p,Qt as m,Sr as h,St as g,Ur as _,Ut as ee,Vi as te,Wt as ne,Xt as re,Yt as ie,Zt as ae,_n as v,br as y,dt as oe,fi as se,gn as b,in as ce,kn as x,l as S,lt as le,on as ue,qt as de,rn as C,si as w,st as fe,ui as T,un as pe,wt as me,xi as he}from"./disk-budget.worker-sqlite-readonly-worker-Bob4L7Jx.mjs";import{F as E,J as D,s as ge,t as _e}from"./disk-budget.worker-sqlite-worker-operation-settlement-B656vNKC.mjs";import{t as O}from"./disk-budget.worker-errors-DTPr0dgo.mjs";import"./disk-budget.worker-gateway-process-argv-lGmvE77y.mjs";import{E as k,b as A,f as j,g as M,h as N,ht as P,j as F,s as I,v as ve,x as L,xt as ye,y as be,z as R}from"./disk-budget.worker-kysely-sync-BBbkOhNM.mjs";import"./disk-budget.worker-runtime-binary-B_EAZwtR.mjs";import"./disk-budget.worker-runtime-worker-url-MsqcyVdt.mjs";import{MessageChannel as z,receiveMessageOnPort as xe,threadId as B}from"node:worker_threads";import{AsyncLocalStorage as V}from"node:async_hooks";import{createHash as Se,randomUUID as Ce}from"node:crypto";import H,{realpathSync as we}from"node:fs";import U from"node:path";import"node:v8";import{channel as W}from"node:diagnostics_channel";import"node:child_process";function preparePostgresQuery(e){let t=``,n=0,r=!0,i,a;for(let o=0;o<e.length;){let s=e.slice(o),c=/^(?:[eE]'(?:\\[\s\S]|''|[^'\\])*'|'(?:''|[^'])*'|"(?:""|[^"])*"|`(?:``|[^`])*`|\[[^\]]*\]|--[^\n]*(?:\n|$))/.exec(s),l=/^\$(?:[A-Za-z_][A-Za-z_0-9]*)?\$/.exec(s)?.[0];if(s.startsWith(`/*`)){let n=o+2,r=1;for(;n<e.length&&r>0;)e.startsWith(`/*`,n)?(r++,n+=2):e.startsWith(`*/`,n)?(r--,n+=2):n++;t+=e.slice(o,n),o=n}else if(l){let n=e.indexOf(l,o+l.length),a=n<0?e.length:n+l.length;t+=e.slice(o,a),o=a,i=void 0,r=!1}else if(c)t+=c[0],o+=c[0].length,c[0].startsWith(`--`)||(i=void 0,r=!1);else{if(r&&/^pragma\b/i.test(s))throw Error(`The PostgreSQL engine does not support PRAGMA statements`);let c=/^(?:\d[\d_]*(?:\.[\d_]*)?|\.[\d_]+)(?:[eE][+-]?[\d_]+)?/.exec(s)?.[0];if(c){t+=c,o+=c.length,i=void 0,r=!1;continue}let l=/^[A-Za-z_][A-Za-z_0-9$]*/.exec(s)?.[0];if(l){let e=l.toUpperCase();i!==`AS`&&i!==`.`&&(e===`INTO`&&i!==`INSERT`&&i!==`MERGE`?a=`unscoped`:a===void 0&&/^(?:INSERT|UPDATE|DELETE|MERGE)$/.test(e)&&(e!==`UPDATE`||i!==`FOR`&&i!==`KEY`)&&(a=`scoped`)),i=e,t+=l,o+=l.length,r=!1;continue}let u=e.charAt(o);/\s/.test(u)||(i=u),u===`?`&&e[o+1]===`?`?(t+=`?`,o+=2):u===`?`?(t+=`$${++n}`,o++):(t+=u,o++),u===`;`?r=!0:/\s/.test(u)||(r=!1)}}return{sql:t,mutation:a}}function validatePostgresBindings(e){for(let t of e)if(t!==null&&typeof t!=`string`&&typeof t!=`number`&&typeof t!=`bigint`&&!ArrayBuffer.isView(t))throw TypeError(`SQL bindings must be null, numbers, bigints, strings, or ArrayBuffer views`)}function decodePostgresRows(e,t){return e.rows.map(n=>Object.fromEntries(e.fields.map(e=>{let r=n[e.name],i;if(r===null)i=null;else if(e.dataTypeID===20){if(typeof r!=`string`)throw TypeError(`PostgreSQL int8 results must be text`);let e=BigInt(r);if(t)i=e;else{let t=Number(e);if(!Number.isSafeInteger(t))throw RangeError(`PostgreSQL int8 ${e} cannot be represented safely as a number`);i=t}}else if(r instanceof Uint8Array)i=new Uint8Array(r);else if(typeof r==`boolean`)i=Number(r);else if(typeof r==`string`||typeof r==`number`||typeof r==`bigint`)i=r;else throw TypeError(`Unsupported PostgreSQL result type for column ${e.name}`);return[e.name,i]})))}function isPostgresConnectionError(e){return!e||e.startsWith(`08`)||/^57P0[123]$/.test(e)}function decodePostgresError(e){let t=Object.assign(Error(e.message),e);e.code===`57014`&&(t.name=`PostgresQueryCanceledError`);let n={23505:[2067,`UNIQUE`],23503:[787,`FOREIGN KEY`],23502:[1299,`NOT NULL`],23514:[275,`CHECK`]}[e.code??``];return n?Object.assign(Error(`${n[1]} constraint failed: ${e.constraint??e.column??`unknown`}`,{cause:t}),{code:`ERR_SQLITE_ERROR`,errcode:n[0]}):t}const G={statement:W(`openclaw.database.statement`),request:W(`openclaw.database.request`)},K=/* @__PURE__ */ new WeakSet;function normalizeSql(e,t){let n=``;for(let r=0;r<t.length;){let i=t.slice(r);if(i.startsWith(`/*`)){let e=1;for(r+=2;r<t.length&&e;)t.startsWith(`/*`,r)?(e++,r+=2):t.startsWith(`*/`,r)?(e--,r+=2):r++;n+=` `;continue}let a=/^--[^\r\n]*/.exec(i)?.[0],o=(e===`postgres`?/^[eE]'(?:\\[\s\S]|''|[^'\\])*(?:'|$)/.exec(i)?.[0]:void 0)??/^(?:[uU]&)?'(?:''|[^'])*(?:'|$)/.exec(i)?.[0],s=/^\$(?:[A-Za-z_][\w]*)?\$/.exec(i)?.[0],c=/^(?:"(?:""|[^"])*"|`(?:``|[^`])*`|\[[^\]]*\])/.exec(i)?.[0],l=/[\w$]/.test(t[r-1]??``)?void 0:/^(?:0x[\da-f]+|\d+(?:\.\d*)?(?:e[+-]?\d+)?)(?!\w)/i.exec(i)?.[0];if(s){let e=t.indexOf(s,r+s.length);r=e<0?t.length:e+s.length,n+=`?`}else if(a||o||c||l){let e=a??o??c??l??``;r+=e.length,n+=a?` `:c?e:`?`}else n+=t[r++]}return n.replace(/\s+/g,` `).trim()}function observeDatabaseOperation(e,t,n,r){let i=G[t];if(!i.hasSubscribers)return r();let a=performance.now(),o=`error`;try{let e=r();return o=`ok`,e}finally{let t=performance.now()-a;i.publish({engine:e,sql:n===void 0?void 0:normalizeSql(e,n),threadId:B,outcome:o,durationMs:t})}}function observeConnection(e){if(K.has(e))return e;K.add(e);let t=e.exec.bind(e),n=e.prepare.bind(e);return e.exec=e=>observeDatabaseOperation(`sqlite`,`statement`,e,()=>t(e)),e.prepare=e=>{let t=n(e);for(let n of[`get`,`all`,`run`]){let r=t[n].bind(t);Object.defineProperty(t,n,{configurable:!0,writable:!0,value:(...t)=>observeDatabaseOperation(`sqlite`,`statement`,e,()=>r(...t))})}let r=t.iterate.bind(t);return t.iterate=(...t)=>{let n=r(...t);if(!G.statement.hasSubscribers)return n;let i=0,a=!1,o=!1,finish=t=>{o||(o=!0,a&&G.statement.publish({engine:`sqlite`,sql:normalizeSql(`sqlite`,e),threadId:B,outcome:t,durationMs:i}))},step=e=>{if(o)return e();let t=performance.now();try{let n=e();return i+=performance.now()-t,n.done&&finish(`ok`),n}catch(e){throw i+=performance.now()-t,finish(`error`),e}},s={next:(...e)=>(a=!0,step(()=>n.next(...e))),return:e=>step(()=>n.return?.(e)??{done:!0,value:e}),[Symbol.iterator](){return this}};return Object.setPrototypeOf(s,Object.getPrototypeOf(n)),s},t},e}const q=/* @__PURE__ */ new Map;function closeBridge(e){e.port.close()}function closeIdleBridges(){let e=[...q.values()];q.clear(),unwatch();for(let{bridge:t,timeout:n}of e)clearTimeout(n),closeBridge(t)}function unwatch(){q.size||(process.off(`beforeExit`,closeIdleBridges),process.off(`exit`,closeIdleBridges))}function removeIdleBridge(e){let t=q.get(e);return q.delete(e),t&&clearTimeout(t.timeout),unwatch(),t?.bridge}function takeIdlePostgresBridge(e){let t=removeIdleBridge(e);if(t&&Atomics.load(t.service,1))closeBridge(t);else return t}function retainIdlePostgresBridge(e,t){let n=removeIdleBridge(e);if(n&&closeBridge(n),q.size===2){let e=q.keys().next().value;closeBridge(removeIdleBridge(e))}q.size||(process.once(`beforeExit`,closeIdleBridges),process.once(`exit`,closeIdleBridges));let r=setTimeout(()=>{let t=removeIdleBridge(e);t&&closeBridge(t)},18e4);r.unref(),q.set(e,{bridge:t,timeout:r})}function postgresBridgeReuseKey(e){return R(JSON.stringify([e.url,e.lockTimeoutMs??6e4,e.statementTimeoutMs??9e4]))}function preparedBridgeKey(e){return JSON.stringify([postgresBridgeReuseKey(e),e.schema,e.storeId])}function createPostgresBridge(e){let{port1:t,port2:n}=new z,r=new SharedArrayBuffer(8),i=new Int32Array(r),{port:a,signal:o,nextStep:s}=ge(),c=new Int32Array(o);if(Atomics.load(c,1)){t.close(),n.close();let e=/* @__PURE__ */ Error(`PostgreSQL I/O service is unavailable.${s?` Run ${s}.`:``}`);throw D(e),e}try{a.postMessage({connection:{port:n,signal:r,url:e.url,schema:e.schema,connectTimeoutMs:6e4,lockTimeoutMs:e.lockTimeoutMs??6e4,statementTimeoutMs:e.statementTimeoutMs??9e4}},[n])}catch(e){throw t.close(),n.close(),e}return t.unref(),{port:t,control:i,service:c,nextStep:s,requestId:0}}const Te=new V;function findPreparedBridge(e){let t=Te.getStore();for(;t;){if(t.key===e&&t.bridge&&!Atomics.load(t.bridge.service,1))return t;t=t.parent}}function takePreparedPostgresBridge(e){let t=findPreparedBridge(preparedBridgeKey(e)),n=t?.bridge;return t&&n&&(t.bridge=void 0,t.detachAbort()),n}function assertPostgresOperationCurrent(){let e=_e.getStore();if(e&&(!e.active||e.owner.refusal))throw e.owner.refusal??/* @__PURE__ */ Error(`PostgreSQL worker operation is no longer active`)}function runPostgresTransactionSync(e,t,n,r=!1,o=!1){assertPostgresOperationCurrent();let s=h(e);return f(s,()=>{let s=e.isTransaction&&!o,c=!1,l;try{s?e.exec(`SAVEPOINT openclaw_tx_nested`):e.isTransaction||e.exec(r?`BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY`:`BEGIN ISOLATION LEVEL READ COMMITTED; SELECT pg_advisory_xact_lock(${e.advisoryLockKey})`),r&&!s&&(l=p(e));let i=t();if(y(i),s)e.exec(`RELEASE SAVEPOINT openclaw_tx_nested`);else{let commit=()=>{assertPostgresOperationCurrent(),r||x(e),e.exec(r?`ROLLBACK`:`COMMIT`),c=!r};n?.withCommit?y(n.withCommit(commit)):commit()}return i}catch(t){let n=i(t)||c;if(!n)try{s?(e.exec(`ROLLBACK TO SAVEPOINT openclaw_tx_nested`),e.exec(`RELEASE SAVEPOINT openclaw_tx_nested`)):e.isTransaction&&e.exec(`ROLLBACK`)}catch{n=!0}if(n)try{a(e,t,`unknown`)}finally{try{e.close()}catch{}}throw t}finally{l?.()}})}var PostgresSyncConnection=class{constructor(e,t,n,r,i){this.schema=t,this.anchor=n,this.storeId=r,this.isOpen=!0,this.isTransaction=!1,this.mutationRevision=0,this.idleCheckout=!1,this.lastResponseAt=Date.now(),this.outcomeUnknown=!0,this.readOnlyTransaction=!1,this.pendingWrite=!1,this.mainThread=B===0,j(),Object.defineProperty(this,Symbol.for(`openclaw.postgres-sync-connection`),{value:!0}),this.advisoryLockKey=Se(`sha256`).update(r).digest().readBigInt64BE(),this.bridgeParameters={url:e,schema:t,storeId:r,...i},this.reuseKey=i?.reuse?postgresBridgeReuseKey(this.bridgeParameters):void 0,this.connect()}connect(){let e=this.reuseKey?takeIdlePostgresBridge(this.reuseKey):void 0,t=e??takePreparedPostgresBridge(this.bridgeParameters)??createPostgresBridge(this.bridgeParameters);if(this.bridge=t,this.idleCheckout=e!==void 0,t.port.unref(),e)return t;try{this.request({operation:`connect`,schema:this.schema})}catch(e){throw this.isOpen=!1,this.isTransaction=!1,this.bridge=void 0,t.port.close(),e}return t}runTransaction(e,t,...n){return runPostgresTransactionSync(this,e,t,...n)}readRecoveryGeneration(e=!1){return this.request({operation:`recovery-generation`,schema:this.schema,storeId:this.storeId,lock:e},!1)}loseConnection(){!this.failure&&this.outcomeUnknown&&(this.pendingWrite=!0,C(h(this),!0)),this.finishWrite(),this.failure??=this.outcomeUnknown?new he(`PostgreSQL connection lost; outcome unknown`,`outcome-unknown`):/* @__PURE__ */ Error(`PostgreSQL connection lost; transaction rolled back`);let e=this.bridge;return e?.nextStep&&!this.failure.message.includes(e.nextStep)&&(this.failure.message+=` Run ${e.nextStep}.`),e&&Atomics.load(e.service,1)&&D(this.failure),this.isOpen=!1,this.isTransaction=!1,e?.port.close(),this.bridge=void 0,this.failure}finishWrite(){this.pendingWrite&&(this.pendingWrite=!1,ce(h(this)))}assertOpen(){if(this.failure)throw this.failure;if(!this.isOpen)throw Error(`PostgreSQL connection is closed`)}request(e,t=!0){this.mainThread&&e.operation!==`close`&&e.operation!==`release`&&j(),this.assertOpen();let n=this.bridge??this.connect();this.outcomeUnknown=t;let r=++n.requestId;if(r>2147483647)throw this.loseConnection();let i=performance.now()+12e4,a=n.inTransaction===!1,o=(this.idleCheckout||a)&&(e.operation===`query`||e.operation===`recovery-generation`),s=o&&(this.idleCheckout||a&&Date.now()-this.lastResponseAt>=1e3);n.inTransaction=void 0,this.idleCheckout=!1,n.port.postMessage({...e,...o?{reconnectIfIdle:o}:{},...s?{validateIfIdle:s}:{},id:r},[]),E(`sqlite_request`,`to_worker`);for(let e=Atomics.load(n.control,0);e!==r;e=Atomics.load(n.control,0)){if(Atomics.load(n.service,1))throw this.loseConnection();let t=i-performance.now();if(t<=0)throw Atomics.store(n.service,1,1),Atomics.notify(n.service,1),this.loseConnection();Atomics.wait(n.control,0,e,Math.min(t,50))}let c=xe(n.port)?.message;if(c&&E(`sqlite_reply`,`from_worker`),!c||c.id!==r)throw this.loseConnection();if(`error`in c)throw e.operation===`connect`?decodePostgresError(c.error):isPostgresConnectionError(c.error.code)?this.loseConnection():(e.operation===`query`&&/^\s*COMMIT\b/i.test(e.sql)&&(this.isTransaction=!1,this.finishWrite()),decodePostgresError(c.error));return this.lastResponseAt=Date.now(),`reusable`in c?(n.inTransaction=!c.reusable,c.reusable):(n.inTransaction=`generation`in c?c.inTransaction:c.result.inTransaction,`generation`in c?c.generation:c.result)}query(e,t=[],n=!1){return observeDatabaseOperation(`postgres`,`statement`,e,()=>this.execute(preparePostgresQuery(e),t,n))}execute({sql:e,mutation:t},n,r){validatePostgresBindings(n);let i=this.isTransaction;/^\s*BEGIN\b/i.test(e)&&(this.isTransaction=!0);let a=this.request({operation:`query`,schema:this.schema,sql:e,parameters:n},!i||/^\s*COMMIT\b/i.test(e)),o=this.readOnlyTransaction;if(this.isTransaction=a.inTransaction,this.readOnlyTransaction=this.isTransaction&&(o||/^\s*BEGIN\b[^;]*\bREAD\s+ONLY\b/i.test(e)),/^\s*COMMIT\s*;?\s*$/i.test(e)&&a.command!==`COMMIT`)throw this.finishWrite(),Error(`PostgreSQL transaction rolled back instead of committing`);let s=a.mutation===`unscoped`||t===`unscoped`?`unscoped`:a.mutation??t,c=s!==void 0;if(c){if(o||this.readOnlyTransaction)throw Error(`PostgreSQL read snapshot cannot execute a mutation`);this.mutationRevision++,this.pendingWrite=!0,C(h(this),s===`unscoped`)}return!this.isTransaction&&(c||i)&&f(h(this),()=>{this.finishWrite()}),this.outcomeUnknown=!this.isTransaction,{rows:decodePostgresRows(a,r),rowCount:a.rowCount,columns:a.fields.map(({name:e})=>({name:e}))}}exec(e){this.query(e)}prepare(e){this.assertOpen();let t=preparePostgresQuery(e),n=!1,r=[],execute=i=>{let a=observeDatabaseOperation(`postgres`,`statement`,e,()=>this.execute(t,i,n));return r=a.columns,a};return{get:(...e)=>execute(e).rows[0],all:(...e)=>execute(e).rows,iterate:(...e)=>execute(e).rows[Symbol.iterator](),run:(...e)=>({changes:execute(e).rowCount,lastInsertRowid:0}),columns:()=>r,setReadBigInts:e=>{n=e}}}releaseIdleTransport(){let e=this.bridge;if(!this.isOpen||!e||!this.reuseKey||this.isTransaction)return;let t=!1;try{e.inTransaction===!1||this.request({operation:`release`})?(retainIdlePostgresBridge(this.reuseKey,e),t=!0):(this.isOpen=!1,this.finishWrite())}finally{this.bridge=void 0,t||e.port.close()}}close(){if(this.isOpen)try{this.reuseKey&&!this.isTransaction?this.releaseIdleTransport():this.bridge&&this.request({operation:`close`})}finally{this.finishWrite(),this.isOpen=!1,this.isTransaction=!1,this.bridge?.port.close(),this.bridge=void 0}}};new I;const J=`memory_index_sources`,Y=`memory_index_chunks_fts`,X=`memory_index_paths_fts`;function buildMemoryFtsTriggers(e,t,n,r,i){let trigger=(n,r,i)=>({name:`${e}_after_${n}`,sql:` CREATE TRIGGER IF NOT EXISTS main.${e}_after_${n} AFTER ${r} ON ${t} BEGIN ${i} END; `});return[trigger(`insert`,`INSERT`,r),trigger(`update`,`UPDATE OF ${n}`,`${i} ${r}`),trigger(`delete`,`DELETE`,i)]}const Ee=buildMemoryFtsTriggers(X,J,`id, path, source`,` INSERT INTO ${X} (rowid, path, source) VALUES (NEW.id, NEW.path, NEW.source);`,` DELETE FROM ${X} WHERE rowid = OLD.id;`),De=buildMemoryFtsTriggers(Y,`memory_index_chunks`,`chunk_rowid, text, id, path, source, model, start_line, end_line`,` INSERT INTO ${Y} (rowid, text, id, path, source, model, start_line, end_line) VALUES (NEW.chunk_rowid, NEW.text, NEW.id, NEW.path, NEW.source, NEW.model, NEW.start_line, NEW.end_line);`,` DELETE FROM ${Y} WHERE rowid = OLD.chunk_rowid;`),Z={sqlite:{openConnection:({anchor:e})=>observeConnection(e),schema:{bootstrap:e=>e.openSqlite()}},postgres:{openConnection:e=>{if(!e.input||!e.storeId||!e.namespace)throw Error(`PostgreSQL store is not admitted`);try{return new PostgresSyncConnection(e.input.connection,e.namespace,e.anchor,e.storeId,{reuse:e.reusePostgresConnection,lockTimeoutMs:6e4,statementTimeoutMs:9e4})}catch(t){let r=t instanceof Error&&`code`in t&&typeof t.code==`string`?`${t.code}: `:``,i=n(`${r}${t instanceof Error?t.message:String(t)}`.replaceAll(e.input.connection,`[REDACTED]`),{mode:`tools`});throw Error(`Cannot open PostgreSQL connection: ${i}; verify database.postgres.connection and server availability.`,{cause:t})}},schema:{bootstrap:(e,t)=>{if(!e.schema.postgres)throw Error(`Store has no PostgreSQL schema`);t.exec(u(e.schema,e.namespace)),t.prepare(`INSERT INTO openclaw_schema_meta (store, version, store_id) VALUES (?, ?, ?)`).run(e.schema.id,e.schema.version,e.storeId)},migrate:(e,t,n)=>{if(t>e.schema.version)throw Error(`PostgreSQL ${e.schema.id} schema ${t} is newer than this build (expected ${e.schema.version}); use a compatible binary, or reverse-port with a compatible binary before downgrading.`);for(let r=t+1;r<=e.schema.version;r++){let t=e.schema.postgresMigrations?.find(e=>e.version===r);if(!t)throw Error(`Missing PostgreSQL ${e.schema.id} migration to version ${r}; use a compatible binary or restore a matching backup.`);let i=l(n,e.namespace,e.schema.id),a=ae(e.schema,i);if(re(n,e.namespace,{...a,version:r-1,postgres:t.fromSchema.postgres,postgresFragments:t.fromSchema.postgresFragments,postgresVectorDecoderVersion:t.fromSchema.postgresVectorDecoderVersion,postgresVectorSearchVersion:t.fromSchema.postgresVectorSearchVersion,postgresTextSearchVersion:t.fromSchema.postgresTextSearchVersion},i),t.schema.postgresVectorSearchVersion===2&&t.fromSchema.postgresVectorSearchVersion!==2)for(let t of[a.search,...Object.values(a.searchExtensions??{})])t&&m(n,t,e.namespace,2);e.beforeMigrate?.(n,r-1,new Set(i.catalog.filter(e=>e.kind===`table`).map(e=>e.table))),n.exec(t.sql),n.prepare(`UPDATE openclaw_schema_meta SET version = ? WHERE store = ?`).run(r,e.schema.id),ie(n,e.namespace,{...a,version:r,postgres:t.schema.postgres,postgresFragments:t.schema.postgresFragments,postgresVectorDecoderVersion:t.schema.postgresVectorDecoderVersion,postgresVectorSearchVersion:t.schema.postgresVectorSearchVersion,postgresTextSearchVersion:t.schema.postgresTextSearchVersion})}}}}};function readCommittedContent(e,t,n,r){let i=g(t.location);T({release:()=>i.close()},`Database generation checkpoint`,()=>P(i,t.location)),n?.(t.location,e);let a=r?.(),o=a?L(t.location,t.cleanupRoot??U.dirname(t.location)):void 0;if(a&&!o)throw Error(`Database generation private image cannot be retained`);let s=t.journalFreeContent;if(s)return fe(t.location,s.identity,s),{sha256:s.sha256,family:o};let c=H.openSync(t.location,`r`);return{sha256:T({release:()=>H.closeSync(c)},`Database generation digest`,()=>oe(c).sha256),family:o}}function inspectDrainedSource(e,t){let n=me(e);if(t){t(n,e);return}let r=g(n,{readOnly:!0});T({release:()=>r.close()},`Database generation admission`,()=>c(r))}function readWalIndexHeader(t){let n=`${t}-shm`,r;try{r=H.openSync(n,`r`)}catch(t){return e(t)??null}try{let e=H.fstatSync(r,{bigint:!0}),i=Buffer.alloc(96),a=H.readSync(r,i,0,48,0),o=H.readSync(r,i,48,48,48),s=H.fstatSync(r,{bigint:!0}),c=H.lstatSync(n,{bigint:!0});if(!e.isFile()||!c.isFile()||[s,c].some(t=>e.dev!==t.dev||e.ino!==t.ino)||a!==48||o!==48||!i.subarray(0,48).equals(i.subarray(48,96)))throw Error(`SQLite WAL commit header is unavailable or changing: ${t}`);return i}finally{H.closeSync(r)}}function isRebuiltWalIndex(e,t){return t.readUInt32LE(8)===0&&t.subarray(0,8).equals(e.subarray(0,8))&&t.subarray(12,40).equals(e.subarray(12,40))}function sameWalCommitPublication(e,t,n){return(e===null?t===null:t!==null&&(t.equals(e)||isRebuiltWalIndex(e,t)))?!0:n.journal||(n.wal?.size??0n)!==0n?!1:t===null||e===null&&t.readUInt32LE(8)===0&&t.readBigUInt64LE(24)===0n}function readGenerationFamily(e){let t=[``,`-journal`,`-wal`].map(t=>H.lstatSync(`${e}${t}`,{bigint:!0,throwIfNoEntry:!1}));if(!t[0]&&t.slice(1).some(Boolean))throw Error(`Database is absent but retained journal data exists: ${e}`);if(t.some(e=>e&&!e.isFile()))throw Error(`Database generation requires a regular file: ${e}`);return t.map((e,t)=>t===2&&e?.size===0n?void 0:e)}function verifyGenerationFamily(e,t,n){let r=readGenerationFamily(e);if([n.database,n.journal,n.wal?.size===0n?void 0:n.wal].some((e,n)=>[t[n],r[n]].some(t=>e===void 0?t!==void 0:!t||!le(t,e))))throw Error(`SQLite file generation changed while reading: ${e}`)}function serializePhysicalGeneration(e,t){return R(JSON.stringify([A(e.wal?.size===0n?{...e,wal:void 0}:e),t?.toString(`hex`)??null]))}function readUpdateDatabaseGeneration(e,t,n){let r=readGenerationFamily(e),i=r[0];if(!i)return{generation:null,physical:null};let a=readWalIndexHeader(e),s=N(),c=s(e),observe=(t,n)=>{let l=ve(e,n?s:void 0),u=readWalIndexHeader(e);if(verifyGenerationFamily(e,r,l),!be(c,l)||!sameWalCommitPublication(a,u,l)||c.wal&&c.wal.size>0n&&u?.[12]!==1)throw Error(`SQLite WAL commit publication could not be verified: ${e}`);let d=[c.database.dev.toString(),c.database.ino.toString(),o(i),t.sha256],f=u?.subarray(8,12).toString(`hex`)??null,p=u?.subarray(24,32).toString(`hex`)??null,fingerprint=(e,t)=>R(JSON.stringify([...d,e,t])),m=!c.journal&&(c.wal?.size??0n)===0n&&(u===null||f===`00000000`&&p===`0000000000000000`),h;if(t.family&&n){let r=L(n.location,n.cleanupRoot??U.dirname(n.location));if(r?.main!==t.family.main||r?.wal!==t.family.wal)throw Error(`Database generation private image changed before retention`);h={sourcePath:e,prepared:n,family:t.family}}return{retained:h!==void 0,observation:{generation:fingerprint(f,p),physical:serializePhysicalGeneration(l,u),...u!==null&&(c.wal?.size??0n)!==0n&&f!==`00000000`?{rebuiltIndexAlternate:fingerprint(`00000000`,p)}:{},...m?{emptyReaderAlternate:u===null?fingerprint(`00000000`,`0000000000000000`):fingerprint(null,null)}:{},...h?{preparedSource:h}:{}}}},l=!c.journal&&(c.wal?.size??0n)===0n;if(l&&!n)try{return inspectDrainedSource(e,t),observe({sha256:c.database.sha256}).observation}catch{}let u=k(e,n?.stagingRoot,{key:`file:${te(c.database)}`},l?{sha256:c.database.sha256,sizeBytes:Number(c.database.size)}:void 0),d=!1;return T({release:()=>{if(!d){if(!n)u.cleanup();else try{if(!u.cleanup())throw Error(`Database generation snapshot cleanup did not settle`)}catch(e){throw new w(`Database generation snapshot cleanup failed`,{cause:e})}}}},`Database generation snapshot`,()=>{let r=readCommittedContent(e,u,t,n?.accept),i=observe(r,u);return d=i.retained,i.observation})}function readMatchingUpdateDatabaseGeneration(e,t){let{generation:n,emptyReaderAlternate:r}=readUpdateDatabaseGeneration(e);return n!==null&&t.includes(n)||r!==void 0&&t.includes(r)?n??void 0:void 0}function resolveUpdateSqlitePath(n){try{return we.native(n)}catch(r){return e(r),t(n)}}const Q=new V;function getDoctorMigrationBackup(e,t){let n=Q.getStore();if(n?.capture){if(n.capture.expected(resolveUpdateSqlitePath(t.path))!==void 0)throw Error(`Updater migration requires its captured source generation.`);return n.capture.refuse(`The migration source path is outside the updater's captured paths.`),Q.run({...n,capture:void 0,source:void 0},()=>n.backup?.(e,t))}return n?.backup?.(e,t)}function migrationAuthority(e,t,n){let r=_();if(!r?.ownsSchemaMaintenance)throw e.refuse(`Migration did not retain schema maintenance custody.`),Error(`Database migration requires schema maintenance custody.`);return()=>{r.assertAdmission(),n?n():F(t),e.assertCurrent()}}function readSqliteGeneration(e){let t=JSON.parse(S(e,void 0,`update-generation`));if(t!==null&&(typeof t!=`string`||!/^[a-f0-9]{64}$/u.test(t)))throw Error(`Database generation child returned an invalid generation.`);return t}function readSqliteFiles(e){return M(S(e,void 0,`file-generation`))}function getUpdateDoctorMigrationSource(e){let t=Q.getStore()?.source;if(!t||t.path!==resolveUpdateSqlitePath(e))return;let{generation:n,assertCurrent:r}=t;return r(),{path:e,generation:n,assertCurrent:r}}function runUpdateSqliteMigration(e,t,n,r){let i=Q.getStore();if(!i?.capture)return n();let a=resolveUpdateSqlitePath(t);if(i.source?.path===a)return i.source.assertCurrent(),n();let{capture:o}=i,s=o.expected(a),c=o.openedSqlitePaths?.has(a);if(typeof s!=`string`&&!(s===null&&r?.created))return n();let l=migrationAuthority(o,t);if(l(),e.isTransaction)throw Error(`Update migration exclusion must precede the source transaction.`);let u=e.prepare(`PRAGMA locking_mode`).get()?.locking_mode;return T({release(){r?.close&&o.openedSqlitePaths?.delete(a);try{if(e.isOpen&&u!==`exclusive`&&!r?.retainExclusive){if(e.isTransaction)throw Error(`Update migration left its source transaction open.`);e.exec(`PRAGMA locking_mode=NORMAL; PRAGMA page_count;`)}}catch(e){throw o.refuse(`SQLite migration native custody could not be released.`),e}}},`Update migration exclusion`,()=>{try{if(s===null){let e=readSqliteFiles(t);if(e.database.size!==0n||e.journal||e.wal)throw Error(`Created SQLite migration family is no longer empty.`)}let i=o.rebuiltIndex(a),d=s===null?null:c||u===`exclusive`?readSqliteGeneration(t):readMatchingUpdateDatabaseGeneration(t,i===void 0?[s]:[s,i]);if(l(),d===void 0||!c&&u===`exclusive`&&d!==s&&d!==i)throw Error(`SQLite migration source changed after update capture: ${t}`);o.openedSqlitePaths?.add(a),d!==s&&o.accept(a,s,d),u!==`exclusive`&&e.prepare(`PRAGMA schema_version`).get(),e.exec(`PRAGMA locking_mode=EXCLUSIVE; BEGIN EXCLUSIVE; ROLLBACK;`),l();let f=d===null?void 0:{path:a,generation:d,assertCurrent:l};return Q.run({capture:o,source:f,assertMigrationCurrent:l},()=>{let i=n();if(se(i))throw Error(`Update migration callbacks must remain synchronous.`);if(e.isTransaction)throw Error(`Update migration publication requires its committed native owner.`);l(),P(e,t),r?.close?.();let s=readSqliteGeneration(t);return l(),o.accept(a,d,s),i})}catch(e){throw o.refuse(`SQLite migration publication could not be verified: ${O(e)}`),e}})}function beginUpdateSqliteCompanion(e,t,n){let r=Q.getStore(),i=r?.capture;if(!i)return;let a=resolveUpdateSqlitePath(t),o=i.expected(a);if(o===void 0)return;let s=r?.assertMigrationCurrent;if(!s)throw i.refuse(`Migration companion has no verified source custody.`),Error(`Migration companion requires verified source custody.`);if(s(),e.prepare(`PRAGMA locking_mode`).get()?.locking_mode!==`exclusive`)throw Error(`Migration companion requires its exclusive native owner.`);let c=n&&o===null?null:readSqliteGeneration(t);if(s(),!i.openedSqlitePaths?.has(a)&&c!==o&&c!==i.rebuiltIndex(a))throw i.refuse(`Migration companion changed after update capture.`),Error(`Database migration companion no longer matches its capture.`);return i.openedSqlitePaths?.add(a),{complete(){if(s(),!e.isOpen||e.isTransaction)throw Error(`Migration companion publication requires its committed native owner.`);let n=readSqliteGeneration(t);s(),i.accept(a,c,n)}}}function beginUpdatePostgresMigration(e,t){let n=Q.getStore()?.capture,r=e.anchor.location(),i=r&&n?.expected(r);if(!n||!r||typeof i!=`string`)return;if(!_()?.ownsSchemaMaintenance){n.refuse(`PostgreSQL migration did not retain schema maintenance custody.`);return}let a=migrationAuthority(n,r,t);a();let o=e.readRecoveryGeneration(!0);if(o!==i)throw n.refuse(`PostgreSQL changed before migration acquired native custody.`),Error(`PostgreSQL migration source changed after update capture.`);let s={path:r,generation:o,assertCurrent:a},publish;return{run(e){return Q.run({capture:n,source:s,assertMigrationCurrent:a},e)},beforeCommit(){a();let t=e.readRecoveryGeneration(!1);publish=()=>n.accept(r,o,t),a()},committed(){a(),publish?.()}}}const $={name:`database.engine`};function readEngineAnchor(e,t=`identity`,n=!1){try{return t===`schema`?[e.prepare(`SELECT schema FROM openclaw_engine_anchor LIMIT 1`).get()]:e.prepare(`SELECT store_id, engine, schema FROM openclaw_engine_anchor`).all()}catch(e){if(n||!(e instanceof Error)||e.message!==`no such table: openclaw_engine_anchor`)throw e;return}}function familySetting(e){return`database.families.${e.id===`team_reports`?`team-reports`:e.id}.engine`}function refusePostgresAnchor(e,t){let n=readEngineAnchor(e,`schema`);if(n)throw Error(`This store lives in PostgreSQL schema ${String(n[0]?.schema??`unknown`)}; set ${familySetting(t)} to postgres and configure database.postgres.connection.`)}function openEngineStore(e){let{anchor:t}=e,n=e.schema;observeConnection(t);let i=e.input!==void 0&&n.postgres!==void 0,a=ue(t,$);if(!i){if(a?.engine===`postgres`)throw Error(`This store lives in PostgreSQL schema ${a.namespace}; set ${familySetting(n)} to postgres and configure database.postgres.connection.`);return!a&&e.inspectSqlite().hasEngineAnchor&&refusePostgresAnchor(t,n),e.prepareAnchor(),Z.sqlite.schema.bootstrap({...e,input:e.input},t),b(t,$,{engine:`sqlite`}),Z.sqlite.openConnection({...e,input:e.input})}if(a?.engine===`sqlite`)throw Error(`Existing SQLite ${n.id} data cannot switch engines; stop the Gateway and use openclaw database port for a supported store family before changing ${familySetting(n)}.`);e.prepareAnchor();let readOrCreateAnchor=()=>{let r=e.inspectSqlite();if(r.hasExistingData)throw Error(`Existing SQLite ${n.id} data cannot switch engines; stop the Gateway and use openclaw database port for a supported store family before changing ${familySetting(n)}.`);if(!r.hasEngineAnchor&&e.existingOnly)throw Error(`Missing PostgreSQL anchor; restore the matching PostgreSQL schema and anchor.`);r.hasEngineAnchor||t.exec(`CREATE TABLE IF NOT EXISTS openclaw_engine_anchor (store_id TEXT NOT NULL, engine TEXT NOT NULL CHECK (engine = 'postgres'), schema TEXT NOT NULL)`);let i=readEngineAnchor(t,`identity`,!0)??[];if(i.length>1||r.hasEngineAnchor&&i.length===0)throw Error(`Invalid engine anchor: expected exactly one identity. Restore a matching backup.`);let a=i[0];if(a){if(typeof a.store_id!=`string`||a.engine!==`postgres`||typeof a.schema!=`string`)throw Error(`Invalid PostgreSQL anchor identity. Restore a matching backup.`);return{storeId:a.store_id,namespace:a.schema}}let o=Ce(),s=de(e.input.schemaPrefix,n.id,o);return t.prepare(`INSERT INTO openclaw_engine_anchor (store_id, engine, schema) VALUES (?, 'postgres', ?)`).run(o,s),e.onFreshAnchor?.(t),{storeId:o,namespace:s}},o=a?.engine===`postgres`?a:e.existingOnly?readOrCreateAnchor():ye(t,readOrCreateAnchor),c={...e,input:e.input,...o},l=Z.postgres,u=l.openConnection(c),admit=t=>{r({db:u,namespace:o.namespace,storeId:o.storeId,store:n.id,version:n.version,schema:n,recordSchema:t,preserveSchemaSeal:e.existingVersion}),e.admitPostgres?.(u,t)};try{let r=n.search?m(u,n.search,o.namespace,e.existingVersion?1:n.postgresVectorSearchVersion):void 0;if(!a||a.engine===`postgres`&&a.version!==n.version){ee(u);let t,r;u.runTransaction(()=>{let i=!u.prepare(`SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname = ?`).get(o.namespace);i&&!e.existingOnly&&(u.exec(`CREATE SCHEMA IF NOT EXISTS "${o.namespace.replaceAll(`"`,`""`)}"`),u.exec(s));let a;try{a=u.prepare(`SELECT version, store_id FROM openclaw_schema_meta WHERE store = ?`).get(n.id)}catch(e){throw Error(`Missing PostgreSQL metadata; use the matching OpenClaw version or restore the matching PostgreSQL schema and anchor.`,{cause:e})}if(a){if(a.store_id!==o.storeId)throw Error(`PostgreSQL database identity mismatch: expected ${o.storeId}, found ${String(a.store_id)}. Restore the matching anchor and PostgreSQL backup.`);if(a.version!==n.version){if(e.existingVersion){let e=n.postgresMigrations?.find(e=>e.version===Number(a.version)+1)?.fromSchema;if(!e)throw Error(`Missing PostgreSQL source schema for inspection`);n={...n,...e,postgresVectorDecoderVersion:e.postgresVectorDecoderVersion,postgresVectorSearchVersion:e.postgresVectorSearchVersion,postgresTextSearchVersion:e.postgresTextSearchVersion,version:Number(a.version)}}else{r=e.assertMigrationCurrent,r?.(),t=beginUpdatePostgresMigration(u,r),pe(u),d(u,{stage:()=>{},rollback:()=>{},commit:()=>v(u),invalidate:()=>v(u)});let migrate=()=>l.schema.migrate(c,Number(a.version),u);t?t.run(migrate):migrate()}}}else{if(e.existingOnly||!i)throw Error(`Missing PostgreSQL metadata; restore the matching PostgreSQL schema and anchor.`);l.schema.bootstrap(c,u)}admit(!a)},{withCommit(e){r?.(),t?.beforeCommit(),e()}},!1),t?.committed()}else admit(!1);(!a||a.engine===`postgres`&&a.version!==n.version)&&b(t,$,{engine:`postgres`,...o,version:n.version}),r?.();for(let e of Object.values(ne(u)?.searchExtensions??{}))m(u,e,o.namespace,n.postgresVectorSearchVersion)?.();return u}catch(t){if(e.closeOnFailure)return e.closeOnFailure(u,t);throw u.close(),t}}export{getUpdateDoctorMigrationSource as a,J as c,getDoctorMigrationBackup as i,Ee as l,readEngineAnchor as n,runUpdateSqliteMigration as o,beginUpdateSqliteCompanion as r,De as s,openEngineStore as t};