dsh-tdai-memory 0.2.9 → 0.2.11
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 +21 -21
- package/README.md +130 -130
- package/README.zh.md +72 -72
- package/THIRD-PARTY-NOTICES.md +20 -20
- package/client.js +349 -311
- package/cordis.patch.yml +8 -8
- package/index.js +421 -421
- package/package.json +8 -5
- package/recall-inject.js +86 -86
- package/vendor/dsh-settings-expose.js +75 -75
- package/vendor/tdai/adapters/index.js +15 -15
- package/vendor/tdai/adapters/openclaw/host-adapter.js +83 -83
- package/vendor/tdai/adapters/openclaw/index.js +5 -5
- package/vendor/tdai/adapters/openclaw/llm-runner.js +69 -69
- package/vendor/tdai/adapters/standalone/host-adapter.js +58 -58
- package/vendor/tdai/adapters/standalone/index.js +5 -5
- package/vendor/tdai/adapters/standalone/llm-runner.js +246 -246
- package/vendor/tdai/config.js +363 -363
- package/vendor/tdai/core/conversation/l0-recorder.js +420 -420
- package/vendor/tdai/core/hooks/auto-capture.js +236 -236
- package/vendor/tdai/core/hooks/auto-recall.js +640 -640
- package/vendor/tdai/core/index.js +8 -8
- package/vendor/tdai/core/persona/persona-generator.js +184 -184
- package/vendor/tdai/core/persona/persona-trigger.js +94 -94
- package/vendor/tdai/core/profile/profile-sync.js +200 -200
- package/vendor/tdai/core/prompts/l1-dedup.js +72 -72
- package/vendor/tdai/core/prompts/l1-extraction.js +34 -34
- package/vendor/tdai/core/prompts/persona-generation.js +35 -35
- package/vendor/tdai/core/prompts/scene-extraction.js +45 -45
- package/vendor/tdai/core/record/l1-dedup.js +318 -318
- package/vendor/tdai/core/record/l1-extractor.js +379 -379
- package/vendor/tdai/core/record/l1-reader.js +178 -178
- package/vendor/tdai/core/record/l1-writer.js +141 -141
- package/vendor/tdai/core/report/reporter.js +86 -86
- package/vendor/tdai/core/scene/filename-normalizer.js +161 -161
- package/vendor/tdai/core/scene/scene-extractor.js +410 -410
- package/vendor/tdai/core/scene/scene-format.js +53 -53
- package/vendor/tdai/core/scene/scene-index.js +82 -82
- package/vendor/tdai/core/scene/scene-navigation.js +57 -57
- package/vendor/tdai/core/seed/input.js +404 -404
- package/vendor/tdai/core/seed/seed-runtime.js +314 -314
- package/vendor/tdai/core/seed/types.js +9 -9
- package/vendor/tdai/core/store/bm25-client.js +117 -117
- package/vendor/tdai/core/store/bm25-local.js +68 -68
- package/vendor/tdai/core/store/embedding.js +632 -632
- package/vendor/tdai/core/store/factory.js +95 -95
- package/vendor/tdai/core/store/search-utils.js +54 -54
- package/vendor/tdai/core/store/sqlite.js +1632 -1632
- package/vendor/tdai/core/store/tcvdb-client.js +221 -221
- package/vendor/tdai/core/store/tcvdb.js +1047 -1047
- package/vendor/tdai/core/store/types.js +17 -17
- package/vendor/tdai/core/tdai-core.js +446 -446
- package/vendor/tdai/core/tools/conversation-search.js +199 -199
- package/vendor/tdai/core/tools/memory-search.js +207 -207
- package/vendor/tdai/core/types.js +12 -12
- package/vendor/tdai/utils/backup.js +189 -189
- package/vendor/tdai/utils/checkpoint.js +360 -360
- package/vendor/tdai/utils/clean-context-runner.js +472 -472
- package/vendor/tdai/utils/ensure-hook-policy.js +213 -213
- package/vendor/tdai/utils/env.js +13 -13
- package/vendor/tdai/utils/managed-timer.js +127 -127
- package/vendor/tdai/utils/manifest.js +91 -91
- package/vendor/tdai/utils/memory-cleaner.js +300 -300
- package/vendor/tdai/utils/no-think-fetch.js +109 -109
- package/vendor/tdai/utils/openclaw-state-dir.js +26 -26
- package/vendor/tdai/utils/pipeline-factory.js +517 -517
- package/vendor/tdai/utils/pipeline-manager.js +892 -892
- package/vendor/tdai/utils/sanitize.js +360 -360
- package/vendor/tdai/utils/serial-queue.js +103 -103
- package/vendor/tdai/utils/session-filter.js +88 -88
- package/vendor/tdai/utils/text-utils.js +29 -29
- package/vendor/tdai/utils/time.js +252 -252
|
@@ -1,207 +1,207 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* memory_search tool: Agent-callable tool for searching L1 memory records.
|
|
3
|
-
*
|
|
4
|
-
* Supports three search strategies with automatic degradation:
|
|
5
|
-
* 1. **hybrid** (default) — FTS5 keyword + vector embedding in parallel,
|
|
6
|
-
* merged via Reciprocal Rank Fusion (RRF).
|
|
7
|
-
* 2. **embedding** — pure vector similarity (when FTS5 is unavailable).
|
|
8
|
-
* 3. **fts** — pure FTS5 keyword search (when embedding is unavailable).
|
|
9
|
-
*
|
|
10
|
-
* The tool is registered via `api.registerTool()` in index.ts.
|
|
11
|
-
*/
|
|
12
|
-
import { buildFtsQuery } from "../store/sqlite.js";
|
|
13
|
-
const TAG = "[memory-tdai][tdai_memory_search]";
|
|
14
|
-
// ============================
|
|
15
|
-
// RRF (Reciprocal Rank Fusion)
|
|
16
|
-
// ============================
|
|
17
|
-
/** Standard RRF constant from the original RRF paper. */
|
|
18
|
-
const RRF_K = 60;
|
|
19
|
-
/**
|
|
20
|
-
* Merge multiple ranked lists of `MemorySearchResultItem` via Reciprocal Rank
|
|
21
|
-
* Fusion. Items appearing in multiple lists get their RRF scores summed.
|
|
22
|
-
*
|
|
23
|
-
* Returns items sorted by descending RRF score. The `score` field of each
|
|
24
|
-
* returned item is replaced by the RRF score for consistent ranking semantics.
|
|
25
|
-
*/
|
|
26
|
-
function rrfMergeL1(...lists) {
|
|
27
|
-
const map = new Map();
|
|
28
|
-
for (const list of lists) {
|
|
29
|
-
for (let rank = 0; rank < list.length; rank++) {
|
|
30
|
-
const item = list[rank];
|
|
31
|
-
const score = 1 / (RRF_K + rank + 1);
|
|
32
|
-
const existing = map.get(item.id);
|
|
33
|
-
if (existing) {
|
|
34
|
-
existing.rrfScore += score;
|
|
35
|
-
}
|
|
36
|
-
else {
|
|
37
|
-
map.set(item.id, { item, rrfScore: score });
|
|
38
|
-
}
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
return [...map.values()]
|
|
42
|
-
.sort((a, b) => b.rrfScore - a.rrfScore)
|
|
43
|
-
.map(({ item, rrfScore }) => ({ ...item, score: rrfScore }));
|
|
44
|
-
}
|
|
45
|
-
// ============================
|
|
46
|
-
// Search implementation
|
|
47
|
-
// ============================
|
|
48
|
-
export async function executeMemorySearch(params) {
|
|
49
|
-
const { query, limit, type: typeFilter, scene: sceneFilter, vectorStore, embeddingService, logger, } = params;
|
|
50
|
-
logger?.debug?.(`${TAG} CALLED: query="${query.slice(0, 100)}", limit=${limit}, ` +
|
|
51
|
-
`typeFilter=${typeFilter ?? "(none)"}, sceneFilter=${sceneFilter ?? "(none)"}, ` +
|
|
52
|
-
`vectorStore=${vectorStore ? "available" : "UNAVAILABLE"}, ` +
|
|
53
|
-
`embeddingService=${embeddingService ? "available" : "UNAVAILABLE"}`);
|
|
54
|
-
if (!query || query.trim().length === 0) {
|
|
55
|
-
logger?.debug?.(`${TAG} Empty query, returning empty`);
|
|
56
|
-
return { results: [], total: 0, strategy: "none" };
|
|
57
|
-
}
|
|
58
|
-
if (!vectorStore) {
|
|
59
|
-
logger?.warn?.(`${TAG} VectorStore not available`);
|
|
60
|
-
return { results: [], total: 0, strategy: "none" };
|
|
61
|
-
}
|
|
62
|
-
// ── Determine available capabilities ──
|
|
63
|
-
const hasEmbedding = !!embeddingService;
|
|
64
|
-
const hasFts = vectorStore.isFtsAvailable();
|
|
65
|
-
if (!hasEmbedding && !hasFts) {
|
|
66
|
-
logger?.warn?.(`${TAG} Neither EmbeddingService nor FTS5 available — cannot search`);
|
|
67
|
-
return {
|
|
68
|
-
results: [],
|
|
69
|
-
total: 0,
|
|
70
|
-
strategy: "none",
|
|
71
|
-
message: "Embedding service is not configured and FTS is not available. " +
|
|
72
|
-
"Memory search requires an embedding provider or FTS5 support. " +
|
|
73
|
-
"Please configure an embedding provider in the embedding.provider setting (e.g. openai_compatible).",
|
|
74
|
-
};
|
|
75
|
-
}
|
|
76
|
-
// ── Over-retrieve for later filtering and RRF merging ──
|
|
77
|
-
const candidateK = limit * 3;
|
|
78
|
-
// ── Run available search strategies in parallel ──
|
|
79
|
-
const [ftsItems, vecItems] = await Promise.all([
|
|
80
|
-
// FTS5 keyword search
|
|
81
|
-
(async () => {
|
|
82
|
-
if (!hasFts)
|
|
83
|
-
return [];
|
|
84
|
-
try {
|
|
85
|
-
const ftsQuery = buildFtsQuery(query);
|
|
86
|
-
if (!ftsQuery) {
|
|
87
|
-
logger?.debug?.(`${TAG} [hybrid-fts] No usable FTS tokens from query`);
|
|
88
|
-
return [];
|
|
89
|
-
}
|
|
90
|
-
logger?.debug?.(`${TAG} [hybrid-fts] FTS5 query: "${ftsQuery}"`);
|
|
91
|
-
const ftsResults = await vectorStore.searchL1Fts(ftsQuery, candidateK);
|
|
92
|
-
logger?.debug?.(`${TAG} [hybrid-fts] FTS5 returned ${ftsResults.length} candidates`);
|
|
93
|
-
return ftsResults.map((r) => ({
|
|
94
|
-
id: r.record_id,
|
|
95
|
-
content: r.content,
|
|
96
|
-
type: r.type,
|
|
97
|
-
priority: r.priority,
|
|
98
|
-
scene_name: r.scene_name,
|
|
99
|
-
score: r.score,
|
|
100
|
-
created_at: r.timestamp_start,
|
|
101
|
-
updated_at: r.timestamp_end,
|
|
102
|
-
}));
|
|
103
|
-
}
|
|
104
|
-
catch (err) {
|
|
105
|
-
logger?.warn?.(`${TAG} [hybrid-fts] FTS5 search failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`);
|
|
106
|
-
return [];
|
|
107
|
-
}
|
|
108
|
-
})(),
|
|
109
|
-
// Vector embedding search
|
|
110
|
-
(async () => {
|
|
111
|
-
if (!hasEmbedding)
|
|
112
|
-
return [];
|
|
113
|
-
try {
|
|
114
|
-
logger?.debug?.(`${TAG} [hybrid-vec] Generating query embedding...`);
|
|
115
|
-
const queryEmbedding = await embeddingService.embed(query);
|
|
116
|
-
logger?.debug?.(`${TAG} [hybrid-vec] Embedding OK, dims=${queryEmbedding.length}, searching top-${candidateK}...`);
|
|
117
|
-
const vecResults = await vectorStore.searchL1Vector(queryEmbedding, candidateK, query);
|
|
118
|
-
logger?.debug?.(`${TAG} [hybrid-vec] Vector search returned ${vecResults.length} candidates`);
|
|
119
|
-
return vecResults.map((r) => ({
|
|
120
|
-
id: r.record_id,
|
|
121
|
-
content: r.content,
|
|
122
|
-
type: r.type,
|
|
123
|
-
priority: r.priority,
|
|
124
|
-
scene_name: r.scene_name,
|
|
125
|
-
score: r.score,
|
|
126
|
-
created_at: r.timestamp_start,
|
|
127
|
-
updated_at: r.timestamp_end,
|
|
128
|
-
}));
|
|
129
|
-
}
|
|
130
|
-
catch (err) {
|
|
131
|
-
logger?.warn?.(`${TAG} [hybrid-vec] Embedding search failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`);
|
|
132
|
-
return [];
|
|
133
|
-
}
|
|
134
|
-
})(),
|
|
135
|
-
]);
|
|
136
|
-
// ── Determine effective strategy ──
|
|
137
|
-
const ftsOk = ftsItems.length > 0;
|
|
138
|
-
const vecOk = vecItems.length > 0;
|
|
139
|
-
let strategy;
|
|
140
|
-
if (ftsOk && vecOk) {
|
|
141
|
-
strategy = "hybrid";
|
|
142
|
-
}
|
|
143
|
-
else if (vecOk) {
|
|
144
|
-
strategy = "embedding";
|
|
145
|
-
}
|
|
146
|
-
else if (ftsOk) {
|
|
147
|
-
strategy = "fts";
|
|
148
|
-
}
|
|
149
|
-
else {
|
|
150
|
-
logger?.debug?.(`${TAG} Both search paths returned 0 results`);
|
|
151
|
-
return { results: [], total: 0, strategy: hasEmbedding ? "embedding" : "fts" };
|
|
152
|
-
}
|
|
153
|
-
// ── Merge results ──
|
|
154
|
-
let results;
|
|
155
|
-
if (strategy === "hybrid") {
|
|
156
|
-
results = rrfMergeL1(ftsItems, vecItems);
|
|
157
|
-
logger?.debug?.(`${TAG} [hybrid] RRF merged: fts=${ftsItems.length}, vec=${vecItems.length} → ${results.length} unique`);
|
|
158
|
-
}
|
|
159
|
-
else {
|
|
160
|
-
// Single-source: use whichever list has results (already sorted by score)
|
|
161
|
-
results = ftsOk ? ftsItems : vecItems;
|
|
162
|
-
}
|
|
163
|
-
// ── Apply secondary filters (type, scene) ──
|
|
164
|
-
const preFilterCount = results.length;
|
|
165
|
-
if (typeFilter) {
|
|
166
|
-
results = results.filter((r) => r.type === typeFilter);
|
|
167
|
-
logger?.debug?.(`${TAG} After type filter "${typeFilter}": ${results.length}/${preFilterCount}`);
|
|
168
|
-
}
|
|
169
|
-
if (sceneFilter) {
|
|
170
|
-
const normalizedScene = sceneFilter.toLowerCase();
|
|
171
|
-
results = results.filter((r) => r.scene_name.toLowerCase().includes(normalizedScene));
|
|
172
|
-
logger?.debug?.(`${TAG} After scene filter "${sceneFilter}": ${results.length}/${preFilterCount}`);
|
|
173
|
-
}
|
|
174
|
-
// ── Trim to requested limit ──
|
|
175
|
-
const trimmed = results.slice(0, limit);
|
|
176
|
-
logger?.debug?.(`${TAG} RESULT (strategy=${strategy}): returning ${trimmed.length} memories ` +
|
|
177
|
-
`(scores: [${trimmed.map((r) => r.score.toFixed(3)).join(", ")}])`);
|
|
178
|
-
return {
|
|
179
|
-
results: trimmed,
|
|
180
|
-
total: trimmed.length,
|
|
181
|
-
strategy,
|
|
182
|
-
};
|
|
183
|
-
}
|
|
184
|
-
// ============================
|
|
185
|
-
// Tool response formatter
|
|
186
|
-
// ============================
|
|
187
|
-
export function formatSearchResponse(result) {
|
|
188
|
-
if (result.message) {
|
|
189
|
-
return result.message;
|
|
190
|
-
}
|
|
191
|
-
if (result.results.length === 0) {
|
|
192
|
-
return "No matching memories found.";
|
|
193
|
-
}
|
|
194
|
-
const lines = [
|
|
195
|
-
`Found ${result.total} matching memories:`,
|
|
196
|
-
"",
|
|
197
|
-
];
|
|
198
|
-
for (const item of result.results) {
|
|
199
|
-
const scoreStr = typeof item.score === "number" ? ` (score: ${item.score.toFixed(3)})` : "";
|
|
200
|
-
const sceneStr = item.scene_name ? ` [scene: ${item.scene_name}]` : "";
|
|
201
|
-
const priorityStr = item.priority >= 0 ? ` (priority: ${item.priority})` : " (global instruction)";
|
|
202
|
-
lines.push(`- **[${item.type}]**${priorityStr}${sceneStr}${scoreStr}`);
|
|
203
|
-
lines.push(` ${item.content}`);
|
|
204
|
-
lines.push("");
|
|
205
|
-
}
|
|
206
|
-
return lines.join("\n");
|
|
207
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* memory_search tool: Agent-callable tool for searching L1 memory records.
|
|
3
|
+
*
|
|
4
|
+
* Supports three search strategies with automatic degradation:
|
|
5
|
+
* 1. **hybrid** (default) — FTS5 keyword + vector embedding in parallel,
|
|
6
|
+
* merged via Reciprocal Rank Fusion (RRF).
|
|
7
|
+
* 2. **embedding** — pure vector similarity (when FTS5 is unavailable).
|
|
8
|
+
* 3. **fts** — pure FTS5 keyword search (when embedding is unavailable).
|
|
9
|
+
*
|
|
10
|
+
* The tool is registered via `api.registerTool()` in index.ts.
|
|
11
|
+
*/
|
|
12
|
+
import { buildFtsQuery } from "../store/sqlite.js";
|
|
13
|
+
const TAG = "[memory-tdai][tdai_memory_search]";
|
|
14
|
+
// ============================
|
|
15
|
+
// RRF (Reciprocal Rank Fusion)
|
|
16
|
+
// ============================
|
|
17
|
+
/** Standard RRF constant from the original RRF paper. */
|
|
18
|
+
const RRF_K = 60;
|
|
19
|
+
/**
|
|
20
|
+
* Merge multiple ranked lists of `MemorySearchResultItem` via Reciprocal Rank
|
|
21
|
+
* Fusion. Items appearing in multiple lists get their RRF scores summed.
|
|
22
|
+
*
|
|
23
|
+
* Returns items sorted by descending RRF score. The `score` field of each
|
|
24
|
+
* returned item is replaced by the RRF score for consistent ranking semantics.
|
|
25
|
+
*/
|
|
26
|
+
function rrfMergeL1(...lists) {
|
|
27
|
+
const map = new Map();
|
|
28
|
+
for (const list of lists) {
|
|
29
|
+
for (let rank = 0; rank < list.length; rank++) {
|
|
30
|
+
const item = list[rank];
|
|
31
|
+
const score = 1 / (RRF_K + rank + 1);
|
|
32
|
+
const existing = map.get(item.id);
|
|
33
|
+
if (existing) {
|
|
34
|
+
existing.rrfScore += score;
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
map.set(item.id, { item, rrfScore: score });
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return [...map.values()]
|
|
42
|
+
.sort((a, b) => b.rrfScore - a.rrfScore)
|
|
43
|
+
.map(({ item, rrfScore }) => ({ ...item, score: rrfScore }));
|
|
44
|
+
}
|
|
45
|
+
// ============================
|
|
46
|
+
// Search implementation
|
|
47
|
+
// ============================
|
|
48
|
+
export async function executeMemorySearch(params) {
|
|
49
|
+
const { query, limit, type: typeFilter, scene: sceneFilter, vectorStore, embeddingService, logger, } = params;
|
|
50
|
+
logger?.debug?.(`${TAG} CALLED: query="${query.slice(0, 100)}", limit=${limit}, ` +
|
|
51
|
+
`typeFilter=${typeFilter ?? "(none)"}, sceneFilter=${sceneFilter ?? "(none)"}, ` +
|
|
52
|
+
`vectorStore=${vectorStore ? "available" : "UNAVAILABLE"}, ` +
|
|
53
|
+
`embeddingService=${embeddingService ? "available" : "UNAVAILABLE"}`);
|
|
54
|
+
if (!query || query.trim().length === 0) {
|
|
55
|
+
logger?.debug?.(`${TAG} Empty query, returning empty`);
|
|
56
|
+
return { results: [], total: 0, strategy: "none" };
|
|
57
|
+
}
|
|
58
|
+
if (!vectorStore) {
|
|
59
|
+
logger?.warn?.(`${TAG} VectorStore not available`);
|
|
60
|
+
return { results: [], total: 0, strategy: "none" };
|
|
61
|
+
}
|
|
62
|
+
// ── Determine available capabilities ──
|
|
63
|
+
const hasEmbedding = !!embeddingService;
|
|
64
|
+
const hasFts = vectorStore.isFtsAvailable();
|
|
65
|
+
if (!hasEmbedding && !hasFts) {
|
|
66
|
+
logger?.warn?.(`${TAG} Neither EmbeddingService nor FTS5 available — cannot search`);
|
|
67
|
+
return {
|
|
68
|
+
results: [],
|
|
69
|
+
total: 0,
|
|
70
|
+
strategy: "none",
|
|
71
|
+
message: "Embedding service is not configured and FTS is not available. " +
|
|
72
|
+
"Memory search requires an embedding provider or FTS5 support. " +
|
|
73
|
+
"Please configure an embedding provider in the embedding.provider setting (e.g. openai_compatible).",
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
// ── Over-retrieve for later filtering and RRF merging ──
|
|
77
|
+
const candidateK = limit * 3;
|
|
78
|
+
// ── Run available search strategies in parallel ──
|
|
79
|
+
const [ftsItems, vecItems] = await Promise.all([
|
|
80
|
+
// FTS5 keyword search
|
|
81
|
+
(async () => {
|
|
82
|
+
if (!hasFts)
|
|
83
|
+
return [];
|
|
84
|
+
try {
|
|
85
|
+
const ftsQuery = buildFtsQuery(query);
|
|
86
|
+
if (!ftsQuery) {
|
|
87
|
+
logger?.debug?.(`${TAG} [hybrid-fts] No usable FTS tokens from query`);
|
|
88
|
+
return [];
|
|
89
|
+
}
|
|
90
|
+
logger?.debug?.(`${TAG} [hybrid-fts] FTS5 query: "${ftsQuery}"`);
|
|
91
|
+
const ftsResults = await vectorStore.searchL1Fts(ftsQuery, candidateK);
|
|
92
|
+
logger?.debug?.(`${TAG} [hybrid-fts] FTS5 returned ${ftsResults.length} candidates`);
|
|
93
|
+
return ftsResults.map((r) => ({
|
|
94
|
+
id: r.record_id,
|
|
95
|
+
content: r.content,
|
|
96
|
+
type: r.type,
|
|
97
|
+
priority: r.priority,
|
|
98
|
+
scene_name: r.scene_name,
|
|
99
|
+
score: r.score,
|
|
100
|
+
created_at: r.timestamp_start,
|
|
101
|
+
updated_at: r.timestamp_end,
|
|
102
|
+
}));
|
|
103
|
+
}
|
|
104
|
+
catch (err) {
|
|
105
|
+
logger?.warn?.(`${TAG} [hybrid-fts] FTS5 search failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`);
|
|
106
|
+
return [];
|
|
107
|
+
}
|
|
108
|
+
})(),
|
|
109
|
+
// Vector embedding search
|
|
110
|
+
(async () => {
|
|
111
|
+
if (!hasEmbedding)
|
|
112
|
+
return [];
|
|
113
|
+
try {
|
|
114
|
+
logger?.debug?.(`${TAG} [hybrid-vec] Generating query embedding...`);
|
|
115
|
+
const queryEmbedding = await embeddingService.embed(query);
|
|
116
|
+
logger?.debug?.(`${TAG} [hybrid-vec] Embedding OK, dims=${queryEmbedding.length}, searching top-${candidateK}...`);
|
|
117
|
+
const vecResults = await vectorStore.searchL1Vector(queryEmbedding, candidateK, query);
|
|
118
|
+
logger?.debug?.(`${TAG} [hybrid-vec] Vector search returned ${vecResults.length} candidates`);
|
|
119
|
+
return vecResults.map((r) => ({
|
|
120
|
+
id: r.record_id,
|
|
121
|
+
content: r.content,
|
|
122
|
+
type: r.type,
|
|
123
|
+
priority: r.priority,
|
|
124
|
+
scene_name: r.scene_name,
|
|
125
|
+
score: r.score,
|
|
126
|
+
created_at: r.timestamp_start,
|
|
127
|
+
updated_at: r.timestamp_end,
|
|
128
|
+
}));
|
|
129
|
+
}
|
|
130
|
+
catch (err) {
|
|
131
|
+
logger?.warn?.(`${TAG} [hybrid-vec] Embedding search failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`);
|
|
132
|
+
return [];
|
|
133
|
+
}
|
|
134
|
+
})(),
|
|
135
|
+
]);
|
|
136
|
+
// ── Determine effective strategy ──
|
|
137
|
+
const ftsOk = ftsItems.length > 0;
|
|
138
|
+
const vecOk = vecItems.length > 0;
|
|
139
|
+
let strategy;
|
|
140
|
+
if (ftsOk && vecOk) {
|
|
141
|
+
strategy = "hybrid";
|
|
142
|
+
}
|
|
143
|
+
else if (vecOk) {
|
|
144
|
+
strategy = "embedding";
|
|
145
|
+
}
|
|
146
|
+
else if (ftsOk) {
|
|
147
|
+
strategy = "fts";
|
|
148
|
+
}
|
|
149
|
+
else {
|
|
150
|
+
logger?.debug?.(`${TAG} Both search paths returned 0 results`);
|
|
151
|
+
return { results: [], total: 0, strategy: hasEmbedding ? "embedding" : "fts" };
|
|
152
|
+
}
|
|
153
|
+
// ── Merge results ──
|
|
154
|
+
let results;
|
|
155
|
+
if (strategy === "hybrid") {
|
|
156
|
+
results = rrfMergeL1(ftsItems, vecItems);
|
|
157
|
+
logger?.debug?.(`${TAG} [hybrid] RRF merged: fts=${ftsItems.length}, vec=${vecItems.length} → ${results.length} unique`);
|
|
158
|
+
}
|
|
159
|
+
else {
|
|
160
|
+
// Single-source: use whichever list has results (already sorted by score)
|
|
161
|
+
results = ftsOk ? ftsItems : vecItems;
|
|
162
|
+
}
|
|
163
|
+
// ── Apply secondary filters (type, scene) ──
|
|
164
|
+
const preFilterCount = results.length;
|
|
165
|
+
if (typeFilter) {
|
|
166
|
+
results = results.filter((r) => r.type === typeFilter);
|
|
167
|
+
logger?.debug?.(`${TAG} After type filter "${typeFilter}": ${results.length}/${preFilterCount}`);
|
|
168
|
+
}
|
|
169
|
+
if (sceneFilter) {
|
|
170
|
+
const normalizedScene = sceneFilter.toLowerCase();
|
|
171
|
+
results = results.filter((r) => r.scene_name.toLowerCase().includes(normalizedScene));
|
|
172
|
+
logger?.debug?.(`${TAG} After scene filter "${sceneFilter}": ${results.length}/${preFilterCount}`);
|
|
173
|
+
}
|
|
174
|
+
// ── Trim to requested limit ──
|
|
175
|
+
const trimmed = results.slice(0, limit);
|
|
176
|
+
logger?.debug?.(`${TAG} RESULT (strategy=${strategy}): returning ${trimmed.length} memories ` +
|
|
177
|
+
`(scores: [${trimmed.map((r) => r.score.toFixed(3)).join(", ")}])`);
|
|
178
|
+
return {
|
|
179
|
+
results: trimmed,
|
|
180
|
+
total: trimmed.length,
|
|
181
|
+
strategy,
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
// ============================
|
|
185
|
+
// Tool response formatter
|
|
186
|
+
// ============================
|
|
187
|
+
export function formatSearchResponse(result) {
|
|
188
|
+
if (result.message) {
|
|
189
|
+
return result.message;
|
|
190
|
+
}
|
|
191
|
+
if (result.results.length === 0) {
|
|
192
|
+
return "No matching memories found.";
|
|
193
|
+
}
|
|
194
|
+
const lines = [
|
|
195
|
+
`Found ${result.total} matching memories:`,
|
|
196
|
+
"",
|
|
197
|
+
];
|
|
198
|
+
for (const item of result.results) {
|
|
199
|
+
const scoreStr = typeof item.score === "number" ? ` (score: ${item.score.toFixed(3)})` : "";
|
|
200
|
+
const sceneStr = item.scene_name ? ` [scene: ${item.scene_name}]` : "";
|
|
201
|
+
const priorityStr = item.priority >= 0 ? ` (priority: ${item.priority})` : " (global instruction)";
|
|
202
|
+
lines.push(`- **[${item.type}]**${priorityStr}${sceneStr}${scoreStr}`);
|
|
203
|
+
lines.push(` ${item.content}`);
|
|
204
|
+
lines.push("");
|
|
205
|
+
}
|
|
206
|
+
return lines.join("\n");
|
|
207
|
+
}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* TDAI Core — Host-neutral type definitions and abstract interfaces.
|
|
3
|
-
*
|
|
4
|
-
* These types define the boundary between TDAI Core (memory algorithms)
|
|
5
|
-
* and the host environment (OpenClaw, Hermes, standalone Gateway, etc.).
|
|
6
|
-
*
|
|
7
|
-
* Design principles:
|
|
8
|
-
* 1. TDAI Core depends ONLY on these interfaces — never on a specific host.
|
|
9
|
-
* 2. Each host provides its own implementation of HostAdapter + LLMRunnerFactory.
|
|
10
|
-
* 3. RuntimeContext is the single source of truth for session/user identity.
|
|
11
|
-
*/
|
|
12
|
-
export {};
|
|
1
|
+
/**
|
|
2
|
+
* TDAI Core — Host-neutral type definitions and abstract interfaces.
|
|
3
|
+
*
|
|
4
|
+
* These types define the boundary between TDAI Core (memory algorithms)
|
|
5
|
+
* and the host environment (OpenClaw, Hermes, standalone Gateway, etc.).
|
|
6
|
+
*
|
|
7
|
+
* Design principles:
|
|
8
|
+
* 1. TDAI Core depends ONLY on these interfaces — never on a specific host.
|
|
9
|
+
* 2. Each host provides its own implementation of HostAdapter + LLMRunnerFactory.
|
|
10
|
+
* 3. RuntimeContext is the single source of truth for session/user identity.
|
|
11
|
+
*/
|
|
12
|
+
export {};
|