UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1 lines • 15.8 kB
import{f as e}from"./transcript-plugin-instance-invocation-7y9lfaeO.mjs";import{d as t,o as n,v as r,y as i}from"./transcript-sqlite-database-admission-IPmtadyc.mjs";import{s as a}from"./transcript-path-guards-u0N7Z9_x.mjs";import{a as o,f as s}from"./transcript-sqlite-worker-identity-CA1Up8Es.mjs";import{et as c,l,nt as u}from"./transcript-sqlite-readonly-worker-cXU3LbpW.mjs";import{t as d}from"./transcript-errors-B-oBGrpW.mjs";import{S as f,s as p,v as m,w as h}from"./transcript-sqlite-post-commit-B_pko32i.mjs";import{A as g,D as _,E as v,I as y,O as b,g as x,x as S}from"./transcript-sqlite-schema-facts-C1_zV4Yg.mjs";import{a as C}from"./transcript-sqlite-transaction-CBQXI8WC.mjs";import{C as w,D as T}from"./transcript-openclaw-agent-db-resources-W6NYYBYU.mjs";import{n as E}from"./transcript-node-crypto-0qW6cl8t.mjs";import"./transcript-gateway-process-argv-CixOvMwa.mjs";import{N as D,b as O,g as k,h as A,j,o as M,t as N,v as P,y as F}from"./transcript-sqlite-private-snapshot-fork-CKFbjfTN.mjs";import{r as I,t as L}from"./transcript-node-sqlite-RfCz-ZxM.mjs";import{i as R,n as z}from"./transcript-adapters-VitZFwpd.mjs";import B from"node:path";import{AsyncLocalStorage as V}from"node:async_hooks";import{randomUUID as H}from"node:crypto";import U,{realpathSync as W}from"node:fs";function readCommittedContent(e,t,n,r){let i=L(t.location);f({release:()=>i.close()},`Database generation checkpoint`,()=>j(i,t.location)),n?.(t.location,e);let a=r?.(),o=a?N(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 c(t.location,s.identity,s),{sha256:s.sha256,family:o};let l=U.openSync(t.location,`r`);return{sha256:f({release:()=>U.closeSync(l)},`Database generation digest`,()=>w(l).sha256),family:o}}function inspectDrainedSource(e,t){let n=I(e);if(t){t(n,e);return}let r=L(n,{readOnly:!0});f({release:()=>r.close()},`Database generation admission`,()=>x(r))}function readWalIndexHeader(e){let t=`${e}-shm`,n;try{n=U.openSync(t,`r`)}catch(e){return a(e)??null}try{let r=U.fstatSync(n,{bigint:!0}),i=Buffer.alloc(96),a=U.readSync(n,i,0,48,0),o=U.readSync(n,i,48,48,48),s=U.fstatSync(n,{bigint:!0}),c=U.lstatSync(t,{bigint:!0});if(!r.isFile()||!c.isFile()||[s,c].some(e=>r.dev!==e.dev||r.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{U.closeSync(n)}}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=>U.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||!u(t,e))))throw Error(`SQLite file generation changed while reading: ${e}`)}function serializePhysicalGeneration(e,t){return E(JSON.stringify([O(e.wal?.size===0n?{...e,wal:void 0}:e),t?.toString(`hex`)??null]))}function readUpdateDatabaseGeneration(e,t,n){let r=readGenerationFamily(e),i=r[0];if(!i)return{generation:null,physical:null};let a=readWalIndexHeader(e),c=A(),l=c(e),observe=(t,n)=>{let o=P(e,n?c:void 0),u=readWalIndexHeader(e);if(verifyGenerationFamily(e,r,o),!F(l,o)||!sameWalCommitPublication(a,u,o)||l.wal&&l.wal.size>0n&&u?.[12]!==1)throw Error(`SQLite WAL commit publication could not be verified: ${e}`);let d=[l.database.dev.toString(),l.database.ino.toString(),s(i),t.sha256],f=u?.subarray(8,12).toString(`hex`)??null,p=u?.subarray(24,32).toString(`hex`)??null,fingerprint=(e,t)=>E(JSON.stringify([...d,e,t])),m=!l.journal&&(l.wal?.size??0n)===0n&&(u===null||f===`00000000`&&p===`0000000000000000`),h;if(t.family&&n){let r=N(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(f,p),physical:serializePhysicalGeneration(o,u),...u!==null&&(l.wal?.size??0n)!==0n&&f!==`00000000`?{rebuiltIndexAlternate:fingerprint(`00000000`,p)}:{},...m?{emptyReaderAlternate:u===null?fingerprint(`00000000`,`0000000000000000`):fingerprint(null,null)}:{},...h?{preparedSource:h}:{}}}},u=!l.journal&&(l.wal?.size??0n)===0n;if(u&&!n)try{return inspectDrainedSource(e,t),observe({sha256:l.database.sha256}).observation}catch{}let d=M(e,n?.stagingRoot,{key:`file:${o(l.database)}`},u?{sha256:l.database.sha256,sizeBytes:Number(l.database.size)}:void 0),p=!1;return f({release:()=>{if(!p){if(!n)d.cleanup();else try{if(!d.cleanup())throw Error(`Database generation snapshot cleanup did not settle`)}catch(e){throw new m(`Database generation snapshot cleanup failed`,{cause:e})}}}},`Database generation snapshot`,()=>{let r=readCommittedContent(e,d,t,n?.accept),i=observe(r,d);return p=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(t){try{return W.native(t)}catch(n){return a(n),e(t)}}const G=new V;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 migrationAuthority(e,t,n){let r=T();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():D(t),e.assertCurrent()}}function readSqliteGeneration(e){let t=JSON.parse(l(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 k(l(e,void 0,`file-generation`))}function getUpdateDoctorMigrationSource(e){let t=G.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=G.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 f({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 G.run({capture:o,source:f,assertMigrationCurrent:l},()=>{let i=n();if(h(i))throw Error(`Update migration callbacks must remain synchronous.`);if(e.isTransaction)throw Error(`Update migration publication requires its committed native owner.`);l(),j(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: ${d(e)}`),e}})}function beginUpdateSqliteCompanion(e,t,n){let r=G.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=G.getStore()?.capture,r=e.anchor.location(),i=r&&n?.expected(r);if(!n||!r||typeof i!=`string`)return;if(!T()?.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 G.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 K={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:a}=e,o=e.schema;R(a);let s=e.input!==void 0&&o.postgres!==void 0,c=n(a,K);if(!s){if(c?.engine===`postgres`)throw Error(`This store lives in PostgreSQL schema ${c.namespace}; set ${familySetting(o)} to postgres and configure database.postgres.connection.`);return!c&&e.inspectSqlite().hasEngineAnchor&&refusePostgresAnchor(a,o),e.prepareAnchor(),z.sqlite.schema.bootstrap({...e,input:e.input},a),r(a,K,{engine:`sqlite`}),z.sqlite.openConnection({...e,input:e.input})}if(c?.engine===`sqlite`)throw Error(`Existing SQLite ${o.id} data cannot switch engines; stop the Gateway and use openclaw database port for a supported store family before changing ${familySetting(o)}.`);e.prepareAnchor();let readOrCreateAnchor=()=>{let t=e.inspectSqlite();if(t.hasExistingData)throw Error(`Existing SQLite ${o.id} data cannot switch engines; stop the Gateway and use openclaw database port for a supported store family before changing ${familySetting(o)}.`);if(!t.hasEngineAnchor&&e.existingOnly)throw Error(`Missing PostgreSQL anchor; restore the matching PostgreSQL schema and anchor.`);t.hasEngineAnchor||a.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 n=readEngineAnchor(a,`identity`,!0)??[];if(n.length>1||t.hasEngineAnchor&&n.length===0)throw Error(`Invalid engine anchor: expected exactly one identity. Restore a matching backup.`);let r=n[0];if(r){if(typeof r.store_id!=`string`||r.engine!==`postgres`||typeof r.schema!=`string`)throw Error(`Invalid PostgreSQL anchor identity. Restore a matching backup.`);return{storeId:r.store_id,namespace:r.schema}}let i=H(),s=g(e.input.schemaPrefix,o.id,i);return a.prepare(`INSERT INTO openclaw_engine_anchor (store_id, engine, schema) VALUES (?, 'postgres', ?)`).run(i,s),e.onFreshAnchor?.(a),{storeId:i,namespace:s}},l=c?.engine===`postgres`?c:e.existingOnly?readOrCreateAnchor():C(a,readOrCreateAnchor),u={...e,input:e.input,...l},d=z.postgres,f=d.openConnection(u),admit=t=>{S({db:f,namespace:l.namespace,storeId:l.storeId,store:o.id,version:o.version,schema:o,recordSchema:t,preserveSchemaSeal:e.existingVersion}),e.admitPostgres?.(f,t)};try{let n=o.search?y(f,o.search,l.namespace,e.existingVersion?1:o.postgresVectorSearchVersion):void 0;if(!c||c.engine===`postgres`&&c.version!==o.version){v(f);let n,r;f.runTransaction(()=>{let a=!f.prepare(`SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname = ?`).get(l.namespace);a&&!e.existingOnly&&(f.exec(`CREATE SCHEMA IF NOT EXISTS "${l.namespace.replaceAll(`"`,`""`)}"`),f.exec(b));let s;try{s=f.prepare(`SELECT version, store_id FROM openclaw_schema_meta WHERE store = ?`).get(o.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!==l.storeId)throw Error(`PostgreSQL database identity mismatch: expected ${l.storeId}, found ${String(s.store_id)}. Restore the matching anchor and PostgreSQL backup.`);if(s.version!==o.version){if(e.existingVersion){let e=o.postgresMigrations?.find(e=>e.version===Number(s.version)+1)?.fromSchema;if(!e)throw Error(`Missing PostgreSQL source schema for inspection`);o={...o,...e,postgresVectorDecoderVersion:e.postgresVectorDecoderVersion,postgresVectorSearchVersion:e.postgresVectorSearchVersion,postgresTextSearchVersion:e.postgresTextSearchVersion,version:Number(s.version)}}else{r=e.assertMigrationCurrent,r?.(),n=beginUpdatePostgresMigration(f,r),t(f),p(f,{stage:()=>{},rollback:()=>{},commit:()=>i(f),invalidate:()=>i(f)});let migrate=()=>d.schema.migrate(u,Number(s.version),f);n?n.run(migrate):migrate()}}}else{if(e.existingOnly||!a)throw Error(`Missing PostgreSQL metadata; restore the matching PostgreSQL schema and anchor.`);d.schema.bootstrap(u,f)}admit(!s)},{withCommit(e){r?.(),n?.beforeCommit(),e()}},!1),n?.committed()}else admit(!1);(!c||c.engine===`postgres`&&c.version!==o.version)&&r(a,K,{engine:`postgres`,...l,version:o.version}),n?.();for(let e of Object.values(_(f)?.searchExtensions??{}))y(f,e,l.namespace,o.postgresVectorSearchVersion)?.();return f}catch(t){if(e.closeOnFailure)return e.closeOnFailure(f,t);throw f.close(),t}}export{getUpdateDoctorMigrationSource as a,getDoctorMigrationBackup as i,readEngineAnchor as n,runUpdateSqliteMigration as o,beginUpdateSqliteCompanion as r,openEngineStore as t};