openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
17 lines • 23.6 kB
JavaScript
import{H as e}from"./openclaw-state-read-map-size-DJbMcZYM.mjs";import{S as t,a as n,ht as r,p as i,pt as a,s as o,t as s,x as c}from"./openclaw-state-read-sqlite-database-admission-Ck6VG7rE.mjs";import{s as l}from"./openclaw-state-read-pool-1Cp_Z7yz.mjs";import{t as u}from"./openclaw-state-read-promise-like-3qqJObCs.mjs";import{h as d}from"./openclaw-state-read-logger-Ix7jXPG1.mjs";import{n as f}from"./openclaw-state-read-sqlite-worker-operation-settlement-ogK5IsJy.mjs";import{c as p,d as m,i as h,l as g,n as ee,s as _}from"./openclaw-state-read-sqlite-post-commit-CEHMNIsB.mjs";import"./openclaw-state-read-runtime-process-entrypoints-ItwYqjQs.mjs";import"./openclaw-state-read-runtime-worker-url-ClM3d-g2.mjs";import{p as v}from"./openclaw-state-read-worker-cpu-Ca-4Z8Q3.mjs";import{c as y}from"./openclaw-state-read-sqlite-snapshot-capacity-error-Df9fZtJA.mjs";import{f as b}from"./openclaw-state-read-kysely-sync-DQyYiAw5.mjs";import{A as x,C as S,D as te,E as ne,F as C,M as re,N as ie,O as ae,P as oe,j as se,k as ce,r as w}from"./openclaw-state-read-sqlite-schema-facts-DxLfPKu-.mjs";import{c as T,i as E,l as D}from"./openclaw-state-read-sqlite-transaction-V1rK3HH2.mjs";import"./openclaw-state-read-context-D0V7bHDr.mjs";import"./openclaw-state-read-child-runtime-viability-CqVmSQzb.mjs";import"./openclaw-state-read-spawn-diagnostics-CpCgfk1o.mjs";import"./openclaw-state-read-sqlite-schema-catalog-DLcl4287.mjs";import{n as O}from"./openclaw-state-read-async-work-scope-CNcLd_yE.mjs";import{r as k}from"./openclaw-state-read-sqlite-handle-lifecycle-DQ13SM2U.mjs";import{t as A}from"./openclaw-state-read-boundary-path-CCynIYBo.mjs";import{c as j,i as M,l as N,n as P,o as F,s as I,t as L,u as R}from"./openclaw-state-read-bridge-prestart-DGQ3c5jM.mjs";import"./openclaw-state-read-windows-appcontainer-spawn-B9xODvkk.mjs";import"./openclaw-state-read-linux-exec-cgroup-CrpNVYDK.mjs";import"node:v8";import{realpathSync as z}from"node:fs";import{receiveMessageOnPort as B,threadId as V}from"node:worker_threads";import"node:child_process";import{createHash as H,randomUUID as U}from"node:crypto";import{AsyncLocalStorage as W}from"node:async_hooks";import"node:events";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);if(e.code===`57014`&&(t.name=`PostgresQueryCanceledError`),e.code===`55P03`||e.code===`40P01`||e.code===`40001`)return Object.assign(Error(e.message,{cause:t}),{code:`ERR_SQLITE_ERROR`,errcode:5});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 resolveUpdateSqlitePath(t){try{return z.native(t)}catch(n){return e(n),A(t)}}const G=new W;function hasUpdateDoctorMigrationCapture(){return G.getStore()?.capture!==void 0}function getUpdateDoctorMigrationSource(e){let t=G.getStore(),n=resolveUpdateSqlitePath(e),r=t?.source?.path===n?t.source:t?.companions?.find(e=>e.path===n);if(!r)return;let{generation:i,assertCurrent:a}=r;return a(),{path:e,generation:i,assertCurrent:a}}function getDoctorMigrationBackup(e,t){let n=G.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.`),G.run({...n,capture:void 0,source:void 0},()=>n.backup?.(e,t))}return n?.backup?.(e,t)}function capturedAttribution(){if(hasUpdateDoctorMigrationCapture())throw Error(`Update migration capture is active without its attribution owner.`)}function runUpdateSqliteMigration(...e){let t=capturedAttribution();return t?t.runSqlite(...e):e[2]()}async function runUpdateSqliteMigrationAsync(...e){let t=capturedAttribution();if(t)return await t.runSqliteAsync(...e);y(O())?.throwIfAborted();let n=e[2]();if(u(n))throw Error(`Update migration callbacks must remain synchronous.`);return n}function beginUpdatePostgresMigration(e,t){return capturedAttribution()?.beginPostgres(e,t)}function beginUpdateSqliteCompanion(e,t,n){return capturedAttribution()?.beginSqliteCompanion(e,t,n)}function assertPostgresOperationCurrent(){let e=f.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,i=!1,a=!1){assertPostgresOperationCurrent();let o=m(e);return p(o,()=>{let o=e.isTransaction&&!a,s=!1,c;try{i&&!o&&(c=w(e)),o?e.exec(`SAVEPOINT openclaw_tx_nested`):e.isTransaction||e.exec(i?`BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY`:`BEGIN ISOLATION LEVEL READ COMMITTED; SELECT pg_advisory_xact_lock(${e.advisoryLockKey})`);let r=n?.maintenance&&o?String(e.prepare(`SHOW statement_timeout`).get().statement_timeout):void 0;n?.maintenance&&e.exec(`SET LOCAL statement_timeout = '${N}ms'`);let a=t();if(g(a),o)r!==void 0&&e.prepare(`SELECT set_config('statement_timeout', ?, true)`).get(r),e.exec(`RELEASE SAVEPOINT openclaw_tx_nested`);else{let commit=()=>{assertPostgresOperationCurrent(),i||h(e),e.exec(i?`ROLLBACK`:`COMMIT`),s=!i};n?.withCommit?g(n.withCommit(commit)):commit()}return a}catch(t){let n=r(t)||s;if(!n)try{o?(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{ee(e,t,`unknown`)}finally{try{e.close()}catch{}}throw t}finally{c?.()}})}function beginPostgresReadOnlyTransaction(e){if(e.isTransaction)throw Error(`A held PostgreSQL read snapshot requires an idle connection`);assertPostgresOperationCurrent();let t,end=()=>{try{e.isTransaction&&e.exec(`ROLLBACK`)}catch{try{e.close()}catch{}}finally{t?.()}};try{t=w(e),e.exec(`BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY`)}catch(e){throw end(),e}return end}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.lastResponseAt=Date.now(),this.outcomeUnknown=!0,this.readOnlyTransaction=!1,this.pendingWrite=!1,this.mainThread=V===0,this.maintenance=!1,k(),this.admissionReadOnly=i?.readOnly===!0,Object.defineProperty(this,Symbol.for(`openclaw.postgres-sync-connection`),{value:!0}),this.advisoryLockKey=H(`sha256`).update(r).digest().readBigInt64BE(),this.bridgeParameters={url:e,schema:t,storeId:r,...i},this.reuseKey=i?.reuse?P(this.bridgeParameters):void 0,this.connect()}connect(){let e=this.reuseKey?I(this.reuseKey):void 0,t=e?.bridge??M(this.bridgeParameters)??L(this.bridgeParameters);if(this.bridge=t,this.idleCheckout=e?e.validate?`validate`:`reconnect`: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){let r=this.maintenance;this.maintenance=r||t?.maintenance===!0;try{return runPostgresTransactionSync(this,e,t,this.admissionReadOnly||n[0],n[1])}finally{this.maintenance=r}}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,s(m(this),!0)),this.finishWrite(),this.failure??=this.outcomeUnknown?new a(`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)&&l(this.failure),this.isOpen=!1,this.isTransaction=!1,e?.port.close(),this.bridge=void 0,this.failure}finishWrite(){this.pendingWrite&&(this.pendingWrite=!1,n(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`&&k(),this.assertOpen();let n=this.bridge??this.connect();this.outcomeUnknown=t;let r=++n.requestId;if(r>2147483647)throw this.loseConnection();let i=(this.maintenance?N:this.bridgeParameters.statementTimeoutMs??9e4)+3e4,a=performance.now()+i,o=n.inTransaction===!1,s=(this.idleCheckout!==void 0||o)&&(e.operation===`query`||e.operation===`recovery-generation`),c=s&&(this.idleCheckout===`validate`||o&&Date.now()-this.lastResponseAt>=1e3);n.inTransaction=void 0,this.idleCheckout=void 0,n.port.postMessage({...e,...s?{reconnectIfIdle:s}:{},...c?{validateIfIdle:c}:{},id:r,deadlineMs:i},[]),v(`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=a-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 l=B(n.port)?.message;if(l&&v(`sqlite_reply`,`from_worker`),!l||l.id!==r)throw this.loseConnection();if(`error`in l)throw e.operation===`connect`?decodePostgresError(l.error):isPostgresConnectionError(l.error.code)?this.loseConnection():(e.operation===`query`&&/^\s*COMMIT\b/i.test(e.sql)&&(this.isTransaction=!1,this.finishWrite()),decodePostgresError(l.error));return this.lastResponseAt=Date.now(),`reusable`in l?(n.inTransaction=!l.reusable,l.reusable):(n.inTransaction=`generation`in l?l.inTransaction:l.result.inTransaction,`generation`in l?l.generation:l.result)}query(e,t=[],n=!1){return D(`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 c=a.mutation===`unscoped`||t===`unscoped`?`unscoped`:a.mutation??t,l=c!==void 0;if(l){if(o||this.readOnlyTransaction)throw Error(`PostgreSQL read snapshot cannot execute a mutation`);this.mutationRevision++,this.pendingWrite=!0,s(m(this),c===`unscoped`)}return!this.isTransaction&&(l||i)&&p(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=D(`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`})?(F(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 b;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})=>T(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,readOnly:e.input.readOnly,lockTimeoutMs:j,statementTimeoutMs:R})}catch(t){let n=t instanceof Error&&`code`in t&&typeof t.code==`string`?`${t.code}: `:``,r=d(`${n}${t instanceof Error?t.message:String(t)}`.replaceAll(e.input.connection,`[REDACTED]`),{mode:`tools`});throw Error(`Cannot open PostgreSQL connection: ${r}; 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(ce(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=se(n,e.namespace,e.schema.id),a=oe(e.schema,i);if(ie(n,e.namespace,{...a,version:r-1,postgres:t.fromSchema.postgres,postgresFragments:t.fromSchema.postgresFragments,postgresWithoutOptionalColumn:t.fromSchema.postgresWithoutOptionalColumn,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&&C(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),re(n,e.namespace,{...a,version:r,postgres:t.schema.postgres,postgresFragments:t.schema.postgresFragments,postgresWithoutOptionalColumn:t.schema.postgresWithoutOptionalColumn,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:n}=e,r=e.schema;T(n);let a=e.input!==void 0&&r.postgres!==void 0,s=o(n,$);if(!a){if(s?.engine===`postgres`)throw Error(`This store lives in PostgreSQL schema ${s.namespace}; set ${familySetting(r)} to postgres and configure database.postgres.connection.`);return!s&&e.inspectSqlite().hasEngineAnchor&&refusePostgresAnchor(n,r),e.prepareAnchor(),Q.sqlite.schema.bootstrap({...e,input:e.input},n),c(n,$,{engine:`sqlite`}),Q.sqlite.openConnection({...e,input:e.input})}if(s?.engine===`sqlite`)throw Error(`Existing SQLite ${r.id} data cannot switch engines; stop the Gateway and use openclaw database port for a supported store family before changing ${familySetting(r)}.`);let l=e.input?.readOnly===!0;l||e.prepareAnchor();let readOrCreateAnchor=()=>{let t=e.inspectSqlite();if(t.hasExistingData)throw Error(`Existing SQLite ${r.id} data cannot switch engines; stop the Gateway and use openclaw database port for a supported store family before changing ${familySetting(r)}.`);if(!t.hasEngineAnchor&&(e.existingOnly||l))throw Error(`Missing PostgreSQL anchor; restore the matching PostgreSQL schema and anchor.`);t.hasEngineAnchor||n.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(n,`identity`,!0)??[];if(i.length>1||t.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=U(),s=x(e.input.schemaPrefix,r.id,o);return n.prepare(`INSERT INTO openclaw_engine_anchor (store_id, engine, schema) VALUES (?, 'postgres', ?)`).run(o,s),e.onFreshAnchor?.(n),{storeId:o,namespace:s}},u=s?.engine===`postgres`?s:e.existingOnly||l?readOrCreateAnchor():E(n,readOrCreateAnchor),d={...e,input:e.input,...u},f=Q.postgres,p=f.openConnection(d),admit=t=>{S({db:p,namespace:u.namespace,storeId:u.storeId,store:r.id,version:r.version,schema:r,recordSchema:t,preserveSchemaSeal:e.existingVersion,requireSealedSchema:l}),e.admitPostgres?.(p,t)};try{let a=r.search?C(p,r.search,u.namespace,e.existingVersion?1:r.postgresVectorSearchVersion):void 0;if(l)p.runTransaction(()=>admit(!1),void 0,!0);else if(!s||s.engine===`postgres`&&s.version!==r.version){ne(p);let n,a;p.runTransaction(()=>{let o=!p.prepare(`SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname = ?`).get(u.namespace);o&&!e.existingOnly&&(p.exec(`CREATE SCHEMA IF NOT EXISTS "${u.namespace.replaceAll(`"`,`""`)}"`),p.exec(ae));let s;try{s=p.prepare(`SELECT version, store_id FROM openclaw_schema_meta WHERE store = ?`).get(r.id)}catch(e){throw Error(`Missing PostgreSQL metadata; use the matching OpenClaw version or restore the matching PostgreSQL schema and anchor.`,{cause:e})}if(s){if(s.store_id!==u.storeId)throw Error(`PostgreSQL database identity mismatch: expected ${u.storeId}, found ${String(s.store_id)}. Restore the matching anchor and PostgreSQL backup.`);if(s.version!==r.version){if(e.existingVersion){let e=r.postgresMigrations?.find(e=>e.version===Number(s.version)+1)?.fromSchema;if(!e)throw Error(`Missing PostgreSQL source schema for inspection`);r={...r,...e,postgresVectorDecoderVersion:e.postgresVectorDecoderVersion,postgresVectorSearchVersion:e.postgresVectorSearchVersion,postgresTextSearchVersion:e.postgresTextSearchVersion,version:Number(s.version)}}else{a=e.assertMigrationCurrent,a?.(),n=beginUpdatePostgresMigration(p,a),i(p),_(p,{stage:()=>{},rollback:()=>{},commit:()=>t(p),invalidate:()=>t(p)});let migrate=()=>f.schema.migrate(d,Number(s.version),p);n?n.run(migrate):migrate()}}}else{if(e.existingOnly||!o)throw Error(`Missing PostgreSQL metadata; restore the matching PostgreSQL schema and anchor.`);f.schema.bootstrap(d,p)}admit(!s)},{maintenance:!0,withCommit(e){a?.(),n?.beforeCommit(),e()}},!1),n?.committed()}else admit(!1);(!s||s.engine===`postgres`&&s.version!==r.version)&&c(n,$,{engine:`postgres`,...u,version:r.version}),a?.();for(let e of Object.values(te(p)?.searchExtensions??{}))C(p,e,u.namespace,r.postgresVectorSearchVersion)?.();return p}catch(t){if(e.closeOnFailure)return e.closeOnFailure(p,t);throw p.close(),t}}export{getDoctorMigrationBackup as _,q as a,runUpdateSqliteMigrationAsync as b,K as c,dropMemoryPathFtsTriggers as d,ensureMemoryChunkFtsTriggers as f,beginUpdateSqliteCompanion as g,beginPostgresReadOnlyTransaction 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,getUpdateDoctorMigrationSource as v,runUpdateSqliteMigration as y};