openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
15 lines • 21.4 kB
JavaScript
import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{n as isPostgresSqlConnection}from"./sql-connection-nx8lLUJM.mjs";import{_ as sql,i as executeSqliteQuerySync,p as sqliteStringSet,s as getNodeSqliteKysely}from"./kysely-sync-R08Pt8qn.mjs";import{Y as DatabaseSearchCapabilityUnavailableError,o as getAdmittedSqliteSchemaFacts,t as admitSqliteSchema}from"./sqlite-schema-facts-CWOeTpUB.mjs";import{a as tableExists,o as tableHasColumn}from"./openclaw-state-db-schema-helpers-rYTimzjJ.mjs";import{n as openNodeSqliteDatabase}from"./node-sqlite-DXyF1fBG.mjs";import{n as getDatabaseEngineSelection}from"./context-DZjni16e.mjs";import{i as admitStoreSearch}from"./adapters-qs4MJmRJ.mjs";import{a as MEMORY_INDEX_SOURCES_TABLE,n as MEMORY_INDEX_CHUNKS_TABLE,r as MEMORY_INDEX_FTS_TABLE}from"./sqlite-search-schema-B4FvDa7W.mjs";import{o as readOpenClawAgentDatabaseIdentity}from"./openclaw-agent-db-identity-D6YwE2-y.mjs";import{r as memoryPathPostgresExpressions}from"./memory-path-postgres-ByPGtNrE.mjs";import{c as memoryVectorSearchSchema,h as MEMORY_INDEX_STATE_TABLE,m as MEMORY_INDEX_META_TABLE,s as memoryTextSearchSchema}from"./memory-schema-CKKgpsuR.mjs";import{a as withFreshOpenClawAgentDatabaseReadOnly,n as openOpenClawAgentDatabaseReadOnly}from"./openclaw-agent-db-readonly-open-D1ygiMvy.mjs";import{n as withOpenClawAgentDatabaseReadOnly,t as retainOpenClawAgentDatabaseReadOnly}from"./openclaw-agent-db-readonly-BQsAKuqV.mjs";import{n as serveWorkerTasks}from"./worker-task-server-BeWxX5OH.mjs";import{t as loadSqliteVecExtension}from"./sqlite-vec-D-Kq5nmv.mjs";import"./worker-task-server-CcyILWmd.mjs";import"./error-runtime-DW-sj0iq.mjs";import"./memory-core-host-engine-knn-D4D2JBXP.mjs";import{a as readCuratedMemoryTriggerCandidates,o as readCuratedProjectMemoryCandidates}from"./engine-storage-BUVD8guN.mjs";import{r as readMemoryEntryOriginsInDatabase}from"./memory-core-host-engine-storage-DWADN4Bs.mjs";import"./sqlite-worker-runtime-D6xJvxBF.mjs";import{n as hasMemorySessionTombstone}from"./memory-session-tombstones-DYntu_P7.mjs";import{n as referencesSession,r as scrubMemoryContent}from"./memory-forget-content-CU4x9kjk.mjs";import{t as isMemorySessionIndexable}from"./manager-session-sync-state-BrcrsAQ1.mjs";import{d as readMemoryRecallData,f as readMemoryRetrievalIndexState,u as readMemoryDatabaseFacts}from"./manager-index-metadata-BEYbHt4P.mjs";import"./memory-core-host-engine-schema-DrdLs2fg.mjs";import{t as readMemoryIndex}from"./manager-search-schema-Cm4K8gcg.mjs";import{o as projectMemorySearchRow}from"./manager-search-knn-DEqAwJ_e.mjs";import"./database-engine-worker-runtime-DKHBfBN5.mjs";import{c as buildMatchQueryFromTerms,l as planKeywordSearch,o as searchKeyword,r as searchChunksByEmbedding,s as searchPathKeyword,t as collectMemoryStatusSnapshot}from"./manager-status-state-BBw92whO.mjs";
//!extensions/memory-core/src/memory-entry-origin-reads.ts
function queryOrigins(e,t){if(t.kind===`origin-rows`)return{kind:t.kind,rows:e&&tableExists(e,`memory_entry_origins`)?readMemoryEntryOriginsInDatabase(e,t):[]};if(!e)return{kind:t.kind,indices:[]};const n=[];const r=Math.min(t.sessionIds.length,256);for(let i=0;i<r;i+=1)if(hasMemorySessionTombstone(e,t.agentId,t.sessionIds[i]))n.push(i);return{kind:t.kind,indices:n}}function readMemoryOriginsInWorker(e){const t=withOpenClawAgentDatabaseReadOnly(({db:t})=>queryOrigins(t,e),{agentId:e.agentId,path:e.databasePath,env:{OPENCLAW_STATE_DIR:e.stateDir}});return t.found?t.value:queryOrigins(void 0,e)}
//!extensions/memory-core/src/memory-forget-index-read.ts
async function readMemoryForgetIndexInWorker(e){const t={agentId:e.agentId,path:e.databasePath,env:{OPENCLAW_STATE_DIR:e.stateDir}};const n={agentId:e.agentId,removedPaths:new Set(e.removedPaths),sessionIds:new Set(e.sessionIds),excludedSessionIds:new Set(e.excludedSessionIds),entryKeys:new Set(e.entryKeys),corpusSnippets:new Set(e.corpusSnippets)};const r=withFreshOpenClawAgentDatabaseReadOnly(({db:t})=>{const r=isPostgresSqlConnection(t);const i=getNodeSqliteKysely(t);const a=executeSqliteQuerySync(t,i.selectFrom(`memory_index_chunks as chunk`).select([`chunk.id`,`chunk.path`,`chunk.source`]).$if(tableExists(t,`memory_index_chunk_provenance`),e=>e.leftJoin(`memory_index_chunk_provenance as provenance`,`provenance.chunk_id`,`chunk.id`).select([`provenance.origin_class as originClass`,`provenance.session_kind as sessionKind`])).select(e=>e.case(`chunk.source`).when(`sessions`).then(``).else(e.ref(`chunk.text`)).end().as(`text`))).rows;const o=new Set(e.changedPaths);for(const e of a)if(e.source===`memory`&&scrubMemoryContent({...n,content:e.text}).content!==e.text)o.add(e.path);const s=a.filter(e=>o.has(e.path)||referencesSession(e.path,n.agentId,n.sessionIds)||n.sessionIds.size>0&&e.source===`sessions`&&(e.originClass===`system`||!isMemorySessionIndexable({sessionKind:e.sessionKind??`unknown`})||referencesSession(e.path,n.agentId,n.excludedSessionIds)));const c=new Set(s.filter(e=>e.source===`sessions`).map(e=>e.path));const l=n.removedPaths.size>0||c.size>0?executeSqliteQuerySync(t,i.selectFrom(`memory_index_sources`).select([`path`,`source`])).rows.filter(e=>n.removedPaths.has(e.path)||e.source===`sessions`&&c.has(e.path)):[];const u=s.map(e=>e.id);const d=r?tableHasColumn(t,`memory_index_chunks`,`openclaw_search`)?u.length:0:u.length>0&&tableExists(t,`memory_index_chunks_fts`)?executeSqliteQuerySync(t,i.selectFrom(`memory_index_chunks_fts`).select(e=>e.fn.countAll().as(`count`)).where(`rowid`,`in`,i.selectFrom(`memory_index_chunks`).select(`chunk_rowid`).where(`id`,`in`,u))).rows[0].count:0;const f=tableExists(t,`memory_index_chunks_vec`);const p=r&&f&&u.length>0?executeSqliteQuerySync(t,i.selectFrom(`memory_index_chunks_vec`).select(e=>e.fn.countAll().as(`count`)).where(`id`,`in`,sqliteStringSet(u))).rows[0].count:0;let m=0;if(n.sessionIds.size>0&&tableExists(t,`memory_embedding_cache`))m=executeSqliteQuerySync(t,i.selectFrom(`memory_embedding_cache`).select(e=>e.fn.countAll().as(`count`))).rows[0].count;return{chunks:s.map(({id:e,path:t,source:n})=>({id:e,path:t,source:n})),sources:l,ftsRows:d,embeddingCacheRows:m,hasVectorTable:f,vectorRows:p,postgres:r}},t);if(!r.found)return{chunks:[],sources:[],ftsRows:0,vectorRows:0,embeddingCacheRows:0,hasVectorTable:false};const{postgres:i,...a}=r.value;if(i)return a;let o=0;let s;if(r.value.hasVectorTable&&r.value.chunks.length>0){const e=openNodeSqliteDatabase(`:memory:`,{allowExtension:true});let n;try{const t=await loadSqliteVecExtension({db:e});if(!t.ok||!t.extensionPath)throw new Error(`memory forget cannot inspect vector index: ${t.error??`load failed`}`);n=t.extensionPath}finally{e.close()}s=n;const i=withFreshOpenClawAgentDatabaseReadOnly(({db:e})=>{if(isPostgresSqlConnection(e))throw new Error(`memory forget vector extension requires a SQLite connection`);const t=e;t.enableLoadExtension(true);t.loadExtension(n);const i=getNodeSqliteKysely(t);return executeSqliteQuerySync(t,i.selectFrom(`memory_index_chunks_vec`).select(e=>e.fn.countAll().as(`count`)).where(`id`,`in`,r.value.chunks.map(e=>e.id))).rows[0].count},t,{allowExtension:true});o=i.found?i.value:0}return{...a,vectorRows:o,extensionPath:s}}
//!extensions/memory-core/src/memory/manager-search-keyword.ts
async function searchKeywordWithFallback(e){const runBody=(t=false)=>searchKeyword({...e.body,db:e.db,matchAny:t}).then(e=>({rows:e,error:void 0})).catch(e=>({rows:[],error:formatErrorMessage(e)}));let t=await runBody();const n=await searchPathKeyword({...e.path,db:e.db}).then(e=>({rows:e,error:void 0})).catch(e=>({rows:[],error:formatErrorMessage(e)}));if(t.rows.length===0&&n.rows.length===0&&!t.error&&!n.error)t=await runBody(true);return{body:t,path:n}}
//!extensions/memory-core/src/memory/manager-search-postgres.ts
function sessionExclusion(e,t){const n=sql.ref(t?`${t}.source`:`source`);const r=sql.ref(t?`${t}.path`:`path`);return sql`(${n} != 'sessions' OR ${r} NOT IN ${sqliteStringSet(e)})`}function textIntent(e,t,n=false){const r=planKeywordSearch({query:e,ftsTokenizer:t,matchAny:n});const i=buildMatchQueryFromTerms(r.tokens,void 0,n);if(!i)return;return t===`trigram`?{kind:n?`any`:`all`,clauses:r.tokens.map(e=>({kind:`contains`,text:e}))}:i}function textCapability(e,t){const n=admitStoreSearch(e,memoryTextSearchSchema(t??`unicode61`));if(!n.fullText)throw new DatabaseSearchCapabilityUnavailableError(`fullText`,n.diagnostics.join(`; `));return{fullText:n.fullText,indexes:n.text}}async function searchPostgresMemoryVector(e,t){if(t.limit<=0||t.candidateIds?.length===0||t.queryVec.length===0)return[];const n=admitStoreSearch(e,memoryVectorSearchSchema(t.queryVec.length));if(!n.vector)throw new DatabaseSearchCapabilityUnavailableError(`vector`,n.diagnostics.join(`; `));const r=getNodeSqliteKysely(e);const i=[.../* @__PURE__ */ new Set([t.providerModel,...(t.providerModelAliases??[]).filter(Boolean)])];const scoped=()=>{let e=r.selectFrom(`memory_index_chunks_vec as v`).innerJoin(`memory_index_chunks as c`,`c.id`,`v.id`).where(`c.model`,`in`,i);if(t.sourceFilter.params.length)e=e.where(`c.source`,`in`,t.sourceFilter.params);if(t.sourceFilter.excludedSessionPaths?.length)e=e.where(sessionExclusion(t.sourceFilter.excludedSessionPaths,`c`));if(t.candidateIds)e=e.where(`c.id`,`in`,t.candidateIds);return e};return(await n.vector.nearest({index:n.vectors.chunks,vector:t.queryVec,limit:t.limit,textPrefix:{column:`text`,maxChars:t.snippetMaxChars},scopeCount:scoped().select(r.fn.countAll().as(`count`)),isRow:e=>typeof e===`object`&&e!==null&&`dist`in e&&typeof e.dist===`number`,candidates:({match:e,distance:n,limit:r})=>t.candidateIds&&t.candidateIds.length<=r?void 0:scoped().select(`v.id`).where(e).orderBy(n).orderBy(`v.id`).limit(r),query:({match:e,distance:n})=>scoped().select([`c.id`,`c.path`,`c.start_line`,`c.end_line`,`c.source`,sql`left(c.text, ${t.snippetMaxChars})`.as(`text`),n.as(`dist`)]).where(e).orderBy(`dist`).orderBy(`c.id`).limit(t.limit)})).rows.map(e=>projectMemorySearchRow(e,t.snippetMaxChars,1-e.dist))}function bodyStatement(e,t,n=false){const r=textIntent(t.query,t.ftsTokenizer,n);if(t.limit<=0||!r)return;const{fullText:i,indexes:a}=textCapability(e,t.ftsTokenizer);const o=a.body;const s=textRank(i,o,r,t.ftsTokenizer);const c=getNodeSqliteKysely(e);let l=c.selectFrom(`memory_index_chunks`).select([`id`,s.as(`rank`)]).where(textMatch(i,o,r));if(t.sourceFilter.params.length)l=l.where(`source`,`in`,t.sourceFilter.params);if(t.sourceFilter.excludedSessionPaths?.length)l=l.where(sessionExclusion(t.sourceFilter.excludedSessionPaths));return c.with(e=>e(`ranked`).materialized(),()=>l.orderBy(`rank`,`desc`).orderBy(`id`).limit(t.limit)).selectFrom(`ranked as r`).innerJoin(`memory_index_chunks as c`,`c.id`,`r.id`).select([`c.id`,`c.path`,`c.source`,`c.start_line`,`c.end_line`,sql`left(c.text, ${t.snippetMaxChars})`.as(`text`),calibrateTextRank(sql`r.rank`,t.ftsTokenizer).as(`rank`),sql`0`.as(`specificity`),sql`0`.as(`branch`)]).orderBy(`r.rank`,`desc`).orderBy(`c.id`)}function projectBodyRows(e,t){return e.map(e=>Object.assign(projectMemorySearchRow(e,t.snippetMaxChars,e.rank),{textScore:e.rank,hasBodyMatch:true}))}function searchBody(e,t,n=false){const r=bodyStatement(e,t,n);return projectBodyRows(r?executeSqliteQuerySync(e,r).rows:[],t)}function textMatch(e,t,n){if(n.kind===`all`||n.kind===`any`){const r=n.clauses.map(n=>textMatch(e,t,n));return n.kind===`all`?sql`(${sql.join(r,sql` AND `)})`:sql`(${sql.join(r,sql` OR `)})`}return e.match(t,n)}function textRank(e,t,n,r){if(r!==`trigram`)return e.rank(t,n,{postgres:{normalization:0,rank:`frequency`}}).value;if(n.kind!==`all`&&n.kind!==`any`)return e.rank(t,n).value;const i=n.clauses.map(n=>textRank(e,t,n,r));return sql`(${sql.join(i,sql` + `)}) / ${i.length}`}function calibrateTextRank(e,t){return t===`trigram`?e:sql`${e} / (${e} + 0.0027)`}function pathSpecificity(e){if(!e||e===`.`)return sql`0`;const t=memoryPathPostgresExpressions(`s.path`);const n=sql.raw(t.normalized);if(e.includes(`/`))return sql`CASE WHEN ${n} = ${e} THEN 3 ELSE 0 END`;const r=sql.raw(t.basename);const i=sql.raw(t.stem);return sql`CASE WHEN ${n} = ${e} THEN 3 WHEN ${r} = ${e} THEN 2 WHEN ${i} = ${e} THEN 1 ELSE 0 END`}function pathStatements(e,t){const n=Math.max(0,Math.floor(t.exactPathLimit??t.limit));if(t.limit<=0&&n<=0)return[];const r=textIntent(t.query,t.ftsTokenizer);const{fullText:i,indexes:a}=textCapability(e,t.ftsTokenizer);const o={...a.paths,alias:`s`};const s=r?calibrateTextRank(textRank(i,o,r,t.ftsTokenizer),t.ftsTokenizer):sql`0`;const c=getNodeSqliteKysely(e);const l=t.query.trim().replaceAll(`\\`,`/`).replace(/^\.\//,``).normalize(`NFC`).toLowerCase();const u=pathSpecificity(l);const select=(e,n)=>{if(n<=0||!e&&!r)return;const a=c.selectFrom(`memory_index_sources as s`).select([`s.path`,`s.source`,`s.openclaw_search`]);const d=e?c.with(e=>e(`exact_candidates`).materialized(),()=>a.where(sql`(${sql.join(memoryPathPostgresExpressions(`s.path`).keys.slice(0,l.includes(`/`)?1:void 0).map(e=>sql`${sql.raw(e)} = pg_catalog.md5(${l})`),sql` OR `)})`)).selectFrom(`exact_candidates`).selectAll().as(`s`):a.as(`s`);let f=c.selectFrom(d).select([`s.path`,`s.source`,s.as(`rank`),u.as(`specificity`)]).where(u,e?`>`:`=`,0).where(e=>e.exists(e.selectFrom(`memory_index_chunks as live`).select(`live.id`).whereRef(`live.path`,`=`,`s.path`).whereRef(`live.source`,`=`,`s.source`)));if(!e&&r)f=f.where(textMatch(i,o,r));if(t.sourceFilter.params.length)f=f.where(`s.source`,`in`,t.sourceFilter.params);if(t.sourceFilter.excludedSessionPaths?.length)f=f.where(sessionExclusion(t.sourceFilter.excludedSessionPaths,`s`));const p=f.orderBy(e?u:s,`desc`).orderBy(`s.path`).orderBy(`s.source`).limit(n);return c.with(e=>e(`retained`).materialized(),()=>p).selectFrom(`retained as p`).innerJoinLateral(e=>e.selectFrom(`memory_index_chunks as first`).select([`first.id`,`first.start_line`,`first.end_line`,sql`left(first.text, ${t.snippetMaxChars})`.as(`text`)]).whereRef(`first.path`,`=`,`p.path`).whereRef(`first.source`,`=`,`p.source`).orderBy(`first.start_line`).orderBy(`first.end_line`).orderBy(`first.id`).limit(1).as(`c`),e=>e.onTrue()).select([`c.id`,`p.path`,`p.source`,`c.start_line`,`c.end_line`,`c.text`,`p.rank`,`p.specificity`,sql`${sql.lit(e?1:2)}`.as(`branch`)]).orderBy(e?`p.specificity`:`p.rank`,`desc`).orderBy(`p.path`).orderBy(`p.source`)};return[select(true,n),select(false,t.limit)].filter(e=>e!==void 0)}function projectPathRows(e,t){const n=Math.max(0,Math.floor(t.exactPathLimit??t.limit));return e.map(e=>Object.assign(projectMemorySearchRow(e,t.snippetMaxChars,e.rank),{textScore:0,pathScore:e.rank,exactPathSpecificity:e.specificity,hasBodyMatch:false})).slice(0,t.exactPathLimit===void 0?t.limit:n+t.limit)}function searchPaths(e,t){return projectPathRows(pathStatements(e,t).flatMap(t=>executeSqliteQuerySync(e,t).rows),t)}function searchIndependentBranches(e,t){const n=[bodyStatement(e,t.body),...pathStatements(e,t.path)].filter(e=>e!==void 0);const r=sql`(${sql.join(n.map(e=>sql`(${e})`),sql` UNION ALL `)})`;const i=bodyStatement(e,t.body,true);const a=i?sql`(WITH primary_matches AS MATERIALIZED ${r}
SELECT * FROM primary_matches
UNION ALL (${i.where(sql`NOT EXISTS (SELECT 1 FROM primary_matches)`)}))`:r;const o=n.length?executeSqliteQuerySync(e,getNodeSqliteKysely(e).selectFrom(a.as(`matches`)).selectAll().orderBy(`branch`).orderBy(sql`CASE WHEN branch = 1 THEN specificity ELSE rank END`,`desc`).orderBy(sql`CASE WHEN branch = 0 THEN id ELSE path END`).orderBy(`source`)).rows:[];return{body:{rows:projectBodyRows(o.filter(e=>e.branch===0),t.body)},path:{rows:projectPathRows(o.filter(e=>e.branch!==0),t.path)}}}async function searchPostgresMemoryKeyword(e,t){const run=e=>{try{return{rows:e()}}catch(e){return{rows:[],error:formatErrorMessage(e)}}};let n;try{return searchIndependentBranches(e,t)}catch{n={body:run(()=>searchBody(e,t.body)),path:run(()=>searchPaths(e,t.path))}}let{body:r}=n;const{path:i}=n;if(!r.rows.length&&!i.rows.length&&!r.error&&!i.error)r=run(()=>searchBody(e,t.body,true));return{body:r,path:i}}
//!extensions/memory-core/src/memory/manager-status-presence.ts
const MEMORY_INDEX_META_KEY=`memory_index_meta_v1`;function inspectMemoryIndexPresenceInWorker(e){let t;try{t=openNodeSqliteDatabase(e,{readOnly:true});admitSqliteSchema(t);const n=[{meta:MEMORY_INDEX_META_TABLE,sources:MEMORY_INDEX_SOURCES_TABLE,chunks:MEMORY_INDEX_CHUNKS_TABLE},{meta:`meta`,sources:`files`,chunks:`chunks`}];for(const e of n){if(tableExists(t,e.meta)&&t.prepare(`SELECT 1 AS ok FROM ${e.meta} WHERE key = ? LIMIT 1`).get(MEMORY_INDEX_META_KEY))return true;for(const n of[e.sources,e.chunks])if(tableExists(t,n)&&t.prepare(`SELECT 1 AS ok FROM ${n} LIMIT 1`).get())return true}return false}catch{return false}finally{try{t?.close()}catch{}}}
//!extensions/memory-core/src/memory/manager-search.worker.ts
async function executeMemorySearchWorkerQuery(e,t){if(isPostgresSqlConnection(e))return t.kind===`vector`?{kind:`vector`,rows:await searchPostgresMemoryVector(e,t.query)}:{kind:`keyword`,...await searchPostgresMemoryKeyword(e,t.query)};const n=e;return t.kind===`vector`?{kind:`vector`,rows:await searchChunksByEmbedding({...t.query,db:n})}:{kind:`keyword`,...await searchKeywordWithFallback({...t.query,db:n})}}serveWorkerTasks(async e=>{const t=e;if(t.kind===`prewarm`)return{kind:`prewarm`};if(t.kind===`presence`){if(getDatabaseEngineSelection()?.effectiveEngines.agent===`postgres`){const e=withOpenClawAgentDatabaseReadOnly(({db:e})=>{if(!tableExists(e,`memory_index_state`))return false;const t=readMemoryDatabaseFacts(e);return t.meta!==null||t.hasIndexedChunks||Boolean(e.prepare(`SELECT 1 FROM memory_index_sources LIMIT 1`).get())},{agentId:t.agentId??`main`,path:t.databasePath});return{kind:`presence`,present:e.found&&e.value}}return{kind:`presence`,present:inspectMemoryIndexPresenceInWorker(t.databasePath)}}if(t.kind===`forget-index-plan`)return{kind:t.kind,plan:await readMemoryForgetIndexInWorker(t)};if(t.kind===`origin-rows`||t.kind===`session-tombstones`)return readMemoryOriginsInWorker(t);if(t.kind===`recall-metadata`){const e=withOpenClawAgentDatabaseReadOnly(({db:e})=>readMemoryRecallData(e,t),{agentId:t.agentId,path:t.databasePath});if(!e.found)throw new Error(`Memory search database unavailable: ${e.reason}`);return{kind:`recall-metadata`,...e.value}}const n={agentId:t.agentId,path:t.databasePath};const r=t.kind===`vector-load`?openOpenClawAgentDatabaseReadOnly(n,{allowExtension:true}):retainOpenClawAgentDatabaseReadOnly(n);if(!r.found){if(r.reason===`database-missing`&&t.kind===`admission`)return{kind:`admission`,admission:{hasIndex:false,ftsAvailable:false}};if(r.reason===`database-missing`&&t.kind===`status`)return{kind:`status`,snapshot:collectMemoryStatusSnapshot(void 0,t.databasePath,t.query)};if(r.reason===`database-missing`&&(t.kind===`index-state`||t.kind===`keyword`&&t.includeIndexState)){const e={meta:null,hasIndexedChunks:false,hasFtsContent:false,vectorState:{state:`empty`}};return t.kind===`index-state`?{kind:`index-state`,state:e}:{kind:`keyword`,indexState:e,body:{rows:[]},path:{rows:[]}}}throw new Error(`Memory search database unavailable: ${r.reason}`)}try{const e=r.database.db;if(t.kind===`admission`||t.kind===`status`){const n=getAdmittedSqliteSchemaFacts(e);const i=isPostgresSqlConnection(e);if(!n&&!i)throw new Error(`Memory reader requires admitted schema facts`);const a=tableExists(e,MEMORY_INDEX_STATE_TABLE);if(t.kind===`admission`)return{kind:`admission`,admission:{hasIndex:a,...i?{engine:`postgres`}:{},ftsAvailable:a&&(i?tableHasColumn(e,`memory_index_chunks`,`openclaw_search`):n.tables.has(`memory_index_chunks_fts`)),facts:a?readMemoryDatabaseFacts(e):void 0,identity:readOpenClawAgentDatabaseIdentity(r.database)}};return{kind:`status`,snapshot:collectMemoryStatusSnapshot(a?e:void 0,t.databasePath,t.query)}}if(t.kind===`vector-load`){if(isPostgresSqlConnection(e))return{kind:`vector-load`,result:{ok:true}};return{kind:`vector-load`,result:await loadSqliteVecExtension({db:e,extensionPath:t.extensionPath})}}if(t.kind===`index-read`)return{kind:`index-read`,read:readMemoryIndex(e,t.command)};if(t.kind===`index-state`)return{kind:`index-state`,state:readMemoryRetrievalIndexState(e)};if(t.kind===`curated`){const n=t.checkProvenanceRepair&&executeSqliteQuerySync(e,getNodeSqliteKysely(e).selectFrom(`memory_index_sources`).select(`hash`).where(`source`,`=`,`memory`).where(`hash`,`=`,``).limit(1)).rows.length>0;return{kind:`curated`,provenanceRepairPending:n,rows:n?[]:t.projectsOnly?readCuratedProjectMemoryCandidates(e,t.limit,t.activeProjectKeys??[]):readCuratedMemoryTriggerCandidates(e,t.limit,t.activeProjectKeys)}}if(t.kind===`vector`)try{return await executeMemorySearchWorkerQuery(e,t)}catch(e){if(e instanceof DatabaseSearchCapabilityUnavailableError)return{kind:`vector`,rows:[],capabilityError:{capability:e.capability,message:e.message}};throw e}const n=t.includeIndexState?readMemoryRetrievalIndexState(e):void 0;const{body:i,path:a}=await executeMemorySearchWorkerQuery(e,t);const o=t.query.includeRecallMetadata?readMemoryRecallData(e,{candidates:[...i.rows,...a.rows],includeMemoryMtimes:false}):void 0;return{kind:`keyword`,body:i,path:a,...n?{indexState:n}:{},...o?{recallData:o}:{}}}finally{if(`claim`in r)r.claim.release();else r.database.close()}});export{executeMemorySearchWorkerQuery as t};