openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
15 lines • 25.3 kB
JavaScript
import{A as e,Lt as t,f as n,rt as r}from"./sqlite-readonly-subsystem-Bfq7Sewc.mjs";import{U as i}from"./sqlite-readonly-runtime-process-manifest-DDSkIpjb.mjs";import"./sqlite-readonly-sqlite-schema-catalog-8883sMXx.mjs";import{Qt as a,Xt as o,a as s,an as c,b as l,f as u,ft as d,jn as f,nn as p,s as ee,sn as m,t as h,tn as te,ut as ne,y as g}from"./sqlite-readonly-sqlite-database-admission-Bj6bmeyX.mjs";import{A as re,C as ie,D as ae,E as oe,O as _,S as se,T as ce,j as v,k as y,s as b,w as x,y as S}from"./sqlite-readonly-node-sqlite-C-jA8uc4.mjs";import"./sqlite-readonly-runtime-binary-CQkI442k.mjs";import"./sqlite-readonly-runtime-worker-url-Ca-_reGi.mjs";import{F as C,I as le,Q as w,ot as ue}from"./sqlite-readonly-location.worker.js";import{a as T,i as de}from"./sqlite-readonly-pool-m9JiklDF.mjs";import{a as E}from"./sqlite-readonly-spawn-diagnostics-ChQW81dO.mjs";import{n as D}from"./sqlite-readonly-async-work-scope-BqIHG2vr.mjs";import{n as O}from"./sqlite-readonly-sqlite-worker-operation-settlement-MwRfpsC2.mjs";import{c as k,i as A,s as j}from"./sqlite-readonly-sqlite-transaction-8ZzF2aMT.mjs";import"./sqlite-readonly-windows-appcontainer-spawn-DGtrwkIS.mjs";import"node:path";import"node:v8";import{createHash as M,randomUUID as N}from"node:crypto";import{readFile as P,realpathSync as F}from"node:fs";import"node:os";import{MessageChannel as I,receiveMessageOnPort as L,threadId as R}from"node:worker_threads";import{promisify as z}from"node:util";import{AsyncLocalStorage as B}from"node:async_hooks";import"node:child_process";function preparePostgresQuery(e){let t=``,n=0,r=!0,i,a;for(let o=0;o<e.length;){let s=e.slice(o),c=/^(?:[eE]'(?:\\[\s\S]|''|[^'\\])*'|'(?:''|[^'])*'|"(?:""|[^"])*"|`(?:``|[^`])*`|\[[^\]]*\]|--[^\n]*(?:\n|$))/.exec(s),l=/^\$(?:[A-Za-z_][A-Za-z_0-9]*)?\$/.exec(s)?.[0];if(s.startsWith(`/*`)){let n=o+2,r=1;for(;n<e.length&&r>0;)e.startsWith(`/*`,n)?(r++,n+=2):e.startsWith(`*/`,n)?(r--,n+=2):n++;t+=e.slice(o,n),o=n}else if(l){let n=e.indexOf(l,o+l.length),a=n<0?e.length:n+l.length;t+=e.slice(o,a),o=a,i=void 0,r=!1}else if(c)t+=c[0],o+=c[0].length,c[0].startsWith(`--`)||(i=void 0,r=!1);else{if(r&&/^pragma\b/i.test(s))throw Error(`The PostgreSQL engine does not support PRAGMA statements`);let c=/^(?:\d[\d_]*(?:\.[\d_]*)?|\.[\d_]+)(?:[eE][+-]?[\d_]+)?/.exec(s)?.[0];if(c){t+=c,o+=c.length,i=void 0,r=!1;continue}let l=/^[A-Za-z_][A-Za-z_0-9$]*/.exec(s)?.[0];if(l){let e=l.toUpperCase();i!==`AS`&&i!==`.`&&(e===`INTO`&&i!==`INSERT`&&i!==`MERGE`?a=`unscoped`:a===void 0&&/^(?:INSERT|UPDATE|DELETE|MERGE)$/.test(e)&&(e!==`UPDATE`||i!==`FOR`&&i!==`KEY`)&&(a=`scoped`)),i=e,t+=l,o+=l.length,r=!1;continue}let u=e.charAt(o);/\s/.test(u)||(i=u),u===`?`&&e[o+1]===`?`?(t+=`?`,o+=2):u===`?`?(t+=`$${++n}`,o++):(t+=u,o++),u===`;`?r=!0:/\s/.test(u)||(r=!1)}}return{sql:t,mutation:a}}function validatePostgresBindings(e){for(let t of e)if(t!==null&&typeof t!=`string`&&typeof t!=`number`&&typeof t!=`bigint`&&!ArrayBuffer.isView(t))throw TypeError(`SQL bindings must be null, numbers, bigints, strings, or ArrayBuffer views`)}function decodePostgresRows(e,t){return e.rows.map(n=>Object.fromEntries(e.fields.map(e=>{let r=n[e.name],i;if(r===null)i=null;else if(e.dataTypeID===20){if(typeof r!=`string`)throw TypeError(`PostgreSQL int8 results must be text`);let e=BigInt(r);if(t)i=e;else{let t=Number(e);if(!Number.isSafeInteger(t))throw RangeError(`PostgreSQL int8 ${e} cannot be represented safely as a number`);i=t}}else if(r instanceof Uint8Array)i=new Uint8Array(r);else if(typeof r==`boolean`)i=Number(r);else if(typeof r==`string`||typeof r==`number`||typeof r==`bigint`)i=r;else throw TypeError(`Unsupported PostgreSQL result type for column ${e.name}`);return[e.name,i]})))}function isPostgresConnectionError(e){return!e||e.startsWith(`08`)||/^57P0[123]$/.test(e)}function decodePostgresError(e){let t=Object.assign(Error(e.message),e);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 resolvePathViaExistingAncestorSync(e){return n(()=>i(e))}const V=t(Symbol.for(`openclaw.databaseProcessRole`),()=>({}));function getDatabaseProcessRole(){return V.role}let H=0;function withEngineStoreAdmission(e){H+=1;try{let t=e();if(f(t))throw Error(`Database engine admission must remain synchronous`);return t}finally{--H}}function assertEngineStoreExecutionAllowed(){if(R===0&&H===0&&V.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 U=18e5;function resolveAgentDatabaseIdleHandleTtlMs(){return getDatabaseProcessRole()===`cli-oneshot`?3e4:U}const W=36e5,G=/* @__PURE__ */ new Map;function closeBridge(e){e.port.close()}function closeIdleBridges(){let e=[...G.values()];G.clear(),unwatch();for(let{bridge:t,timeout:n}of e)clearTimeout(n),closeBridge(t)}function unwatch(){G.size||(process.off(`beforeExit`,closeIdleBridges),process.off(`exit`,closeIdleBridges))}function removeIdleBridge(e){let t=G.get(e);return G.delete(e),t&&clearTimeout(t.timeout),unwatch(),t}function takeIdlePostgresBridge(e){let t=removeIdleBridge(e);if(t){if(Atomics.load(t.bridge.service,1))closeBridge(t.bridge);else return{bridge:t.bridge,validate:Date.now()-t.releasedAt>=1e3}}}function retainIdlePostgresBridge(e,t){let n=removeIdleBridge(e);if(n&&closeBridge(n.bridge),G.size===2){let e=G.keys().next().value;closeBridge(removeIdleBridge(e).bridge)}G.size||(process.once(`beforeExit`,closeIdleBridges),process.once(`exit`,closeIdleBridges));let r=setTimeout(()=>{let t=removeIdleBridge(e);t&&closeBridge(t.bridge)},18e4);r.unref(),G.set(e,{bridge:t,timeout:r,releasedAt:Date.now()})}function postgresBridgeReuseKey(e){return ue(JSON.stringify([e.url,e.lockTimeoutMs??6e4,e.statementTimeoutMs??9e4,e.readOnly===!0]))}function preparedBridgeKey(e){return JSON.stringify([postgresBridgeReuseKey(e),e.schema,e.storeId])}function createPostgresBridge(e){let{port1:t,port2:n}=new I,r=new SharedArrayBuffer(8),i=new Int32Array(r),{port:a,signal:o,nextStep:s}=de(),c=new Int32Array(o);if(Atomics.load(c,1)){t.close(),n.close();let e=/* @__PURE__ */ Error(`PostgreSQL I/O service is unavailable.${s?` Run ${s}.`:``}`);throw T(e),e}try{a.postMessage({connection:{port:n,signal:r,url:e.url,schema:e.schema,connectTimeoutMs:6e4,lockTimeoutMs:e.lockTimeoutMs??6e4,statementTimeoutMs:e.statementTimeoutMs??9e4,readOnly:e.readOnly===!0}},[n])}catch(e){throw t.close(),n.close(),e}return t.unref(),{port:t,control:i,service:c,nextStep:s,requestId:0}}const K=new B;function findPreparedBridge(e){let t=K.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=O.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 s=m(e);return p(s,()=>{let s=e.isTransaction&&!i,l=!1,u;try{r&&!s&&(u=b(e)),s?e.exec(`SAVEPOINT openclaw_tx_nested`):e.isTransaction||e.exec(r?`BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY`:`BEGIN ISOLATION LEVEL READ COMMITTED; SELECT pg_advisory_xact_lock(${e.advisoryLockKey})`);let i=n?.maintenance&&s?String(e.prepare(`SHOW statement_timeout`).get().statement_timeout):void 0;n?.maintenance&&e.exec(`SET LOCAL statement_timeout = '${W}ms'`);let o=t();if(c(o),s)i!==void 0&&e.prepare(`SELECT set_config('statement_timeout', ?, true)`).get(i),e.exec(`RELEASE SAVEPOINT openclaw_tx_nested`);else{let commit=()=>{assertPostgresOperationCurrent(),r||a(e),e.exec(r?`ROLLBACK`:`COMMIT`),l=!r};n?.withCommit?c(n.withCommit(commit)):commit()}return o}catch(t){let n=d(t)||l;if(!n)try{s?(e.exec(`ROLLBACK TO SAVEPOINT openclaw_tx_nested`),e.exec(`RELEASE SAVEPOINT openclaw_tx_nested`)):e.isTransaction&&e.exec(`ROLLBACK`)}catch{n=!0}if(n)try{o(e,t,`unknown`)}finally{try{e.close()}catch{}}throw t}finally{u?.()}})}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=R===0,this.maintenance=!1,assertEngineStoreExecutionAllowed(),this.admissionReadOnly=i?.readOnly===!0,Object.defineProperty(this,Symbol.for(`openclaw.postgres-sync-connection`),{value:!0}),this.advisoryLockKey=M(`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?.bridge??takePreparedPostgresBridge(this.bridgeParameters)??createPostgresBridge(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,h(m(this),!0)),this.finishWrite(),this.failure??=this.outcomeUnknown?new ne(`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)&&T(this.failure),this.isOpen=!1,this.isTransaction=!1,e?.port.close(),this.bridge=void 0,this.failure}finishWrite(){this.pendingWrite&&(this.pendingWrite=!1,s(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=(this.maintenance?W: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},[]),w(`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=L(n.port)?.message;if(l&&w(`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 k(`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,h(m(this),s===`unscoped`)}return!this.isTransaction&&(c||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=k(`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}}};Buffer.from(`
VmRSS:`),Buffer.from(`
VmSwap:`),Buffer.from(`
Pss:`),Buffer.from(`
SwapPss:`);const q=C(process.versions.node);!process.versions.bun&&q&&(q.major===24&&q.minor>=19||q.major===26&&q.minor>=4&&q.minor),z(P),t(Symbol.for(`openclaw.hostExecMemory`),()=>({watches:/* @__PURE__ */ new Set,sampling:!1,assessmentPending:!1})),new le;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 fe=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;`),pe=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})=>j(e),schema:{bootstrap:e=>e.openSqlite()}},postgres:{openConnection:t=>{if(!t.input||!t.storeId||!t.namespace)throw Error(`PostgreSQL store is not admitted`);try{return new PostgresSyncConnection(t.input.connection,t.namespace,t.anchor,t.storeId,{reuse:t.reusePostgresConnection,readOnly:t.input.readOnly,lockTimeoutMs:6e4,statementTimeoutMs:9e4})}catch(n){let r=n instanceof Error&&`code`in n&&typeof n.code==`string`?`${n.code}: `:``,i=e(`${r}${n instanceof Error?n.message:String(n)}`.replaceAll(t.input.connection,`[REDACTED]`),{mode:`tools`});throw Error(`Cannot open PostgreSQL connection: ${i}; verify database.postgres.connection and server availability.`,{cause:n})}},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=ae(n,e.namespace,e.schema.id),a=re(e.schema,i);if(y(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&&v(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),_(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 resolveUpdateSqlitePath(e){try{return F.native(e)}catch(t){return r(t),resolvePathViaExistingAncestorSync(e)}}const Q=new B;function hasUpdateDoctorMigrationCapture(){return Q.getStore()?.capture!==void 0}function getUpdateDoctorMigrationSource(e){let t=Q.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=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 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);E(D())?.throwIfAborted();let n=e[2]();if(f(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)}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;j(t);let r=e.input!==void 0&&n.postgres!==void 0,i=ee(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),g(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)}.`);let a=e.input?.readOnly===!0;a||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||a))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 o=i[0];if(o){if(typeof o.store_id!=`string`||o.engine!==`postgres`||typeof o.schema!=`string`)throw Error(`Invalid PostgreSQL anchor identity. Restore a matching backup.`);return{storeId:o.store_id,namespace:o.schema}}let s=N(),c=oe(e.input.schemaPrefix,n.id,s);return t.prepare(`INSERT INTO openclaw_engine_anchor (store_id, engine, schema) VALUES (?, 'postgres', ?)`).run(s,c),e.onFreshAnchor?.(t),{storeId:s,namespace:c}},o=i?.engine===`postgres`?i:e.existingOnly||a?readOrCreateAnchor():A(t,readOrCreateAnchor),s={...e,input:e.input,...o},c=Z.postgres,d=c.openConnection(s),admit=t=>{S({db:d,namespace:o.namespace,storeId:o.storeId,store:n.id,version:n.version,schema:n,recordSchema:t,preserveSchemaSeal:e.existingVersion,requireSealedSchema:a}),e.admitPostgres?.(d,t)};try{let r=n.search?v(d,n.search,o.namespace,e.existingVersion?1:n.postgresVectorSearchVersion):void 0;if(a)d.runTransaction(()=>admit(!1),void 0,!0);else if(!i||i.engine===`postgres`&&i.version!==n.version){se(d);let t,r;d.runTransaction(()=>{let i=!d.prepare(`SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname = ?`).get(o.namespace);i&&!e.existingOnly&&(d.exec(`CREATE SCHEMA IF NOT EXISTS "${o.namespace.replaceAll(`"`,`""`)}"`),d.exec(x));let a;try{a=d.prepare(`SELECT version, store_id FROM openclaw_schema_meta WHERE store = ?`).get(n.id)}catch(e){throw Error(`Missing PostgreSQL metadata; use the matching OpenClaw version or restore the matching PostgreSQL schema and anchor.`,{cause:e})}if(a){if(a.store_id!==o.storeId)throw Error(`PostgreSQL database identity mismatch: expected ${o.storeId}, found ${String(a.store_id)}. Restore the matching anchor and PostgreSQL backup.`);if(a.version!==n.version){if(e.existingVersion){let e=n.postgresMigrations?.find(e=>e.version===Number(a.version)+1)?.fromSchema;if(!e)throw Error(`Missing PostgreSQL source schema for inspection`);n={...n,...e,postgresVectorDecoderVersion:e.postgresVectorDecoderVersion,postgresVectorSearchVersion:e.postgresVectorSearchVersion,postgresTextSearchVersion:e.postgresTextSearchVersion,version:Number(a.version)}}else{r=e.assertMigrationCurrent,r?.(),t=beginUpdatePostgresMigration(d,r),u(d),te(d,{stage:()=>{},rollback:()=>{},commit:()=>l(d),invalidate:()=>l(d)});let migrate=()=>c.schema.migrate(s,Number(a.version),d);t?t.run(migrate):migrate()}}}else{if(e.existingOnly||!i)throw Error(`Missing PostgreSQL metadata; restore the matching PostgreSQL schema and anchor.`);c.schema.bootstrap(s,d)}admit(!a)},{maintenance:!0,withCommit(e){r?.(),t?.beforeCommit(),e()}},!1),t?.committed()}else admit(!1);(!i||i.engine===`postgres`&&i.version!==n.version)&&g(t,$,{engine:`postgres`,...o,version:n.version}),r?.();for(let e of Object.values(ie(d)?.searchExtensions??{}))v(d,e,o.namespace,n.postgresVectorSearchVersion)?.();return d}catch(t){if(e.closeOnFailure)return e.closeOnFailure(d,t);throw d.close(),t}}export{getUpdateDoctorMigrationSource as a,pe as c,U as d,resolveAgentDatabaseIdleHandleTtlMs as f,resolvePathViaExistingAncestorSync as h,getDoctorMigrationBackup as i,J as l,withEngineStoreAdmission as m,readEngineAnchor as n,runUpdateSqliteMigration as o,getDatabaseProcessRole as p,beginUpdateSqliteCompanion as r,runUpdateSqliteMigrationAsync as s,openEngineStore as t,fe as u};