@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.
@@ -0,0 +1,220 @@
1
+ import {
2
+ db,
3
+ embedSingle
4
+ } from "./chunk-3WGYBAYR.js";
5
+ import "./chunk-QGM4M3NI.js";
6
+
7
+ // ../src/engine/memory/consolidation.ts
8
+ import OpenAI from "openai";
9
+ var openai = new OpenAI({
10
+ apiKey: process.env.OPENAI_API_KEY || ""
11
+ });
12
+ async function findDuplicateMemories(params) {
13
+ const {
14
+ projectId,
15
+ userId,
16
+ similarityThreshold = 0.95,
17
+ limit = 50
18
+ } = params;
19
+ const maxMemories = Math.min(Math.max(limit, 10), 100);
20
+ const memories = await db.memory.findMany({
21
+ where: {
22
+ projectId,
23
+ userId,
24
+ isActive: true,
25
+ validUntil: null
26
+ },
27
+ orderBy: { importance: "desc" },
28
+ take: maxMemories
29
+ });
30
+ const clusters = [];
31
+ const processed = /* @__PURE__ */ new Set();
32
+ for (let i = 0; i < memories.length; i++) {
33
+ const memory = memories[i];
34
+ if (processed.has(memory.id)) continue;
35
+ const similar = [];
36
+ const candidates = memories.slice(i + 1);
37
+ const batchSimilarities = await calculateBatchSimilarity(memory.id, candidates.map((c) => c.id));
38
+ for (let j = 0; j < candidates.length; j++) {
39
+ const other = candidates[j];
40
+ if (processed.has(other.id)) continue;
41
+ const similarity = batchSimilarities[j];
42
+ if (similarity >= similarityThreshold) {
43
+ similar.push({ ...other, similarity });
44
+ processed.add(other.id);
45
+ }
46
+ }
47
+ if (similar.length > 0) {
48
+ clusters.push({
49
+ representative: memory,
50
+ duplicates: similar,
51
+ similarity: similar.reduce((sum, m) => sum + m.similarity, 0) / similar.length
52
+ });
53
+ processed.add(memory.id);
54
+ }
55
+ }
56
+ return clusters;
57
+ }
58
+ async function calculateBatchSimilarity(memoryId, otherIds) {
59
+ if (otherIds.length === 0) return [];
60
+ const placeholders = otherIds.map((_, i) => `(m1.embedding <=> $${i + 2}::vector)`).join(" + ");
61
+ const conditions = otherIds.map((id, i) => `m2.id = $${i + 2}`).join(" OR ");
62
+ const result = await db.$queryRaw`
63
+ SELECT
64
+ 1 - (m1.embedding <=> m2.embedding) as similarity,
65
+ m2.id as id
66
+ FROM memories m1, memories m2
67
+ WHERE m1.id = ${memoryId} AND (${conditions})
68
+ `;
69
+ const similarityMap = new Map(result.map((r) => [r.id, r.similarity]));
70
+ return otherIds.map((id) => similarityMap.get(id) || 0);
71
+ }
72
+ async function mergeDuplicateMemories(cluster) {
73
+ const memories = [cluster.representative, ...cluster.duplicates];
74
+ const prompt = `You are merging duplicate memories into a single, comprehensive memory.
75
+
76
+ **Memories to merge:**
77
+ ${memories.map(
78
+ (m, i) => `${i + 1}. "${m.content}" (confidence: ${m.confidence}, date: ${m.documentDate?.toISOString() || "unknown"})`
79
+ ).join("\n")}
80
+
81
+ **Instructions:**
82
+ 1. Combine all unique information from these memories
83
+ 2. Resolve any contradictions by keeping the most recent or most confident information
84
+ 3. Extract all unique entity mentions
85
+ 4. Use the highest confidence score
86
+ 5. Keep the most recent document date
87
+
88
+ Return JSON:
89
+ {
90
+ "merged_content": "comprehensive merged memory",
91
+ "entity_mentions": ["list", "of", "entities"],
92
+ "confidence": 0.0-1.0,
93
+ "reasoning": "brief explanation of how you merged"
94
+ }`;
95
+ const response = await openai.chat.completions.create({
96
+ model: "gpt-4o",
97
+ max_tokens: 2048,
98
+ temperature: 0,
99
+ messages: [{ role: "user", content: prompt }],
100
+ response_format: { type: "json_object" }
101
+ });
102
+ const text = response.choices[0]?.message?.content?.trim();
103
+ if (!text) {
104
+ throw new Error("Failed to merge memories");
105
+ }
106
+ const jsonMatch = text.match(/```json\n?([\s\S]*?)\n?```/) || text.match(/\{[\s\S]*\}/);
107
+ const jsonStr = jsonMatch ? jsonMatch[1] || jsonMatch[0] : text;
108
+ const result = JSON.parse(jsonStr);
109
+ const embedding = await embedSingle(result.merged_content);
110
+ const mergedMemory = await db.memory.create({
111
+ data: {
112
+ projectId: cluster.representative.projectId,
113
+ orgId: cluster.representative.orgId,
114
+ userId: cluster.representative.userId,
115
+ sessionId: cluster.representative.sessionId,
116
+ memoryType: cluster.representative.memoryType,
117
+ content: result.merged_content,
118
+ embedding,
119
+ entityMentions: result.entity_mentions || [],
120
+ confidence: result.confidence || cluster.representative.confidence,
121
+ documentDate: cluster.representative.documentDate,
122
+ eventDate: cluster.representative.eventDate,
123
+ validFrom: /* @__PURE__ */ new Date(),
124
+ importance: Math.max(...memories.map((m) => m.importance || 0.5)),
125
+ metadata: {
126
+ mergedFrom: memories.map((m) => m.id),
127
+ mergeReasoning: result.reasoning,
128
+ mergedAt: (/* @__PURE__ */ new Date()).toISOString()
129
+ }
130
+ }
131
+ });
132
+ for (const memory of memories) {
133
+ await db.memory.update({
134
+ where: { id: memory.id },
135
+ data: {
136
+ isActive: false,
137
+ validUntil: /* @__PURE__ */ new Date(),
138
+ supersededBy: mergedMemory.id
139
+ }
140
+ });
141
+ }
142
+ return mergedMemory.id;
143
+ }
144
+ async function consolidateMemories(params) {
145
+ const { projectId, userId, similarityThreshold = 0.95, dryRun = false } = params;
146
+ console.log(`\u{1F50D} Finding duplicate memories in project ${projectId}...`);
147
+ const clusters = await findDuplicateMemories({
148
+ projectId,
149
+ userId,
150
+ similarityThreshold
151
+ });
152
+ console.log(`\u{1F4CA} Found ${clusters.length} memory clusters`);
153
+ if (dryRun) {
154
+ for (const cluster of clusters) {
155
+ console.log(`
156
+ Cluster (similarity: ${cluster.similarity.toFixed(2)}):`);
157
+ console.log(` Representative: "${cluster.representative.content}"`);
158
+ console.log(` Duplicates: ${cluster.duplicates.length}`);
159
+ cluster.duplicates.forEach((d) => {
160
+ console.log(` - "${d.content}"`);
161
+ });
162
+ }
163
+ return {
164
+ clustersFound: clusters.length,
165
+ memoriesMerged: 0,
166
+ memoriesDeactivated: 0
167
+ };
168
+ }
169
+ let memoriesMerged = 0;
170
+ let memoriesDeactivated = 0;
171
+ for (const cluster of clusters) {
172
+ try {
173
+ console.log(`\u{1F517} Merging cluster with ${cluster.duplicates.length + 1} memories...`);
174
+ await mergeDuplicateMemories(cluster);
175
+ memoriesMerged++;
176
+ memoriesDeactivated += cluster.duplicates.length + 1;
177
+ console.log(`\u2705 Merged successfully`);
178
+ } catch (error) {
179
+ console.error(`\u274C Failed to merge cluster:`, error);
180
+ }
181
+ }
182
+ console.log(
183
+ `
184
+ \u2705 Consolidation complete: ${memoriesMerged} clusters merged, ${memoriesDeactivated} memories deactivated`
185
+ );
186
+ return {
187
+ clustersFound: clusters.length,
188
+ memoriesMerged,
189
+ memoriesDeactivated
190
+ };
191
+ }
192
+ async function scheduledConsolidation(orgId) {
193
+ console.log(`\u{1F504} Running scheduled consolidation for org ${orgId}...`);
194
+ const projects = await db.project.findMany({
195
+ where: { orgId }
196
+ });
197
+ for (const project of projects) {
198
+ try {
199
+ const result = await consolidateMemories({
200
+ projectId: project.id,
201
+ similarityThreshold: 0.92
202
+ // Slightly lower for scheduled runs
203
+ });
204
+ if (result.memoriesMerged > 0) {
205
+ console.log(
206
+ `\u{1F4CA} Project ${project.name}: merged ${result.memoriesMerged} clusters`
207
+ );
208
+ }
209
+ } catch (error) {
210
+ console.error(`Failed to consolidate project ${project.name}:`, error);
211
+ }
212
+ }
213
+ console.log("\u2705 Scheduled consolidation complete");
214
+ }
215
+ export {
216
+ consolidateMemories,
217
+ findDuplicateMemories,
218
+ mergeDuplicateMemories,
219
+ scheduledConsolidation
220
+ };
@@ -0,0 +1,307 @@
1
+ import {
2
+ getSessionMemories
3
+ } from "./chunk-T7KMSTWP.js";
4
+ import "./chunk-EI5CE3EY.js";
5
+ import "./chunk-5KBZQHDL.js";
6
+ import {
7
+ db
8
+ } from "./chunk-3WGYBAYR.js";
9
+ import "./chunk-QGM4M3NI.js";
10
+
11
+ // ../node_modules/nanoid/index.js
12
+ import { webcrypto as crypto } from "crypto";
13
+
14
+ // ../node_modules/nanoid/url-alphabet/index.js
15
+ var urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
16
+
17
+ // ../node_modules/nanoid/index.js
18
+ var POOL_SIZE_MULTIPLIER = 128;
19
+ var pool;
20
+ var poolOffset;
21
+ function fillPool(bytes) {
22
+ if (!pool || pool.length < bytes) {
23
+ pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER);
24
+ crypto.getRandomValues(pool);
25
+ poolOffset = 0;
26
+ } else if (poolOffset + bytes > pool.length) {
27
+ crypto.getRandomValues(pool);
28
+ poolOffset = 0;
29
+ }
30
+ poolOffset += bytes;
31
+ }
32
+ function nanoid(size = 21) {
33
+ fillPool(size |= 0);
34
+ let id = "";
35
+ for (let i = poolOffset - size; i < poolOffset; i++) {
36
+ id += urlAlphabet[pool[i] & 63];
37
+ }
38
+ return id;
39
+ }
40
+
41
+ // ../src/engine/context-sharing.ts
42
+ async function createSharedContext(params) {
43
+ const {
44
+ sessionId,
45
+ projectId,
46
+ orgId,
47
+ userId,
48
+ includeMemories = true,
49
+ includeMessages = true,
50
+ includeChunks = false,
51
+ expiryDays = 7,
52
+ metadata = {}
53
+ } = params;
54
+ const shareId = nanoid(12);
55
+ const session = await db.session.findUnique({
56
+ where: { id: sessionId }
57
+ });
58
+ if (!session) {
59
+ throw new Error("Session not found");
60
+ }
61
+ const shareData = {
62
+ sessionId,
63
+ projectId,
64
+ userId,
65
+ metadata
66
+ };
67
+ if (includeMemories) {
68
+ const memories = await getSessionMemories({
69
+ sessionId,
70
+ projectId,
71
+ limit: 200
72
+ });
73
+ shareData.memories = memories.map((m) => ({
74
+ id: m.id,
75
+ content: m.content,
76
+ type: m.memoryType,
77
+ entities: m.entityMentions,
78
+ confidence: m.confidence,
79
+ documentDate: m.documentDate?.toISOString(),
80
+ eventDate: m.eventDate?.toISOString()
81
+ }));
82
+ } else {
83
+ shareData.memories = [];
84
+ }
85
+ if (includeMessages) {
86
+ const messages = await db.message.findMany({
87
+ where: { sessionId },
88
+ orderBy: { createdAt: "asc" },
89
+ take: 500
90
+ });
91
+ shareData.messages = messages.map((m) => ({
92
+ role: m.role,
93
+ content: m.content,
94
+ createdAt: m.createdAt.toISOString()
95
+ }));
96
+ } else {
97
+ shareData.messages = [];
98
+ }
99
+ if (includeChunks) {
100
+ const chunkIds = shareData.memories.map((m) => m.sourceChunkId).filter(Boolean).slice(0, 50);
101
+ if (chunkIds.length > 0) {
102
+ const chunks = await db.chunk.findMany({
103
+ where: {
104
+ id: { in: chunkIds }
105
+ },
106
+ select: {
107
+ id: true,
108
+ content: true,
109
+ metadata: true,
110
+ chunkType: true
111
+ },
112
+ take: 50
113
+ });
114
+ shareData.chunks = chunks;
115
+ } else {
116
+ shareData.chunks = [];
117
+ }
118
+ } else {
119
+ shareData.chunks = [];
120
+ }
121
+ const expiresAt = expiryDays ? new Date(Date.now() + expiryDays * 24 * 60 * 60 * 1e3) : null;
122
+ await db.$executeRaw`
123
+ INSERT INTO shared_contexts (
124
+ id, session_id, project_id, org_id, user_id,
125
+ share_data, expires_at, created_at, access_count
126
+ ) VALUES (
127
+ ${shareId}, ${sessionId}, ${projectId}, ${orgId}, ${userId || null},
128
+ ${JSON.stringify(shareData)}::jsonb, ${expiresAt}, NOW(), 0
129
+ )
130
+ ON CONFLICT (id) DO NOTHING
131
+ `;
132
+ const baseUrl = process.env.BASE_URL || "http://localhost:4000";
133
+ const shareUrl = `${baseUrl}/shared/${shareId}`;
134
+ return {
135
+ id: shareId,
136
+ sessionId,
137
+ projectId,
138
+ userId,
139
+ shareUrl,
140
+ memories: shareData.memories,
141
+ messages: shareData.messages,
142
+ chunks: shareData.chunks,
143
+ metadata,
144
+ createdAt: /* @__PURE__ */ new Date(),
145
+ expiresAt,
146
+ accessCount: 0
147
+ };
148
+ }
149
+ async function loadSharedContext(shareId) {
150
+ const result = await db.$queryRaw`
151
+ SELECT * FROM shared_contexts
152
+ WHERE id = ${shareId}
153
+ AND (expires_at IS NULL OR expires_at > NOW())
154
+ `;
155
+ if (result.length === 0) {
156
+ return null;
157
+ }
158
+ const row = result[0];
159
+ await db.$executeRaw`
160
+ UPDATE shared_contexts
161
+ SET access_count = access_count + 1,
162
+ last_accessed_at = NOW()
163
+ WHERE id = ${shareId}
164
+ `;
165
+ const baseUrl = process.env.BASE_URL || "http://localhost:4000";
166
+ return {
167
+ id: row.id,
168
+ sessionId: row.session_id,
169
+ projectId: row.project_id,
170
+ userId: row.user_id,
171
+ shareUrl: `${baseUrl}/shared/${shareId}`,
172
+ memories: row.share_data.memories || [],
173
+ messages: row.share_data.messages || [],
174
+ chunks: row.share_data.chunks || [],
175
+ metadata: row.share_data.metadata || {},
176
+ createdAt: row.created_at,
177
+ expiresAt: row.expires_at,
178
+ accessCount: row.access_count
179
+ };
180
+ }
181
+ async function resumeFromSharedContext(params) {
182
+ const { shareId, projectId, orgId, userId, newSessionId } = params;
183
+ const sharedContext = await loadSharedContext(shareId);
184
+ if (!sharedContext) {
185
+ throw new Error("Shared context not found or expired");
186
+ }
187
+ const sessionId = newSessionId || nanoid();
188
+ await db.session.create({
189
+ data: {
190
+ id: sessionId,
191
+ projectId,
192
+ orgId,
193
+ userId,
194
+ title: `Resumed from ${sharedContext.id}`,
195
+ metadata: {
196
+ resumedFrom: shareId,
197
+ originalSessionId: sharedContext.sessionId,
198
+ ...sharedContext.metadata
199
+ }
200
+ }
201
+ });
202
+ let memoriesRestored = 0;
203
+ for (const memory of sharedContext.memories) {
204
+ try {
205
+ await db.memory.create({
206
+ data: {
207
+ projectId,
208
+ orgId,
209
+ userId,
210
+ sessionId,
211
+ memoryType: memory.type,
212
+ content: memory.content,
213
+ entityMentions: memory.entities || [],
214
+ confidence: memory.confidence || 0.8,
215
+ documentDate: memory.documentDate ? new Date(memory.documentDate) : null,
216
+ eventDate: memory.eventDate ? new Date(memory.eventDate) : null,
217
+ validFrom: /* @__PURE__ */ new Date(),
218
+ metadata: {
219
+ restoredFrom: shareId
220
+ }
221
+ }
222
+ });
223
+ memoriesRestored++;
224
+ } catch (error) {
225
+ console.error("Failed to restore memory:", error);
226
+ }
227
+ }
228
+ for (const msg of sharedContext.messages) {
229
+ try {
230
+ await db.message.create({
231
+ data: {
232
+ sessionId,
233
+ role: msg.role,
234
+ content: msg.content,
235
+ metadata: {
236
+ restoredFrom: shareId,
237
+ originalTimestamp: msg.createdAt
238
+ }
239
+ }
240
+ });
241
+ } catch (error) {
242
+ console.error("Failed to restore message:", error);
243
+ }
244
+ }
245
+ return {
246
+ sessionId,
247
+ memoriesRestored
248
+ };
249
+ }
250
+ async function cleanupExpiredContexts() {
251
+ const result = await db.$executeRaw`
252
+ DELETE FROM shared_contexts
253
+ WHERE expires_at IS NOT NULL
254
+ AND expires_at < NOW()
255
+ `;
256
+ return result;
257
+ }
258
+ async function listSharedContexts(params) {
259
+ const { userId, projectId, orgId, limit = 50 } = params;
260
+ const maxLimit = Math.min(limit, 100);
261
+ const whereClauses = [`org_id = ${orgId}`];
262
+ if (userId) whereClauses.push(`user_id = ${userId}`);
263
+ if (projectId) whereClauses.push(`project_id = ${projectId}`);
264
+ const results = await db.$queryRaw`
265
+ SELECT id, session_id, created_at, expires_at, access_count, share_data
266
+ FROM shared_contexts
267
+ WHERE ${db.Prisma.raw(whereClauses.join(" AND "))}
268
+ ORDER BY created_at DESC
269
+ LIMIT ${maxLimit}
270
+ `;
271
+ const baseUrl = process.env.BASE_URL || "http://localhost:4000";
272
+ return results.map((row) => ({
273
+ id: row.id,
274
+ shareUrl: `${baseUrl}/shared/${row.id}`,
275
+ createdAt: row.created_at,
276
+ expiresAt: row.expires_at,
277
+ accessCount: row.access_count,
278
+ metadata: row.share_data?.metadata || {}
279
+ }));
280
+ }
281
+ var SHARED_CONTEXTS_MIGRATION = `
282
+ CREATE TABLE IF NOT EXISTS shared_contexts (
283
+ id TEXT PRIMARY KEY,
284
+ session_id TEXT NOT NULL,
285
+ project_id TEXT NOT NULL,
286
+ org_id TEXT NOT NULL,
287
+ user_id TEXT,
288
+ share_data JSONB NOT NULL DEFAULT '{}',
289
+ expires_at TIMESTAMPTZ,
290
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
291
+ access_count INTEGER NOT NULL DEFAULT 0,
292
+ last_accessed_at TIMESTAMPTZ
293
+ );
294
+
295
+ CREATE INDEX IF NOT EXISTS idx_shared_contexts_org ON shared_contexts(org_id);
296
+ CREATE INDEX IF NOT EXISTS idx_shared_contexts_user ON shared_contexts(user_id);
297
+ CREATE INDEX IF NOT EXISTS idx_shared_contexts_expires ON shared_contexts(expires_at);
298
+ CREATE INDEX IF NOT EXISTS idx_shared_contexts_session ON shared_contexts(session_id);
299
+ `;
300
+ export {
301
+ SHARED_CONTEXTS_MIGRATION,
302
+ cleanupExpiredContexts,
303
+ createSharedContext,
304
+ listSharedContexts,
305
+ loadSharedContext,
306
+ resumeFromSharedContext
307
+ };