@wipcomputer/memory-crystal 0.7.34-alpha.2 → 0.7.34-alpha.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/dist/bridge.js +64 -7
- package/dist/bulk-copy.js +67 -16
- package/dist/cc-hook.js +2163 -62
- package/dist/cc-poller.js +1967 -70
- package/dist/cli.js +4538 -139
- package/dist/core.js +1789 -6
- package/dist/crypto.js +153 -14
- package/dist/crystal-serve.js +64 -12
- package/dist/doctor.js +517 -52
- package/dist/dream-weaver.js +1755 -7
- package/dist/file-sync.js +407 -9
- package/dist/installer.js +840 -145
- package/dist/ldm.js +231 -16
- package/dist/mcp-server.js +1882 -17
- package/dist/migrate.js +1707 -11
- package/dist/mirror-sync.js +2052 -34
- package/dist/openclaw.js +1895 -84
- package/dist/pair.js +112 -16
- package/dist/poller.js +2275 -80
- package/dist/role.js +159 -7
- package/dist/staging.js +235 -10
- package/dist/summarize.js +142 -5
- package/package.json +3 -3
package/dist/mcp-server.js
CHANGED
|
@@ -1,27 +1,1892 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __esm = (fn, res) => function __init() {
|
|
5
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
6
|
+
};
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
// src/llm.ts
|
|
13
|
+
var llm_exports = {};
|
|
14
|
+
__export(llm_exports, {
|
|
15
|
+
detectProvider: () => detectProvider,
|
|
16
|
+
expandQuery: () => expandQuery,
|
|
17
|
+
hasSampling: () => hasSampling,
|
|
18
|
+
rerankResults: () => rerankResults,
|
|
19
|
+
setLLMCacheDb: () => setLLMCacheDb,
|
|
20
|
+
setSamplingServer: () => setSamplingServer
|
|
21
|
+
});
|
|
22
|
+
import { existsSync, readFileSync } from "fs";
|
|
23
|
+
import { join } from "path";
|
|
24
|
+
import { homedir } from "os";
|
|
25
|
+
import { execSync } from "child_process";
|
|
26
|
+
function setSamplingServer(server2) {
|
|
27
|
+
samplingServer = server2;
|
|
28
|
+
}
|
|
29
|
+
function hasSampling() {
|
|
30
|
+
return samplingServer !== null;
|
|
31
|
+
}
|
|
32
|
+
function setLLMCacheDb(db) {
|
|
33
|
+
_cacheDb = db;
|
|
34
|
+
}
|
|
35
|
+
function dbCacheGet(key) {
|
|
36
|
+
if (!_cacheDb) return null;
|
|
37
|
+
try {
|
|
38
|
+
const row = _cacheDb.prepare(
|
|
39
|
+
"SELECT result FROM llm_cache WHERE cache_key = ? AND created_at > ?"
|
|
40
|
+
).get(key, new Date(Date.now() - CACHE_TTL_DAYS * 864e5).toISOString());
|
|
41
|
+
if (row) {
|
|
42
|
+
_cacheDb.prepare("UPDATE llm_cache SET hit_count = hit_count + 1, last_hit_at = ? WHERE cache_key = ?").run((/* @__PURE__ */ new Date()).toISOString(), key);
|
|
43
|
+
return row.result;
|
|
44
|
+
}
|
|
45
|
+
} catch {
|
|
46
|
+
}
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
function dbCacheSet(key, type, query, intent, result, provider) {
|
|
50
|
+
if (!_cacheDb) return;
|
|
51
|
+
try {
|
|
52
|
+
_cacheDb.prepare(
|
|
53
|
+
"INSERT OR REPLACE INTO llm_cache (cache_key, cache_type, query, intent, result, provider, created_at, hit_count, last_hit_at) VALUES (?, ?, ?, ?, ?, ?, ?, 0, NULL)"
|
|
54
|
+
).run(key, type, query, intent || null, result, provider, (/* @__PURE__ */ new Date()).toISOString());
|
|
55
|
+
} catch {
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
function getOpSecret(itemName, fieldLabel) {
|
|
59
|
+
try {
|
|
60
|
+
const saTokenPath = join(homedir(), ".openclaw/secrets/op-sa-token");
|
|
61
|
+
if (!existsSync(saTokenPath)) return void 0;
|
|
62
|
+
const saToken = readFileSync(saTokenPath, "utf-8").trim();
|
|
63
|
+
const result = execSync(
|
|
64
|
+
`OP_SERVICE_ACCOUNT_TOKEN="${saToken}" op item get "${itemName}" --vault "Agent Secrets" --fields "${fieldLabel}" --reveal`,
|
|
65
|
+
{ encoding: "utf-8", timeout: 5e3, stdio: ["pipe", "pipe", "pipe"] }
|
|
66
|
+
).trim();
|
|
67
|
+
return result || void 0;
|
|
68
|
+
} catch {
|
|
69
|
+
return void 0;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
async function detectProvider() {
|
|
73
|
+
if (detectionDone && detectedProvider) return detectedProvider;
|
|
74
|
+
detectionDone = true;
|
|
75
|
+
if (samplingServer) {
|
|
76
|
+
detectedProvider = { provider: "sampling", baseURL: "", apiKey: "", model: "client-selected" };
|
|
77
|
+
process.stderr.write("[memory-crystal] LLM provider: MCP Sampling (via client)\n");
|
|
78
|
+
return detectedProvider;
|
|
79
|
+
}
|
|
80
|
+
try {
|
|
81
|
+
const resp = await fetch("http://localhost:18791/v1/models", { signal: AbortSignal.timeout(1e3) });
|
|
82
|
+
if (resp.ok) {
|
|
83
|
+
const data = await resp.json();
|
|
84
|
+
const model = data?.data?.[0]?.id || "default";
|
|
85
|
+
detectedProvider = { provider: "mlx", baseURL: "http://localhost:18791/v1", apiKey: "not-needed", model };
|
|
86
|
+
process.stderr.write(`[memory-crystal] LLM provider: MLX (${model})
|
|
87
|
+
`);
|
|
88
|
+
return detectedProvider;
|
|
89
|
+
}
|
|
90
|
+
} catch {
|
|
91
|
+
}
|
|
92
|
+
try {
|
|
93
|
+
const resp = await fetch("http://localhost:11434/api/tags", { signal: AbortSignal.timeout(1e3) });
|
|
94
|
+
if (resp.ok) {
|
|
95
|
+
const data = await resp.json();
|
|
96
|
+
const models = data?.models || [];
|
|
97
|
+
const embeddingOnly = ["nomic-embed-text", "mxbai-embed", "all-minilm", "snowflake-arctic-embed"];
|
|
98
|
+
const chatModel = models.find((m) => !embeddingOnly.some((e) => m.name.startsWith(e)));
|
|
99
|
+
if (chatModel) {
|
|
100
|
+
detectedProvider = { provider: "ollama", baseURL: "http://localhost:11434/v1", apiKey: "ollama", model: chatModel.name };
|
|
101
|
+
process.stderr.write(`[memory-crystal] LLM provider: Ollama (${chatModel.name})
|
|
102
|
+
`);
|
|
103
|
+
return detectedProvider;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
} catch {
|
|
107
|
+
}
|
|
108
|
+
const openaiKey = process.env.OPENAI_API_KEY || getOpSecret("OpenAI API", "api key");
|
|
109
|
+
if (openaiKey) {
|
|
110
|
+
detectedProvider = { provider: "openai", baseURL: "https://api.openai.com/v1", apiKey: openaiKey, model: "gpt-4o-mini" };
|
|
111
|
+
process.stderr.write("[memory-crystal] LLM provider: OpenAI API\n");
|
|
112
|
+
return detectedProvider;
|
|
113
|
+
}
|
|
114
|
+
const anthropicKey = process.env.ANTHROPIC_API_KEY || getOpSecret("Anthropic Auth Token - remote bunkers", "Auth Token");
|
|
115
|
+
if (anthropicKey && !anthropicKey.startsWith("sk-ant-oat")) {
|
|
116
|
+
detectedProvider = { provider: "anthropic", baseURL: "https://api.anthropic.com", apiKey: anthropicKey, model: "claude-haiku-4-5-20251001" };
|
|
117
|
+
process.stderr.write("[memory-crystal] LLM provider: Anthropic API\n");
|
|
118
|
+
return detectedProvider;
|
|
119
|
+
}
|
|
120
|
+
detectedProvider = { provider: "none", baseURL: "", apiKey: "", model: "" };
|
|
121
|
+
process.stderr.write("[memory-crystal] LLM provider: none (deep search unavailable)\n");
|
|
122
|
+
return detectedProvider;
|
|
123
|
+
}
|
|
124
|
+
async function chatComplete(config2, messages, maxTokens = 300) {
|
|
125
|
+
if (config2.provider === "sampling") {
|
|
126
|
+
return samplingComplete(messages, maxTokens);
|
|
127
|
+
}
|
|
128
|
+
if (config2.provider === "anthropic") {
|
|
129
|
+
return anthropicComplete(config2, messages, maxTokens);
|
|
130
|
+
}
|
|
131
|
+
const resp = await fetch(`${config2.baseURL}/chat/completions`, {
|
|
132
|
+
method: "POST",
|
|
133
|
+
headers: {
|
|
134
|
+
"Content-Type": "application/json",
|
|
135
|
+
"Authorization": `Bearer ${config2.apiKey}`
|
|
136
|
+
},
|
|
137
|
+
body: JSON.stringify({
|
|
138
|
+
model: config2.model,
|
|
139
|
+
messages,
|
|
140
|
+
max_tokens: maxTokens,
|
|
141
|
+
temperature: 0.7
|
|
142
|
+
})
|
|
143
|
+
});
|
|
144
|
+
if (!resp.ok) throw new Error(`LLM request failed: ${resp.status}`);
|
|
145
|
+
const data = await resp.json();
|
|
146
|
+
return data.choices?.[0]?.message?.content || "";
|
|
147
|
+
}
|
|
148
|
+
async function anthropicComplete(config2, messages, maxTokens) {
|
|
149
|
+
const systemMsg = messages.find((m) => m.role === "system");
|
|
150
|
+
const userMessages = messages.filter((m) => m.role !== "system");
|
|
151
|
+
const body = {
|
|
152
|
+
model: config2.model,
|
|
153
|
+
max_tokens: maxTokens,
|
|
154
|
+
messages: userMessages
|
|
155
|
+
};
|
|
156
|
+
if (systemMsg) body.system = systemMsg.content;
|
|
157
|
+
const resp = await fetch("https://api.anthropic.com/v1/messages", {
|
|
158
|
+
method: "POST",
|
|
159
|
+
headers: {
|
|
160
|
+
"Content-Type": "application/json",
|
|
161
|
+
"x-api-key": config2.apiKey,
|
|
162
|
+
"anthropic-version": "2023-06-01"
|
|
163
|
+
},
|
|
164
|
+
body: JSON.stringify(body)
|
|
165
|
+
});
|
|
166
|
+
if (!resp.ok) throw new Error(`Anthropic request failed: ${resp.status}`);
|
|
167
|
+
const data = await resp.json();
|
|
168
|
+
return data.content?.[0]?.text || "";
|
|
169
|
+
}
|
|
170
|
+
async function samplingComplete(messages, maxTokens) {
|
|
171
|
+
if (!samplingServer) throw new Error("MCP sampling server not set");
|
|
172
|
+
const systemMsg = messages.find((m) => m.role === "system");
|
|
173
|
+
const userMessages = messages.filter((m) => m.role !== "system");
|
|
174
|
+
const result = await samplingServer.createMessage({
|
|
175
|
+
messages: userMessages.map((m) => ({
|
|
176
|
+
role: m.role,
|
|
177
|
+
content: { type: "text", text: m.content }
|
|
178
|
+
})),
|
|
179
|
+
systemPrompt: systemMsg?.content,
|
|
180
|
+
maxTokens,
|
|
181
|
+
modelPreferences: {
|
|
182
|
+
// Request cheap, fast model (Haiku-class). We don't need Opus for query expansion.
|
|
183
|
+
costPriority: 0.9,
|
|
184
|
+
speedPriority: 0.8,
|
|
185
|
+
intelligencePriority: 0.3,
|
|
186
|
+
hints: [{ name: "haiku" }]
|
|
187
|
+
}
|
|
188
|
+
});
|
|
189
|
+
if (result?.content?.type === "text") return result.content.text;
|
|
190
|
+
if (typeof result?.content === "string") return result.content;
|
|
191
|
+
return "";
|
|
192
|
+
}
|
|
193
|
+
async function expandQuery(query, intent) {
|
|
194
|
+
const cacheKey = intent ? `expand:${query}||${intent}` : `expand:${query}`;
|
|
195
|
+
const dbCached = dbCacheGet(cacheKey);
|
|
196
|
+
if (dbCached) {
|
|
197
|
+
try {
|
|
198
|
+
return JSON.parse(dbCached);
|
|
199
|
+
} catch {
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
const cached = expansionCache.get(cacheKey);
|
|
203
|
+
if (cached) return cached;
|
|
204
|
+
const config2 = await detectProvider();
|
|
205
|
+
if (config2.provider === "none") return [];
|
|
206
|
+
try {
|
|
207
|
+
const intentContext = intent ? `
|
|
208
|
+
Query intent: ${intent}. Use this to guide your variations toward the intended domain.` : "";
|
|
209
|
+
const result = await chatComplete(config2, [
|
|
210
|
+
{ role: "system", content: EXPAND_PROMPT + intentContext },
|
|
211
|
+
{ role: "user", content: query }
|
|
212
|
+
], 300);
|
|
213
|
+
const lines = result.trim().split("\n");
|
|
214
|
+
const queryLower = query.toLowerCase();
|
|
215
|
+
const queryTerms = queryLower.replace(/[^a-z0-9\s]/g, " ").split(/\s+/).filter(Boolean);
|
|
216
|
+
const hasQueryTerm = (text) => {
|
|
217
|
+
const lower = text.toLowerCase();
|
|
218
|
+
if (queryTerms.length === 0) return true;
|
|
219
|
+
return queryTerms.some((term) => lower.includes(term));
|
|
220
|
+
};
|
|
221
|
+
const variations = lines.map((line) => {
|
|
222
|
+
const colonIdx = line.indexOf(":");
|
|
223
|
+
if (colonIdx === -1) return null;
|
|
224
|
+
const type = line.slice(0, colonIdx).trim();
|
|
225
|
+
if (type !== "lex" && type !== "vec" && type !== "hyde") return null;
|
|
226
|
+
const text = line.slice(colonIdx + 1).trim();
|
|
227
|
+
if (!text || !hasQueryTerm(text)) return null;
|
|
228
|
+
return { type, text };
|
|
229
|
+
}).filter((v) => v !== null);
|
|
230
|
+
if (variations.length > 0) {
|
|
231
|
+
expansionCache.set(cacheKey, variations);
|
|
232
|
+
dbCacheSet(cacheKey, "expansion", query, intent, JSON.stringify(variations), config2.provider);
|
|
233
|
+
return variations;
|
|
234
|
+
}
|
|
235
|
+
} catch (err) {
|
|
236
|
+
process.stderr.write(`[memory-crystal] Query expansion failed: ${err.message}
|
|
237
|
+
`);
|
|
238
|
+
}
|
|
239
|
+
const fallback = [
|
|
240
|
+
{ type: "lex", text: query },
|
|
241
|
+
{ type: "vec", text: query },
|
|
242
|
+
{ type: "hyde", text: `Information about ${query}` }
|
|
243
|
+
];
|
|
244
|
+
return fallback;
|
|
245
|
+
}
|
|
246
|
+
async function rerankResults(query, passages) {
|
|
247
|
+
const config2 = await detectProvider();
|
|
248
|
+
if (config2.provider === "none") {
|
|
249
|
+
return passages.map((_, i) => ({ index: i, score: 1 - i * 0.01 }));
|
|
250
|
+
}
|
|
251
|
+
const { createHash: createHash2 } = await import("crypto");
|
|
252
|
+
const contentHash = createHash2("sha256").update(passages.map((p) => p.slice(0, 200)).sort().join("|")).digest("hex").slice(0, 16);
|
|
253
|
+
const rerankCacheKey = `rerank:${query}||${contentHash}`;
|
|
254
|
+
const dbCachedRerank = dbCacheGet(rerankCacheKey);
|
|
255
|
+
if (dbCachedRerank) {
|
|
256
|
+
try {
|
|
257
|
+
return JSON.parse(dbCachedRerank);
|
|
258
|
+
} catch {
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
try {
|
|
262
|
+
const passageList = passages.map((p, i) => `[${i}] ${p.slice(0, 500)}`).join("\n\n");
|
|
263
|
+
const result = await chatComplete(config2, [
|
|
264
|
+
{ role: "system", content: RERANK_PROMPT },
|
|
265
|
+
{ role: "user", content: `Query: ${query}
|
|
266
|
+
|
|
267
|
+
Passages:
|
|
268
|
+
${passageList}` }
|
|
269
|
+
], 200);
|
|
270
|
+
const results = [];
|
|
271
|
+
for (const line of result.trim().split("\n")) {
|
|
272
|
+
const match = line.match(/^(\d+):\s*([\d.]+)/);
|
|
273
|
+
if (match) {
|
|
274
|
+
results.push({ index: parseInt(match[1]), score: parseFloat(match[2]) });
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
const scored = new Set(results.map((r) => r.index));
|
|
278
|
+
for (let i = 0; i < passages.length; i++) {
|
|
279
|
+
if (!scored.has(i)) results.push({ index: i, score: 0 });
|
|
280
|
+
}
|
|
281
|
+
const sorted = results.sort((a, b) => b.score - a.score);
|
|
282
|
+
dbCacheSet(rerankCacheKey, "rerank", query, void 0, JSON.stringify(sorted), config2.provider);
|
|
283
|
+
return sorted;
|
|
284
|
+
} catch (err) {
|
|
285
|
+
process.stderr.write(`[memory-crystal] Reranking failed: ${err.message}
|
|
286
|
+
`);
|
|
287
|
+
return passages.map((_, i) => ({ index: i, score: 1 - i * 0.01 }));
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
var samplingServer, expansionCache, _cacheDb, CACHE_TTL_DAYS, detectedProvider, detectionDone, EXPAND_PROMPT, RERANK_PROMPT;
|
|
291
|
+
var init_llm = __esm({
|
|
292
|
+
"src/llm.ts"() {
|
|
293
|
+
"use strict";
|
|
294
|
+
samplingServer = null;
|
|
295
|
+
expansionCache = /* @__PURE__ */ new Map();
|
|
296
|
+
_cacheDb = null;
|
|
297
|
+
CACHE_TTL_DAYS = parseInt(process.env.CRYSTAL_CACHE_TTL_DAYS || "7", 10);
|
|
298
|
+
detectedProvider = null;
|
|
299
|
+
detectionDone = false;
|
|
300
|
+
EXPAND_PROMPT = `You are a search query expander. Given a search query, generate exactly 3 variations to improve search recall.
|
|
301
|
+
|
|
302
|
+
Output exactly 3 lines in this format (no other text):
|
|
303
|
+
lex: <keyword-focused variation for full-text search>
|
|
304
|
+
vec: <semantic variation rephrased for embedding similarity>
|
|
305
|
+
hyde: <hypothetical document snippet that would answer this query>
|
|
306
|
+
|
|
307
|
+
Rules:
|
|
308
|
+
- Each variation must contain at least one term from the original query
|
|
309
|
+
- Keep variations concise (under 30 words each)
|
|
310
|
+
- lex should use specific keywords and synonyms
|
|
311
|
+
- vec should rephrase the intent naturally
|
|
312
|
+
- hyde should be a short passage as if answering the query`;
|
|
313
|
+
RERANK_PROMPT = `You are a search result re-ranker. Given a query and a list of text passages, rate each passage's relevance to the query.
|
|
314
|
+
|
|
315
|
+
Output one line per passage in this exact format:
|
|
316
|
+
<index>: <score>
|
|
317
|
+
|
|
318
|
+
Where index is the passage number (0-based) and score is a float from 0.0 to 1.0.
|
|
319
|
+
- 1.0 = perfectly relevant, directly answers the query
|
|
320
|
+
- 0.7 = highly relevant, closely related
|
|
321
|
+
- 0.4 = somewhat relevant, tangentially related
|
|
322
|
+
- 0.1 = barely relevant
|
|
323
|
+
- 0.0 = not relevant at all
|
|
324
|
+
|
|
325
|
+
Rate ALL passages. Output nothing else.`;
|
|
326
|
+
}
|
|
327
|
+
});
|
|
328
|
+
|
|
329
|
+
// src/search-pipeline.ts
|
|
330
|
+
var search_pipeline_exports = {};
|
|
331
|
+
__export(search_pipeline_exports, {
|
|
332
|
+
deepSearch: () => deepSearch
|
|
333
|
+
});
|
|
334
|
+
async function deepSearch(crystal2, query, options = {}) {
|
|
335
|
+
const limit = options.limit || 5;
|
|
336
|
+
const candidateLimit = options.candidateLimit || DEFAULT_CANDIDATE_LIMIT;
|
|
337
|
+
const intent = options.intent;
|
|
338
|
+
const filter = options.filter;
|
|
339
|
+
const explain = options.explain || false;
|
|
340
|
+
const provider = await detectProvider();
|
|
341
|
+
if (provider.provider === "none") {
|
|
342
|
+
return crystal2.search(query, limit, filter);
|
|
343
|
+
}
|
|
344
|
+
const db = crystal2.sqliteDb;
|
|
345
|
+
if (!db) return crystal2.search(query, limit, filter);
|
|
346
|
+
const sinceDate = filter?.since ? crystal2.parseSince(filter.since) : void 0;
|
|
347
|
+
const untilDate = filter?.until ? crystal2.parseSince(filter.until) : void 0;
|
|
348
|
+
const internalFilter = { ...filter, sinceDate, untilDate };
|
|
349
|
+
const initialFts = crystal2.searchFTS(query, 20, internalFilter);
|
|
350
|
+
const topScore = initialFts[0]?.score ?? 0;
|
|
351
|
+
const secondScore = initialFts[1]?.score ?? 0;
|
|
352
|
+
const hasStrongSignal = !intent && initialFts.length > 0 && topScore >= STRONG_SIGNAL_MIN_SCORE && topScore - secondScore >= STRONG_SIGNAL_MIN_GAP;
|
|
353
|
+
const expanded = hasStrongSignal ? [] : await expandQuery(query, intent);
|
|
354
|
+
const allResultLists = [];
|
|
355
|
+
if (initialFts.length > 0) allResultLists.push(initialFts);
|
|
356
|
+
const [queryEmbedding] = await crystal2.embed([query]);
|
|
357
|
+
const originalVec = crystal2.searchVec(queryEmbedding, 30, internalFilter);
|
|
358
|
+
if (originalVec.length > 0) allResultLists.push(originalVec);
|
|
359
|
+
for (const variation of expanded) {
|
|
360
|
+
if (variation.type === "lex") {
|
|
361
|
+
const ftsResults = crystal2.searchFTS(variation.text, 20, internalFilter);
|
|
362
|
+
if (ftsResults.length > 0) allResultLists.push(ftsResults);
|
|
363
|
+
} else {
|
|
364
|
+
const [embedding] = await crystal2.embed([variation.text]);
|
|
365
|
+
const vecResults = crystal2.searchVec(embedding, 20, internalFilter);
|
|
366
|
+
if (vecResults.length > 0) allResultLists.push(vecResults);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
const weights = allResultLists.map((_, i) => i < 2 ? 2 : 1);
|
|
370
|
+
const fused = crystal2.reciprocalRankFusion(allResultLists, weights);
|
|
371
|
+
const candidates = fused.slice(0, candidateLimit);
|
|
372
|
+
if (candidates.length === 0) return [];
|
|
373
|
+
const ftsScoreMap = /* @__PURE__ */ new Map();
|
|
374
|
+
const vecScoreMap = /* @__PURE__ */ new Map();
|
|
375
|
+
if (explain) {
|
|
376
|
+
for (const r of initialFts) ftsScoreMap.set(r.text.slice(0, 200), r.score);
|
|
377
|
+
for (const r of originalVec) vecScoreMap.set(r.text.slice(0, 200), r.score);
|
|
378
|
+
}
|
|
379
|
+
const passages = candidates.map((c) => c.text.slice(0, 500));
|
|
380
|
+
const rerankQuery = intent ? `${intent}: ${query}` : query;
|
|
381
|
+
const reranked = await rerankResults(rerankQuery, passages);
|
|
382
|
+
const now = Date.now();
|
|
383
|
+
const blended = reranked.map((r) => {
|
|
384
|
+
const candidate = candidates[r.index];
|
|
385
|
+
if (!candidate) return null;
|
|
386
|
+
const rrfRank = r.index + 1;
|
|
387
|
+
let rrfWeight;
|
|
388
|
+
if (rrfRank <= 3) rrfWeight = 0.75;
|
|
389
|
+
else if (rrfRank <= 10) rrfWeight = 0.6;
|
|
390
|
+
else rrfWeight = 0.4;
|
|
391
|
+
const rrfScore = 1 / rrfRank;
|
|
392
|
+
const blendedScore = rrfWeight * rrfScore + (1 - rrfWeight) * r.score;
|
|
393
|
+
const ageDays = candidate.created_at ? (now - new Date(candidate.created_at).getTime()) / 864e5 : 0;
|
|
394
|
+
const recency = candidate.created_at ? crystal2.recencyWeight(ageDays) : 1;
|
|
395
|
+
const finalScore = blendedScore * recency;
|
|
396
|
+
const freshness = candidate.created_at ? crystal2.freshnessLabel(ageDays) : void 0;
|
|
397
|
+
const result = {
|
|
398
|
+
...candidate,
|
|
399
|
+
score: finalScore,
|
|
400
|
+
freshness
|
|
401
|
+
};
|
|
402
|
+
if (explain) {
|
|
403
|
+
const dedup = candidate.text.slice(0, 200);
|
|
404
|
+
result.explain = {
|
|
405
|
+
fts_score: ftsScoreMap.get(dedup),
|
|
406
|
+
vec_score: vecScoreMap.get(dedup),
|
|
407
|
+
rrf_rank: rrfRank,
|
|
408
|
+
rrf_score: rrfScore,
|
|
409
|
+
rerank_score: r.score,
|
|
410
|
+
recency_weight: recency,
|
|
411
|
+
final_score: finalScore
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
return result;
|
|
415
|
+
}).filter((r) => r !== null);
|
|
416
|
+
const sorted = blended.sort((a, b) => b.score - a.score).slice(0, limit);
|
|
417
|
+
const topNormScore = sorted[0]?.score || 1;
|
|
418
|
+
return sorted.map((r) => ({ ...r, score: Math.min(r.score / topNormScore * 0.95, 0.95) }));
|
|
419
|
+
}
|
|
420
|
+
var STRONG_SIGNAL_MIN_SCORE, STRONG_SIGNAL_MIN_GAP, DEFAULT_CANDIDATE_LIMIT;
|
|
421
|
+
var init_search_pipeline = __esm({
|
|
422
|
+
"src/search-pipeline.ts"() {
|
|
423
|
+
"use strict";
|
|
424
|
+
init_llm();
|
|
425
|
+
STRONG_SIGNAL_MIN_SCORE = 0.85;
|
|
426
|
+
STRONG_SIGNAL_MIN_GAP = 0.15;
|
|
427
|
+
DEFAULT_CANDIDATE_LIMIT = 40;
|
|
428
|
+
}
|
|
429
|
+
});
|
|
14
430
|
|
|
15
431
|
// src/mcp-server.ts
|
|
16
432
|
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
17
433
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
18
434
|
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
19
|
-
|
|
435
|
+
|
|
436
|
+
// src/core.ts
|
|
437
|
+
import * as lancedb from "@lancedb/lancedb";
|
|
438
|
+
import Database from "better-sqlite3";
|
|
439
|
+
import * as sqliteVec from "sqlite-vec";
|
|
440
|
+
import { readFileSync as readFileSync2, existsSync as existsSync2, mkdirSync, readdirSync, statSync } from "fs";
|
|
441
|
+
import { execSync as execSync2 } from "child_process";
|
|
442
|
+
import { join as join2, relative, extname, basename } from "path";
|
|
443
|
+
import { createHash } from "crypto";
|
|
444
|
+
import http from "http";
|
|
445
|
+
import https from "https";
|
|
446
|
+
async function embedOpenAI(texts, apiKey, model) {
|
|
447
|
+
return new Promise((resolve, reject) => {
|
|
448
|
+
const body = JSON.stringify({ input: texts, model });
|
|
449
|
+
const req = https.request({
|
|
450
|
+
hostname: "api.openai.com",
|
|
451
|
+
path: "/v1/embeddings",
|
|
452
|
+
method: "POST",
|
|
453
|
+
headers: {
|
|
454
|
+
"Content-Type": "application/json",
|
|
455
|
+
"Authorization": `Bearer ${apiKey}`,
|
|
456
|
+
"Content-Length": Buffer.byteLength(body)
|
|
457
|
+
},
|
|
458
|
+
timeout: 3e4
|
|
459
|
+
}, (res) => {
|
|
460
|
+
let data = "";
|
|
461
|
+
res.on("data", (chunk) => data += chunk);
|
|
462
|
+
res.on("end", () => {
|
|
463
|
+
if (res.statusCode !== 200) {
|
|
464
|
+
reject(new Error(`OpenAI API error ${res.statusCode}: ${data.slice(0, 200)}`));
|
|
465
|
+
return;
|
|
466
|
+
}
|
|
467
|
+
const parsed = JSON.parse(data);
|
|
468
|
+
resolve(parsed.data.map((d) => d.embedding));
|
|
469
|
+
});
|
|
470
|
+
});
|
|
471
|
+
req.on("error", reject);
|
|
472
|
+
req.on("timeout", () => {
|
|
473
|
+
req.destroy();
|
|
474
|
+
reject(new Error("OpenAI timeout"));
|
|
475
|
+
});
|
|
476
|
+
req.write(body);
|
|
477
|
+
req.end();
|
|
478
|
+
});
|
|
479
|
+
}
|
|
480
|
+
async function embedOllama(texts, host, model) {
|
|
481
|
+
const results = [];
|
|
482
|
+
for (const text of texts) {
|
|
483
|
+
const result = await new Promise((resolve, reject) => {
|
|
484
|
+
const url = new URL("/api/embeddings", host);
|
|
485
|
+
const body = JSON.stringify({ model, prompt: text });
|
|
486
|
+
const req = http.request({
|
|
487
|
+
hostname: url.hostname,
|
|
488
|
+
port: url.port,
|
|
489
|
+
path: url.pathname,
|
|
490
|
+
method: "POST",
|
|
491
|
+
headers: {
|
|
492
|
+
"Content-Type": "application/json",
|
|
493
|
+
"Content-Length": Buffer.byteLength(body)
|
|
494
|
+
},
|
|
495
|
+
timeout: 15e3
|
|
496
|
+
}, (res) => {
|
|
497
|
+
let data = "";
|
|
498
|
+
res.on("data", (chunk) => data += chunk);
|
|
499
|
+
res.on("end", () => {
|
|
500
|
+
if (res.statusCode !== 200) {
|
|
501
|
+
reject(new Error(`Ollama error ${res.statusCode}: ${data.slice(0, 200)}`));
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
resolve(JSON.parse(data).embedding);
|
|
505
|
+
});
|
|
506
|
+
});
|
|
507
|
+
req.on("error", reject);
|
|
508
|
+
req.on("timeout", () => {
|
|
509
|
+
req.destroy();
|
|
510
|
+
reject(new Error("Ollama timeout"));
|
|
511
|
+
});
|
|
512
|
+
req.write(body);
|
|
513
|
+
req.end();
|
|
514
|
+
});
|
|
515
|
+
results.push(result);
|
|
516
|
+
}
|
|
517
|
+
return results;
|
|
518
|
+
}
|
|
519
|
+
async function embedGoogle(texts, apiKey, model) {
|
|
520
|
+
return new Promise((resolve, reject) => {
|
|
521
|
+
const body = JSON.stringify({
|
|
522
|
+
requests: texts.map((text) => ({ model: `models/${model}`, content: { parts: [{ text }] } }))
|
|
523
|
+
});
|
|
524
|
+
const req = https.request({
|
|
525
|
+
hostname: "generativelanguage.googleapis.com",
|
|
526
|
+
path: `/v1beta/models/${model}:batchEmbedContents?key=${apiKey}`,
|
|
527
|
+
method: "POST",
|
|
528
|
+
headers: {
|
|
529
|
+
"Content-Type": "application/json",
|
|
530
|
+
"Content-Length": Buffer.byteLength(body)
|
|
531
|
+
},
|
|
532
|
+
timeout: 3e4
|
|
533
|
+
}, (res) => {
|
|
534
|
+
let data = "";
|
|
535
|
+
res.on("data", (chunk) => data += chunk);
|
|
536
|
+
res.on("end", () => {
|
|
537
|
+
if (res.statusCode !== 200) {
|
|
538
|
+
reject(new Error(`Google API error ${res.statusCode}: ${data.slice(0, 200)}`));
|
|
539
|
+
return;
|
|
540
|
+
}
|
|
541
|
+
const parsed = JSON.parse(data);
|
|
542
|
+
resolve(parsed.embeddings.map((e) => e.values));
|
|
543
|
+
});
|
|
544
|
+
});
|
|
545
|
+
req.on("error", reject);
|
|
546
|
+
req.on("timeout", () => {
|
|
547
|
+
req.destroy();
|
|
548
|
+
reject(new Error("Google timeout"));
|
|
549
|
+
});
|
|
550
|
+
req.write(body);
|
|
551
|
+
req.end();
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
var Crystal = class _Crystal {
|
|
555
|
+
config;
|
|
556
|
+
lanceDb = null;
|
|
557
|
+
sqliteDb = null;
|
|
558
|
+
chunksTable = null;
|
|
559
|
+
vecDimensions = null;
|
|
560
|
+
constructor(config2) {
|
|
561
|
+
this.config = config2;
|
|
562
|
+
if (!existsSync2(config2.dataDir)) {
|
|
563
|
+
mkdirSync(config2.dataDir, { recursive: true });
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
// ── Initialization ──
|
|
567
|
+
async init() {
|
|
568
|
+
const lanceDir = join2(this.config.dataDir, "lance");
|
|
569
|
+
const sqlitePath = join2(this.config.dataDir, "crystal.db");
|
|
570
|
+
if (!existsSync2(lanceDir)) mkdirSync(lanceDir, { recursive: true });
|
|
571
|
+
this.lanceDb = await lancedb.connect(lanceDir);
|
|
572
|
+
this.sqliteDb = new Database(sqlitePath);
|
|
573
|
+
this.sqliteDb.pragma("journal_mode = WAL");
|
|
574
|
+
sqliteVec.load(this.sqliteDb);
|
|
575
|
+
this.initSqliteTables();
|
|
576
|
+
this.initChunksTables();
|
|
577
|
+
await this.initLanceTables();
|
|
578
|
+
}
|
|
579
|
+
initSqliteTables() {
|
|
580
|
+
const db = this.sqliteDb;
|
|
581
|
+
db.exec(`
|
|
582
|
+
CREATE TABLE IF NOT EXISTS sources (
|
|
583
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
584
|
+
type TEXT NOT NULL,
|
|
585
|
+
uri TEXT NOT NULL,
|
|
586
|
+
title TEXT,
|
|
587
|
+
agent_id TEXT NOT NULL,
|
|
588
|
+
metadata TEXT DEFAULT '{}',
|
|
589
|
+
ingested_at TEXT NOT NULL,
|
|
590
|
+
chunk_count INTEGER DEFAULT 0
|
|
591
|
+
);
|
|
592
|
+
|
|
593
|
+
CREATE TABLE IF NOT EXISTS capture_state (
|
|
594
|
+
agent_id TEXT NOT NULL,
|
|
595
|
+
source_id TEXT NOT NULL,
|
|
596
|
+
last_message_count INTEGER DEFAULT 0,
|
|
597
|
+
capture_count INTEGER DEFAULT 0,
|
|
598
|
+
last_capture_at TEXT,
|
|
599
|
+
PRIMARY KEY (agent_id, source_id)
|
|
600
|
+
);
|
|
601
|
+
|
|
602
|
+
CREATE TABLE IF NOT EXISTS memories (
|
|
603
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
604
|
+
text TEXT NOT NULL,
|
|
605
|
+
category TEXT NOT NULL DEFAULT 'fact',
|
|
606
|
+
confidence REAL NOT NULL DEFAULT 1.0,
|
|
607
|
+
source_ids TEXT DEFAULT '[]',
|
|
608
|
+
status TEXT NOT NULL DEFAULT 'active',
|
|
609
|
+
created_at TEXT NOT NULL,
|
|
610
|
+
updated_at TEXT NOT NULL
|
|
611
|
+
);
|
|
612
|
+
|
|
613
|
+
CREATE TABLE IF NOT EXISTS entities (
|
|
614
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
615
|
+
name TEXT NOT NULL UNIQUE,
|
|
616
|
+
type TEXT NOT NULL DEFAULT 'concept',
|
|
617
|
+
description TEXT,
|
|
618
|
+
properties TEXT DEFAULT '{}',
|
|
619
|
+
created_at TEXT NOT NULL,
|
|
620
|
+
updated_at TEXT NOT NULL
|
|
621
|
+
);
|
|
622
|
+
|
|
623
|
+
CREATE TABLE IF NOT EXISTS relationships (
|
|
624
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
625
|
+
source_id INTEGER NOT NULL REFERENCES entities(id),
|
|
626
|
+
target_id INTEGER NOT NULL REFERENCES entities(id),
|
|
627
|
+
type TEXT NOT NULL,
|
|
628
|
+
description TEXT,
|
|
629
|
+
weight REAL DEFAULT 1.0,
|
|
630
|
+
valid_from TEXT NOT NULL,
|
|
631
|
+
valid_until TEXT,
|
|
632
|
+
created_at TEXT NOT NULL
|
|
633
|
+
);
|
|
634
|
+
|
|
635
|
+
CREATE INDEX IF NOT EXISTS idx_sources_agent ON sources(agent_id);
|
|
636
|
+
CREATE INDEX IF NOT EXISTS idx_memories_status ON memories(status);
|
|
637
|
+
CREATE INDEX IF NOT EXISTS idx_entities_name ON entities(name);
|
|
638
|
+
CREATE INDEX IF NOT EXISTS idx_relationships_source ON relationships(source_id);
|
|
639
|
+
CREATE INDEX IF NOT EXISTS idx_relationships_target ON relationships(target_id);
|
|
640
|
+
|
|
641
|
+
-- LLM cache (persistent expansion + reranking results)
|
|
642
|
+
CREATE TABLE IF NOT EXISTS llm_cache (
|
|
643
|
+
cache_key TEXT PRIMARY KEY,
|
|
644
|
+
cache_type TEXT NOT NULL,
|
|
645
|
+
query TEXT NOT NULL,
|
|
646
|
+
intent TEXT,
|
|
647
|
+
result TEXT NOT NULL,
|
|
648
|
+
provider TEXT NOT NULL,
|
|
649
|
+
created_at TEXT NOT NULL,
|
|
650
|
+
hit_count INTEGER DEFAULT 0,
|
|
651
|
+
last_hit_at TEXT
|
|
652
|
+
);
|
|
653
|
+
CREATE INDEX IF NOT EXISTS idx_llm_cache_type ON llm_cache(cache_type);
|
|
654
|
+
CREATE INDEX IF NOT EXISTS idx_llm_cache_created ON llm_cache(created_at);
|
|
655
|
+
|
|
656
|
+
-- Source file indexing (optional feature)
|
|
657
|
+
CREATE TABLE IF NOT EXISTS source_collections (
|
|
658
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
659
|
+
name TEXT NOT NULL UNIQUE,
|
|
660
|
+
root_path TEXT NOT NULL,
|
|
661
|
+
glob_patterns TEXT NOT NULL DEFAULT '["**/*"]',
|
|
662
|
+
ignore_patterns TEXT NOT NULL DEFAULT '[]',
|
|
663
|
+
file_count INTEGER DEFAULT 0,
|
|
664
|
+
chunk_count INTEGER DEFAULT 0,
|
|
665
|
+
last_sync_at TEXT,
|
|
666
|
+
created_at TEXT NOT NULL
|
|
667
|
+
);
|
|
668
|
+
|
|
669
|
+
CREATE TABLE IF NOT EXISTS source_files (
|
|
670
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
671
|
+
collection_id INTEGER NOT NULL REFERENCES source_collections(id) ON DELETE CASCADE,
|
|
672
|
+
file_path TEXT NOT NULL,
|
|
673
|
+
file_hash TEXT NOT NULL,
|
|
674
|
+
file_size INTEGER NOT NULL,
|
|
675
|
+
chunk_count INTEGER DEFAULT 0,
|
|
676
|
+
last_indexed_at TEXT NOT NULL
|
|
677
|
+
);
|
|
678
|
+
|
|
679
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_source_files_path ON source_files(collection_id, file_path);
|
|
680
|
+
CREATE INDEX IF NOT EXISTS idx_source_files_collection ON source_files(collection_id);
|
|
681
|
+
`);
|
|
682
|
+
}
|
|
683
|
+
initChunksTables() {
|
|
684
|
+
const db = this.sqliteDb;
|
|
685
|
+
db.exec(`
|
|
686
|
+
CREATE TABLE IF NOT EXISTS chunks (
|
|
687
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
688
|
+
text TEXT NOT NULL,
|
|
689
|
+
text_hash TEXT NOT NULL,
|
|
690
|
+
role TEXT,
|
|
691
|
+
source_type TEXT,
|
|
692
|
+
source_id TEXT,
|
|
693
|
+
agent_id TEXT,
|
|
694
|
+
token_count INTEGER,
|
|
695
|
+
created_at TEXT NOT NULL
|
|
696
|
+
);
|
|
697
|
+
|
|
698
|
+
CREATE INDEX IF NOT EXISTS idx_chunks_agent ON chunks(agent_id);
|
|
699
|
+
CREATE INDEX IF NOT EXISTS idx_chunks_source ON chunks(source_type);
|
|
700
|
+
CREATE INDEX IF NOT EXISTS idx_chunks_hash ON chunks(text_hash);
|
|
701
|
+
CREATE INDEX IF NOT EXISTS idx_chunks_created ON chunks(created_at);
|
|
702
|
+
|
|
703
|
+
-- FTS5 full-text search table
|
|
704
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5(
|
|
705
|
+
text,
|
|
706
|
+
tokenize='porter unicode61'
|
|
707
|
+
);
|
|
708
|
+
|
|
709
|
+
-- Sync trigger: populate FTS on chunk insert
|
|
710
|
+
CREATE TRIGGER IF NOT EXISTS chunks_fts_insert AFTER INSERT ON chunks
|
|
711
|
+
BEGIN
|
|
712
|
+
INSERT INTO chunks_fts(rowid, text) VALUES (NEW.id, NEW.text);
|
|
713
|
+
END;
|
|
714
|
+
|
|
715
|
+
-- Sync trigger: clean up FTS and vec on chunk delete
|
|
716
|
+
CREATE TRIGGER IF NOT EXISTS chunks_cleanup AFTER DELETE ON chunks
|
|
717
|
+
BEGIN
|
|
718
|
+
DELETE FROM chunks_vec WHERE chunk_id = OLD.id;
|
|
719
|
+
INSERT INTO chunks_fts(chunks_fts, rowid, text) VALUES('delete', OLD.id, OLD.text);
|
|
720
|
+
END;
|
|
721
|
+
`);
|
|
722
|
+
const vecTable = db.prepare(
|
|
723
|
+
`SELECT name FROM sqlite_master WHERE type='table' AND name='chunks_vec'`
|
|
724
|
+
).get();
|
|
725
|
+
if (vecTable) {
|
|
726
|
+
try {
|
|
727
|
+
const row = db.prepare("SELECT embedding FROM chunks_vec LIMIT 1").get();
|
|
728
|
+
if (row?.embedding) {
|
|
729
|
+
this.vecDimensions = row.embedding.length / 4;
|
|
730
|
+
}
|
|
731
|
+
} catch {
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
ensureVecTable(dimensions) {
|
|
736
|
+
const db = this.sqliteDb;
|
|
737
|
+
const existing = db.prepare(
|
|
738
|
+
`SELECT name FROM sqlite_master WHERE type='table' AND name='chunks_vec'`
|
|
739
|
+
).get();
|
|
740
|
+
if (!existing) {
|
|
741
|
+
db.exec(`
|
|
742
|
+
CREATE VIRTUAL TABLE chunks_vec USING vec0(
|
|
743
|
+
chunk_id INTEGER PRIMARY KEY,
|
|
744
|
+
embedding float[${dimensions}] distance_metric=cosine
|
|
745
|
+
);
|
|
746
|
+
`);
|
|
747
|
+
}
|
|
748
|
+
this.vecDimensions = dimensions;
|
|
749
|
+
}
|
|
750
|
+
async initLanceTables() {
|
|
751
|
+
const db = this.lanceDb;
|
|
752
|
+
const tableNames = await db.tableNames();
|
|
753
|
+
if (tableNames.includes("chunks")) {
|
|
754
|
+
this.chunksTable = await db.openTable("chunks");
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
// ── Embedding ──
|
|
758
|
+
async embed(texts) {
|
|
759
|
+
if (texts.length === 0) return [];
|
|
760
|
+
const cfg = this.config;
|
|
761
|
+
switch (cfg.embeddingProvider) {
|
|
762
|
+
case "openai": {
|
|
763
|
+
if (!cfg.openaiApiKey) throw new Error("OpenAI API key required");
|
|
764
|
+
const model = cfg.openaiModel || "text-embedding-3-small";
|
|
765
|
+
const maxCharsPerBatch = 8e5;
|
|
766
|
+
const results = [];
|
|
767
|
+
let batch = [];
|
|
768
|
+
let batchChars = 0;
|
|
769
|
+
for (const text of texts) {
|
|
770
|
+
if (batchChars + text.length > maxCharsPerBatch && batch.length > 0) {
|
|
771
|
+
results.push(...await embedOpenAI(batch, cfg.openaiApiKey, model));
|
|
772
|
+
batch = [];
|
|
773
|
+
batchChars = 0;
|
|
774
|
+
}
|
|
775
|
+
batch.push(text);
|
|
776
|
+
batchChars += text.length;
|
|
777
|
+
}
|
|
778
|
+
if (batch.length > 0) {
|
|
779
|
+
results.push(...await embedOpenAI(batch, cfg.openaiApiKey, model));
|
|
780
|
+
}
|
|
781
|
+
return results;
|
|
782
|
+
}
|
|
783
|
+
case "ollama":
|
|
784
|
+
return embedOllama(texts, cfg.ollamaHost || "http://localhost:11434", cfg.ollamaModel || "nomic-embed-text");
|
|
785
|
+
case "google":
|
|
786
|
+
if (!cfg.googleApiKey) throw new Error("Google API key required");
|
|
787
|
+
return embedGoogle(texts, cfg.googleApiKey, cfg.googleModel || "text-embedding-004");
|
|
788
|
+
default:
|
|
789
|
+
throw new Error(`Unknown embedding provider: ${cfg.embeddingProvider}`);
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
// ── Chunking ──
|
|
793
|
+
chunkText(text, targetTokens = 400, overlapTokens = 80) {
|
|
794
|
+
const targetChars = targetTokens * 4;
|
|
795
|
+
const overlapChars = overlapTokens * 4;
|
|
796
|
+
const chunks = [];
|
|
797
|
+
let start = 0;
|
|
798
|
+
while (start < text.length) {
|
|
799
|
+
let end = Math.min(start + targetChars, text.length);
|
|
800
|
+
if (end < text.length) {
|
|
801
|
+
const minBreak = start + Math.floor(targetChars * 0.5);
|
|
802
|
+
const paraBreak = text.lastIndexOf("\n\n", end);
|
|
803
|
+
if (paraBreak > minBreak) {
|
|
804
|
+
end = paraBreak;
|
|
805
|
+
} else {
|
|
806
|
+
const sentBreak = text.lastIndexOf(". ", end);
|
|
807
|
+
if (sentBreak > minBreak) {
|
|
808
|
+
end = sentBreak + 1;
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
const chunk = text.slice(start, end).trim();
|
|
813
|
+
if (chunk.length > 0) chunks.push(chunk);
|
|
814
|
+
if (end >= text.length) break;
|
|
815
|
+
start = end - overlapChars;
|
|
816
|
+
if (start <= (chunks.length > 0 ? end - targetChars : 0)) {
|
|
817
|
+
start = end;
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
return chunks;
|
|
821
|
+
}
|
|
822
|
+
// ── Ingest ──
|
|
823
|
+
async ingest(chunks) {
|
|
824
|
+
if (chunks.length === 0) return 0;
|
|
825
|
+
const db = this.sqliteDb;
|
|
826
|
+
const newChunks = chunks.filter((c) => {
|
|
827
|
+
const hash = createHash("sha256").update(c.text).digest("hex");
|
|
828
|
+
return !db.prepare("SELECT 1 FROM chunks WHERE text_hash = ?").get(hash);
|
|
829
|
+
});
|
|
830
|
+
if (newChunks.length === 0) return 0;
|
|
831
|
+
const texts = newChunks.map((c) => c.text);
|
|
832
|
+
const embeddings = await this.embed(texts);
|
|
833
|
+
if (!this.vecDimensions && embeddings.length > 0) {
|
|
834
|
+
this.ensureVecTable(embeddings[0].length);
|
|
835
|
+
}
|
|
836
|
+
const insertChunk = db.prepare(`
|
|
837
|
+
INSERT INTO chunks (text, text_hash, role, source_type, source_id, agent_id, token_count, created_at)
|
|
838
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
839
|
+
`);
|
|
840
|
+
const insertVec = db.prepare(`
|
|
841
|
+
INSERT INTO chunks_vec (chunk_id, embedding) VALUES (?, ?)
|
|
842
|
+
`);
|
|
843
|
+
const transaction = db.transaction(() => {
|
|
844
|
+
for (let i = 0; i < newChunks.length; i++) {
|
|
845
|
+
const c = newChunks[i];
|
|
846
|
+
const hash = createHash("sha256").update(c.text).digest("hex");
|
|
847
|
+
const result = insertChunk.run(
|
|
848
|
+
c.text,
|
|
849
|
+
hash,
|
|
850
|
+
c.role,
|
|
851
|
+
c.source_type,
|
|
852
|
+
c.source_id,
|
|
853
|
+
c.agent_id,
|
|
854
|
+
c.token_count,
|
|
855
|
+
c.created_at || (/* @__PURE__ */ new Date()).toISOString()
|
|
856
|
+
);
|
|
857
|
+
const chunkId = typeof result.lastInsertRowid === "bigint" ? result.lastInsertRowid : BigInt(result.lastInsertRowid);
|
|
858
|
+
insertVec.run(chunkId, new Float32Array(embeddings[i]));
|
|
859
|
+
}
|
|
860
|
+
});
|
|
861
|
+
transaction();
|
|
862
|
+
const records = newChunks.map((chunk, i) => ({
|
|
863
|
+
text: chunk.text,
|
|
864
|
+
vector: embeddings[i],
|
|
865
|
+
role: chunk.role,
|
|
866
|
+
source_type: chunk.source_type,
|
|
867
|
+
source_id: chunk.source_id,
|
|
868
|
+
agent_id: chunk.agent_id,
|
|
869
|
+
token_count: chunk.token_count,
|
|
870
|
+
created_at: chunk.created_at || (/* @__PURE__ */ new Date()).toISOString()
|
|
871
|
+
}));
|
|
872
|
+
try {
|
|
873
|
+
if (!this.chunksTable) {
|
|
874
|
+
this.chunksTable = await this.lanceDb.createTable("chunks", records);
|
|
875
|
+
} else {
|
|
876
|
+
await this.chunksTable.add(records);
|
|
877
|
+
}
|
|
878
|
+
} catch (err) {
|
|
879
|
+
console.warn("LanceDB dual-write failed (non-fatal):", err.message);
|
|
880
|
+
}
|
|
881
|
+
return newChunks.length;
|
|
882
|
+
}
|
|
883
|
+
// ── Delta Sync (export/import pre-embedded chunks) ──
|
|
884
|
+
/** Export interface for delta sync payloads. */
|
|
885
|
+
static DELTA_VERSION = 1;
|
|
886
|
+
/** Export chunks with IDs greater than sinceId. Returns pre-embedded chunks for delta sync.
|
|
887
|
+
* Core calls this to build delta payloads for Nodes. */
|
|
888
|
+
exportChunksSince(sinceId) {
|
|
889
|
+
const db = this.sqliteDb;
|
|
890
|
+
const rows = db.prepare(`
|
|
891
|
+
SELECT c.id, c.text, c.text_hash, c.role, c.source_type, c.source_id,
|
|
892
|
+
c.agent_id, c.token_count, c.created_at, v.embedding
|
|
893
|
+
FROM chunks c
|
|
894
|
+
LEFT JOIN chunks_vec v ON v.chunk_id = c.id
|
|
895
|
+
WHERE c.id > ?
|
|
896
|
+
ORDER BY c.id ASC
|
|
897
|
+
`).all(sinceId);
|
|
898
|
+
return rows.map((row) => ({
|
|
899
|
+
id: row.id,
|
|
900
|
+
text: row.text,
|
|
901
|
+
text_hash: row.text_hash,
|
|
902
|
+
role: row.role,
|
|
903
|
+
source_type: row.source_type,
|
|
904
|
+
source_id: row.source_id,
|
|
905
|
+
agent_id: row.agent_id,
|
|
906
|
+
token_count: row.token_count,
|
|
907
|
+
created_at: row.created_at,
|
|
908
|
+
// Convert Float32Array buffer to number[] for JSON serialization
|
|
909
|
+
embedding: row.embedding ? Array.from(new Float32Array(row.embedding.buffer, row.embedding.byteOffset, row.embedding.byteLength / 4)) : null
|
|
910
|
+
}));
|
|
911
|
+
}
|
|
912
|
+
/** Get the highest chunk ID in the database. Used for watermark tracking. */
|
|
913
|
+
getMaxChunkId() {
|
|
914
|
+
const db = this.sqliteDb;
|
|
915
|
+
const row = db.prepare("SELECT MAX(id) as maxId FROM chunks").get();
|
|
916
|
+
return row.maxId || 0;
|
|
917
|
+
}
|
|
918
|
+
/** Import pre-embedded chunks from Core. Node calls this to apply delta payloads.
|
|
919
|
+
* Skips chunks that already exist (by text_hash). Does NOT re-embed. */
|
|
920
|
+
importChunks(exported) {
|
|
921
|
+
if (exported.length === 0) return 0;
|
|
922
|
+
const db = this.sqliteDb;
|
|
923
|
+
const firstWithEmbed = exported.find((c) => c.embedding && c.embedding.length > 0);
|
|
924
|
+
if (firstWithEmbed && !this.vecDimensions) {
|
|
925
|
+
this.ensureVecTable(firstWithEmbed.embedding.length);
|
|
926
|
+
}
|
|
927
|
+
const insertChunk = db.prepare(`
|
|
928
|
+
INSERT INTO chunks (text, text_hash, role, source_type, source_id, agent_id, token_count, created_at)
|
|
929
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
930
|
+
`);
|
|
931
|
+
const insertVec = db.prepare(`
|
|
932
|
+
INSERT INTO chunks_vec (chunk_id, embedding) VALUES (?, ?)
|
|
933
|
+
`);
|
|
934
|
+
const checkHash = db.prepare("SELECT 1 FROM chunks WHERE text_hash = ?");
|
|
935
|
+
let imported = 0;
|
|
936
|
+
const transaction = db.transaction(() => {
|
|
937
|
+
for (const chunk of exported) {
|
|
938
|
+
if (checkHash.get(chunk.text_hash)) continue;
|
|
939
|
+
const result = insertChunk.run(
|
|
940
|
+
chunk.text,
|
|
941
|
+
chunk.text_hash,
|
|
942
|
+
chunk.role,
|
|
943
|
+
chunk.source_type,
|
|
944
|
+
chunk.source_id,
|
|
945
|
+
chunk.agent_id,
|
|
946
|
+
chunk.token_count,
|
|
947
|
+
chunk.created_at
|
|
948
|
+
);
|
|
949
|
+
if (chunk.embedding && chunk.embedding.length > 0) {
|
|
950
|
+
const chunkId = typeof result.lastInsertRowid === "bigint" ? result.lastInsertRowid : BigInt(result.lastInsertRowid);
|
|
951
|
+
insertVec.run(chunkId, new Float32Array(chunk.embedding));
|
|
952
|
+
}
|
|
953
|
+
imported++;
|
|
954
|
+
}
|
|
955
|
+
});
|
|
956
|
+
transaction();
|
|
957
|
+
return imported;
|
|
958
|
+
}
|
|
959
|
+
// ── Recency helpers ──
|
|
960
|
+
recencyWeight(ageDays) {
|
|
961
|
+
return Math.max(0.3, Math.exp(-ageDays * 0.1));
|
|
962
|
+
}
|
|
963
|
+
/** Parse relative time strings ("24h", "7d", "30d") or ISO dates into ISO date strings. */
|
|
964
|
+
parseSince(since) {
|
|
965
|
+
const match = since.match(/^(\d+)(h|d)$/);
|
|
966
|
+
if (match) {
|
|
967
|
+
const [, num, unit] = match;
|
|
968
|
+
const ms = unit === "h" ? parseInt(num) * 36e5 : parseInt(num) * 864e5;
|
|
969
|
+
return new Date(Date.now() - ms).toISOString();
|
|
970
|
+
}
|
|
971
|
+
const parsed = new Date(since);
|
|
972
|
+
if (!isNaN(parsed.getTime())) return parsed.toISOString();
|
|
973
|
+
return void 0;
|
|
974
|
+
}
|
|
975
|
+
freshnessLabel(ageDays) {
|
|
976
|
+
if (ageDays < 3) return "fresh";
|
|
977
|
+
if (ageDays < 7) return "recent";
|
|
978
|
+
if (ageDays < 14) return "aging";
|
|
979
|
+
return "stale";
|
|
980
|
+
}
|
|
981
|
+
// ── Search (Hybrid: BM25 + Vector + RRF fusion + Recency) ──
|
|
982
|
+
async search(query, limit = 5, filter) {
|
|
983
|
+
const db = this.sqliteDb;
|
|
984
|
+
const sqliteChunks = db.prepare("SELECT COUNT(*) as count FROM chunks").get()?.count || 0;
|
|
985
|
+
let lanceChunks = 0;
|
|
986
|
+
if (this.chunksTable) {
|
|
987
|
+
try {
|
|
988
|
+
lanceChunks = await this.chunksTable.countRows();
|
|
989
|
+
} catch {
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
if (sqliteChunks === 0 || lanceChunks > 0 && sqliteChunks < lanceChunks * 0.5) {
|
|
993
|
+
return this.searchLanceFallback(query, limit, filter);
|
|
994
|
+
}
|
|
995
|
+
const sinceDate = filter?.since ? this.parseSince(filter.since) : void 0;
|
|
996
|
+
const untilDate = filter?.until ? this.parseSince(filter.until) : void 0;
|
|
997
|
+
const [embedding] = await this.embed([query]);
|
|
998
|
+
const fetchLimit = Math.max(limit * 5, 50);
|
|
999
|
+
const vecResults = this.searchVec(embedding, fetchLimit, { ...filter, sinceDate, untilDate });
|
|
1000
|
+
const ftsResults = this.searchFTS(query, fetchLimit, { ...filter, sinceDate, untilDate });
|
|
1001
|
+
const fused = this.reciprocalRankFusion([ftsResults, vecResults], [2, 1]);
|
|
1002
|
+
const now = Date.now();
|
|
1003
|
+
const scored = fused.map((r) => {
|
|
1004
|
+
const ageDays = r.created_at ? (now - new Date(r.created_at).getTime()) / 864e5 : 0;
|
|
1005
|
+
const recency = r.created_at ? this.recencyWeight(ageDays) : 1;
|
|
1006
|
+
const rescaled = r.score * recency;
|
|
1007
|
+
return {
|
|
1008
|
+
...r,
|
|
1009
|
+
score: rescaled,
|
|
1010
|
+
freshness: r.created_at ? this.freshnessLabel(ageDays) : void 0
|
|
1011
|
+
};
|
|
1012
|
+
});
|
|
1013
|
+
const sorted = scored.sort((a, b) => b.score - a.score).slice(0, limit);
|
|
1014
|
+
const topScore = sorted[0]?.score || 1;
|
|
1015
|
+
return sorted.map((r) => ({ ...r, score: Math.min(r.score / topScore * 0.95, 0.95) }));
|
|
1016
|
+
}
|
|
1017
|
+
/** Deep search: query expansion + LLM re-ranking + position-aware blending.
|
|
1018
|
+
* Falls back to standard search if no LLM provider is available.
|
|
1019
|
+
* Supports intent disambiguation, candidateLimit tuning, and explain traces. */
|
|
1020
|
+
async deepSearch(query, limit = 5, filter, options) {
|
|
1021
|
+
const { deepSearch: deepSearchFn } = await Promise.resolve().then(() => (init_search_pipeline(), search_pipeline_exports));
|
|
1022
|
+
return deepSearchFn(this, query, { limit, filter, ...options });
|
|
1023
|
+
}
|
|
1024
|
+
/** Structured search: pass pre-expanded queries to skip LLM expansion.
|
|
1025
|
+
* Each query is typed (lex, vec, hyde) and searched independently, then fused with RRF. */
|
|
1026
|
+
async structuredSearch(queries, limit = 5, filter) {
|
|
1027
|
+
const db = this.sqliteDb;
|
|
1028
|
+
const sinceDate = filter?.since ? this.parseSince(filter.since) : void 0;
|
|
1029
|
+
const untilDate = filter?.until ? this.parseSince(filter.until) : void 0;
|
|
1030
|
+
const internalFilter = { ...filter, sinceDate, untilDate };
|
|
1031
|
+
const allResultLists = [];
|
|
1032
|
+
for (const q of queries) {
|
|
1033
|
+
if (q.type === "lex") {
|
|
1034
|
+
const fts = this.searchFTS(q.text, Math.max(limit * 5, 50), internalFilter);
|
|
1035
|
+
if (fts.length > 0) allResultLists.push(fts);
|
|
1036
|
+
} else {
|
|
1037
|
+
const [embedding] = await this.embed([q.text]);
|
|
1038
|
+
const vec = this.searchVec(embedding, Math.max(limit * 5, 50), internalFilter);
|
|
1039
|
+
if (vec.length > 0) allResultLists.push(vec);
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
const weights = allResultLists.map((_, i) => i === 0 ? 2 : 1);
|
|
1043
|
+
const fused = this.reciprocalRankFusion(allResultLists, weights);
|
|
1044
|
+
const now = Date.now();
|
|
1045
|
+
const scored = fused.map((r) => {
|
|
1046
|
+
const ageDays = r.created_at ? (now - new Date(r.created_at).getTime()) / 864e5 : 0;
|
|
1047
|
+
const recency = r.created_at ? this.recencyWeight(ageDays) : 1;
|
|
1048
|
+
return { ...r, score: r.score * recency, freshness: r.created_at ? this.freshnessLabel(ageDays) : void 0 };
|
|
1049
|
+
});
|
|
1050
|
+
const sorted = scored.sort((a, b) => b.score - a.score).slice(0, limit);
|
|
1051
|
+
const topScore = sorted[0]?.score || 1;
|
|
1052
|
+
return sorted.map((r) => ({ ...r, score: Math.min(r.score / topScore * 0.95, 0.95) }));
|
|
1053
|
+
}
|
|
1054
|
+
/** Vector search via sqlite-vec. Two-step pattern: MATCH first, then JOIN. */
|
|
1055
|
+
searchVec(embedding, limit, filter) {
|
|
1056
|
+
const db = this.sqliteDb;
|
|
1057
|
+
if (!this.vecDimensions) return [];
|
|
1058
|
+
const vecRows = db.prepare(`
|
|
1059
|
+
SELECT chunk_id, distance
|
|
1060
|
+
FROM chunks_vec
|
|
1061
|
+
WHERE embedding MATCH ? AND k = ?
|
|
1062
|
+
`).all(new Float32Array(embedding), limit);
|
|
1063
|
+
if (vecRows.length === 0) return [];
|
|
1064
|
+
const ids = vecRows.map((r) => r.chunk_id);
|
|
1065
|
+
const distMap = new Map(vecRows.map((r) => [r.chunk_id, r.distance]));
|
|
1066
|
+
const placeholders = ids.map(() => "?").join(",");
|
|
1067
|
+
let sql = `SELECT id, text, role, source_type, source_id, agent_id, created_at FROM chunks WHERE id IN (${placeholders})`;
|
|
1068
|
+
const params = [...ids];
|
|
1069
|
+
if (filter?.agent_id) {
|
|
1070
|
+
sql += " AND agent_id = ?";
|
|
1071
|
+
params.push(filter.agent_id);
|
|
1072
|
+
}
|
|
1073
|
+
if (filter?.source_type) {
|
|
1074
|
+
sql += " AND source_type = ?";
|
|
1075
|
+
params.push(filter.source_type);
|
|
1076
|
+
}
|
|
1077
|
+
if (filter?.sinceDate) {
|
|
1078
|
+
sql += " AND created_at >= ?";
|
|
1079
|
+
params.push(filter.sinceDate);
|
|
1080
|
+
}
|
|
1081
|
+
if (filter?.untilDate) {
|
|
1082
|
+
sql += " AND created_at < ?";
|
|
1083
|
+
params.push(filter.untilDate);
|
|
1084
|
+
}
|
|
1085
|
+
const rows = db.prepare(sql).all(...params);
|
|
1086
|
+
return rows.map((row) => ({
|
|
1087
|
+
text: row.text,
|
|
1088
|
+
role: row.role,
|
|
1089
|
+
score: 1 - (distMap.get(row.id) || 1),
|
|
1090
|
+
// cosine similarity from distance
|
|
1091
|
+
source_type: row.source_type,
|
|
1092
|
+
source_id: row.source_id,
|
|
1093
|
+
agent_id: row.agent_id,
|
|
1094
|
+
created_at: row.created_at
|
|
1095
|
+
}));
|
|
1096
|
+
}
|
|
1097
|
+
/** Full-text search via FTS5 with BM25 scoring. */
|
|
1098
|
+
searchFTS(query, limit, filter) {
|
|
1099
|
+
const db = this.sqliteDb;
|
|
1100
|
+
const ftsQuery = this.buildFTS5Query(query);
|
|
1101
|
+
if (!ftsQuery) return [];
|
|
1102
|
+
let sql = `
|
|
1103
|
+
SELECT c.id, c.text, c.role, c.source_type, c.source_id, c.agent_id, c.created_at,
|
|
1104
|
+
bm25(chunks_fts) as bm25_score
|
|
1105
|
+
FROM chunks_fts f
|
|
1106
|
+
JOIN chunks c ON c.id = f.rowid
|
|
1107
|
+
WHERE chunks_fts MATCH ?
|
|
1108
|
+
`;
|
|
1109
|
+
const params = [ftsQuery];
|
|
1110
|
+
if (filter?.agent_id) {
|
|
1111
|
+
sql += " AND c.agent_id = ?";
|
|
1112
|
+
params.push(filter.agent_id);
|
|
1113
|
+
}
|
|
1114
|
+
if (filter?.source_type) {
|
|
1115
|
+
sql += " AND c.source_type = ?";
|
|
1116
|
+
params.push(filter.source_type);
|
|
1117
|
+
}
|
|
1118
|
+
if (filter?.sinceDate) {
|
|
1119
|
+
sql += " AND c.created_at >= ?";
|
|
1120
|
+
params.push(filter.sinceDate);
|
|
1121
|
+
}
|
|
1122
|
+
if (filter?.untilDate) {
|
|
1123
|
+
sql += " AND c.created_at < ?";
|
|
1124
|
+
params.push(filter.untilDate);
|
|
1125
|
+
}
|
|
1126
|
+
sql += " ORDER BY bm25_score LIMIT ?";
|
|
1127
|
+
params.push(limit);
|
|
1128
|
+
const rows = db.prepare(sql).all(...params);
|
|
1129
|
+
return rows.map((row) => ({
|
|
1130
|
+
text: row.text,
|
|
1131
|
+
role: row.role,
|
|
1132
|
+
// BM25 scores are negative (lower = better). Normalize to [0..1).
|
|
1133
|
+
// |x| / (1 + |x|) maps: strong(-10)->0.91, medium(-2)->0.67, weak(-0.5)->0.33
|
|
1134
|
+
score: Math.abs(row.bm25_score) / (1 + Math.abs(row.bm25_score)),
|
|
1135
|
+
source_type: row.source_type,
|
|
1136
|
+
source_id: row.source_id,
|
|
1137
|
+
agent_id: row.agent_id,
|
|
1138
|
+
created_at: row.created_at
|
|
1139
|
+
}));
|
|
1140
|
+
}
|
|
1141
|
+
/** Build a safe FTS5 query from user input. */
|
|
1142
|
+
buildFTS5Query(query) {
|
|
1143
|
+
const terms = query.split(/\s+/).map((t) => t.replace(/[^\p{L}\p{N}']/gu, "").toLowerCase()).filter((t) => t.length > 0);
|
|
1144
|
+
if (terms.length === 0) return null;
|
|
1145
|
+
if (terms.length === 1) return `"${terms[0]}"*`;
|
|
1146
|
+
return terms.map((t) => `"${t}"*`).join(" AND ");
|
|
1147
|
+
}
|
|
1148
|
+
/**
|
|
1149
|
+
* Reciprocal Rank Fusion. Ported from QMD (MIT License, Tobi Lutke, 2024-2026).
|
|
1150
|
+
* Fuses multiple ranked result lists into one using RRF scoring.
|
|
1151
|
+
* Uses text content as dedup key (instead of QMD's file path).
|
|
1152
|
+
*/
|
|
1153
|
+
reciprocalRankFusion(resultLists, weights = [], k = 60) {
|
|
1154
|
+
const scores = /* @__PURE__ */ new Map();
|
|
1155
|
+
for (let listIdx = 0; listIdx < resultLists.length; listIdx++) {
|
|
1156
|
+
const list = resultLists[listIdx];
|
|
1157
|
+
if (!list) continue;
|
|
1158
|
+
const weight = weights[listIdx] ?? 1;
|
|
1159
|
+
for (let rank = 0; rank < list.length; rank++) {
|
|
1160
|
+
const result = list[rank];
|
|
1161
|
+
if (!result) continue;
|
|
1162
|
+
const rrfContribution = weight / (k + rank + 1);
|
|
1163
|
+
const dedup = result.text.slice(0, 200);
|
|
1164
|
+
const existing = scores.get(dedup);
|
|
1165
|
+
if (existing) {
|
|
1166
|
+
existing.rrfScore += rrfContribution;
|
|
1167
|
+
existing.topRank = Math.min(existing.topRank, rank);
|
|
1168
|
+
} else {
|
|
1169
|
+
scores.set(dedup, {
|
|
1170
|
+
result,
|
|
1171
|
+
rrfScore: rrfContribution,
|
|
1172
|
+
topRank: rank
|
|
1173
|
+
});
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
for (const entry of scores.values()) {
|
|
1178
|
+
if (entry.topRank === 0) {
|
|
1179
|
+
entry.rrfScore += 0.05;
|
|
1180
|
+
} else if (entry.topRank <= 2) {
|
|
1181
|
+
entry.rrfScore += 0.02;
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
return Array.from(scores.values()).sort((a, b) => b.rrfScore - a.rrfScore).map((e) => ({ ...e.result, score: e.rrfScore }));
|
|
1185
|
+
}
|
|
1186
|
+
/** LanceDB fallback for search (used when sqlite-vec tables are empty, pre-migration). */
|
|
1187
|
+
async searchLanceFallback(query, limit, filter) {
|
|
1188
|
+
if (!this.chunksTable) return [];
|
|
1189
|
+
const [embedding] = await this.embed([query]);
|
|
1190
|
+
const fetchLimit = Math.max(limit * 3, 30);
|
|
1191
|
+
let queryBuilder = this.chunksTable.vectorSearch(embedding).distanceType("cosine").limit(fetchLimit);
|
|
1192
|
+
if (filter?.agent_id) {
|
|
1193
|
+
queryBuilder = queryBuilder.where(`agent_id = '${filter.agent_id}'`);
|
|
1194
|
+
}
|
|
1195
|
+
if (filter?.source_type) {
|
|
1196
|
+
queryBuilder = queryBuilder.where(`source_type = '${filter.source_type}'`);
|
|
1197
|
+
}
|
|
1198
|
+
const results = await queryBuilder.toArray();
|
|
1199
|
+
const now = Date.now();
|
|
1200
|
+
return results.map((row) => {
|
|
1201
|
+
const cosine = row._distance != null ? 1 - row._distance : 0;
|
|
1202
|
+
const createdAt = row.created_at || "";
|
|
1203
|
+
const ageDays = createdAt ? (now - new Date(createdAt).getTime()) / 864e5 : 0;
|
|
1204
|
+
const weight = createdAt ? this.recencyWeight(ageDays) : 1;
|
|
1205
|
+
return {
|
|
1206
|
+
text: row.text,
|
|
1207
|
+
role: row.role,
|
|
1208
|
+
score: cosine * weight,
|
|
1209
|
+
source_type: row.source_type,
|
|
1210
|
+
source_id: row.source_id,
|
|
1211
|
+
agent_id: row.agent_id,
|
|
1212
|
+
created_at: createdAt,
|
|
1213
|
+
freshness: createdAt ? this.freshnessLabel(ageDays) : void 0
|
|
1214
|
+
};
|
|
1215
|
+
}).sort((a, b) => b.score - a.score).slice(0, limit);
|
|
1216
|
+
}
|
|
1217
|
+
// ── Remember (explicit fact storage) ──
|
|
1218
|
+
async remember(text, category = "fact") {
|
|
1219
|
+
const db = this.sqliteDb;
|
|
1220
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1221
|
+
const stmt = db.prepare(`
|
|
1222
|
+
INSERT INTO memories (text, category, confidence, source_ids, status, created_at, updated_at)
|
|
1223
|
+
VALUES (?, ?, 1.0, '[]', 'active', ?, ?)
|
|
1224
|
+
`);
|
|
1225
|
+
const result = stmt.run(text, category, now, now);
|
|
1226
|
+
await this.ingest([{
|
|
1227
|
+
text,
|
|
1228
|
+
role: "system",
|
|
1229
|
+
source_type: "manual",
|
|
1230
|
+
source_id: `memory:${result.lastInsertRowid}`,
|
|
1231
|
+
agent_id: "system",
|
|
1232
|
+
token_count: Math.ceil(text.length / 4),
|
|
1233
|
+
created_at: now
|
|
1234
|
+
}]);
|
|
1235
|
+
return result.lastInsertRowid;
|
|
1236
|
+
}
|
|
1237
|
+
// ── Forget (deprecate a memory) ──
|
|
1238
|
+
forget(memoryId) {
|
|
1239
|
+
const db = this.sqliteDb;
|
|
1240
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1241
|
+
const result = db.prepare(`
|
|
1242
|
+
UPDATE memories SET status = 'deprecated', updated_at = ? WHERE id = ? AND status = 'active'
|
|
1243
|
+
`).run(now, memoryId);
|
|
1244
|
+
return result.changes > 0;
|
|
1245
|
+
}
|
|
1246
|
+
// ── Status ──
|
|
1247
|
+
async status() {
|
|
1248
|
+
const db = this.sqliteDb;
|
|
1249
|
+
const sqliteChunks = db.prepare("SELECT COUNT(*) as count FROM chunks").get()?.count || 0;
|
|
1250
|
+
let lanceChunks = 0;
|
|
1251
|
+
if (this.chunksTable) {
|
|
1252
|
+
try {
|
|
1253
|
+
lanceChunks = await this.chunksTable.countRows();
|
|
1254
|
+
} catch {
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
const chunks = Math.max(sqliteChunks, lanceChunks);
|
|
1258
|
+
const oldest = db.prepare("SELECT MIN(created_at) as ts FROM chunks").get()?.ts || null;
|
|
1259
|
+
const newest = db.prepare("SELECT MAX(created_at) as ts FROM chunks").get()?.ts || null;
|
|
1260
|
+
const memories = db.prepare("SELECT COUNT(*) as count FROM memories WHERE status = ?").get("active")?.count || 0;
|
|
1261
|
+
const sources = db.prepare("SELECT COUNT(*) as count FROM sources").get()?.count || 0;
|
|
1262
|
+
const chunkAgentRows = db.prepare("SELECT DISTINCT agent_id FROM chunks WHERE agent_id IS NOT NULL").all();
|
|
1263
|
+
const sourceAgentRows = db.prepare("SELECT DISTINCT agent_id FROM sources").all();
|
|
1264
|
+
const captureAgentRows = db.prepare("SELECT DISTINCT agent_id FROM capture_state").all();
|
|
1265
|
+
const agents = [.../* @__PURE__ */ new Set([
|
|
1266
|
+
...chunkAgentRows.map((r) => r.agent_id),
|
|
1267
|
+
...sourceAgentRows.map((r) => r.agent_id),
|
|
1268
|
+
...captureAgentRows.map((r) => r.agent_id)
|
|
1269
|
+
])];
|
|
1270
|
+
const captureInfo = db.prepare(
|
|
1271
|
+
"SELECT COUNT(*) as count, MAX(last_capture_at) as latest FROM capture_state"
|
|
1272
|
+
).get();
|
|
1273
|
+
return {
|
|
1274
|
+
chunks,
|
|
1275
|
+
memories,
|
|
1276
|
+
sources,
|
|
1277
|
+
agents,
|
|
1278
|
+
oldestChunk: oldest,
|
|
1279
|
+
newestChunk: newest,
|
|
1280
|
+
embeddingProvider: this.config.embeddingProvider,
|
|
1281
|
+
dataDir: this.config.dataDir,
|
|
1282
|
+
capturedSessions: captureInfo?.count || 0,
|
|
1283
|
+
latestCapture: captureInfo?.latest || null
|
|
1284
|
+
};
|
|
1285
|
+
}
|
|
1286
|
+
// ── Capture State (for incremental ingestion) ──
|
|
1287
|
+
getCaptureState(agentId, sourceId) {
|
|
1288
|
+
const db = this.sqliteDb;
|
|
1289
|
+
const row = db.prepare("SELECT last_message_count, capture_count FROM capture_state WHERE agent_id = ? AND source_id = ?").get(agentId, sourceId);
|
|
1290
|
+
if (!row) return { lastMessageCount: 0, captureCount: 0 };
|
|
1291
|
+
return {
|
|
1292
|
+
lastMessageCount: row.last_message_count,
|
|
1293
|
+
captureCount: row.capture_count
|
|
1294
|
+
};
|
|
1295
|
+
}
|
|
1296
|
+
setCaptureState(agentId, sourceId, messageCount, captureCount) {
|
|
1297
|
+
const db = this.sqliteDb;
|
|
1298
|
+
db.prepare(`
|
|
1299
|
+
INSERT OR REPLACE INTO capture_state (agent_id, source_id, last_message_count, capture_count, last_capture_at)
|
|
1300
|
+
VALUES (?, ?, ?, ?, ?)
|
|
1301
|
+
`).run(agentId, sourceId, messageCount, captureCount, (/* @__PURE__ */ new Date()).toISOString());
|
|
1302
|
+
}
|
|
1303
|
+
// ── Source File Indexing (optional feature) ──
|
|
1304
|
+
//
|
|
1305
|
+
// Add directories as "collections", sync to index/re-index changed files.
|
|
1306
|
+
// All source chunks get source_type='file' so they're searchable alongside
|
|
1307
|
+
// conversations and memories. Nothing here is required... you can use MC
|
|
1308
|
+
// without ever touching sources.
|
|
1309
|
+
// Default patterns for files worth indexing
|
|
1310
|
+
static DEFAULT_INCLUDE = [
|
|
1311
|
+
"**/*.ts",
|
|
1312
|
+
"**/*.js",
|
|
1313
|
+
"**/*.tsx",
|
|
1314
|
+
"**/*.jsx",
|
|
1315
|
+
"**/*.py",
|
|
1316
|
+
"**/*.rs",
|
|
1317
|
+
"**/*.go",
|
|
1318
|
+
"**/*.java",
|
|
1319
|
+
"**/*.md",
|
|
1320
|
+
"**/*.txt",
|
|
1321
|
+
"**/*.json",
|
|
1322
|
+
"**/*.yaml",
|
|
1323
|
+
"**/*.yml",
|
|
1324
|
+
"**/*.toml",
|
|
1325
|
+
"**/*.sh",
|
|
1326
|
+
"**/*.bash",
|
|
1327
|
+
"**/*.zsh",
|
|
1328
|
+
"**/*.css",
|
|
1329
|
+
"**/*.html",
|
|
1330
|
+
"**/*.svg",
|
|
1331
|
+
"**/*.sql",
|
|
1332
|
+
"**/*.graphql",
|
|
1333
|
+
"**/*.c",
|
|
1334
|
+
"**/*.cpp",
|
|
1335
|
+
"**/*.h",
|
|
1336
|
+
"**/*.hpp",
|
|
1337
|
+
"**/*.swift",
|
|
1338
|
+
"**/*.kt",
|
|
1339
|
+
"**/*.rb",
|
|
1340
|
+
"**/*.env.example",
|
|
1341
|
+
"**/*.gitignore",
|
|
1342
|
+
"**/Makefile",
|
|
1343
|
+
"**/Dockerfile",
|
|
1344
|
+
"**/Cargo.toml",
|
|
1345
|
+
"**/package.json",
|
|
1346
|
+
"**/tsconfig.json"
|
|
1347
|
+
];
|
|
1348
|
+
static DEFAULT_IGNORE = [
|
|
1349
|
+
"**/node_modules/**",
|
|
1350
|
+
"**/.git/**",
|
|
1351
|
+
"**/dist/**",
|
|
1352
|
+
"**/build/**",
|
|
1353
|
+
"**/.next/**",
|
|
1354
|
+
"**/.cache/**",
|
|
1355
|
+
"**/coverage/**",
|
|
1356
|
+
"**/__pycache__/**",
|
|
1357
|
+
"**/target/**",
|
|
1358
|
+
"**/vendor/**",
|
|
1359
|
+
"**/.venv/**",
|
|
1360
|
+
"**/*.lock",
|
|
1361
|
+
"**/package-lock.json",
|
|
1362
|
+
"**/yarn.lock",
|
|
1363
|
+
"**/bun.lockb",
|
|
1364
|
+
"**/*.min.js",
|
|
1365
|
+
"**/*.min.css",
|
|
1366
|
+
"**/*.map",
|
|
1367
|
+
"**/*.png",
|
|
1368
|
+
"**/*.jpg",
|
|
1369
|
+
"**/*.jpeg",
|
|
1370
|
+
"**/*.gif",
|
|
1371
|
+
"**/*.ico",
|
|
1372
|
+
"**/*.webp",
|
|
1373
|
+
"**/*.woff",
|
|
1374
|
+
"**/*.woff2",
|
|
1375
|
+
"**/*.ttf",
|
|
1376
|
+
"**/*.eot",
|
|
1377
|
+
"**/*.mp3",
|
|
1378
|
+
"**/*.mp4",
|
|
1379
|
+
"**/*.wav",
|
|
1380
|
+
"**/*.ogg",
|
|
1381
|
+
"**/*.webm",
|
|
1382
|
+
"**/*.zip",
|
|
1383
|
+
"**/*.tar",
|
|
1384
|
+
"**/*.gz",
|
|
1385
|
+
"**/*.br",
|
|
1386
|
+
"**/*.sqlite",
|
|
1387
|
+
"**/*.db",
|
|
1388
|
+
"**/*.lance/**",
|
|
1389
|
+
"**/*.jsonl",
|
|
1390
|
+
"**/secrets/**",
|
|
1391
|
+
"**/.env"
|
|
1392
|
+
];
|
|
1393
|
+
/** Add a directory as a source collection for indexing. */
|
|
1394
|
+
async sourcesAdd(rootPath, name, options) {
|
|
1395
|
+
const db = this.sqliteDb;
|
|
1396
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1397
|
+
const includePatterns = JSON.stringify(options?.include || _Crystal.DEFAULT_INCLUDE);
|
|
1398
|
+
const ignorePatterns = JSON.stringify(options?.ignore || _Crystal.DEFAULT_IGNORE);
|
|
1399
|
+
const existing = db.prepare("SELECT * FROM source_collections WHERE name = ?").get(name);
|
|
1400
|
+
if (existing) {
|
|
1401
|
+
throw new Error(`Collection "${name}" already exists. Use sourcesSync() to update it.`);
|
|
1402
|
+
}
|
|
1403
|
+
db.prepare(`
|
|
1404
|
+
INSERT INTO source_collections (name, root_path, glob_patterns, ignore_patterns, created_at)
|
|
1405
|
+
VALUES (?, ?, ?, ?, ?)
|
|
1406
|
+
`).run(name, rootPath, includePatterns, ignorePatterns, now);
|
|
1407
|
+
const row = db.prepare("SELECT * FROM source_collections WHERE name = ?").get(name);
|
|
1408
|
+
return row;
|
|
1409
|
+
}
|
|
1410
|
+
/** Remove a source collection and its file records. Chunks remain in LanceDB. */
|
|
1411
|
+
sourcesRemove(name) {
|
|
1412
|
+
const db = this.sqliteDb;
|
|
1413
|
+
const col = db.prepare("SELECT id FROM source_collections WHERE name = ?").get(name);
|
|
1414
|
+
if (!col) return false;
|
|
1415
|
+
db.prepare("DELETE FROM source_files WHERE collection_id = ?").run(col.id);
|
|
1416
|
+
db.prepare("DELETE FROM source_collections WHERE id = ?").run(col.id);
|
|
1417
|
+
return true;
|
|
1418
|
+
}
|
|
1419
|
+
/** Sync a collection: scan files, detect changes, re-index what changed. */
|
|
1420
|
+
async sourcesSync(name, options) {
|
|
1421
|
+
const db = this.sqliteDb;
|
|
1422
|
+
const startTime = Date.now();
|
|
1423
|
+
const batchSize = options?.batchSize || 20;
|
|
1424
|
+
const col = db.prepare("SELECT * FROM source_collections WHERE name = ?").get(name);
|
|
1425
|
+
if (!col) throw new Error(`Collection "${name}" not found. Add it first with sourcesAdd().`);
|
|
1426
|
+
const includePatterns = JSON.parse(col.glob_patterns);
|
|
1427
|
+
const ignorePatterns = JSON.parse(col.ignore_patterns);
|
|
1428
|
+
const files = this.scanDirectory(col.root_path, includePatterns, ignorePatterns);
|
|
1429
|
+
const existingFiles = /* @__PURE__ */ new Map();
|
|
1430
|
+
const rows = db.prepare("SELECT id, file_path, file_hash FROM source_files WHERE collection_id = ?").all(col.id);
|
|
1431
|
+
for (const row of rows) {
|
|
1432
|
+
existingFiles.set(row.file_path, { id: row.id, file_hash: row.file_hash });
|
|
1433
|
+
}
|
|
1434
|
+
let added = 0;
|
|
1435
|
+
let updated = 0;
|
|
1436
|
+
let removed = 0;
|
|
1437
|
+
let chunksAdded = 0;
|
|
1438
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1439
|
+
const toIndex = [];
|
|
1440
|
+
for (const absPath of files) {
|
|
1441
|
+
const relPath = relative(col.root_path, absPath);
|
|
1442
|
+
let content;
|
|
1443
|
+
try {
|
|
1444
|
+
content = readFileSync2(absPath, "utf-8");
|
|
1445
|
+
} catch {
|
|
1446
|
+
continue;
|
|
1447
|
+
}
|
|
1448
|
+
const stat = statSync(absPath);
|
|
1449
|
+
if (stat.size > 500 * 1024) continue;
|
|
1450
|
+
const hash = createHash("sha256").update(content).digest("hex");
|
|
1451
|
+
const existing = existingFiles.get(relPath);
|
|
1452
|
+
if (existing) {
|
|
1453
|
+
existingFiles.delete(relPath);
|
|
1454
|
+
if (existing.file_hash === hash) continue;
|
|
1455
|
+
toIndex.push({ relPath, absPath, hash, size: stat.size, isUpdate: true });
|
|
1456
|
+
} else {
|
|
1457
|
+
toIndex.push({ relPath, absPath, hash, size: stat.size, isUpdate: false });
|
|
1458
|
+
}
|
|
1459
|
+
}
|
|
1460
|
+
if (options?.dryRun) {
|
|
1461
|
+
const newFiles = toIndex.filter((f) => !f.isUpdate).length;
|
|
1462
|
+
const updatedFiles = toIndex.filter((f) => f.isUpdate).length;
|
|
1463
|
+
return {
|
|
1464
|
+
collection: name,
|
|
1465
|
+
added: newFiles,
|
|
1466
|
+
updated: updatedFiles,
|
|
1467
|
+
removed: existingFiles.size,
|
|
1468
|
+
chunks_added: 0,
|
|
1469
|
+
duration_ms: Date.now() - startTime
|
|
1470
|
+
};
|
|
1471
|
+
}
|
|
1472
|
+
for (let i = 0; i < toIndex.length; i += batchSize) {
|
|
1473
|
+
const batch = toIndex.slice(i, i + batchSize);
|
|
1474
|
+
const allChunks = [];
|
|
1475
|
+
for (const file of batch) {
|
|
1476
|
+
const content = readFileSync2(file.absPath, "utf-8");
|
|
1477
|
+
const ext = extname(file.absPath);
|
|
1478
|
+
const fileName = basename(file.absPath);
|
|
1479
|
+
const header = `File: ${file.relPath}
|
|
1480
|
+
|
|
1481
|
+
`;
|
|
1482
|
+
const textChunks = this.chunkText(header + content, 400, 80);
|
|
1483
|
+
const fileChunks = textChunks.map((text) => ({
|
|
1484
|
+
text,
|
|
1485
|
+
role: "system",
|
|
1486
|
+
source_type: "file",
|
|
1487
|
+
source_id: `file:${name}:${file.relPath}`,
|
|
1488
|
+
agent_id: "system",
|
|
1489
|
+
token_count: Math.ceil(text.length / 4),
|
|
1490
|
+
created_at: now
|
|
1491
|
+
}));
|
|
1492
|
+
allChunks.push(...fileChunks);
|
|
1493
|
+
if (file.isUpdate) {
|
|
1494
|
+
db.prepare(`
|
|
1495
|
+
UPDATE source_files SET file_hash = ?, file_size = ?, chunk_count = ?, last_indexed_at = ?
|
|
1496
|
+
WHERE collection_id = ? AND file_path = ?
|
|
1497
|
+
`).run(file.hash, file.size, fileChunks.length, now, col.id, file.relPath);
|
|
1498
|
+
updated++;
|
|
1499
|
+
} else {
|
|
1500
|
+
db.prepare(`
|
|
1501
|
+
INSERT INTO source_files (collection_id, file_path, file_hash, file_size, chunk_count, last_indexed_at)
|
|
1502
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
1503
|
+
`).run(col.id, file.relPath, file.hash, file.size, fileChunks.length, now);
|
|
1504
|
+
added++;
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
if (allChunks.length > 0) {
|
|
1508
|
+
const ingested = await this.ingest(allChunks);
|
|
1509
|
+
chunksAdded += ingested;
|
|
1510
|
+
}
|
|
1511
|
+
}
|
|
1512
|
+
for (const [relPath, { id }] of existingFiles) {
|
|
1513
|
+
db.prepare("DELETE FROM source_files WHERE id = ?").run(id);
|
|
1514
|
+
removed++;
|
|
1515
|
+
}
|
|
1516
|
+
const fileCount = db.prepare("SELECT COUNT(*) as count FROM source_files WHERE collection_id = ?").get(col.id).count;
|
|
1517
|
+
const chunkCount = db.prepare("SELECT SUM(chunk_count) as total FROM source_files WHERE collection_id = ?").get(col.id).total || 0;
|
|
1518
|
+
db.prepare("UPDATE source_collections SET file_count = ?, chunk_count = ?, last_sync_at = ? WHERE id = ?").run(fileCount, chunkCount, now, col.id);
|
|
1519
|
+
return {
|
|
1520
|
+
collection: name,
|
|
1521
|
+
added,
|
|
1522
|
+
updated,
|
|
1523
|
+
removed,
|
|
1524
|
+
chunks_added: chunksAdded,
|
|
1525
|
+
duration_ms: Date.now() - startTime
|
|
1526
|
+
};
|
|
1527
|
+
}
|
|
1528
|
+
/** Get status of all source collections. */
|
|
1529
|
+
sourcesStatus() {
|
|
1530
|
+
const db = this.sqliteDb;
|
|
1531
|
+
const collections = db.prepare("SELECT name, root_path, file_count, chunk_count, last_sync_at FROM source_collections").all();
|
|
1532
|
+
const totalFiles = collections.reduce((sum, c) => sum + c.file_count, 0);
|
|
1533
|
+
const totalChunks = collections.reduce((sum, c) => sum + c.chunk_count, 0);
|
|
1534
|
+
return {
|
|
1535
|
+
collections: collections.map((c) => ({
|
|
1536
|
+
name: c.name,
|
|
1537
|
+
root_path: c.root_path,
|
|
1538
|
+
file_count: c.file_count,
|
|
1539
|
+
chunk_count: c.chunk_count,
|
|
1540
|
+
last_sync_at: c.last_sync_at
|
|
1541
|
+
})),
|
|
1542
|
+
total_files: totalFiles,
|
|
1543
|
+
total_chunks: totalChunks
|
|
1544
|
+
};
|
|
1545
|
+
}
|
|
1546
|
+
/** Scan a directory recursively, matching include/ignore patterns. */
|
|
1547
|
+
scanDirectory(rootPath, includePatterns, ignorePatterns) {
|
|
1548
|
+
const results = [];
|
|
1549
|
+
const allowedExtensions = /* @__PURE__ */ new Set();
|
|
1550
|
+
const allowedExactNames = /* @__PURE__ */ new Set();
|
|
1551
|
+
for (const pattern of includePatterns) {
|
|
1552
|
+
const extMatch = pattern.match(/\*\*\/\*(\.\w+)$/);
|
|
1553
|
+
if (extMatch) {
|
|
1554
|
+
allowedExtensions.add(extMatch[1]);
|
|
1555
|
+
}
|
|
1556
|
+
const nameMatch = pattern.match(/\*\*\/([^*]+)$/);
|
|
1557
|
+
if (nameMatch && !nameMatch[1].startsWith("*.")) {
|
|
1558
|
+
allowedExactNames.add(nameMatch[1]);
|
|
1559
|
+
}
|
|
1560
|
+
}
|
|
1561
|
+
const ignoreDirs = /* @__PURE__ */ new Set();
|
|
1562
|
+
for (const pattern of ignorePatterns) {
|
|
1563
|
+
const dirMatch = pattern.match(/\*\*\/([^/*]+)\/\*\*$/);
|
|
1564
|
+
if (dirMatch) {
|
|
1565
|
+
ignoreDirs.add(dirMatch[1]);
|
|
1566
|
+
}
|
|
1567
|
+
}
|
|
1568
|
+
const ignoreFiles = /* @__PURE__ */ new Set();
|
|
1569
|
+
for (const pattern of ignorePatterns) {
|
|
1570
|
+
const fileMatch = pattern.match(/\*\*\/\*(\.\w+)$/);
|
|
1571
|
+
if (fileMatch) {
|
|
1572
|
+
ignoreFiles.add(fileMatch[1]);
|
|
1573
|
+
}
|
|
1574
|
+
const exactMatch = pattern.match(/\*\*\/([^*]+)$/);
|
|
1575
|
+
if (exactMatch && !exactMatch[1].includes("/")) {
|
|
1576
|
+
ignoreFiles.add(exactMatch[1]);
|
|
1577
|
+
}
|
|
1578
|
+
}
|
|
1579
|
+
const walk = (dir) => {
|
|
1580
|
+
let entries;
|
|
1581
|
+
try {
|
|
1582
|
+
entries = readdirSync(dir);
|
|
1583
|
+
} catch {
|
|
1584
|
+
return;
|
|
1585
|
+
}
|
|
1586
|
+
for (const entry of entries) {
|
|
1587
|
+
const fullPath = join2(dir, entry);
|
|
1588
|
+
let stat;
|
|
1589
|
+
try {
|
|
1590
|
+
stat = statSync(fullPath);
|
|
1591
|
+
} catch {
|
|
1592
|
+
continue;
|
|
1593
|
+
}
|
|
1594
|
+
if (stat.isDirectory()) {
|
|
1595
|
+
if (ignoreDirs.has(entry)) continue;
|
|
1596
|
+
if (entry.startsWith(".")) continue;
|
|
1597
|
+
walk(fullPath);
|
|
1598
|
+
} else if (stat.isFile()) {
|
|
1599
|
+
const ext = extname(entry);
|
|
1600
|
+
if (ignoreFiles.has(ext)) continue;
|
|
1601
|
+
if (ignoreFiles.has(entry)) continue;
|
|
1602
|
+
if (allowedExtensions.has(ext) || allowedExactNames.has(entry)) {
|
|
1603
|
+
results.push(fullPath);
|
|
1604
|
+
}
|
|
1605
|
+
}
|
|
1606
|
+
}
|
|
1607
|
+
};
|
|
1608
|
+
walk(rootPath);
|
|
1609
|
+
return results;
|
|
1610
|
+
}
|
|
1611
|
+
// ── Orphan Cleanup ──
|
|
1612
|
+
/** Clean orphaned entries in chunks_vec and chunks_fts that no longer have
|
|
1613
|
+
* corresponding rows in the chunks table. Returns counts of what was found/cleaned. */
|
|
1614
|
+
cleanOrphans(options) {
|
|
1615
|
+
const db = this.sqliteDb;
|
|
1616
|
+
const dryRun = options?.dryRun ?? false;
|
|
1617
|
+
const orphanedVec = db.prepare(
|
|
1618
|
+
"SELECT COUNT(*) as cnt FROM chunks_vec WHERE chunk_id NOT IN (SELECT id FROM chunks)"
|
|
1619
|
+
).get().cnt;
|
|
1620
|
+
const orphanedFts = db.prepare(
|
|
1621
|
+
"SELECT COUNT(*) as cnt FROM chunks_fts WHERE rowid NOT IN (SELECT id FROM chunks)"
|
|
1622
|
+
).get().cnt;
|
|
1623
|
+
if (dryRun) {
|
|
1624
|
+
return { orphanedVec, orphanedFts, cleanedVec: 0, cleanedFts: 0, dryRun: true };
|
|
1625
|
+
}
|
|
1626
|
+
let cleanedVec = 0;
|
|
1627
|
+
if (orphanedVec > 0) {
|
|
1628
|
+
const ids = db.prepare(
|
|
1629
|
+
"SELECT chunk_id FROM chunks_vec WHERE chunk_id NOT IN (SELECT id FROM chunks)"
|
|
1630
|
+
).all();
|
|
1631
|
+
const del = db.prepare("DELETE FROM chunks_vec WHERE chunk_id = ?");
|
|
1632
|
+
const BATCH = 1e3;
|
|
1633
|
+
for (let i = 0; i < ids.length; i += BATCH) {
|
|
1634
|
+
const batch = ids.slice(i, i + BATCH);
|
|
1635
|
+
db.transaction(() => {
|
|
1636
|
+
for (const r of batch) {
|
|
1637
|
+
del.run(r.chunk_id);
|
|
1638
|
+
cleanedVec++;
|
|
1639
|
+
}
|
|
1640
|
+
})();
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1643
|
+
let cleanedFts = 0;
|
|
1644
|
+
if (orphanedFts > 0) {
|
|
1645
|
+
db.exec("DELETE FROM chunks_fts");
|
|
1646
|
+
db.exec("INSERT INTO chunks_fts(rowid, text) SELECT id, text FROM chunks");
|
|
1647
|
+
cleanedFts = orphanedFts;
|
|
1648
|
+
}
|
|
1649
|
+
return { orphanedVec, orphanedFts, cleanedVec, cleanedFts, dryRun: false };
|
|
1650
|
+
}
|
|
1651
|
+
// ── Cleanup ──
|
|
1652
|
+
close() {
|
|
1653
|
+
this.sqliteDb?.close();
|
|
1654
|
+
}
|
|
1655
|
+
};
|
|
1656
|
+
function resolveConfig(overrides) {
|
|
1657
|
+
const HOME2 = process.env.HOME || "";
|
|
1658
|
+
const ldmMemory = join2(HOME2, ".ldm", "memory");
|
|
1659
|
+
let dataDir = overrides?.dataDir || process.env.CRYSTAL_DATA_DIR;
|
|
1660
|
+
if (!dataDir) {
|
|
1661
|
+
if (existsSync2(join2(ldmMemory, "crystal.db"))) {
|
|
1662
|
+
dataDir = ldmMemory;
|
|
1663
|
+
} else {
|
|
1664
|
+
const legacyDir = join2(HOME2, ".openclaw", "memory-crystal");
|
|
1665
|
+
if (existsSync2(join2(legacyDir, "crystal.db"))) {
|
|
1666
|
+
dataDir = legacyDir;
|
|
1667
|
+
} else {
|
|
1668
|
+
dataDir = ldmMemory;
|
|
1669
|
+
}
|
|
1670
|
+
}
|
|
1671
|
+
}
|
|
1672
|
+
loadEnvFile(join2(dataDir, ".env"));
|
|
1673
|
+
const openaiApiKey = overrides?.openaiApiKey || process.env.OPENAI_API_KEY || opRead("OpenAI API", "api key");
|
|
1674
|
+
const googleApiKey = overrides?.googleApiKey || process.env.GOOGLE_API_KEY || opRead("Google AI", "api key");
|
|
1675
|
+
const remoteToken = overrides?.remoteToken || process.env.CRYSTAL_REMOTE_TOKEN || opRead("Memory Crystal Remote", "token");
|
|
1676
|
+
return {
|
|
1677
|
+
dataDir,
|
|
1678
|
+
embeddingProvider: overrides?.embeddingProvider || process.env.CRYSTAL_EMBEDDING_PROVIDER || "openai",
|
|
1679
|
+
openaiApiKey,
|
|
1680
|
+
openaiModel: overrides?.openaiModel || process.env.CRYSTAL_OPENAI_MODEL || "text-embedding-3-small",
|
|
1681
|
+
ollamaHost: overrides?.ollamaHost || process.env.CRYSTAL_OLLAMA_HOST || "http://localhost:11434",
|
|
1682
|
+
ollamaModel: overrides?.ollamaModel || process.env.CRYSTAL_OLLAMA_MODEL || "nomic-embed-text",
|
|
1683
|
+
googleApiKey,
|
|
1684
|
+
googleModel: overrides?.googleModel || process.env.CRYSTAL_GOOGLE_MODEL || "text-embedding-004",
|
|
1685
|
+
remoteUrl: overrides?.remoteUrl || process.env.CRYSTAL_REMOTE_URL,
|
|
1686
|
+
remoteToken
|
|
1687
|
+
};
|
|
1688
|
+
}
|
|
1689
|
+
function loadEnvFile(path) {
|
|
1690
|
+
if (!existsSync2(path)) return;
|
|
1691
|
+
const content = readFileSync2(path, "utf8");
|
|
1692
|
+
for (const line of content.split("\n")) {
|
|
1693
|
+
const trimmed = line.trim();
|
|
1694
|
+
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
1695
|
+
const eqIdx = trimmed.indexOf("=");
|
|
1696
|
+
if (eqIdx === -1) continue;
|
|
1697
|
+
const key = trimmed.slice(0, eqIdx).trim();
|
|
1698
|
+
let value = trimmed.slice(eqIdx + 1).trim();
|
|
1699
|
+
if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
|
|
1700
|
+
value = value.slice(1, -1);
|
|
1701
|
+
}
|
|
1702
|
+
if (key && !process.env[key]) {
|
|
1703
|
+
process.env[key] = value;
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
}
|
|
1707
|
+
function opRead(item, field) {
|
|
1708
|
+
try {
|
|
1709
|
+
const HOME2 = process.env.HOME || "";
|
|
1710
|
+
let saTokenPath = join2(HOME2, ".ldm", "secrets", "op-sa-token");
|
|
1711
|
+
if (!existsSync2(saTokenPath)) {
|
|
1712
|
+
saTokenPath = join2(HOME2, ".openclaw", "secrets", "op-sa-token");
|
|
1713
|
+
}
|
|
1714
|
+
if (!existsSync2(saTokenPath)) return void 0;
|
|
1715
|
+
const saToken = readFileSync2(saTokenPath, "utf8").trim();
|
|
1716
|
+
return execSync2(`op read "op://Agent Secrets/${item}/${field}" 2>/dev/null`, {
|
|
1717
|
+
encoding: "utf8",
|
|
1718
|
+
env: { ...process.env, OP_SERVICE_ACCOUNT_TOKEN: saToken },
|
|
1719
|
+
timeout: 1e4
|
|
1720
|
+
}).trim() || void 0;
|
|
1721
|
+
} catch {
|
|
1722
|
+
return void 0;
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
var RemoteCrystal = class {
|
|
1726
|
+
url;
|
|
1727
|
+
token;
|
|
1728
|
+
constructor(url, token) {
|
|
1729
|
+
this.url = url.replace(/\/$/, "");
|
|
1730
|
+
this.token = token;
|
|
1731
|
+
}
|
|
1732
|
+
async init() {
|
|
1733
|
+
const resp = await fetch(`${this.url}/health`);
|
|
1734
|
+
if (!resp.ok) {
|
|
1735
|
+
throw new Error(`Remote crystal unreachable: ${resp.status}`);
|
|
1736
|
+
}
|
|
1737
|
+
}
|
|
1738
|
+
async request(path, body) {
|
|
1739
|
+
const resp = await fetch(`${this.url}${path}`, {
|
|
1740
|
+
method: body ? "POST" : "GET",
|
|
1741
|
+
headers: {
|
|
1742
|
+
"Authorization": `Bearer ${this.token}`,
|
|
1743
|
+
"Content-Type": "application/json"
|
|
1744
|
+
},
|
|
1745
|
+
...body ? { body: JSON.stringify(body) } : {}
|
|
1746
|
+
});
|
|
1747
|
+
if (!resp.ok) {
|
|
1748
|
+
const err = await resp.text();
|
|
1749
|
+
throw new Error(`Remote crystal error ${resp.status}: ${err}`);
|
|
1750
|
+
}
|
|
1751
|
+
return resp.json();
|
|
1752
|
+
}
|
|
1753
|
+
async search(query, limit = 5, filter) {
|
|
1754
|
+
const data = await this.request("/search", { query, limit, agent_id: filter?.agent_id });
|
|
1755
|
+
return data.results || [];
|
|
1756
|
+
}
|
|
1757
|
+
async ingest(chunks) {
|
|
1758
|
+
const data = await this.request("/ingest", { chunks });
|
|
1759
|
+
return data.ingested || 0;
|
|
1760
|
+
}
|
|
1761
|
+
async remember(text, category = "fact") {
|
|
1762
|
+
const data = await this.request("/remember", { text, category });
|
|
1763
|
+
return data.id;
|
|
1764
|
+
}
|
|
1765
|
+
forget(memoryId) {
|
|
1766
|
+
return this.request("/forget", { id: memoryId }).then((d) => d.ok);
|
|
1767
|
+
}
|
|
1768
|
+
async status() {
|
|
1769
|
+
const data = await this.request("/status");
|
|
1770
|
+
return {
|
|
1771
|
+
chunks: data.chunks || 0,
|
|
1772
|
+
memories: data.memories || 0,
|
|
1773
|
+
sources: 0,
|
|
1774
|
+
agents: data.agents || [],
|
|
1775
|
+
oldestChunk: data.oldestChunk,
|
|
1776
|
+
newestChunk: data.newestChunk,
|
|
1777
|
+
embeddingProvider: "remote",
|
|
1778
|
+
dataDir: this.url,
|
|
1779
|
+
capturedSessions: data.capturedSessions || 0,
|
|
1780
|
+
latestCapture: data.newestChunk
|
|
1781
|
+
};
|
|
1782
|
+
}
|
|
1783
|
+
// Expose chunkText from a local Crystal instance for cc-hook to use
|
|
1784
|
+
chunkText(text) {
|
|
1785
|
+
const targetChars = 400 * 4;
|
|
1786
|
+
const overlapChars = 80 * 4;
|
|
1787
|
+
if (text.length <= targetChars) return [text];
|
|
1788
|
+
const chunks = [];
|
|
1789
|
+
let start = 0;
|
|
1790
|
+
while (start < text.length) {
|
|
1791
|
+
let end = start + targetChars;
|
|
1792
|
+
if (end >= text.length) {
|
|
1793
|
+
chunks.push(text.slice(start));
|
|
1794
|
+
break;
|
|
1795
|
+
}
|
|
1796
|
+
const paraBreak = text.lastIndexOf("\n\n", end);
|
|
1797
|
+
if (paraBreak > start + targetChars * 0.5) end = paraBreak;
|
|
1798
|
+
else {
|
|
1799
|
+
const sentBreak = text.lastIndexOf(". ", end);
|
|
1800
|
+
if (sentBreak > start + targetChars * 0.5) end = sentBreak + 1;
|
|
1801
|
+
}
|
|
1802
|
+
chunks.push(text.slice(start, end));
|
|
1803
|
+
start = end - overlapChars;
|
|
1804
|
+
}
|
|
1805
|
+
return chunks;
|
|
1806
|
+
}
|
|
1807
|
+
};
|
|
1808
|
+
function createCrystal(config2) {
|
|
1809
|
+
if (config2.remoteUrl && config2.remoteToken) {
|
|
1810
|
+
return new RemoteCrystal(config2.remoteUrl, config2.remoteToken);
|
|
1811
|
+
}
|
|
1812
|
+
return new Crystal(config2);
|
|
1813
|
+
}
|
|
1814
|
+
|
|
1815
|
+
// src/ldm.ts
|
|
1816
|
+
import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync, copyFileSync, chmodSync, readdirSync as readdirSync2 } from "fs";
|
|
1817
|
+
import { join as join3, dirname } from "path";
|
|
1818
|
+
import { execSync as execSync3 } from "child_process";
|
|
1819
|
+
import { fileURLToPath } from "url";
|
|
1820
|
+
var HOME = process.env.HOME || "";
|
|
1821
|
+
var LDM_ROOT = join3(HOME, ".ldm");
|
|
1822
|
+
function loadAgentConfig(id) {
|
|
1823
|
+
const cfgPath = join3(LDM_ROOT, "agents", id, "config.json");
|
|
1824
|
+
try {
|
|
1825
|
+
if (existsSync3(cfgPath)) return JSON.parse(readFileSync3(cfgPath, "utf-8"));
|
|
1826
|
+
} catch {
|
|
1827
|
+
}
|
|
1828
|
+
return null;
|
|
1829
|
+
}
|
|
1830
|
+
function getAgentId(harnessHint) {
|
|
1831
|
+
if (process.env.CRYSTAL_AGENT_ID) return process.env.CRYSTAL_AGENT_ID;
|
|
1832
|
+
const agentsDir = join3(LDM_ROOT, "agents");
|
|
1833
|
+
if (existsSync3(agentsDir)) {
|
|
1834
|
+
try {
|
|
1835
|
+
for (const d of readdirSync2(agentsDir)) {
|
|
1836
|
+
const cfg = loadAgentConfig(d);
|
|
1837
|
+
if (!cfg || !cfg.agentId) continue;
|
|
1838
|
+
if (!harnessHint) return cfg.agentId;
|
|
1839
|
+
if (harnessHint === "claude-code" && cfg.harness === "claude-code-cli") return cfg.agentId;
|
|
1840
|
+
if (harnessHint === "openclaw" && cfg.harness === "openclaw") return cfg.agentId;
|
|
1841
|
+
}
|
|
1842
|
+
} catch {
|
|
1843
|
+
}
|
|
1844
|
+
}
|
|
1845
|
+
return harnessHint === "openclaw" ? "oc-lesa-mini" : "cc-mini";
|
|
1846
|
+
}
|
|
1847
|
+
function ldmPaths(agentId) {
|
|
1848
|
+
const id = agentId || getAgentId();
|
|
1849
|
+
const agentRoot = join3(LDM_ROOT, "agents", id);
|
|
1850
|
+
return {
|
|
1851
|
+
root: LDM_ROOT,
|
|
1852
|
+
bin: join3(LDM_ROOT, "bin"),
|
|
1853
|
+
secrets: join3(LDM_ROOT, "secrets"),
|
|
1854
|
+
state: join3(LDM_ROOT, "state"),
|
|
1855
|
+
config: join3(LDM_ROOT, "config.json"),
|
|
1856
|
+
crystalDb: join3(LDM_ROOT, "memory", "crystal.db"),
|
|
1857
|
+
crystalLance: join3(LDM_ROOT, "memory", "lance"),
|
|
1858
|
+
agentRoot,
|
|
1859
|
+
transcripts: join3(agentRoot, "memory", "transcripts"),
|
|
1860
|
+
sessions: join3(agentRoot, "memory", "sessions"),
|
|
1861
|
+
daily: join3(agentRoot, "memory", "daily"),
|
|
1862
|
+
journals: join3(agentRoot, "memory", "journals"),
|
|
1863
|
+
workspace: join3(agentRoot, "memory", "workspace")
|
|
1864
|
+
};
|
|
1865
|
+
}
|
|
1866
|
+
var LEGACY_OC_DIR = join3(HOME, ".openclaw");
|
|
1867
|
+
function resolveStatePath(filename) {
|
|
1868
|
+
const paths = ldmPaths();
|
|
1869
|
+
const ldmPath = join3(paths.state, filename);
|
|
1870
|
+
if (existsSync3(ldmPath)) return ldmPath;
|
|
1871
|
+
const legacyPath = join3(LEGACY_OC_DIR, "memory", filename);
|
|
1872
|
+
if (existsSync3(legacyPath)) return legacyPath;
|
|
1873
|
+
return ldmPath;
|
|
1874
|
+
}
|
|
1875
|
+
function stateWritePath(filename) {
|
|
1876
|
+
const paths = ldmPaths();
|
|
1877
|
+
const dir = paths.state;
|
|
1878
|
+
if (!existsSync3(dir)) mkdirSync2(dir, { recursive: true });
|
|
1879
|
+
return join3(dir, filename);
|
|
1880
|
+
}
|
|
1881
|
+
|
|
1882
|
+
// src/mcp-server.ts
|
|
1883
|
+
init_llm();
|
|
1884
|
+
import { existsSync as existsSync4, readFileSync as readFileSync4, appendFileSync } from "fs";
|
|
20
1885
|
var PRIVATE_MODE_PATH = resolveStatePath("memory-capture-state.json");
|
|
21
1886
|
function isPrivateMode() {
|
|
22
1887
|
try {
|
|
23
|
-
if (
|
|
24
|
-
const state = JSON.parse(
|
|
1888
|
+
if (existsSync4(PRIVATE_MODE_PATH)) {
|
|
1889
|
+
const state = JSON.parse(readFileSync4(PRIVATE_MODE_PATH, "utf-8"));
|
|
25
1890
|
return state.enabled === false;
|
|
26
1891
|
}
|
|
27
1892
|
} catch {
|
|
@@ -146,8 +2011,8 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
146
2011
|
try {
|
|
147
2012
|
await crystal.init();
|
|
148
2013
|
if (!isRemote && crystal.sqliteDb) {
|
|
149
|
-
const { setLLMCacheDb } = await
|
|
150
|
-
|
|
2014
|
+
const { setLLMCacheDb: setLLMCacheDb2 } = await Promise.resolve().then(() => (init_llm(), llm_exports));
|
|
2015
|
+
setLLMCacheDb2(crystal.sqliteDb);
|
|
151
2016
|
}
|
|
152
2017
|
switch (name) {
|
|
153
2018
|
case "crystal_search": {
|