UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

11 lines • 29.3 kB
import{$ as e,Mt as t,tt as n,w as r}from"./sqlite-readonly-subsystem-C-VJT-xk.mjs";import{a as i,g as a,i as o}from"./sqlite-readonly-pool-CKutEb9N.mjs";import{H as s,P as c}from"./sqlite-readonly-sqlite-readonly-location-CKoGOncu.mjs";import{c as l}from"./sqlite-readonly-sqlite-wal-CjNCU3qS.mjs";import{A as u,C as d,D as f,E as p,En as m,G as h,H as g,It as ee,Jn as te,O as ne,Rt as re,S as ie,T as ae,U as oe,Xn as _,Y as v,bt as y,gt as se,j as b,k as x,mt as ce,nt as S,s as le,tt as C,w,wn as T,y as ue,yt as de}from"./sqlite-readonly-node-sqlite-u3RAlsBE.mjs";import{X as E}from"./sqlite-readonly-sqlite-snapshot-capacity-error-Dx-DuFsZ.mjs";import{u as D}from"./sqlite-readonly-worker-cpu-COshMrit.mjs";import"./sqlite-readonly-runtime-binary-BIdoCQkJ.mjs";import"./sqlite-readonly-runtime-worker-url-D7L1HCPF.mjs";import{t as O}from"./sqlite-readonly-errors-bSzGfuz-.mjs";import{i as k}from"./sqlite-readonly-sqlite-transaction-CZJn2Fa5.mjs";import"./sqlite-readonly-location.worker.js";import{t as A}from"./sqlite-readonly-sqlite-worker-operation-settlement-4j7LHCL7.mjs";import{r as j,t as M}from"./sqlite-readonly-update-database-generations-CCiRrbIC.mjs";import{s as N}from"./sqlite-readonly-kysely-sync-DYhhbB39.mjs";import"node:v8";import{createHash as P,randomUUID as F}from"node:crypto";import{realpathSync as I}from"node:fs";import{MessageChannel as L,receiveMessageOnPort as R,threadId as z}from"node:worker_threads";import{AsyncLocalStorage as B}from"node:async_hooks";import"node:child_process";import{channel as V}from"node:diagnostics_channel";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 H=t(Symbol.for(`openclaw.databaseProcessRole`),()=>({}));function getDatabaseProcessRole(){return H.role}let U=0;function withEngineStoreAdmission(e){U+=1;try{let t=e();if(_(t))throw Error(`Database engine admission must remain synchronous`);return t}finally{--U}}function assertEngineStoreExecutionAllowed(){if(z===0&&U===0&&H.role!==`cli-oneshot`)throw Error(`PostgreSQL connections must run in a worker; only synchronous admission, migrations, and CLI one-shots may run on the main thread`)}const W=18e5;function resolveAgentDatabaseIdleHandleTtlMs(){return getDatabaseProcessRole()===`cli-oneshot`?3e4:W}const G={statement:V(`openclaw.database.statement`),request:V(`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:z,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:z,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 s(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 L,r=new SharedArrayBuffer(8),a=new Int32Array(r),{port:s,signal:c,nextStep:l}=o(),u=new Int32Array(c);if(Atomics.load(u,1)){t.close(),n.close();let e=/* @__PURE__ */ Error(`PostgreSQL I/O service is unavailable.${l?` Run ${l}.`:``}`);throw i(e),e}try{s.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:a,service:u,nextStep:l,requestId:0}}const fe=new B;function findPreparedBridge(e){let t=fe.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=A.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,i=!1){assertPostgresOperationCurrent();let a=m(e);return y(a,()=>{let a=e.isTransaction&&!i,o=!1,s;try{a?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&&!a&&(s=le(e));let i=t();if(T(i),a)e.exec(`RELEASE SAVEPOINT openclaw_tx_nested`);else{let commit=()=>{assertPostgresOperationCurrent(),r||se(e),e.exec(r?`ROLLBACK`:`COMMIT`),o=!r};n?.withCommit?T(n.withCommit(commit)):commit()}return i}catch(t){let n=re(t)||o;if(!n)try{a?(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{ce(e,t,`unknown`)}finally{try{e.close()}catch{}}throw t}finally{s?.()}})}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=z===0,assertEngineStoreExecutionAllowed(),Object.defineProperty(this,Symbol.for(`openclaw.postgres-sync-connection`),{value:!0}),this.advisoryLockKey=P(`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,g(m(this),!0)),this.finishWrite(),this.failure??=this.outcomeUnknown?new ee(`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)&&i(this.failure),this.isOpen=!1,this.isTransaction=!1,e?.port.close(),this.bridge=void 0,this.failure}finishWrite(){this.pendingWrite&&(this.pendingWrite=!1,oe(m(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`&&assertEngineStoreExecutionAllowed(),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},[]),D(`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=R(n.port)?.message;if(c&&D(`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,g(m(this),s===`unscoped`)}return!this.isTransaction&&(c||i)&&y(m(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 N;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 pe=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;`),me=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 n=t instanceof Error&&`code`in t&&typeof t.code==`string`?`${t.code}: `:``,i=r(`${n}${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(ae(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=f(n,e.namespace,e.schema.id),a=u(e.schema,i);if(x(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&&b(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),ne(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 resolveUpdateSqlitePath(t){try{return I.native(t)}catch(r){return n(r),e(t)}}const Q=new B;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=E();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():c(t),e.assertCurrent()}}function readSqliteGeneration(e){let t=JSON.parse(a(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 j(a(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 u=migrationAuthority(o,t);if(u(),e.isTransaction)throw Error(`Update migration exclusion must precede the source transaction.`);let d=e.prepare(`PRAGMA locking_mode`).get()?.locking_mode;return te({release(){r?.close&&o.openedSqlitePaths?.delete(a);try{if(e.isOpen&&d!==`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),f=s===null?null:c||d===`exclusive`?readSqliteGeneration(t):M(t,i===void 0?[s]:[s,i]);if(u(),f===void 0||!c&&d===`exclusive`&&f!==s&&f!==i)throw Error(`SQLite migration source changed after update capture: ${t}`);o.openedSqlitePaths?.add(a),f!==s&&o.accept(a,s,f),d!==`exclusive`&&e.prepare(`PRAGMA schema_version`).get(),e.exec(`PRAGMA locking_mode=EXCLUSIVE; BEGIN EXCLUSIVE; ROLLBACK;`),u();let p=f===null?void 0:{path:a,generation:f,assertCurrent:u};return Q.run({capture:o,source:p,assertMigrationCurrent:u},()=>{let i=n();if(_(i))throw Error(`Update migration callbacks must remain synchronous.`);if(e.isTransaction)throw Error(`Update migration publication requires its committed native owner.`);u(),l(e,t),r?.close?.();let s=readSqliteGeneration(t);return u(),o.accept(a,f,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(!E()?.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 r=e.input!==void 0&&n.postgres!==void 0,i=h(t,$);if(!r){if(i?.engine===`postgres`)throw Error(`This store lives in PostgreSQL schema ${i.namespace}; set ${familySetting(n)} to postgres and configure database.postgres.connection.`);return!i&&e.inspectSqlite().hasEngineAnchor&&refusePostgresAnchor(t,n),e.prepareAnchor(),Z.sqlite.schema.bootstrap({...e,input:e.input},t),C(t,$,{engine:`sqlite`}),Z.sqlite.openConnection({...e,input:e.input})}if(i?.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=F(),s=p(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}},a=i?.engine===`postgres`?i:e.existingOnly?readOrCreateAnchor():k(t,readOrCreateAnchor),o={...e,input:e.input,...a},s=Z.postgres,c=s.openConnection(o),admit=t=>{ue({db:c,namespace:a.namespace,storeId:a.storeId,store:n.id,version:n.version,schema:n,recordSchema:t,preserveSchemaSeal:e.existingVersion}),e.admitPostgres?.(c,t)};try{let r=n.search?b(c,n.search,a.namespace,e.existingVersion?1:n.postgresVectorSearchVersion):void 0;if(!i||i.engine===`postgres`&&i.version!==n.version){ie(c);let t,r;c.runTransaction(()=>{let i=!c.prepare(`SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname = ?`).get(a.namespace);i&&!e.existingOnly&&(c.exec(`CREATE SCHEMA IF NOT EXISTS "${a.namespace.replaceAll(`"`,`""`)}"`),c.exec(w));let l;try{l=c.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(l){if(l.store_id!==a.storeId)throw Error(`PostgreSQL database identity mismatch: expected ${a.storeId}, found ${String(l.store_id)}. Restore the matching anchor and PostgreSQL backup.`);if(l.version!==n.version){if(e.existingVersion){let e=n.postgresMigrations?.find(e=>e.version===Number(l.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(l.version)}}else{r=e.assertMigrationCurrent,r?.(),t=beginUpdatePostgresMigration(c,r),v(c),de(c,{stage:()=>{},rollback:()=>{},commit:()=>S(c),invalidate:()=>S(c)});let migrate=()=>s.schema.migrate(o,Number(l.version),c);t?t.run(migrate):migrate()}}}else{if(e.existingOnly||!i)throw Error(`Missing PostgreSQL metadata; restore the matching PostgreSQL schema and anchor.`);s.schema.bootstrap(o,c)}admit(!l)},{withCommit(e){r?.(),t?.beforeCommit(),e()}},!1),t?.committed()}else admit(!1);(!i||i.engine===`postgres`&&i.version!==n.version)&&C(t,$,{engine:`postgres`,...a,version:n.version}),r?.();for(let e of Object.values(d(c)?.searchExtensions??{}))b(c,e,a.namespace,n.postgresVectorSearchVersion)?.();return c}catch(t){if(e.closeOnFailure)return e.closeOnFailure(c,t);throw c.close(),t}}export{getUpdateDoctorMigrationSource as a,J as c,resolveAgentDatabaseIdleHandleTtlMs as d,getDatabaseProcessRole as f,getDoctorMigrationBackup as i,pe as l,readEngineAnchor as n,runUpdateSqliteMigration as o,withEngineStoreAdmission as p,beginUpdateSqliteCompanion as r,me as s,openEngineStore as t,W as u};