openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
17 lines • 32.5 kB
JavaScript
import{Et as e,Nt as t,o as n}from"./openclaw-state-read-subsystem-Dwoo5bcz.mjs";import{Pt as r,d as i,i as a,o,rt as s,t as c,tt as l,v as u,y as d,zt as f}from"./openclaw-state-read-sqlite-database-admission-CrkztOzk.mjs";import{s as p}from"./openclaw-state-read-pool-B6DWjH6F.mjs";import{t as m}from"./openclaw-state-read-promise-like-3qqJObCs.mjs";import{S as h,c as g,d as _,i as ee,l as v,n as te,s as ne,v as re}from"./openclaw-state-read-sqlite-post-commit-CsXPYVOo.mjs";import{o as ie,t as y,w as b}from"./openclaw-state-read-sqlite-private-snapshot-fork-B2lPOtW3.mjs";import{Et as ae,Ot as oe,l as x}from"./openclaw-state-read-sqlite-readonly-worker-D6FdUovN.mjs";import{c as S}from"./openclaw-state-read-runtime-worker-generation-DIZIqsAo.mjs";import{t as C}from"./openclaw-state-read-node-crypto-40z5rHq3.mjs";import{s as w}from"./openclaw-state-read-sqlite-wal-write-admission-BvF6tHCz.mjs";import{t as se}from"./openclaw-state-read-sqlite-worker-operation-settlement-DOkqmUGd.mjs";import"./openclaw-state-read-runtime-binary-BjmkF9EB.mjs";import"./openclaw-state-read-runtime-worker-url-C8NPtAdy.mjs";import{f as T}from"./openclaw-state-read-worker-cpu-CbvwBMyE.mjs";import{t as ce}from"./openclaw-state-read-errors-D4PLrhBz.mjs";import{A as le,C as ue,D as de,E as fe,F as E,M as pe,N as me,O as he,P as ge,j as _e,k as D,r as O,v as k}from"./openclaw-state-read-sqlite-schema-facts-Dtolu7-X.mjs";import{i as A,n as j}from"./openclaw-state-read-node-sqlite-B_Qn1gsS.mjs";import{f as M}from"./openclaw-state-read-kysely-sync-Bcu0Qb7F.mjs";import{i as N}from"./openclaw-state-read-sqlite-transaction-Bt-IwVhZ.mjs";import{n as P}from"./openclaw-state-read-file-descriptor-aMlGc_Rn.mjs";import{d as F,l as I,o as ve,r as L,s as ye,u as be}from"./openclaw-state-read-sqlite-handle-lifecycle-uqyIC6ii.mjs";import"./openclaw-state-read-context-RUh9cSel.mjs";import{a as xe,c as Se,i as Ce,n as we,o as R,s as Te,t as Ee}from"./openclaw-state-read-bridge-prestart-DLrgs8ph.mjs";import"node:v8";import z,{realpathSync as De}from"node:fs";import B from"node:path";import{receiveMessageOnPort as Oe,threadId as V}from"node:worker_threads";import"node:child_process";import{createHash as ke,randomUUID as Ae}from"node:crypto";import{AsyncLocalStorage as je}from"node:async_hooks";import{channel as H}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}function readCommittedContent(e,t,n,r){let i=j(t.location);h({release:()=>i.close()},`Database generation checkpoint`,()=>b(i,t.location)),n?.(t.location,e);let a=r?.(),o=a?y(t.location,t.cleanupRoot??B.dirname(t.location)):void 0;if(a&&!o)throw Error(`Database generation private image cannot be retained`);let s=t.journalFreeContent;if(s)return ae(t.location,s.identity,s),{sha256:s.sha256,family:o};let c=z.openSync(t.location,`r`);return{sha256:h({release:()=>z.closeSync(c)},`Database generation digest`,()=>P(c).sha256),family:o}}function inspectDrainedSource(e,t){let n=A(e);if(t){t(n,e);return}let r=j(n,{readOnly:!0});h({release:()=>r.close()},`Database generation admission`,()=>k(r))}function readWalIndexHeader(e){let n=`${e}-shm`,r;try{r=z.openSync(n,`r`)}catch(e){return t(e)??null}try{let t=z.fstatSync(r,{bigint:!0}),i=Buffer.alloc(96),a=z.readSync(r,i,0,48,0),o=z.readSync(r,i,48,48,48),s=z.fstatSync(r,{bigint:!0}),c=z.lstatSync(n,{bigint:!0});if(!t.isFile()||!c.isFile()||[s,c].some(e=>t.dev!==e.dev||t.ino!==e.ino)||a!==48||o!==48||!i.subarray(0,48).equals(i.subarray(48,96)))throw Error(`SQLite WAL commit header is unavailable or changing: ${e}`);return i}finally{z.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=>z.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||!oe(t,e))))throw Error(`SQLite file generation changed while reading: ${e}`)}function serializePhysicalGeneration(e,t){return C(JSON.stringify([F(e.wal?.size===0n?{...e,wal:void 0}:e),t?.toString(`hex`)??null]))}function readUpdateDatabaseGeneration(e,t,n){let i=readGenerationFamily(e),a=i[0];if(!a)return{generation:null,physical:null};let o=readWalIndexHeader(e),s=ve(),c=s(e),observe=(t,n)=>{let r=I(e,n?s:void 0),l=readWalIndexHeader(e);if(verifyGenerationFamily(e,i,r),!be(c,r)||!sameWalCommitPublication(o,l,r)||c.wal&&c.wal.size>0n&&l?.[12]!==1)throw Error(`SQLite WAL commit publication could not be verified: ${e}`);let u=[c.database.dev.toString(),c.database.ino.toString(),f(a),t.sha256],d=l?.subarray(8,12).toString(`hex`)??null,p=l?.subarray(24,32).toString(`hex`)??null,fingerprint=(e,t)=>C(JSON.stringify([...u,e,t])),m=!c.journal&&(c.wal?.size??0n)===0n&&(l===null||d===`00000000`&&p===`0000000000000000`),h;if(t.family&&n){let r=y(n.location,n.cleanupRoot??B.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(d,p),physical:serializePhysicalGeneration(r,l),...l!==null&&(c.wal?.size??0n)!==0n&&d!==`00000000`?{rebuiltIndexAlternate:fingerprint(`00000000`,p)}:{},...m?{emptyReaderAlternate:l===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=ie(e,n?.stagingRoot,{key:`file:${r(c.database)}`},l?{sha256:c.database.sha256,sizeBytes:Number(c.database.size)}:void 0),d=!1;return h({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 re(`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 De.native(n)}catch(r){return t(r),e(n)}}const U=new je;function getDoctorMigrationBackup(e,t){let n=U.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.`),U.run({...n,capture:void 0,source:void 0},()=>n.backup?.(e,t))}return n?.backup?.(e,t)}function migrationAuthority(e,t,n){let r=S();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():w(t),e.assertCurrent()}}function readSqliteGeneration(e){let t=JSON.parse(x(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 ye(x(e,void 0,`file-generation`))}function getUpdateDoctorMigrationSource(e){let t=U.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=U.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 h({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 U.run({capture:o,source:f,assertMigrationCurrent:l},()=>{let i=n();if(m(i))throw Error(`Update migration callbacks must remain synchronous.`);if(e.isTransaction)throw Error(`Update migration publication requires its committed native owner.`);l(),b(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: ${ce(e)}`),e}})}function beginUpdateSqliteCompanion(e,t,n){let r=U.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=U.getStore()?.capture,r=e.anchor.location(),i=r&&n?.expected(r);if(!n||!r||typeof i!=`string`)return;if(!S()?.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 U.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 W={statement:H(`openclaw.database.statement`),request:H(`openclaw.database.request`)},G=/* @__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=W[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:V,outcome:o,durationMs:t})}}function observeConnection(e){if(G.has(e))return e;G.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(!W.statement.hasSubscribers)return n;let i=0,a=!1,o=!1,finish=t=>{o||(o=!0,a&&W.statement.publish({engine:`sqlite`,sql:normalizeSql(`sqlite`,e),threadId:V,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}function assertPostgresOperationCurrent(){let e=se.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=_(e);return g(a,()=>{let a=e.isTransaction&&!i,o=!1,c;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&&(c=O(e));let i=t();if(v(i),a)e.exec(`RELEASE SAVEPOINT openclaw_tx_nested`);else{let commit=()=>{assertPostgresOperationCurrent(),r||ee(e),e.exec(r?`ROLLBACK`:`COMMIT`),o=!r};n?.withCommit?v(n.withCommit(commit)):commit()}return i}catch(t){let n=s(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{te(e,t,`unknown`)}finally{try{e.close()}catch{}}throw t}finally{c?.()}})}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=V===0,L(),Object.defineProperty(this,Symbol.for(`openclaw.postgres-sync-connection`),{value:!0}),this.advisoryLockKey=ke(`sha256`).update(r).digest().readBigInt64BE(),this.bridgeParameters={url:e,schema:t,storeId:r,...i},this.reuseKey=i?.reuse?we(this.bridgeParameters):void 0,this.connect()}connect(){let e=this.reuseKey?R(this.reuseKey):void 0,t=e??Ce(this.bridgeParameters)??Ee(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(_(this),!0)),this.finishWrite(),this.failure??=this.outcomeUnknown?new l(`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)&&p(this.failure),this.isOpen=!1,this.isTransaction=!1,e?.port.close(),this.bridge=void 0,this.failure}finishWrite(){this.pendingWrite&&(this.pendingWrite=!1,a(_(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`&&L(),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},[]),T(`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=Oe(n.port)?.message;if(c&&T(`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,l=s!==void 0;if(l){if(o||this.readOnlyTransaction)throw Error(`PostgreSQL read snapshot cannot execute a mutation`);this.mutationRevision++,this.pendingWrite=!0,c(_(this),s===`unscoped`)}return!this.isTransaction&&(l||i)&&g(_(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`})?(xe(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 M;const K=`memory_index_sources`,q=`memory_index_chunks`,J=`memory_index_chunks_fts`,Y=`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 X=buildMemoryFtsTriggers(Y,K,`id, path, source`,` INSERT INTO ${Y} (rowid, path, source)
VALUES (NEW.id, NEW.path, NEW.source);`,` DELETE FROM ${Y}
WHERE rowid = OLD.id;`),Z=buildMemoryFtsTriggers(J,q,`chunk_rowid, text, id, path, source, model, start_line, end_line`,` INSERT INTO ${J} (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 ${J} WHERE rowid = OLD.chunk_rowid;`);function dropMemoryChunkFtsTriggers(e){for(let t of Z)e.exec(`DROP TRIGGER IF EXISTS main.${t.name}`)}function ensureMemoryChunkFtsTriggers(e){for(let t of Z)e.exec(t.sql)}function rebuildMemoryChunkFts(e,t,n={}){n.fresh||e.exec(`DELETE FROM ${t}`),e.exec(`
INSERT INTO ${t} (
rowid, text, id, path, source, model, start_line, end_line
)
SELECT chunk_rowid, text, id, path, source, model, start_line, end_line
FROM ${q};
`)}function dropMemoryPathFtsTriggers(e){for(let t of X)e.exec(`DROP TRIGGER IF EXISTS main.${t.name}`)}function ensureMemoryPathFtsTriggers(e){for(let t of X)e.exec(t.sql)}const Q={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:Te,statementTimeoutMs:Se})}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(D(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=_e(n,e.namespace,e.schema.id),a=ge(e.schema,i);if(me(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&&E(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),pe(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})}}}}},$={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,a=o(t,$);if(!r){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(),Q.sqlite.schema.bootstrap({...e,input:e.input},t),u(t,$,{engine:`sqlite`}),Q.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=Ae(),s=le(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}},s=a?.engine===`postgres`?a:e.existingOnly?readOrCreateAnchor():N(t,readOrCreateAnchor),c={...e,input:e.input,...s},l=Q.postgres,f=l.openConnection(c),admit=t=>{ue({db:f,namespace:s.namespace,storeId:s.storeId,store:n.id,version:n.version,schema:n,recordSchema:t,preserveSchemaSeal:e.existingVersion}),e.admitPostgres?.(f,t)};try{let r=n.search?E(f,n.search,s.namespace,e.existingVersion?1:n.postgresVectorSearchVersion):void 0;if(!a||a.engine===`postgres`&&a.version!==n.version){fe(f);let t,r;f.runTransaction(()=>{let a=!f.prepare(`SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname = ?`).get(s.namespace);a&&!e.existingOnly&&(f.exec(`CREATE SCHEMA IF NOT EXISTS "${s.namespace.replaceAll(`"`,`""`)}"`),f.exec(he));let o;try{o=f.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(o){if(o.store_id!==s.storeId)throw Error(`PostgreSQL database identity mismatch: expected ${s.storeId}, found ${String(o.store_id)}. Restore the matching anchor and PostgreSQL backup.`);if(o.version!==n.version){if(e.existingVersion){let e=n.postgresMigrations?.find(e=>e.version===Number(o.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(o.version)}}else{r=e.assertMigrationCurrent,r?.(),t=beginUpdatePostgresMigration(f,r),i(f),ne(f,{stage:()=>{},rollback:()=>{},commit:()=>d(f),invalidate:()=>d(f)});let migrate=()=>l.schema.migrate(c,Number(o.version),f);t?t.run(migrate):migrate()}}}else{if(e.existingOnly||!a)throw Error(`Missing PostgreSQL metadata; restore the matching PostgreSQL schema and anchor.`);l.schema.bootstrap(c,f)}admit(!o)},{withCommit(e){r?.(),t?.beforeCommit(),e()}},!1),t?.committed()}else admit(!1);(!a||a.engine===`postgres`&&a.version!==n.version)&&u(t,$,{engine:`postgres`,...s,version:n.version}),r?.();for(let e of Object.values(de(f)?.searchExtensions??{}))E(f,e,s.namespace,n.postgresVectorSearchVersion)?.();return f}catch(t){if(e.closeOnFailure)return e.closeOnFailure(f,t);throw f.close(),t}}export{getUpdateDoctorMigrationSource as _,q as a,K as c,dropMemoryPathFtsTriggers as d,ensureMemoryChunkFtsTriggers as f,getDoctorMigrationBackup as g,beginUpdateSqliteCompanion as h,Z as i,X as l,rebuildMemoryChunkFts as m,readEngineAnchor as n,J as o,ensureMemoryPathFtsTriggers as p,Q as r,Y as s,openEngineStore as t,dropMemoryChunkFtsTriggers as u,runUpdateSqliteMigration as v};