@usewhisper/mcp-server 0.2.3 → 0.3.0
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/README.md +23 -23
- package/dist/autosubscribe-GHO6YR5A.js +4068 -0
- package/dist/chunk-52VJYCZ7.js +455 -0
- package/dist/chunk-5KBZQHDL.js +189 -0
- package/dist/chunk-7SN3CKDK.js +1076 -0
- package/dist/chunk-EI5CE3EY.js +616 -0
- package/dist/chunk-JO3ORBZD.js +616 -0
- package/dist/chunk-LMEYV4JD.js +368 -0
- package/dist/chunk-MEFLJ4PV.js +8385 -0
- package/dist/chunk-PPGYJJED.js +271 -0
- package/dist/chunk-T7KMSTWP.js +399 -0
- package/dist/chunk-TWEIYHI6.js +399 -0
- package/dist/consolidation-2GCKI4RE.js +220 -0
- package/dist/consolidation-4JOPW6BG.js +220 -0
- package/dist/context-sharing-4ITCNKG4.js +307 -0
- package/dist/context-sharing-GYKLXHZA.js +307 -0
- package/dist/context-sharing-Y6LTZZOF.js +307 -0
- package/dist/cost-optimization-7DVSTL6R.js +307 -0
- package/dist/ingest-7T5FAZNC.js +15 -0
- package/dist/ingest-EBNIE7XB.js +15 -0
- package/dist/ingest-FSHT5BCS.js +15 -0
- package/dist/oracle-3RLQF3DP.js +259 -0
- package/dist/oracle-FKRTQUUG.js +282 -0
- package/dist/search-EG6TYWWW.js +13 -0
- package/dist/search-I22QQA7T.js +13 -0
- package/dist/search-T7H5G6DW.js +13 -0
- package/dist/server.js +813 -1088
- package/package.json +2 -6
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
import {
|
|
2
|
+
buildRelationGraph,
|
|
3
|
+
calculateTemporalRelevance,
|
|
4
|
+
parseTemporalQuery
|
|
5
|
+
} from "./chunk-LMEYV4JD.js";
|
|
6
|
+
import {
|
|
7
|
+
db,
|
|
8
|
+
embedSingle
|
|
9
|
+
} from "./chunk-3WGYBAYR.js";
|
|
10
|
+
|
|
11
|
+
// ../src/engine/memory/search.ts
|
|
12
|
+
async function searchMemories(params) {
|
|
13
|
+
const {
|
|
14
|
+
query,
|
|
15
|
+
questionDate,
|
|
16
|
+
userId,
|
|
17
|
+
projectId,
|
|
18
|
+
orgId,
|
|
19
|
+
sessionId,
|
|
20
|
+
topK = 10,
|
|
21
|
+
includeInactive = false,
|
|
22
|
+
memoryTypes
|
|
23
|
+
} = params;
|
|
24
|
+
const temporal = params.temporalFilter || await parseTemporalQuery(query, questionDate);
|
|
25
|
+
const queryEmbedding = await embedSingle(query);
|
|
26
|
+
const semanticResults = await vectorSearchMemories({
|
|
27
|
+
embedding: queryEmbedding,
|
|
28
|
+
userId,
|
|
29
|
+
projectId,
|
|
30
|
+
orgId,
|
|
31
|
+
sessionId,
|
|
32
|
+
temporal,
|
|
33
|
+
includeInactive,
|
|
34
|
+
memoryTypes,
|
|
35
|
+
limit: topK * 3
|
|
36
|
+
// Get more for reranking
|
|
37
|
+
});
|
|
38
|
+
if (semanticResults.length === 0) {
|
|
39
|
+
return [];
|
|
40
|
+
}
|
|
41
|
+
const enriched = await enrichWithRelations(semanticResults, topK * 2);
|
|
42
|
+
const scored = enriched.map((memory) => ({
|
|
43
|
+
...memory,
|
|
44
|
+
temporalScore: memory.documentDate ? calculateTemporalRelevance(memory.documentDate, questionDate) : 0.5
|
|
45
|
+
}));
|
|
46
|
+
const combined = scored.map((m) => ({
|
|
47
|
+
...m,
|
|
48
|
+
finalScore: m.similarity * 0.7 + m.temporalScore * 0.3
|
|
49
|
+
}));
|
|
50
|
+
combined.sort((a, b) => b.finalScore - a.finalScore);
|
|
51
|
+
const topMemories = combined.slice(0, topK);
|
|
52
|
+
const results = await injectSourceChunks(topMemories);
|
|
53
|
+
return results;
|
|
54
|
+
}
|
|
55
|
+
async function vectorSearchMemories(params) {
|
|
56
|
+
const {
|
|
57
|
+
embedding,
|
|
58
|
+
userId,
|
|
59
|
+
projectId,
|
|
60
|
+
orgId,
|
|
61
|
+
sessionId,
|
|
62
|
+
temporal,
|
|
63
|
+
includeInactive,
|
|
64
|
+
memoryTypes,
|
|
65
|
+
limit
|
|
66
|
+
} = params;
|
|
67
|
+
const whereConditions = [
|
|
68
|
+
{ projectId }
|
|
69
|
+
];
|
|
70
|
+
if (orgId) {
|
|
71
|
+
whereConditions.push({ orgId });
|
|
72
|
+
}
|
|
73
|
+
if (userId) {
|
|
74
|
+
whereConditions.push({ userId });
|
|
75
|
+
}
|
|
76
|
+
if (sessionId) {
|
|
77
|
+
whereConditions.push({ sessionId });
|
|
78
|
+
}
|
|
79
|
+
if (!includeInactive) {
|
|
80
|
+
whereConditions.push({ isActive: true });
|
|
81
|
+
}
|
|
82
|
+
whereConditions.push({
|
|
83
|
+
OR: [
|
|
84
|
+
{ validUntil: null },
|
|
85
|
+
{ validUntil: { gt: /* @__PURE__ */ new Date() } }
|
|
86
|
+
]
|
|
87
|
+
});
|
|
88
|
+
if (memoryTypes && memoryTypes.length > 0) {
|
|
89
|
+
whereConditions.push({
|
|
90
|
+
memoryType: { in: memoryTypes }
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
if (temporal.hasTemporalConstraint && temporal.dateRange) {
|
|
94
|
+
whereConditions.push({
|
|
95
|
+
documentDate: {
|
|
96
|
+
gte: temporal.dateRange.start,
|
|
97
|
+
lte: temporal.dateRange.end
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
const embeddingStr = `[${embedding.join(",")}]`;
|
|
102
|
+
const results = await db.$queryRaw`
|
|
103
|
+
SELECT
|
|
104
|
+
id,
|
|
105
|
+
content,
|
|
106
|
+
"memoryType",
|
|
107
|
+
"entityMentions",
|
|
108
|
+
confidence,
|
|
109
|
+
version,
|
|
110
|
+
"documentDate",
|
|
111
|
+
"eventDate",
|
|
112
|
+
"validFrom",
|
|
113
|
+
"validUntil",
|
|
114
|
+
"sourceChunkId",
|
|
115
|
+
metadata,
|
|
116
|
+
1 - (embedding <=> ${embeddingStr}::vector) as similarity
|
|
117
|
+
FROM memories
|
|
118
|
+
WHERE
|
|
119
|
+
"projectId" = ${projectId}
|
|
120
|
+
${orgId ? db.$queryRaw`AND "orgId" = ${orgId}` : db.$queryRaw``}
|
|
121
|
+
${userId ? db.$queryRaw`AND "userId" = ${userId}` : db.$queryRaw``}
|
|
122
|
+
${sessionId ? db.$queryRaw`AND "sessionId" = ${sessionId}` : db.$queryRaw``}
|
|
123
|
+
${!includeInactive ? db.$queryRaw`AND "isActive" = true` : db.$queryRaw``}
|
|
124
|
+
AND ("validUntil" IS NULL OR "validUntil" > NOW())
|
|
125
|
+
${memoryTypes && memoryTypes.length > 0 ? db.$queryRaw`AND "memoryType" = ANY(${memoryTypes})` : db.$queryRaw``}
|
|
126
|
+
${temporal.hasTemporalConstraint && temporal.dateRange ? db.$queryRaw`AND "documentDate" >= ${temporal.dateRange.start} AND "documentDate" <= ${temporal.dateRange.end}` : db.$queryRaw``}
|
|
127
|
+
ORDER BY similarity DESC
|
|
128
|
+
LIMIT ${limit}
|
|
129
|
+
`;
|
|
130
|
+
return results;
|
|
131
|
+
}
|
|
132
|
+
async function enrichWithRelations(memories, maxTotal) {
|
|
133
|
+
if (memories.length === 0) {
|
|
134
|
+
return [];
|
|
135
|
+
}
|
|
136
|
+
const memoryIds = memories.map((m) => m.id);
|
|
137
|
+
const relations = await db.memoryRelation.findMany({
|
|
138
|
+
where: {
|
|
139
|
+
OR: [
|
|
140
|
+
{ fromMemoryId: { in: memoryIds } },
|
|
141
|
+
{ toMemoryId: { in: memoryIds } }
|
|
142
|
+
]
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
if (relations.length === 0) {
|
|
146
|
+
return memories;
|
|
147
|
+
}
|
|
148
|
+
const graph = buildRelationGraph(relations);
|
|
149
|
+
const relatedIds = /* @__PURE__ */ new Set();
|
|
150
|
+
for (const memory of memories) {
|
|
151
|
+
const neighbors = graph.get(memory.id) || [];
|
|
152
|
+
for (const neighbor of neighbors.slice(0, 3)) {
|
|
153
|
+
relatedIds.add(neighbor.memoryId);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
memoryIds.forEach((id) => relatedIds.delete(id));
|
|
157
|
+
if (relatedIds.size === 0) {
|
|
158
|
+
return memories;
|
|
159
|
+
}
|
|
160
|
+
const related = await db.memory.findMany({
|
|
161
|
+
where: {
|
|
162
|
+
id: { in: Array.from(relatedIds) },
|
|
163
|
+
isActive: true
|
|
164
|
+
},
|
|
165
|
+
take: maxTotal - memories.length
|
|
166
|
+
});
|
|
167
|
+
const relatedWithScores = related.map((m) => ({
|
|
168
|
+
...m,
|
|
169
|
+
similarity: 0.6,
|
|
170
|
+
// Lower score for related but not directly matched
|
|
171
|
+
isRelated: true
|
|
172
|
+
}));
|
|
173
|
+
return [...memories, ...relatedWithScores];
|
|
174
|
+
}
|
|
175
|
+
async function injectSourceChunks(memories) {
|
|
176
|
+
const chunkIds = memories.map((m) => m.sourceChunkId).filter((id) => id !== null);
|
|
177
|
+
if (chunkIds.length === 0) {
|
|
178
|
+
return memories.map((m) => ({
|
|
179
|
+
memory: {
|
|
180
|
+
id: m.id,
|
|
181
|
+
content: m.content,
|
|
182
|
+
memoryType: m.memoryType,
|
|
183
|
+
entityMentions: m.entityMentions || [],
|
|
184
|
+
confidence: m.confidence,
|
|
185
|
+
version: m.version,
|
|
186
|
+
temporal: {
|
|
187
|
+
documentDate: m.documentDate,
|
|
188
|
+
eventDate: m.eventDate,
|
|
189
|
+
validFrom: m.validFrom,
|
|
190
|
+
validUntil: m.validUntil
|
|
191
|
+
}
|
|
192
|
+
},
|
|
193
|
+
similarity: m.similarity
|
|
194
|
+
}));
|
|
195
|
+
}
|
|
196
|
+
const chunks = await db.chunk.findMany({
|
|
197
|
+
where: {
|
|
198
|
+
id: { in: chunkIds }
|
|
199
|
+
},
|
|
200
|
+
select: {
|
|
201
|
+
id: true,
|
|
202
|
+
content: true,
|
|
203
|
+
metadata: true
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
const chunkMap = new Map(chunks.map((c) => [c.id, c]));
|
|
207
|
+
return memories.map((m) => ({
|
|
208
|
+
memory: {
|
|
209
|
+
id: m.id,
|
|
210
|
+
content: m.content,
|
|
211
|
+
memoryType: m.memoryType,
|
|
212
|
+
entityMentions: m.entityMentions || [],
|
|
213
|
+
confidence: m.confidence,
|
|
214
|
+
version: m.version,
|
|
215
|
+
temporal: {
|
|
216
|
+
documentDate: m.documentDate,
|
|
217
|
+
eventDate: m.eventDate,
|
|
218
|
+
validFrom: m.validFrom,
|
|
219
|
+
validUntil: m.validUntil
|
|
220
|
+
}
|
|
221
|
+
},
|
|
222
|
+
chunk: m.sourceChunkId && chunkMap.has(m.sourceChunkId) ? {
|
|
223
|
+
id: chunkMap.get(m.sourceChunkId).id,
|
|
224
|
+
content: chunkMap.get(m.sourceChunkId).content,
|
|
225
|
+
metadata: chunkMap.get(m.sourceChunkId).metadata
|
|
226
|
+
} : void 0,
|
|
227
|
+
similarity: m.similarity,
|
|
228
|
+
relations: m.isRelated ? [] : void 0
|
|
229
|
+
}));
|
|
230
|
+
}
|
|
231
|
+
async function getSessionMemories(params) {
|
|
232
|
+
const { sessionId, projectId, limit = 50, sinceDate } = params;
|
|
233
|
+
const where = {
|
|
234
|
+
sessionId,
|
|
235
|
+
projectId,
|
|
236
|
+
isActive: true
|
|
237
|
+
};
|
|
238
|
+
if (sinceDate) {
|
|
239
|
+
where.createdAt = { gte: sinceDate };
|
|
240
|
+
}
|
|
241
|
+
return db.memory.findMany({
|
|
242
|
+
where,
|
|
243
|
+
orderBy: {
|
|
244
|
+
createdAt: "desc"
|
|
245
|
+
},
|
|
246
|
+
take: limit
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
async function getUserProfile(params) {
|
|
250
|
+
const { userId, projectId, memoryTypes, limit = 50 } = params;
|
|
251
|
+
const where = {
|
|
252
|
+
userId,
|
|
253
|
+
projectId,
|
|
254
|
+
isActive: true,
|
|
255
|
+
scope: "USER"
|
|
256
|
+
};
|
|
257
|
+
if (memoryTypes) {
|
|
258
|
+
where.memoryType = { in: memoryTypes };
|
|
259
|
+
}
|
|
260
|
+
return db.memory.findMany({
|
|
261
|
+
where,
|
|
262
|
+
orderBy: { importance: "desc" },
|
|
263
|
+
take: Math.min(limit, 100)
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
export {
|
|
268
|
+
searchMemories,
|
|
269
|
+
getSessionMemories,
|
|
270
|
+
getUserProfile
|
|
271
|
+
};
|
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
import {
|
|
2
|
+
calculateTemporalRelevance,
|
|
3
|
+
parseTemporalQuery
|
|
4
|
+
} from "./chunk-5KBZQHDL.js";
|
|
5
|
+
import {
|
|
6
|
+
db,
|
|
7
|
+
embedSingle
|
|
8
|
+
} from "./chunk-3WGYBAYR.js";
|
|
9
|
+
|
|
10
|
+
// ../src/engine/cache.ts
|
|
11
|
+
import crypto from "crypto";
|
|
12
|
+
var semanticCache = /* @__PURE__ */ new Map();
|
|
13
|
+
var MAX_SEMANTIC_CACHE_SIZE = 500;
|
|
14
|
+
var SEMANTIC_THRESHOLD = 0.92;
|
|
15
|
+
var DEFAULT_CONFIG = {
|
|
16
|
+
ttl: 3600,
|
|
17
|
+
// 1 hour
|
|
18
|
+
enabled: true,
|
|
19
|
+
keyPrefix: "whisper:context:"
|
|
20
|
+
};
|
|
21
|
+
var cacheHits = 0;
|
|
22
|
+
var cacheMisses = 0;
|
|
23
|
+
function recordCacheHit() {
|
|
24
|
+
cacheHits++;
|
|
25
|
+
}
|
|
26
|
+
function recordCacheMiss() {
|
|
27
|
+
cacheMisses++;
|
|
28
|
+
}
|
|
29
|
+
function cosineSimilarity(a, b) {
|
|
30
|
+
if (a.length !== b.length) return 0;
|
|
31
|
+
let dotProduct = 0;
|
|
32
|
+
let normA = 0;
|
|
33
|
+
let normB = 0;
|
|
34
|
+
for (let i = 0; i < a.length; i++) {
|
|
35
|
+
dotProduct += a[i] * b[i];
|
|
36
|
+
normA += a[i] * a[i];
|
|
37
|
+
normB += b[i] * b[i];
|
|
38
|
+
}
|
|
39
|
+
return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
|
|
40
|
+
}
|
|
41
|
+
async function getFromSemanticCache(queryEmbedding) {
|
|
42
|
+
if (!DEFAULT_CONFIG.enabled) return null;
|
|
43
|
+
const now = Date.now();
|
|
44
|
+
let bestMatch = null;
|
|
45
|
+
let bestSimilarity = 0;
|
|
46
|
+
for (const [key, entry] of semanticCache.entries()) {
|
|
47
|
+
if (entry.expiry < now) {
|
|
48
|
+
semanticCache.delete(key);
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
const similarity = cosineSimilarity(queryEmbedding, entry.embedding);
|
|
52
|
+
if (similarity > bestSimilarity) {
|
|
53
|
+
bestSimilarity = similarity;
|
|
54
|
+
bestMatch = { key, ...entry, similarity };
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
if (bestMatch && bestMatch.similarity >= SEMANTIC_THRESHOLD) {
|
|
58
|
+
recordCacheHit();
|
|
59
|
+
return { results: bestMatch.results, similarity: bestMatch.similarity };
|
|
60
|
+
}
|
|
61
|
+
recordCacheMiss();
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
async function setInSemanticCache(queryEmbedding, results) {
|
|
65
|
+
if (!DEFAULT_CONFIG.enabled) return;
|
|
66
|
+
const now = Date.now();
|
|
67
|
+
const key = `sem:${crypto.createHash("md5").update(JSON.stringify(queryEmbedding.slice(0, 10))).digest("hex").substring(0, 8)}`;
|
|
68
|
+
semanticCache.set(key, {
|
|
69
|
+
embedding: queryEmbedding,
|
|
70
|
+
results,
|
|
71
|
+
expiry: now + DEFAULT_CONFIG.ttl * 1e3
|
|
72
|
+
});
|
|
73
|
+
if (semanticCache.size > MAX_SEMANTIC_CACHE_SIZE) {
|
|
74
|
+
let oldestKey = null;
|
|
75
|
+
let oldestExpiry = Infinity;
|
|
76
|
+
for (const [k, v] of semanticCache.entries()) {
|
|
77
|
+
if (v.expiry < oldestExpiry) {
|
|
78
|
+
oldestExpiry = v.expiry;
|
|
79
|
+
oldestKey = k;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
if (oldestKey) {
|
|
83
|
+
semanticCache.delete(oldestKey);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// ../src/engine/memory/search.ts
|
|
89
|
+
var EARLY_EXIT_SIMILARITY = 0.92;
|
|
90
|
+
async function searchMemories(params) {
|
|
91
|
+
const {
|
|
92
|
+
query,
|
|
93
|
+
questionDate,
|
|
94
|
+
userId,
|
|
95
|
+
projectId,
|
|
96
|
+
orgId,
|
|
97
|
+
sessionId,
|
|
98
|
+
topK = 10,
|
|
99
|
+
includeInactive = false,
|
|
100
|
+
memoryTypes
|
|
101
|
+
} = params;
|
|
102
|
+
const queryEmbedding = await embedSingle(query);
|
|
103
|
+
const cached = await getFromSemanticCache(queryEmbedding);
|
|
104
|
+
if (cached && cached.similarity >= EARLY_EXIT_SIMILARITY) {
|
|
105
|
+
console.log(`\u26A1 Semantic cache hit (similarity: ${cached.similarity.toFixed(3)})`);
|
|
106
|
+
return cached.results.slice(0, topK);
|
|
107
|
+
}
|
|
108
|
+
const temporal = params.temporalFilter || await parseTemporalQuery(query, questionDate);
|
|
109
|
+
const semanticResults = await vectorSearchMemories({
|
|
110
|
+
embedding: queryEmbedding,
|
|
111
|
+
userId,
|
|
112
|
+
projectId,
|
|
113
|
+
orgId,
|
|
114
|
+
sessionId,
|
|
115
|
+
temporal,
|
|
116
|
+
includeInactive,
|
|
117
|
+
memoryTypes,
|
|
118
|
+
limit: topK * 3
|
|
119
|
+
// Get more for reranking
|
|
120
|
+
});
|
|
121
|
+
if (semanticResults.length === 0) {
|
|
122
|
+
return [];
|
|
123
|
+
}
|
|
124
|
+
if (semanticResults.length > 0 && semanticResults[0].similarity >= EARLY_EXIT_SIMILARITY) {
|
|
125
|
+
console.log(`\u26A1 Early exit at ${semanticResults[0].similarity.toFixed(3)}`);
|
|
126
|
+
const topMemories2 = semanticResults.slice(0, topK);
|
|
127
|
+
await setInSemanticCache(queryEmbedding, topMemories2);
|
|
128
|
+
return topMemories2;
|
|
129
|
+
}
|
|
130
|
+
const enriched = await enrichWithRelations(semanticResults, topK * 2);
|
|
131
|
+
const scored = enriched.map((memory) => ({
|
|
132
|
+
...memory,
|
|
133
|
+
temporalScore: memory.documentDate ? calculateTemporalRelevance(memory.documentDate, questionDate) : 0.5
|
|
134
|
+
}));
|
|
135
|
+
const combined = scored.map((m) => ({
|
|
136
|
+
...m,
|
|
137
|
+
finalScore: m.similarity * 0.7 + m.temporalScore * 0.3
|
|
138
|
+
}));
|
|
139
|
+
combined.sort((a, b) => b.finalScore - a.finalScore);
|
|
140
|
+
const topMemories = combined.slice(0, topK);
|
|
141
|
+
const results = await injectSourceChunks(topMemories);
|
|
142
|
+
await setInSemanticCache(queryEmbedding, results);
|
|
143
|
+
return results;
|
|
144
|
+
}
|
|
145
|
+
async function vectorSearchMemories(params) {
|
|
146
|
+
const {
|
|
147
|
+
embedding,
|
|
148
|
+
userId,
|
|
149
|
+
projectId,
|
|
150
|
+
orgId,
|
|
151
|
+
sessionId,
|
|
152
|
+
temporal,
|
|
153
|
+
includeInactive,
|
|
154
|
+
memoryTypes,
|
|
155
|
+
limit
|
|
156
|
+
} = params;
|
|
157
|
+
const whereConditions = [
|
|
158
|
+
{ projectId }
|
|
159
|
+
];
|
|
160
|
+
if (orgId) {
|
|
161
|
+
whereConditions.push({ orgId });
|
|
162
|
+
}
|
|
163
|
+
if (userId) {
|
|
164
|
+
whereConditions.push({ userId });
|
|
165
|
+
}
|
|
166
|
+
if (sessionId) {
|
|
167
|
+
whereConditions.push({ sessionId });
|
|
168
|
+
}
|
|
169
|
+
if (!includeInactive) {
|
|
170
|
+
whereConditions.push({ isActive: true });
|
|
171
|
+
}
|
|
172
|
+
whereConditions.push({
|
|
173
|
+
OR: [
|
|
174
|
+
{ validUntil: null },
|
|
175
|
+
{ validUntil: { gt: /* @__PURE__ */ new Date() } }
|
|
176
|
+
]
|
|
177
|
+
});
|
|
178
|
+
if (memoryTypes && memoryTypes.length > 0) {
|
|
179
|
+
whereConditions.push({
|
|
180
|
+
memoryType: { in: memoryTypes }
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
if (temporal.hasTemporalConstraint && temporal.dateRange) {
|
|
184
|
+
whereConditions.push({
|
|
185
|
+
documentDate: {
|
|
186
|
+
gte: temporal.dateRange.start,
|
|
187
|
+
lte: temporal.dateRange.end
|
|
188
|
+
}
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
const embeddingStr = `[${embedding.join(",")}]`;
|
|
192
|
+
let whereClause = `"projectId" = '${projectId}'`;
|
|
193
|
+
if (orgId) whereClause += ` AND "orgId" = '${orgId}'`;
|
|
194
|
+
if (userId) whereClause += ` AND "userId" = '${userId}'`;
|
|
195
|
+
if (sessionId) whereClause += ` AND "sessionId" = '${sessionId}'`;
|
|
196
|
+
if (!includeInactive) whereClause += ` AND "isActive" = true`;
|
|
197
|
+
whereClause += ` AND ("validUntil" IS NULL OR "validUntil" > NOW())`;
|
|
198
|
+
if (memoryTypes && memoryTypes.length > 0) {
|
|
199
|
+
const typesStr = memoryTypes.map((t) => `'${t.replace(/'/g, "''")}'`).join(",");
|
|
200
|
+
whereClause += ` AND "memoryType" IN (${typesStr})`;
|
|
201
|
+
}
|
|
202
|
+
if (temporal.hasTemporalConstraint && temporal.dateRange) {
|
|
203
|
+
whereClause += ` AND "documentDate" >= '${temporal.dateRange.start.toISOString()}' AND "documentDate" <= '${temporal.dateRange.end.toISOString()}'`;
|
|
204
|
+
}
|
|
205
|
+
const results = await db.$queryRawUnsafe(`
|
|
206
|
+
SELECT
|
|
207
|
+
id,
|
|
208
|
+
content,
|
|
209
|
+
"memoryType" as "memoryType",
|
|
210
|
+
confidence,
|
|
211
|
+
version,
|
|
212
|
+
"documentDate" as "documentDate",
|
|
213
|
+
"eventDate" as "eventDate",
|
|
214
|
+
"validFrom" as "validFrom",
|
|
215
|
+
"validUntil" as "validUntil",
|
|
216
|
+
"sourceChunkId" as "sourceChunkId",
|
|
217
|
+
metadata,
|
|
218
|
+
1 - (embedding <=> '${embeddingStr}'::vector) as similarity
|
|
219
|
+
FROM memories
|
|
220
|
+
WHERE ${whereClause}
|
|
221
|
+
ORDER BY embedding <=> '${embeddingStr}'::vector
|
|
222
|
+
LIMIT ${limit}
|
|
223
|
+
`);
|
|
224
|
+
return results;
|
|
225
|
+
}
|
|
226
|
+
async function enrichWithRelations(memories, maxTotal) {
|
|
227
|
+
if (memories.length === 0) {
|
|
228
|
+
return [];
|
|
229
|
+
}
|
|
230
|
+
const memoryIds = memories.map((m) => m.id);
|
|
231
|
+
const memoryIdsList = memoryIds.map((id) => `'${id}'`).join(",");
|
|
232
|
+
const relationsQuery = await db.$queryRawUnsafe(`
|
|
233
|
+
SELECT
|
|
234
|
+
r.id as relation_id,
|
|
235
|
+
r."fromMemoryId",
|
|
236
|
+
r."toMemoryId",
|
|
237
|
+
r."relationType",
|
|
238
|
+
m.id,
|
|
239
|
+
m.content,
|
|
240
|
+
m."memoryType",
|
|
241
|
+
m.confidence,
|
|
242
|
+
m.version,
|
|
243
|
+
m."documentDate",
|
|
244
|
+
m."eventDate",
|
|
245
|
+
m."validFrom",
|
|
246
|
+
m."validUntil",
|
|
247
|
+
m."sourceChunkId",
|
|
248
|
+
m.metadata
|
|
249
|
+
FROM "memory_relations" r
|
|
250
|
+
LEFT JOIN memories m ON m.id = r."toMemoryId"
|
|
251
|
+
WHERE r."fromMemoryId" IN (${memoryIdsList})
|
|
252
|
+
AND m."isActive" = true
|
|
253
|
+
LIMIT 100
|
|
254
|
+
`);
|
|
255
|
+
if (!relationsQuery || relationsQuery.length === 0) {
|
|
256
|
+
return memories;
|
|
257
|
+
}
|
|
258
|
+
const relatedIds = /* @__PURE__ */ new Set();
|
|
259
|
+
const relationMap = /* @__PURE__ */ new Map();
|
|
260
|
+
for (const row of relationsQuery) {
|
|
261
|
+
if (row.toMemoryId && !memoryIds.includes(row.toMemoryId)) {
|
|
262
|
+
relatedIds.add(row.toMemoryId);
|
|
263
|
+
if (!relationMap.has(row.fromMemoryId)) {
|
|
264
|
+
relationMap.set(row.fromMemoryId, []);
|
|
265
|
+
}
|
|
266
|
+
relationMap.get(row.fromMemoryId)?.push({
|
|
267
|
+
memoryId: row.toMemoryId,
|
|
268
|
+
relationType: row.relationType,
|
|
269
|
+
content: row.content
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
if (relatedIds.size === 0) {
|
|
274
|
+
return memories;
|
|
275
|
+
}
|
|
276
|
+
const relatedIdsList = Array.from(relatedIds).map((id) => `'${id}'`).join(",");
|
|
277
|
+
const relatedMemories = await db.$queryRawUnsafe(`
|
|
278
|
+
SELECT
|
|
279
|
+
id,
|
|
280
|
+
content,
|
|
281
|
+
"memoryType" as "memoryType",
|
|
282
|
+
confidence,
|
|
283
|
+
version,
|
|
284
|
+
"documentDate" as "documentDate",
|
|
285
|
+
"eventDate" as "eventDate",
|
|
286
|
+
"validFrom" as "validFrom",
|
|
287
|
+
"validUntil" as "validUntil",
|
|
288
|
+
"sourceChunkId" as "sourceChunkId",
|
|
289
|
+
metadata
|
|
290
|
+
FROM memories
|
|
291
|
+
WHERE id IN (${relatedIdsList})
|
|
292
|
+
AND "isActive" = true
|
|
293
|
+
LIMIT ${maxTotal - memories.length}
|
|
294
|
+
`);
|
|
295
|
+
const relatedWithScores = relatedMemories.map((m) => ({
|
|
296
|
+
...m,
|
|
297
|
+
similarity: 0.6,
|
|
298
|
+
isRelated: true,
|
|
299
|
+
relations: relationMap.get(m.id) || []
|
|
300
|
+
}));
|
|
301
|
+
return [...memories, ...relatedWithScores];
|
|
302
|
+
}
|
|
303
|
+
async function injectSourceChunks(memories) {
|
|
304
|
+
const chunkIds = memories.map((m) => m.sourceChunkId).filter((id) => id !== null);
|
|
305
|
+
if (chunkIds.length === 0) {
|
|
306
|
+
return memories.map((m) => ({
|
|
307
|
+
memory: {
|
|
308
|
+
id: m.id,
|
|
309
|
+
content: m.content,
|
|
310
|
+
memoryType: m.memoryType,
|
|
311
|
+
entityMentions: m.entityMentions || [],
|
|
312
|
+
confidence: m.confidence,
|
|
313
|
+
version: m.version,
|
|
314
|
+
temporal: {
|
|
315
|
+
documentDate: m.documentDate,
|
|
316
|
+
eventDate: m.eventDate,
|
|
317
|
+
validFrom: m.validFrom,
|
|
318
|
+
validUntil: m.validUntil
|
|
319
|
+
}
|
|
320
|
+
},
|
|
321
|
+
similarity: m.similarity
|
|
322
|
+
}));
|
|
323
|
+
}
|
|
324
|
+
const chunks = await db.chunk.findMany({
|
|
325
|
+
where: {
|
|
326
|
+
id: { in: chunkIds }
|
|
327
|
+
},
|
|
328
|
+
select: {
|
|
329
|
+
id: true,
|
|
330
|
+
content: true,
|
|
331
|
+
metadata: true
|
|
332
|
+
}
|
|
333
|
+
});
|
|
334
|
+
const chunkMap = new Map(chunks.map((c) => [c.id, c]));
|
|
335
|
+
return memories.map((m) => ({
|
|
336
|
+
memory: {
|
|
337
|
+
id: m.id,
|
|
338
|
+
content: m.content,
|
|
339
|
+
memoryType: m.memoryType,
|
|
340
|
+
entityMentions: m.entityMentions || [],
|
|
341
|
+
confidence: m.confidence,
|
|
342
|
+
version: m.version,
|
|
343
|
+
temporal: {
|
|
344
|
+
documentDate: m.documentDate,
|
|
345
|
+
eventDate: m.eventDate,
|
|
346
|
+
validFrom: m.validFrom,
|
|
347
|
+
validUntil: m.validUntil
|
|
348
|
+
}
|
|
349
|
+
},
|
|
350
|
+
chunk: m.sourceChunkId && chunkMap.has(m.sourceChunkId) ? {
|
|
351
|
+
id: chunkMap.get(m.sourceChunkId).id,
|
|
352
|
+
content: chunkMap.get(m.sourceChunkId).content,
|
|
353
|
+
metadata: chunkMap.get(m.sourceChunkId).metadata
|
|
354
|
+
} : void 0,
|
|
355
|
+
similarity: m.similarity,
|
|
356
|
+
relations: m.isRelated ? [] : void 0
|
|
357
|
+
}));
|
|
358
|
+
}
|
|
359
|
+
async function getSessionMemories(params) {
|
|
360
|
+
const { sessionId, projectId, limit = 50, sinceDate } = params;
|
|
361
|
+
const where = {
|
|
362
|
+
sessionId,
|
|
363
|
+
projectId,
|
|
364
|
+
isActive: true
|
|
365
|
+
};
|
|
366
|
+
if (sinceDate) {
|
|
367
|
+
where.createdAt = { gte: sinceDate };
|
|
368
|
+
}
|
|
369
|
+
return db.memory.findMany({
|
|
370
|
+
where,
|
|
371
|
+
orderBy: {
|
|
372
|
+
createdAt: "desc"
|
|
373
|
+
},
|
|
374
|
+
take: limit
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
async function getUserProfile(params) {
|
|
378
|
+
const { userId, projectId, memoryTypes, limit = 50 } = params;
|
|
379
|
+
const where = {
|
|
380
|
+
userId,
|
|
381
|
+
projectId,
|
|
382
|
+
isActive: true,
|
|
383
|
+
scope: "USER"
|
|
384
|
+
};
|
|
385
|
+
if (memoryTypes) {
|
|
386
|
+
where.memoryType = { in: memoryTypes };
|
|
387
|
+
}
|
|
388
|
+
return db.memory.findMany({
|
|
389
|
+
where,
|
|
390
|
+
orderBy: { importance: "desc" },
|
|
391
|
+
take: Math.min(limit, 100)
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
export {
|
|
396
|
+
searchMemories,
|
|
397
|
+
getSessionMemories,
|
|
398
|
+
getUserProfile
|
|
399
|
+
};
|