openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
26 lines • 25.2 kB
JavaScript
import{r as truncateUtf16Safe}from"./utf16-slice-DA3Mllbx.mjs";import{a as recordWorkerMessage}from"./worker-message-metrics-CdbgV0zo.mjs";import{t as assertEngineStoreExecutionAllowed}from"./admission-scope-Xl89MEui.mjs";import{c as redactSensitiveText}from"./redact-BT59pdZ_.mjs";import{n as isPostgresSqlConnection,r as sqlPublicationAnchor}from"./sql-connection-nx8lLUJM.mjs";import{E as publishSqliteDatabaseSchemaChange,a as finishSqliteDatabaseWrite,m as invalidateLocalSqliteSchemaAdmissions,t as beginSqliteDatabaseWrite}from"./sqlite-database-admission-B3KDkUt-.mjs";import{t as SqliteWorkerError}from"./sqlite-worker-error-DHUQ0e2U.mjs";import{C as preparePostgresQuery,S as isPostgresConnectionError,b as decodePostgresError,w as validatePostgresBindings,x as decodePostgresRows}from"./sqlite-error-diagnostics-ASl1MXPN.mjs";import{c as withSqlitePostCommitPublications,s as stageSqliteTransactionState}from"./sqlite-post-commit-CAVf6ZAG.mjs";import{_ as sql,i as executeSqliteQuerySync,s as getNodeSqliteKysely,y as createFunctionModule}from"./kysely-sync-R08Pt8qn.mjs";import{B as pgSearchName,E as publishPostgresSearchExtensionFacts,F as verifyAndRecordPostgresSchema,I as verifyPostgresSchema,J as searchConfig,K as publishPostgresSearch,L as withPostgresSearchExtensions,N as readPostgresSchema,P as retainPostgresSchema,R as admitPostgresSearch,U as postgresSearchTokenSeparators,V as postgresSearchSql,j as postgresSchemaSql,k as getAdmittedPostgresSchema,q as rebuildPostgresSearch,w as getPostgresPhysicalFacts,z as assertPostgresSearchAdmitted}from"./sqlite-schema-facts-CWOeTpUB.mjs";import{a as recordPostgresPoolFailure}from"./pool-state-Bcs4kykZ.mjs";import"./sqlite-worker-contract-CcRGAuae.mjs";import{d as observeConnection,f as observeDatabaseOperation,o as runSqliteReadSnapshotSync,r as runSqliteDeferredTransactionSync}from"./sqlite-transaction-CON-dGDv.mjs";import{i as POSTGRES_STATEMENT_TIMEOUT_MS,n as POSTGRES_LOCK_TIMEOUT_MS,r as POSTGRES_MAINTENANCE_STATEMENT_TIMEOUT_MS}from"./policy-CqBNEepG.mjs";import{a as POSTGRES_IDLE_VALIDATION_MS,i as takePreparedPostgresBridge,n as postgresBridgeReuseKey,o as retainIdlePostgresBridge,s as takeIdlePostgresBridge,t as createPostgresBridge}from"./bridge-prestart-ChzIkXKR.mjs";import{n as runPostgresTransactionSync}from"./transaction-X7kuyEm1.mjs";import{i as matchesVectorRow,r as admitSqliteMemoryVectorSearch,t as bindSqliteVectorCapability}from"./sqlite-vector-zlSCsLxB.mjs";import{s as admitSqliteMemoryTextSearch}from"./sqlite-search-schema-B4FvDa7W.mjs";import{createHash}from"node:crypto";import{receiveMessageOnPort,threadId}from"node:worker_threads";
//!src/infra/postgres-sync/connection.ts
var PostgresSyncConnection=class{constructor(e,t,n,r,i){this.schema=t;this.anchor=n;this.storeId=r;this.isOpen=true;this.isTransaction=false;this.mutationRevision=0;this.lastResponseAt=Date.now();this.outcomeUnknown=true;this.readOnlyTransaction=false;this.pendingWrite=false;this.mainThread=threadId===0;this.maintenance=false;assertEngineStoreExecutionAllowed();this.admissionReadOnly=i?.readOnly===true;Object.defineProperty(this,Symbol.for(`openclaw.postgres-sync-connection`),{value:true});this.advisoryLockKey=createHash(`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(){const e=this.reuseKey?takeIdlePostgresBridge(this.reuseKey):void 0;const t=e?.bridge??takePreparedPostgresBridge(this.bridgeParameters)??createPostgresBridge(this.bridgeParameters);this.bridge=t;this.idleCheckout=e?e.validate?`validate`:`reconnect`:void 0;t.port.unref();if(e)return t;try{this.request({operation:`connect`,schema:this.schema})}catch(e){this.isOpen=false;this.isTransaction=false;this.bridge=void 0;t.port.close();throw e}return t}runTransaction(e,t,...n){const r=this.maintenance;this.maintenance=r||t?.maintenance===true;try{return runPostgresTransactionSync(this,e,t,this.admissionReadOnly||n[0],n[1])}finally{this.maintenance=r}}readRecoveryGeneration(e=false){return this.request({operation:`recovery-generation`,schema:this.schema,storeId:this.storeId,lock:e},false)}loseConnection(){if(!this.failure&&this.outcomeUnknown){this.pendingWrite=true;beginSqliteDatabaseWrite(sqlPublicationAnchor(this),true)}this.finishWrite();this.failure??=this.outcomeUnknown?new SqliteWorkerError(`PostgreSQL connection lost; outcome unknown`,`outcome-unknown`):/* @__PURE__ */ new Error(`PostgreSQL connection lost; transaction rolled back`);const e=this.bridge;if(e?.nextStep&&!this.failure.message.includes(e.nextStep))this.failure.message+=` Run ${e.nextStep}.`;if(e&&Atomics.load(e.service,1))recordPostgresPoolFailure(this.failure);this.isOpen=false;this.isTransaction=false;e?.port.close();this.bridge=void 0;return this.failure}finishWrite(){if(this.pendingWrite){this.pendingWrite=false;finishSqliteDatabaseWrite(sqlPublicationAnchor(this))}}assertOpen(){if(this.failure)throw this.failure;if(!this.isOpen)throw new Error(`PostgreSQL connection is closed`)}request(e,t=true){if(this.mainThread&&e.operation!==`close`&&e.operation!==`release`)assertEngineStoreExecutionAllowed();this.assertOpen();const n=this.bridge??this.connect();this.outcomeUnknown=t;const r=++n.requestId;if(r>2147483647)throw this.loseConnection();const i=(this.maintenance?POSTGRES_MAINTENANCE_STATEMENT_TIMEOUT_MS:this.bridgeParameters.statementTimeoutMs??9e4)+3e4;const a=performance.now()+i;const o=n.inTransaction===false;const s=(this.idleCheckout!==void 0||o)&&(e.operation===`query`||e.operation===`recovery-generation`);const 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},[]);recordWorkerMessage(`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();const t=a-performance.now();if(t<=0){Atomics.store(n.service,1,1);Atomics.notify(n.service,1);throw this.loseConnection()}Atomics.wait(n.control,0,e,Math.min(t,50))}const l=receiveMessageOnPort(n.port)?.message;if(l)recordWorkerMessage(`sqlite_reply`,`from_worker`);if(!l||l.id!==r)throw this.loseConnection();if(`error`in l){if(e.operation===`connect`)throw decodePostgresError(l.error);if(isPostgresConnectionError(l.error.code))throw this.loseConnection();if(e.operation===`query`&&/^\s*COMMIT\b/i.test(e.sql)){this.isTransaction=false;this.finishWrite()}throw decodePostgresError(l.error)}this.lastResponseAt=Date.now();if(`reusable`in l){n.inTransaction=!l.reusable;return l.reusable}n.inTransaction=`generation`in l?l.inTransaction:l.result.inTransaction;return`generation`in l?l.generation:l.result}query(e,t=[],n=false){return observeDatabaseOperation(`postgres`,`statement`,e,()=>this.execute(preparePostgresQuery(e),t,n))}execute({sql:e,mutation:t},n,r){validatePostgresBindings(n);const i=this.isTransaction;if(/^\s*BEGIN\b/i.test(e))this.isTransaction=true;const a=this.request({operation:`query`,schema:this.schema,sql:e,parameters:n},!i||/^\s*COMMIT\b/i.test(e));const o=this.readOnlyTransaction;this.isTransaction=a.inTransaction;this.readOnlyTransaction=this.isTransaction&&(o||/^\s*BEGIN\b[^;]*\bREAD\s+ONLY\b/i.test(e));if(/^\s*COMMIT\s*;?\s*$/i.test(e)&&a.command!==`COMMIT`){this.finishWrite();throw new Error(`PostgreSQL transaction rolled back instead of committing`)}const s=a.mutation===`unscoped`||t===`unscoped`?`unscoped`:a.mutation??t;const c=s!==void 0;if(c){if(o||this.readOnlyTransaction)throw new Error(`PostgreSQL read snapshot cannot execute a mutation`);this.mutationRevision++;this.pendingWrite=true;beginSqliteDatabaseWrite(sqlPublicationAnchor(this),s===`unscoped`)}if(!this.isTransaction&&(c||i))withSqlitePostCommitPublications(sqlPublicationAnchor(this),()=>{this.finishWrite()});this.outcomeUnknown=!this.isTransaction;return{rows:decodePostgresRows(a,r),rowCount:a.rowCount,columns:a.fields.map(({name:e})=>({name:e}))}}exec(e){this.query(e)}prepare(e){this.assertOpen();const t=preparePostgresQuery(e);let n=false;let r=[];const execute=i=>{const a=observeDatabaseOperation(`postgres`,`statement`,e,()=>this.execute(t,i,n));r=a.columns;return 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(){const e=this.bridge;if(!this.isOpen||!e||!this.reuseKey||this.isTransaction)return;let t=false;try{if(e.inTransaction===false||this.request({operation:`release`})){retainIdlePostgresBridge(this.reuseKey,e);t=true}else{this.isOpen=false;this.finishWrite()}}finally{this.bridge=void 0;if(!t)e.port.close()}}close(){if(!this.isOpen)return;try{if(this.reuseKey&&!this.isTransaction)this.releaseIdleTransport();else if(this.bridge)this.request({operation:`close`})}finally{this.finishWrite();this.isOpen=false;this.isTransaction=false;this.bridge?.port.close();this.bridge=void 0}}};
//!src/infra/database-engine/postgres-vector.ts
function bindPostgresVector(e,t,n){const r=getNodeSqliteKysely(e);const i=pgSearchName(n.extensionSchema??`public`);const a=getAdmittedPostgresSchema(e)?.postgresVectorSearchVersion===2;const own=n=>{if(!e.isOpen||n.store!==t)throw new Error(`Vector index is not admitted to this open store`);return n.postgres};const write=t=>{const n=own(t);if(!e.isTransaction)throw new Error(`Vector mutation requires the owner's transaction`);return n};return{idSet(e,t){own(e);return sql`SELECT value FROM json_array_elements_text(${JSON.stringify(t)}::json)`},prepareExists(t){own(t);const n=e.prepare(`SELECT id FROM ${pgSearchName(t.table)} WHERE id = ?`);return e=>Boolean(n.get(e))},async nearest(t){const n=own(t.index);t.signal?.throwIfAborted();if(t.vector.length!==n.dimensions||t.vector.some(e=>!Number.isFinite(e)||!Number.isFinite(Math.fround(e)))||!t.vector.some(e=>Math.fround(e)!==0))throw new Error(`PostgreSQL cosine query requires a finite nonzero vector matching the admitted dimensions; rebuild for a changed embedding model.`);const o=`[${t.vector.map(Math.fround).join(`,`)}]`;const s=sql.ref(`${t.index.alias}.embedding`);const c=sql`${sql.ref(`${t.index.alias}.embedding`)} ${sql.raw(`OPERATOR(${i}.<=>)`)} ${o}::${sql.raw(i)}.vector`;const l=sql.ref(`${t.index.alias}.embedding_bits`);const u=a?sql`${l} IS NOT NULL`:sql`${sql.raw(i)}.vector_norm(${s}) > 0`;const d=a?t.candidates?.({match:u,distance:sql`${l} ${sql.raw(`OPERATOR(${i}.<~>)`)} ${sql.raw(i)}.binary_quantize(${o}::${sql.raw(i)}.vector)`,limit:t.limit*8}):void 0;const f=t.query({match:d?sql`${sql.ref(`${t.index.alias}.id`)} IN (SELECT id FROM openclaw_vector_candidates)`:u,distance:c});const p=d?sql`WITH openclaw_vector_candidates AS MATERIALIZED (${d})`:sql``;const m=executeSqliteQuerySync(e,{compile:()=>sql`${p} SELECT * FROM (${f}) AS openclaw_candidates LIMIT ${t.limit}`.compile(r)}).rows;if(!m.every(t.isRow)||!m.every(e=>matchesVectorRow(e,t.index.rowShape)))throw new Error(`PostgreSQL vector query returned an invalid row`);for(const e of m){const n=t.textPrefix;if(n&&e&&typeof e===`object`){const t=Reflect.get(e,n.column);if(typeof t===`string`)Reflect.set(e,n.column,truncateUtf16Safe(t,n.maxChars))}}return{rows:m,fallbackScanRequired:false}},remove(t,n){write(t);const i=`toOperationNode`in n?sql`${n}`:sql`SELECT value FROM json_array_elements_text(${JSON.stringify(n)}::json)`;executeSqliteQuerySync(e,{compile:()=>sql`DELETE FROM ${sql.table(t.table)} WHERE id IN (${i})`.compile(r)})},drop(){throw new Error(`PostgreSQL vector DDL belongs to store schema admission; rebuild the projection instead`)},create(e,t){if(write(e).dimensions!==t)throw new Error(`PostgreSQL vector dimensions changed; reopen with the new search schema and rebuild`)},write(t,n){const r=write(t);const i=e.prepare(`INSERT INTO ${pgSearchName(t.table)}(id, embedding) SELECT ${pgSearchName(r.key)}, openclaw_vector(${pgSearchName(r.embedding)}, ${r.dimensions}) FROM ${pgSearchName(r.source)} WHERE ${pgSearchName(r.key)} = ? AND octet_length(${pgSearchName(r.embedding)}) > 0 ON CONFLICT (id) DO UPDATE SET embedding = excluded.embedding`);for(const e of n)i.run(e.id)}}}
//!src/infra/database-engine/postgres-search.ts
function searchTextFor(e){const t=postgresSearchTokenSeparators;return e===2?e=>sql`regexp_replace(${e}, ${t}, ' ', 'g')`:e=>sql`${e}`}function tsquery(e,t,n){if(e.kind===`contains`)throw new Error(`Contains is only available on an admitted trigram index`);if(e.kind!==`term`&&e.kind!==`phrase`){if(e.clauses.every(e=>e.kind===`term`||e.kind===`phrase`)){const r=e.kind===`all`?` & `:` | `;return sql`coalesce((
SELECT string_agg('(' || nullif(parsed.value::text, '') ||
CASE WHEN atom.prefix THEN ':*' ELSE '' END || ')', ${r})
FROM json_to_recordset(${JSON.stringify(e.clauses)}::json)
AS atom(kind text, text text, prefix boolean)
CROSS JOIN LATERAL (SELECT CASE WHEN atom.kind = 'term'
THEN plainto_tsquery(${sql.lit(t)}::regconfig, ${n(sql`atom.text`)})
ELSE phraseto_tsquery(${sql.lit(t)}::regconfig, ${n(sql`atom.text`)})
END AS value) AS parsed
), '')::tsquery`}const r=e.clauses.map(e=>tsquery(e,t,n));return r.length?sql`(${sql.join(r,sql.raw(e.kind===`all`?` && `:` || `))})`:sql`''::tsquery`}const r=e.kind===`term`?sql`plainto_tsquery(${sql.lit(t)}::regconfig, ${n(e.text)})`:sql`phraseto_tsquery(${sql.lit(t)}::regconfig, ${n(e.text)})`;return e.kind===`phrase`&&e.prefix?sql`coalesce((nullif(${r}::text, '') || ':*')::tsquery, ''::tsquery)`:r}function bindPostgresSearch(e,t){assertPostgresSearchAdmitted(e,t);const n=`${pgSearchName(getPostgresPhysicalFacts(e).namespace)}.${pgSearchName(searchConfig)}`;const r=pgSearchName(t.extensionSchema??`public`);const i=getAdmittedPostgresSchema(e)?.postgresTextSearchVersion;const a=searchTextFor(i);const o={};const s=Object.fromEntries(Object.entries(t.text??{}).map(([e,t])=>[e,{...t,store:o}]));const c=Object.fromEntries(Object.entries(t.vector??{}).map(([e,t])=>[e,{...t,store:o}]));const relation=(t,n=`openclaw_search`)=>{if(!e.isOpen||t.store!==o)throw new Error(`Text index is not admitted to this open store`);return sql.ref(`${t.alias??t.table}.${n}`)};const requireQuery=e=>{if(!e)throw new Error(`PostgreSQL rank and snippet require the literal search query`);return tsquery(e,n,a)};return{text:s,vectors:c,diagnostics:[],rebuild:()=>rebuildPostgresSearch(e,t),fullText:Object.keys(s).length?{match(e,t){const r=relation(e,t.kind===`contains`?e.fields[0]:void 0);if(t.kind===`any`&&t.clauses.length>128&&t.clauses.every(e=>e.kind===`phrase`&&!e.prefix)){const e=t.clauses.map(e=>e.text);return sql`EXISTS (SELECT 1 FROM json_array_elements_text(${JSON.stringify(e)}::json) AS search_terms(value) WHERE ${r} @@ phraseto_tsquery(${sql.lit(n)}::regconfig, ${a(sql`search_terms.value`)}))`}if(t.kind===`contains`){if(e.postgres?.mode!==`trigram`)throw new Error(`Contains requires a declared PostgreSQL trigram index`);const n=`%${t.text.replaceAll(`\\`,`\\\\`).replaceAll(`%`,`\\%`).replaceAll(`_`,`\\_`)}%`;return sql`${r} ILIKE ${n} ESCAPE '\\'`}return sql`${r} @@ ${tsquery(t,n,a)}`},rank(e,t,n){if(t?.kind===`contains`){if(e.postgres?.mode!==`trigram`)throw new Error(`Contains requires a declared PostgreSQL trigram index`);return{value:sql`${sql.raw(r)}.word_similarity(${t.text}, ${relation(e,e.fields[0])})`,order:`desc`,toRank:e=>e}}const i=relation(e);const a=n?.postgres?.rank===`frequency`?sql`ts_rank`:sql`ts_rank_cd`;return{value:sql`${a}(${i}, ${requireQuery(t)}, ${n?.postgres?.normalization??2})`,order:`desc`,toRank:e=>e}},snippet(e,t,r,a,o=500){if(r<2)throw new Error(`PostgreSQL snippets require at least two tokens`);if(!e.fields.includes(t))throw new Error(`Text index has no field ${t}`);const s=`StartSel='', StopSel='', MaxWords=${Math.max(1,Math.min(48,Math.trunc(r)))}, MinWords=1, MaxFragments=1, FragmentDelimiter=' … '`;const c=Math.max(1,Math.min(500,Math.trunc(o)));const l=relation(e,t);if(i!==2)return sql`left(ts_headline(${sql.lit(n)}::regconfig, ${l}, ${requireQuery(a)}, ${s}), ${c})`;const u=sql`regexp_replace(${l}, '[[:punct:]]', ' ', 'g')`;return sql`(SELECT left(substr(${l}, strpos(normalized, headline), length(headline)), ${c}) FROM (SELECT normalized, ts_headline(${sql.lit(n)}::regconfig, normalized, ${requireQuery(a)}, ${s}) AS headline FROM (SELECT ${u} AS normalized OFFSET 0) AS headline_input OFFSET 0) AS headline_result)`},identity:e=>sql`${relation(e,e.postgres.identity)}`,allocatedIdentity(){throw new Error(`PostgreSQL insert identities must use RETURNING`)}}:null,vector:t.mode===`keyword-only`||!Object.keys(c).length?null:bindPostgresVector(e,o,t)}}
//!src/infra/database-engine/sqlite-full-text.ts
function literalQuery(e){if(e.kind===`contains`)throw new Error(`Literal contains requires the owner's SQLite substring policy`);if(e.kind===`term`||e.kind===`phrase`)return`"${e.kind===`term`?e.text.replaceAll(`"`,``):e.text.replaceAll(`"`,`""`)}"${e.kind===`phrase`&&e.prefix?`*`:``}`;let t=e.kind===`any`?` OR `:` AND `;if(e.kind===`all`&&e.clauses.every(e=>e.kind===`phrase`))t=` `;return e.clauses.map(e=>e.kind===`any`?`(${literalQuery(e)})`:literalQuery(e)).join(t)}function bindSqliteFullText(e,t){const relation=n=>{if(n.store!==e||t&&!t.isOpen)throw new Error(`Text index is not admitted to this open store`);return n.alias??n.table};return{match(e,t){const n=relation(e);const r=literalQuery(t);return e.matchField?sql`${sql.ref(`${n}.${e.matchField}`)} match ${r}`:sql`${sql.raw(n)} MATCH ${r}${sql.raw(e.hiddenRank?` AND ${n}.rank MATCH 'bm25()'`:``)}`},rank(e){const t=relation(e);return{value:sql`${sql.raw(e.hiddenRank?`${t}.rank`:`bm25(${t})`)}`,order:`asc`,toRank:e=>Number.isFinite(e)?-e:0}},snippet(e,t,n,r,i,a){const o=relation(e);const s=e.fields.indexOf(t);if(s<0)throw new Error(`Text index has no field ${t}`);const c=a?sql.val(a.start):sql.lit(``);const l=a?sql.val(a.end):sql.lit(``);const u=createFunctionModule()(`snippet`,[sql.table(o),sql.lit(s),c,l,sql.lit(` … `),sql.lit(n)]);return sql`${u}`},identity:e=>sql`${sql.raw(`${relation(e)}.rowid`)}`,allocatedIdentity:e=>{relation(e);return sql`${createFunctionModule()(`last_insert_rowid`,[])}`}}}
//!src/infra/database-engine/search.ts
function bindStoreSearch(e,t){if(`databasePath`in e?Boolean(e.input):isPostgresSqlConnection(e)){if(`databasePath`in e||!isPostgresSqlConnection(e))throw new Error(`PostgreSQL search requires the admitted worker connection`);return bindPostgresSearch(e,t)}const n=`databasePath`in e||isPostgresSqlConnection(e)?void 0:e;const r=`databasePath`in e?e.databasePath:n?.location()??``;const i={};const bindIndexes=(e={})=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{...t,store:i}]));return{fullText:bindSqliteFullText(i,n),vector:bindSqliteVectorCapability({store:i,databasePath:r},n),text:bindIndexes(t.text),vectors:bindIndexes(t.vector),diagnostics:[]}}
//!src/infra/database-engine/search-extension.ts
var SearchExtensionDefinitionChangedError=class extends Error{constructor(...e){super(...e);this.name=`SearchExtensionDefinitionChangedError`}};function arePostgresSearchExtensionsAdmitted(e,t){const n=getAdmittedPostgresSchema(e);return Boolean(n&&getPostgresPhysicalFacts(e)&&Object.entries(t).every(([e,t])=>JSON.stringify(n.searchExtensions?.[e])===JSON.stringify(t)))}function admitStoreSearchExtension(e,t,n){if(!isPostgresSqlConnection(e)){if(t===`memory.vector`)admitSqliteMemoryVectorSearch(e,n);return bindStoreSearch(e,t===`memory.text`?admitSqliteMemoryTextSearch(e,n):n)}const r=getAdmittedPostgresSchema(e);const i=getPostgresPhysicalFacts(e);if(!r||!i)throw new Error(`Search extensions require an admitted PostgreSQL store`);if(JSON.stringify(r.searchExtensions?.[t])===JSON.stringify(n))return bindStoreSearch(e,n);if(r.searchExtensions?.[t])throw new SearchExtensionDefinitionChangedError(`Search extension ${t} changed. Restore its previous definition, or rebuild the derived extension from canonical source data before using the new definition.`);e.runTransaction(()=>{admitPostgresSearch(e,n,i.namespace,r.postgresVectorSearchVersion);const a=[r.search,...Object.values(r.searchExtensions??{})].filter(e=>e!==void 0);if(a.some(e=>(e.extensionSchema??`public`)!==(n.extensionSchema??`public`)))throw new Error(`Search extensions must use the store's admitted extension schema`);const o={...r,searchExtensions:{...r.searchExtensions,[t]:n}};e.exec(postgresSearchSql(n,i.namespace,{text:a.some(e=>Object.keys(e.text??{}).length>0),vector:a.some(e=>e.mode!==`keyword-only`&&Object.keys(e.vector??{}).length>0)},r.postgresVectorDecoderVersion,r.postgresVectorSearchVersion,r.postgresTextSearchVersion));if(!Object.keys(r.searchExtensions??{}).length)e.exec(`ALTER TABLE openclaw_schema_meta ADD COLUMN IF NOT EXISTS search_extensions TEXT`);e.prepare(`UPDATE openclaw_schema_meta SET search_extensions = ? WHERE store = ?`).run(JSON.stringify(o.searchExtensions),r.id);const s=verifyAndRecordPostgresSchema(e,i.namespace,o);invalidateLocalSqliteSchemaAdmissions(e);stageSqliteTransactionState(e,{commit:()=>publishSqliteDatabaseSchemaChange(e)});retainPostgresSchema(e,o);publishPostgresSearchExtensionFacts(e,i,s.catalog,o);for(const t of[o.search,...Object.values(o.searchExtensions)].filter(e=>e!==void 0))publishPostgresSearch(e,t,r.postgresVectorSearchVersion)},{maintenance:true});return bindStoreSearch(e,n)}
//!src/infra/database-engine/search-admission.ts
function admitStoreSearch(e,t,n){if(n){if(`databasePath`in e)throw new Error(`Search extension admission requires the owner's connection`);return admitStoreSearchExtension(e,n.extension,t)}return bindStoreSearch(e,t)}
//!src/infra/database-engine/adapters.ts
const databaseEngineAdapters={sqlite:{openConnection:({anchor:e})=>observeConnection(e),schema:{bootstrap:e=>e.openSqlite()}},postgres:{openConnection:e=>{if(!e.input||!e.storeId||!e.namespace)throw new 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:POSTGRES_LOCK_TIMEOUT_MS,statementTimeoutMs:POSTGRES_STATEMENT_TIMEOUT_MS})}catch(t){const n=t instanceof Error&&`code`in t&&typeof t.code===`string`?`${t.code}: `:``;const r=redactSensitiveText(`${n}${t instanceof Error?t.message:String(t)}`.replaceAll(e.input.connection,`[REDACTED]`),{mode:`tools`});throw new Error(`Cannot open PostgreSQL connection: ${r}; verify database.postgres.connection and server availability.`,{cause:t})}},schema:{bootstrap:(e,t)=>{if(!e.schema.postgres)throw new Error(`Store has no PostgreSQL schema`);t.exec(postgresSchemaSql(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 new 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++){const t=e.schema.postgresMigrations?.find(e=>e.version===r);if(!t)throw new Error(`Missing PostgreSQL ${e.schema.id} migration to version ${r}; use a compatible binary or restore a matching backup.`);const i=readPostgresSchema(n,e.namespace,e.schema.id);const a=withPostgresSearchExtensions(e.schema,i);verifyPostgresSchema(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);if(t.schema.postgresVectorSearchVersion===2&&t.fromSchema.postgresVectorSearchVersion!==2){for(const t of[a.search,...Object.values(a.searchExtensions??{})])if(t)admitPostgresSearch(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);verifyAndRecordPostgresSchema(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})}}}}};function runEngineWorkerWrite(e,t,n){return e?n(t):t()}function runEngineStoreReadSnapshot(e,t){return isPostgresSqlConnection(e)?runSqliteReadSnapshotSync(e,t):runSqliteDeferredTransactionSync(e,t)}export{arePostgresSearchExtensionsAdmitted as a,admitStoreSearch as i,runEngineStoreReadSnapshot as n,runEngineWorkerWrite as r,databaseEngineAdapters as t};