openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
26 lines • 23.5 kB
JavaScript
import{b as uniqueStrings,f as normalizeStringEntries,p as normalizeStringEntriesLower}from"./string-normalization-D_oBUpO3.mjs";import{t as escapeRegExp}from"./regexp-DAJp1ywh.mjs";import{n as isPostgresSqlConnection}from"./sql-connection-nx8lLUJM.mjs";import{g as CompiledQuery,i as executeSqliteQuerySync,s as getNodeSqliteKysely}from"./kysely-sync-R08Pt8qn.mjs";import{a as tableExists}from"./openclaw-state-db-schema-helpers-rYTimzjJ.mjs";import{i as admitStoreSearch}from"./adapters-qs4MJmRJ.mjs";import"./string-coerce-runtime-BYDH9Quw.mjs";import"./text-utility-runtime-CDtGqkrl.mjs";import{t as extractKeywords}from"./query-expansion-C2PfJEXU.mjs";import"./memory-core-host-engine-knn-D4D2JBXP.mjs";import"./memory-core-host-engine-storage-DWADN4Bs.mjs";import"./sqlite-worker-runtime-D6xJvxBF.mjs";import{t as readMemoryEmbeddingRefusal}from"./manager-index-metadata-BEYbHt4P.mjs";import{a as buildMemoryModelFilter,i as buildSqliteMemorySourceFilter,o as projectMemorySearchRow,r as buildMemorySourceFilter,s as resolveSnippetProjection}from"./manager-search-knn-DEqAwJ_e.mjs";import"./database-engine-worker-runtime-DKHBfBN5.mjs";import fs from"node:fs";import{setImmediate}from"node:timers/promises";
//!extensions/memory-core/src/memory/keyword-query.ts
function tokenizeFtsQuery(e,t=false){const n=t?/[\p{L}\p{M}\p{N}_]+/gu:/[\p{L}\p{N}_][\p{L}\p{M}\p{N}_]*/gu;return normalizeStringEntries(e.match(n)??[])}function simpleCaseFold(e){const t=e.toUpperCase();const n=Array.from(t).length===1?t.toLowerCase():e.toLowerCase();return Array.from(n).length===1?n:e}const UNICODE61_DIACRITIC=/[\u0300-\u0304\u0306-\u030c\u030f\u0311\u031b\u0323-\u0328\u032d\u032e\u0330\u0331]/u;const UNICODE61_MARK=/* @__PURE__ */ new RegExp(`[̀-ͯ҃-҉֑-ֽֿׁ-ׂׄ-ׇׅؐ-ًؚ-ٰٟۖ-ۜ۟-ۤۧ-۪ۨ-ܑۭܰ-݊ަ-ް߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣤ-ࣾऀ-ःऺ-़ा-ॏ॑-ॗॢ-ॣঁ-ঃ়া-ৄে-ৈো-্ৗৢ-ৣਁ-ਃ਼ਾ-ੂੇ-ੈੋ-੍ੑੰ-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢ-ૣଁ-ଃ଼ା-ୄେ-ୈୋ-୍ୖ-ୗୢ-ୣஂா-ூெ-ைொ-்ௗఁ-ఃా-ౄె-ైొ-్ౕ-ౖౢ-ౣಂ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕ-ೖೢ-ೣം-ഃാ-ൄെ-ൈൊ-്ൗൢ-ൣං-ඃ්ා-ුූෘ-ෟෲ-ෳัิ-ฺ็-๎ັິ-ູົ-ຼ່-ໍ༘-༹༙༵༷༾-༿ཱ-྄྆-྇ྍ-ྗྙ-ྼ࿆ါ-ှၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏႚ-ႝ፝-፟ᜒ-᜔ᜲ-᜴ᝒ-ᝓᝲ-ᝳ឴-៓៝᠋-᠍ᢩᤠ-ᤫᤰ-᤻ᦰ-ᧀᧈ-ᧉᨗ-ᨛᩕ-ᩞ᩠-᩿᩼ᬀ-ᬄ᬴-᭄᭫-᭳ᮀ-ᮂᮡ-ᮭ᯦-᯳ᰤ-᰷᳐-᳔᳒-᳨᳭ᳲ-᳴᷀-ᷦ᷼-᷿⃐-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙〯-゚꙯-꙲ꙴ-꙽ꚟ꛰-꛱ꠂ꠆ꠋꠣ-ꠧꢀ-ꢁꢴ-꣄꣠-꣱ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀ꨩ-ꨶꩃꩌ-ꩍꩻꪰꪲ-ꪴꪷ-ꪸꪾ-꪿꫁ꫫ-ꫯꫵ-꫶ꯣ-ꯪ꯬-꯭ﬞ︀-️︠-𐇽︦𐨁-𐨃𐨅-𐨆𐨌-𐨏𐨸-𐨿𐨺𑀀-𑀂𑀸-𑁆𑂀-𑂂𑂰-𑂺𑄀-𑄂𑄧-𑄴𑆀-𑆂𑆳-𑇀𑚫-𑚷𖽑-𖽾𖾏-𖾒𝅥-𝅩𝅭-𝅲𝅻-𝆂𝆅-𝆋𝆪-𝆭𝉂-𝉄󠄀-󠇯]`,`u`);function unicode61TokenizerKey(e){let t=``;for(const n of e){if(UNICODE61_DIACRITIC.test(n))continue;if(UNICODE61_MARK.test(n)){t+=` `;continue}const e=Array.from(n.normalize(`NFD`));const r=e[0];const i=r?simpleCaseFold(r):void 0;if(e.length===2&&UNICODE61_DIACRITIC.test(e[1]??``)&&i&&/^[a-z]$/u.test(i)){t+=i;continue}t+=simpleCaseFold(n)}return t.replace(/ +/g,` `).trim()}function canonicalTermForms(e,t){if(!t)return[e];const n=/* @__PURE__ */ new Set;return[e,e.normalize(`NFC`),e.normalize(`NFD`)].filter(e=>{const r=t===`unicode61`?unicode61TokenizerKey(e):Array.from(e,simpleCaseFold).join(``);if(n.has(r))return false;n.add(r);return true})}function buildMatchQueryFromTerms(e,t,n=false){if(e.length===0)return null;const r=uniqueStrings(e).map(e=>{const n=canonicalTermForms(e,t).map(e=>({kind:`term`,text:e}));return n.length===1?n[0]:{kind:`any`,clauses:n}});return{kind:n?`any`:`all`,clauses:r}}function planKeywordSearch(e){const t=e.canonicalVariants?e.ftsTokenizer??`unicode61`:void 0;const n=tokenizeFtsQuery(e.query,e.ftsTokenizer===`trigram`&&e.includeLeadingMarks);if(e.matchAny){const key=e=>Array.from(e.normalize(`NFC`),simpleCaseFold).join(``);const t=new Set(n.map(key));const r=extractKeywords(e.query.normalize(`NFC`),e).slice(0,6);for(const e of tokenizeFtsQuery(r.join(` `)))if(!t.has(key(e))){t.add(key(e));n.push(e)}}if(e.ftsTokenizer!==`trigram`)return{matchQuery:buildMatchQueryFromTerms(n,t,e.matchAny),substringTerms:[],tokens:n};const r=[];const i=[];for(const e of n)if(canonicalTermForms(e,t).some(e=>Array.from(e).length<3))i.push(e);else r.push(e);return{matchQuery:buildMatchQueryFromTerms(r,t,e.matchAny),substringTerms:i,tokens:n}}function bm25RankToScore(e){if(!Number.isFinite(e))return 1/1e3;if(e<0){const t=-e;return t/(1+t)}return 1/(1+e)}
//!extensions/memory-core/src/memory/manager-search.ts
const EXACT_PATH_SPECIFICITY_SQL_FUNCTION=`openclaw_memory_exact_path_specificity`;const NORMALIZED_CONTAINS_SQL_FUNCTION=`openclaw_memory_normalized_contains`;function loadKeywordRowsWithFallback(e,t,n,r){if(e.matchQuery)try{return{rows:t(e.matchQuery,e.substringTerms),usedMatch:true}}catch(i){console.warn(`${r}: ${String(i)}`);return{rows:t(null,uniqueStrings([...n(),...e.substringTerms])),usedMatch:false}}return{rows:t(null,e.substringTerms),usedMatch:false}}function mergePathKeywordScores(e,t){e.pathScore=Math.max(e.pathScore,t.pathScore);e.score=Math.max(e.score,t.score);e.exactPathSpecificity=Math.max(e.exactPathSpecificity,t.exactPathSpecificity)}function comparePathKeywordSearchResults(e,t){const n=t.exactPathSpecificity-e.exactPathSpecificity;if(n!==0)return n;if(e.exactPathSpecificity===0){const n=t.pathScore-e.pathScore;if(n!==0)return n}return e.path.localeCompare(t.path)||e.startLine-t.startLine||e.id.localeCompare(t.id)}function normalizeSearchTokens(e){return normalizeStringEntriesLower(tokenizeFtsQuery(e.normalize(`NFC`)))}function literalSearchMatcher(e,t=false){const n=escapeRegExp(e.normalize(`NFC`));return new RegExp(t?`^(?:${n})$`:n,`iu`)}function scoreFallbackKeywordResult(e){const{queryMatchers:t}=e;if(t.length===0)return e.ftsScore;const n=normalizeSearchTokens(e.text);const r=new Set(n);const i=t.filter(({word:e})=>n.some(t=>e.test(t))).length;const a=i/t.length;const o=i/Math.max(r.size,1);const s=e.path.normalize(`NFC`);const c=t.reduce((e,{substring:t})=>e+(t.test(s)?.18:0),0);const l=Math.min(e.text.length/160,.18);const u=a*.45+o*.2+c+l;return(e.ftsScore+u)/(1+u)}function escapeLikePattern(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`%`,`\\%`).replaceAll(`_`,`\\_`)}function isAscii(e){return!/[^\p{ASCII}]/u.test(e)}function resolveUnicodeCandidateAnchors(e){const t=Array.from(e).find(e=>!isAscii(e));if(!t)return[];return[.../* @__PURE__ */ new Set([t,t.toLowerCase(),t.toUpperCase()])]}function normalizePathIdentifier(e){return e.trim().replaceAll(`\\`,`/`).replace(/^\.\//,``).normalize(`NFC`).toLowerCase()}function prepareExactPathMatcher(e){const t=normalizePathIdentifier(e);if(!t||t===`.`)return()=>0;const n=t.includes(`/`);return e=>{const r=normalizePathIdentifier(e);if(t===r)return 3;if(n)return 0;const i=r.split(`/`).at(-1)??r;if(t===i)return 2;const a=i.lastIndexOf(`.`);const o=a>0?i.slice(0,a):i;return t===o?1:0}}const searchSqlFunctions=/* @__PURE__ */ new WeakMap;function resolveSearchSqlFunctions(e){const t=searchSqlFunctions.get(e);if(t)return t;const n={substringMatchers:/* @__PURE__ */ new Map,matchExactPath:()=>0};e.function(NORMALIZED_CONTAINS_SQL_FUNCTION,{deterministic:true},(e,t)=>typeof e===`string`&&typeof t===`string`?Number(n.substringMatchers.get(t)?.test(e.normalize(`NFC`))===true):0);e.function(EXACT_PATH_SPECIFICITY_SQL_FUNCTION,{deterministic:true},e=>typeof e===`string`?n.matchExactPath(e):0);searchSqlFunctions.set(e,n);return n}function registerSubstringSqlFunction(e,t){resolveSearchSqlFunctions(e).substringMatchers=new Map(t.map(e=>[e,literalSearchMatcher(e)]))}function buildSubstringFilter(e,t,n=false){if(e.length===0)return``;return` AND (${e.map(()=>`${NORMALIZED_CONTAINS_SQL_FUNCTION}(${t}, ?) = 1`).join(n?` OR `:` AND `)})`}function buildExactPathCandidatePatterns(e){const t=e.trim().replaceAll(`\\`,`/`).replace(/^\.\//,``);if(!t||t===`.`)return[];const n=[t.normalize(`NFC`),t.normalize(`NFD`)];const r=new Set(n);if(!isAscii(t))for(const e of n){r.add(e.toLowerCase());r.add(e.toUpperCase())}const i=/* @__PURE__ */ new Set;for(const e of r){const n=escapeLikePattern(e);if(t.includes(`/`)){i.add(n);continue}i.add(n);i.add(`${n}.%`);i.add(`%/${n}`);i.add(`%/${n}.%`)}if(!isAscii(t)){const e=t.normalize(`NFD`).toLowerCase().match(/[a-z0-9_]+/g)?.toSorted((e,t)=>t.length-e.length)[0];if(e)i.add(`%${escapeLikePattern(e)}%`);if(t.toLowerCase()!==t.toUpperCase())for(const e of resolveUnicodeCandidateAnchors(t))i.add(`%${escapeLikePattern(e)}%`)}return[...i]}function planPathKeywordSearch(e){const t=e.ftsTokenizer===`trigram`?/* @__PURE__ */ new Set([e.query.normalize(`NFC`),e.query.normalize(`NFD`)]):/* @__PURE__ */ new Set([e.query]);const n=/* @__PURE__ */ new Set;const r=[];const addPlan=(e,t)=>{const i=JSON.stringify([t.matchQuery,t.substringTerms]);if(!n.has(i)){n.add(i);r.push({query:e,...t})}};for(const n of t)addPlan(n,planKeywordSearch({...e,query:n,includeLeadingMarks:true}));if(e.ftsTokenizer!==`trigram`)for(const t of/* @__PURE__ */ new Set([e.query.normalize(`NFC`),e.query.normalize(`NFD`)])){const e=tokenizeFtsQuery(t,true);const n=e.filter(e=>!isAscii(e));if(n.length>0)addPlan(t,{matchQuery:buildMatchQueryFromTerms(e.filter(isAscii)),substringTerms:n})}return r}async function searchKeyword(e){if(e.limit<=0)return[];const t=planKeywordSearch({query:e.query,ftsTokenizer:e.ftsTokenizer,canonicalVariants:true,matchAny:e.matchAny});if(!t.matchQuery&&t.substringTerms.length===0)return[];const n=buildSqliteMemorySourceFilter(e.sourceFilter,e.ftsTable);const r=admitStoreSearch(e.db,{text:{body:{table:e.ftsTable,fields:[`text`],hiddenRank:true}}});if(!r.fullText)throw new Error(r.diagnostics.join(`; `));const i=r.fullText;const a=r.text.body;const o=getNodeSqliteKysely(e.db);const s=i.rank(a);const c=s.value.compile(o).sql;const l=s.order===`asc`?`ASC`:`DESC`;const u=` AND EXISTS (SELECT 1 FROM memory_index_chunks c WHERE c.id = ${e.ftsTable}.id)`;const loadRows=(t,r)=>{const s=buildSubstringFilter(r,`text`,e.matchAny);if(r.length>0)registerSubstringSqlFunction(e.db,r);const d=t?i.match(a,t).compile(o):void 0;const f=d?.sql??`1=1`;const p=`id, path, source, start_line, end_line, text`;const m=`SELECT ${p}, ${c} AS rank
FROM ${e.ftsTable}
WHERE ${f}${u}${n.sql}
ORDER BY rank ${l} LIMIT +?`;const h=e.matchAny&&t&&r.length>0;const g=h?`WITH matches AS MATERIALIZED (${m}), substrings AS (
SELECT ${p}, NULL AS rank FROM ${e.ftsTable}
WHERE 1=1${s}${u}${n.sql}
AND id NOT IN (SELECT id FROM matches)
LIMIT max(0, ? - (SELECT count(*) FROM matches))
)
SELECT * FROM matches UNION ALL SELECT * FROM substrings
ORDER BY rank ${l} NULLS LAST`:`SELECT ${p}, ${t?c:`NULL`} AS rank
FROM ${e.ftsTable}
WHERE ${f}${s}${u}${n.sql}
${t?`ORDER BY rank ${l}`:``} LIMIT +?`;return executeSqliteQuerySync(e.db,{compile:()=>CompiledQuery.raw(g,[...d?.parameters??[],...h?[...n.params,e.limit]:[],...r,...n.params,e.limit])}).rows};const{rows:d,usedMatch:f}=loadKeywordRowsWithFallback(t,loadRows,()=>t.tokens,`memory search: FTS5 MATCH failed, falling back to substring search`);const p=e.boostFallbackRanking?uniqueStrings(normalizeSearchTokens(e.query)).map(e=>({word:literalSearchMatcher(e,true),substring:literalSearchMatcher(e)})):[];return d.map(t=>{const n=f&&t.rank!==null?bm25RankToScore(t.rank):0;const r=e.boostFallbackRanking?scoreFallbackKeywordResult({queryMatchers:p,path:t.path,text:t.text,ftsScore:n}):n;return Object.assign(projectMemorySearchRow(t,e.snippetMaxChars,r),{textScore:n,hasBodyMatch:true})})}async function searchPathKeyword(e){if(e.limit<=0)return[];const t=buildSqliteMemorySourceFilter(e.sourceFilter,e.pathFtsTable);const n=resolveSnippetProjection(`c.text`,e.snippetMaxChars);const r=admitStoreSearch(e.db,{text:{path:{table:e.pathFtsTable,fields:[`path`]}}});if(!r.fullText)throw new Error(r.diagnostics.join(`; `));const i=r.fullText;const a=r.text.path;const o=getNodeSqliteKysely(e.db);const s=i.rank(a);const c=s.value.compile(o).sql;const l=s.order===`asc`?`ASC`:`DESC`;const u=`${e.pathFtsTable}.path`;const d=planPathKeywordSearch({query:e.query,ftsTokenizer:e.ftsTokenizer});const f=d[0]??{query:e.query,matchQuery:null,substringTerms:[]};const p=buildSubstringFilter(f.substringTerms,u);registerSubstringSqlFunction(e.db,f.substringTerms);const m=prepareExactPathMatcher(e.query);resolveSearchSqlFunctions(e.db).matchExactPath=m;const projectPathRow=(t,n,r=m(t.path))=>Object.assign(projectMemorySearchRow(t,e.snippetMaxChars,n),{textScore:0,pathScore:n,exactPathSpecificity:r,hasBodyMatch:false});const projectFirstChunks=(e,t,r)=>`SELECT c.id, ${e}.path, ${e}.source,\n c.start_line, c.end_line, ${n.sql} AS text, ${e}.${t}\n FROM ${e}\n CROSS JOIN memory_index_chunks c INDEXED BY sqlite_autoindex_memory_index_chunks_1 ON c.id = (\n SELECT candidate.id FROM memory_index_chunks candidate INDEXED BY idx_memory_index_chunks_path_source\n WHERE candidate.path = ${e}.path\n AND candidate.source = ${e}.source\n ORDER BY candidate.start_line, candidate.end_line, candidate.id\n LIMIT 1\n )\n ORDER BY ${e}.${t} ${r}, ${e}.path ASC, ${e}.source ASC`;const h=e.exactPathLimit!==void 0;const g=Math.max(0,Math.floor(e.exactPathLimit??e.limit));const _=buildExactPathCandidatePatterns(e.query);const loadExactRows=r=>{const s=_.map(()=>`${u} LIKE (? || '') ESCAPE '\\'`).join(` OR `);const c=f.matchQuery?i.match(a,f.matchQuery).compile(o):void 0;const l=r?`candidates AS MATERIALIZED (\n SELECT ${e.pathFtsTable}.path, ${e.pathFtsTable}.source\n FROM ${e.pathFtsTable}\n WHERE ${c?.sql??`1=1`}${p}${t.sql}\n), pattern_candidates AS MATERIALIZED (\n SELECT path, source FROM candidates\n WHERE (${_.map(()=>`path LIKE (? || '') ESCAPE '\\'`).join(` OR `)})\n)`:`pattern_candidates AS MATERIALIZED (\n SELECT ${e.pathFtsTable}.path, ${e.pathFtsTable}.source\n FROM ${e.pathFtsTable}\n WHERE (${s})${t.sql}\n)`;const d=r?[...c?.parameters??[],...f.substringTerms,...t.params,..._]:[..._,...t.params];const m=`WITH ${l}, scored_paths AS MATERIALIZED (\n SELECT path, source,\n ${EXACT_PATH_SPECIFICITY_SQL_FUNCTION}(path) AS exact_path_specificity\n FROM pattern_candidates\n), exact_paths AS MATERIALIZED (\n SELECT path, source, exact_path_specificity FROM scored_paths\n WHERE exact_path_specificity > 0\n AND EXISTS (SELECT 1 FROM memory_index_chunks live\n WHERE live.path = scored_paths.path\n AND live.source = scored_paths.source)\n ORDER BY exact_path_specificity DESC, path ASC, source ASC\n LIMIT +?\n)\n`+projectFirstChunks(`exact_paths`,`exact_path_specificity`,`DESC`);return executeSqliteQuerySync(e.db,{compile:()=>CompiledQuery.raw(m,[...d,g,...n.params])}).rows};const v=isAscii(e.query)&&(f.matchQuery!==null||f.substringTerms.length>0);let y=[];if(_.length>0&&g>0)try{y=loadExactRows(v)}catch(e){if(!v)throw e;y=loadExactRows(false)}const b=y.map(e=>projectPathRow(e,0,e.exact_path_specificity));if(!d.some(e=>e.matchQuery||e.substringTerms.length>0))return b;const loadFilteredLexicalRows=(r,s,d,f)=>{const p=buildSubstringFilter(s,u);const m=r?i.match(a,r).compile(o):void 0;const h=` AND ${EXACT_PATH_SPECIFICITY_SQL_FUNCTION}(${u}) ${d===`exact`?`>`:`=`} 0`;const g=[...m?.parameters??[],...s,...t.params];const _=`WITH retained_paths AS MATERIALIZED (\n SELECT ${e.pathFtsTable}.path, ${e.pathFtsTable}.source,\n ${r?c:`0`} AS rank\n FROM ${e.pathFtsTable}\n WHERE ${m?.sql??`1=1`}${p}${t.sql}${h}\n AND EXISTS (SELECT 1 FROM memory_index_chunks live\n WHERE live.path = ${e.pathFtsTable}.path\n AND live.source = ${e.pathFtsTable}.source)\n ORDER BY rank ${l}, ${e.pathFtsTable}.path ASC, ${e.pathFtsTable}.source ASC\n LIMIT +?\n)\n`+projectFirstChunks(`retained_paths`,`rank`,l);return executeSqliteQuerySync(e.db,{compile:()=>CompiledQuery.raw(_,[...g,f,...n.params])}).rows};const loadLexicalRows=t=>{const loadPartitions=(t,n)=>{registerSubstringSqlFunction(e.db,n);return[...g>0?loadFilteredLexicalRows(t,n,`exact`,g):[],...loadFilteredLexicalRows(t,n,`non-exact`,e.limit)]};return loadKeywordRowsWithFallback(t,loadPartitions,()=>tokenizeFtsQuery(t.query,true),`memory search: path FTS5 MATCH failed, falling back to substring search`)};const x=/* @__PURE__ */ new Map;for(const e of d){if(!e.matchQuery&&e.substringTerms.length===0)continue;const{rows:t,usedMatch:n}=loadLexicalRows(e);for(const e of t){const t=projectPathRow(e,n?bm25RankToScore(e.rank):1);const r=x.get(t.id);if(!r){x.set(t.id,t);continue}mergePathKeywordScores(r,t)}}const S=new Map(b.map(e=>[e.id,e]));let C=0;for(const t of[...x.values()].toSorted(comparePathKeywordSearchResults)){const n=S.get(t.id);if(t.exactPathSpecificity>0){if(!n)continue;mergePathKeywordScores(n,t);continue}if(C>=e.limit)continue;S.set(t.id,t);C+=1}const w=h?g+e.limit:e.limit;return[...S.values()].toSorted(comparePathKeywordSearchResults).slice(0,w)}
//!extensions/memory-core/src/memory/manager-search-scorer.ts
function createEmbeddingScorer(e){const t=new Float64Array(e.length+1);let n=0;for(let r=0;r<e.length;r+=1){const i=e[r]??0;n+=i*i;t[r+1]=Math.sqrt(n)}return n=>{if(n.byteLength%8!==0)return 0;const r=new DataView(n.buffer,n.byteOffset,n.byteLength);const i=n.byteLength/8;const a=Math.min(i,e.length);let o=0;let s=0;for(let t=0;t<i;t+=1){const n=r.getFloat64(t*8,true);if(!Number.isFinite(n))return 0;if(t<a){o+=(e[t]??0)*n;s+=n*n}}const c=t[a]??0;if(c===0||s===0)return 0;return o/(c*Math.sqrt(s))}}
//!extensions/memory-core/src/memory/manager-search-vector.ts
const FALLBACK_VECTOR_BATCH_SIZE=256;function resolveProviderModels(e,t){return Array.from(/* @__PURE__ */ new Set([e,...(t??[]).filter(Boolean)]))}async function searchVector(e){if(e.queryVec.length===0||e.limit<=0)return[];e.signal?.throwIfAborted();const t=resolveProviderModels(e.providerModel,e.providerModelAliases);const n=await e.ensureVectorReady(e.queryVec.length);e.signal?.throwIfAborted();if(n){if(!e.runVectorKnn)throw new Error(`memory vector KNN subprocess is unavailable`);const n=await e.runVectorKnn({providerModels:t,queryVec:e.queryVec,limit:e.limit,snippetMaxChars:e.snippetMaxChars,sourceFilter:e.sourceFilterVec},e.signal);if(!n.fallbackScanRequired)return n.rows.map(t=>projectMemorySearchRow(t,e.snippetMaxChars,1-t.dist))}return await e.runFallback()}async function searchChunksByEmbedding(e){if(e.limit<=0||e.candidateIds?.length===0)return[];const t=resolveProviderModels(e.providerModel,e.providerModelAliases);const n=`SELECT rowid AS rowid, embedding
FROM memory_index_chunks
WHERE ${buildMemoryModelFilter(`model`,t)}${e.candidateIds?` AND id IN (${e.candidateIds.map(()=>`?`).join(`, `)})`:``}`;const r=buildSqliteMemorySourceFilter(e.sourceFilter);const i=`${r.sql}\n ORDER BY rowid ASC\n LIMIT ?`;const a=e.db.prepare(`${n}${i}`);const o=e.db.prepare(`${n} AND rowid > ?${i}`);a.setReadBigInts(true);o.setReadBigInts(true);const s=resolveSnippetProjection(`text`,e.snippetMaxChars);const c=e.db.prepare(`SELECT id, path, start_line, end_line, ${s.sql} AS text, source FROM memory_index_chunks WHERE rowid = ?`);const l=createEmbeddingScorer(e.queryVec);const u=[];let d;while(true){const n=(d===void 0?a:o).iterate(...t,...e.candidateIds??[],...d===void 0?[]:[d],...r.params,FALLBACK_VECTOR_BATCH_SIZE);let i=0;for(const t of n){i+=1;d=t.rowid;const n=l(t.embedding);const r=u.at(-1);if(Number.isFinite(n)&&(u.length<e.limit||r&&n>r.score)){const r=c.get(...s.params,t.rowid);const i=projectMemorySearchRow(r,e.snippetMaxChars,n);if(u.length<e.limit){u.push(i);if(u.length===e.limit)u.sort((e,t)=>t.score-e.score)}else{u[u.length-1]=i;u.sort((e,t)=>t.score-e.score)}}}if(i<FALLBACK_VECTOR_BATCH_SIZE)break;await setImmediate();e.signal?.throwIfAborted()}u.sort((e,t)=>t.score-e.score);return u}
//!extensions/memory-core/src/memory/manager-status-state.ts
function collectMemoryStatusSnapshot(e,t,n){const r=buildMemorySourceFilter(void 0,n.sources);const i=collectMemoryStatusAggregate({db:e,sources:n.sources,sourceFilterSql:r.sql,sourceFilterParams:r.params,includeChunkBytes:n.includeStorage});const a=n.includeStorage?collectMemoryStorageStatus(e,t):void 0;return{aggregate:i,storage:a,cacheEntries:a?.embeddingCacheEntries??(e&&n.cacheEnabled?Number(e.prepare(`SELECT COUNT(*) as c FROM memory_embedding_cache`).get()?.c??0):0),embeddingRefusal:e&&tableExists(e,`memory_index_meta`)?readMemoryEmbeddingRefusal(e):null}}function collectMemoryStorageStatus(e,t){const n=e?getNodeSqliteKysely(e).selectFrom(`memory_embedding_cache`).select(e=>[e.fn.countAll().as(`entries`),e.fn.coalesce(e.fn.sum(e.fn(`octet_length`,[`embedding`])),e.val(0)).as(`bytes`)]):void 0;const r=e&&n?executeSqliteQuerySync(e,n).rows[0]:{bytes:0,entries:0};if(e&&isPostgresSqlConnection(e)){const t=[`memory_index_sources`,`memory_index_chunks`,`memory_index_chunk_provenance`,`memory_index_chunk_recall_metadata`,`memory_index_meta`,`memory_index_state`,`memory_embedding_cache`,`memory_index_chunks_vec`].filter(t=>tableExists(e,t));const n=e.prepare(`SELECT COALESCE(SUM(pg_total_relation_size(value::regclass)), 0) AS bytes FROM json_array_elements_text(?::json)`).get(JSON.stringify(t))?.bytes;return{databaseBytes:Number(n??0),walBytes:0,reusableBytes:0,embeddingCacheBytes:r.bytes,embeddingCacheEntries:r.entries}}const i=e?Number(e.prepare(`PRAGMA page_size`).get()?.page_size):0;const a=e?Number(e.prepare(`PRAGMA freelist_count`).get()?.freelist_count):0;return{databaseBytes:fs.statSync(t,{throwIfNoEntry:false})?.size??0,walBytes:fs.statSync(`${t}-wal`,{throwIfNoEntry:false})?.size??0,reusableBytes:a*i,embeddingCacheBytes:r.bytes,embeddingCacheEntries:r.entries}}function resolveStatusProviderInfo(e){if(e.provider)return{provider:e.provider.id,model:e.provider.model,searchMode:`hybrid`};if(e.providerInitialized)return{provider:`none`,model:void 0,searchMode:`fts-only`};return{provider:e.requestedProvider,model:e.resolveConfiguredModel?.()||void 0,searchMode:`hybrid`}}function collectMemoryStatusAggregate(e){const t={files:0,chunks:0};const n={...t,...e.includeChunkBytes?{chunkBytes:0}:{}};const r=/* @__PURE__ */ new Map;const i=e.includeChunkBytes?`COALESCE(SUM(octet_length(text) + octet_length(embedding)), 0)`:`NULL`;const a=e.sourceFilterSql??``;const o=`SELECT 'files' AS kind, source, COUNT(*) as c, 0 AS bytes FROM memory_index_sources WHERE 1=1${a} GROUP BY source\nUNION ALL\nSELECT 'chunks' AS kind, source, COUNT(*) as c, ${i} AS bytes FROM memory_index_chunks WHERE 1=1${a} GROUP BY source`;const s=e.sourceFilterParams??[];const c=e.db?.prepare(o).all(...s,...s);for(const e of c??[]){const i=r.get(e.source)??{...n};i[e.kind]=e.c;t[e.kind]+=e.c;if(e.kind===`chunks`&&e.bytes!==null)i.chunkBytes=e.bytes;r.set(e.source,i)}return{...t,sourceCounts:Array.from(e.sources,e=>Object.assign({source:e,...n},r.get(e)))}}export{prepareExactPathMatcher as a,buildMatchQueryFromTerms as c,searchVector as i,planKeywordSearch as l,resolveStatusProviderInfo as n,searchKeyword as o,searchChunksByEmbedding as r,searchPathKeyword as s,collectMemoryStatusSnapshot as t,tokenizeFtsQuery as u};