@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,282 @@
1
+ import {
2
+ db,
3
+ embedSingle
4
+ } from "./chunk-MEFLJ4PV.js";
5
+ import "./chunk-QGM4M3NI.js";
6
+
7
+ // ../src/engine/oracle.ts
8
+ import OpenAI from "openai";
9
+ var openai = new OpenAI({
10
+ apiKey: process.env.OPENAI_API_KEY || ""
11
+ });
12
+ var MAX_DOCUMENT_CHUNKS = 500;
13
+ async function buildDocumentTree(documentId) {
14
+ const document = await db.document.findUnique({
15
+ where: { id: documentId },
16
+ include: {
17
+ chunks: {
18
+ orderBy: { chunkIndex: "asc" },
19
+ take: MAX_DOCUMENT_CHUNKS
20
+ }
21
+ }
22
+ });
23
+ if (!document) {
24
+ throw new Error("Document not found");
25
+ }
26
+ const root = {
27
+ id: document.id,
28
+ content: document.title,
29
+ type: "document",
30
+ children: [],
31
+ metadata: document.metadata
32
+ };
33
+ const sectionMap = /* @__PURE__ */ new Map();
34
+ for (const chunk of document.chunks) {
35
+ const sectionPath = chunk.metadata?.sectionPath || chunk.sectionPath || "root";
36
+ if (!sectionMap.has(sectionPath)) {
37
+ const sectionNode = {
38
+ id: `${documentId}::${sectionPath}`,
39
+ content: sectionPath,
40
+ type: "section",
41
+ children: [],
42
+ metadata: { path: sectionPath }
43
+ };
44
+ sectionMap.set(sectionPath, sectionNode);
45
+ root.children.push(sectionNode);
46
+ }
47
+ const section = sectionMap.get(sectionPath);
48
+ section.children.push({
49
+ id: chunk.id,
50
+ content: chunk.content,
51
+ type: "chunk",
52
+ children: [],
53
+ metadata: chunk.metadata,
54
+ embedding: chunk.embedding
55
+ });
56
+ }
57
+ return {
58
+ root,
59
+ depth: calculateDepth(root),
60
+ nodeCount: countNodes(root)
61
+ };
62
+ }
63
+ function calculateDepth(node) {
64
+ if (node.children.length === 0) return 1;
65
+ return 1 + Math.max(...node.children.map(calculateDepth));
66
+ }
67
+ function countNodes(node) {
68
+ return 1 + node.children.reduce((sum, child) => sum + countNodes(child), 0);
69
+ }
70
+ async function oracleSearch(params) {
71
+ const { query, projectId, topK = 5, maxDepth = 3 } = params;
72
+ console.log(`\u{1F52E} Oracle search: "${query}"`);
73
+ const queryEmbedding = await embedSingle(query);
74
+ const documents = await db.document.findMany({
75
+ where: { projectId },
76
+ take: 10,
77
+ include: {
78
+ _count: {
79
+ select: { chunks: true }
80
+ }
81
+ }
82
+ });
83
+ console.log(`[Oracle] Found ${documents.length} documents in project`);
84
+ const results = [];
85
+ for (const doc of documents) {
86
+ if (doc._count.chunks === 0) {
87
+ console.log(`[Oracle] Skipping document ${doc.id} - no chunks`);
88
+ continue;
89
+ }
90
+ console.log(`[Oracle] Building tree for document: ${doc.title} (${doc._count.chunks} chunks)`);
91
+ try {
92
+ const tree = await buildDocumentTree(doc.id);
93
+ console.log(`[Oracle] Tree built: ${tree.nodeCount} nodes, depth: ${tree.depth}`);
94
+ if (tree.nodeCount === 0) {
95
+ continue;
96
+ }
97
+ const traversalResults = await guidedTraversal({
98
+ tree,
99
+ query,
100
+ queryEmbedding,
101
+ maxDepth,
102
+ topK
103
+ });
104
+ console.log(`[Oracle] Traversal found ${traversalResults.length} results for ${doc.title}`);
105
+ results.push(...traversalResults);
106
+ } catch (err) {
107
+ console.error(`[Oracle] Error building tree for document ${doc.id}:`, err.message);
108
+ }
109
+ }
110
+ console.log(`[Oracle] Total results before filtering: ${results.length}`);
111
+ results.sort((a, b) => b.relevance - a.relevance);
112
+ const finalResults = results.slice(0, topK);
113
+ console.log(`[Oracle] Returning ${finalResults.length} results`);
114
+ return finalResults;
115
+ }
116
+ async function guidedTraversal(params) {
117
+ const {
118
+ tree,
119
+ query,
120
+ queryEmbedding,
121
+ maxDepth,
122
+ topK,
123
+ currentNode = tree.root,
124
+ currentDepth = 0,
125
+ path = ""
126
+ } = params;
127
+ const results = [];
128
+ if (currentDepth >= maxDepth) {
129
+ return results;
130
+ }
131
+ if (currentNode.type === "chunk") {
132
+ const relevance = currentNode.embedding ? cosineSimilarity(queryEmbedding, currentNode.embedding) : 0;
133
+ if (relevance > 0.3) {
134
+ results.push({
135
+ content: currentNode.content,
136
+ path,
137
+ relevance
138
+ });
139
+ }
140
+ return results;
141
+ }
142
+ const childScores = await Promise.all(
143
+ currentNode.children.map(async (child) => {
144
+ const score = await scoreNode(child, query, queryEmbedding);
145
+ return { child, score };
146
+ })
147
+ );
148
+ childScores.sort((a, b) => b.score - a.score);
149
+ const topChildren = childScores.slice(0, Math.min(3, childScores.length));
150
+ for (const { child, score } of topChildren) {
151
+ if (score > 0.2) {
152
+ const childPath = path ? `${path} > ${child.content.substring(0, 30)}` : child.content;
153
+ const childResults = await guidedTraversal({
154
+ tree,
155
+ query,
156
+ queryEmbedding,
157
+ maxDepth,
158
+ topK,
159
+ currentNode: child,
160
+ currentDepth: currentDepth + 1,
161
+ path: childPath
162
+ });
163
+ results.push(...childResults);
164
+ }
165
+ }
166
+ return results;
167
+ }
168
+ async function scoreNode(node, query, queryEmbedding) {
169
+ if (node.embedding) {
170
+ return cosineSimilarity(queryEmbedding, node.embedding);
171
+ }
172
+ const queryWords = query.toLowerCase().split(/\s+/);
173
+ const nodeWords = node.content.toLowerCase().split(/\s+/);
174
+ const overlap = queryWords.filter((w) => nodeWords.includes(w)).length;
175
+ return overlap / queryWords.length;
176
+ }
177
+ function cosineSimilarity(a, b) {
178
+ if (a.length !== b.length) return 0;
179
+ let dotProduct = 0;
180
+ let normA = 0;
181
+ let normB = 0;
182
+ for (let i = 0; i < a.length; i++) {
183
+ dotProduct += a[i] * b[i];
184
+ normA += a[i] * a[i];
185
+ normB += b[i] * b[i];
186
+ }
187
+ return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
188
+ }
189
+ async function oracleResearch(params) {
190
+ const { question, projectId, maxSteps = 5 } = params;
191
+ const steps = [];
192
+ let currentQuery = question;
193
+ for (let step = 1; step <= maxSteps; step++) {
194
+ console.log(`\u{1F52E} Oracle step ${step}: ${currentQuery}`);
195
+ const results = await oracleSearch({
196
+ query: currentQuery,
197
+ projectId,
198
+ topK: 5
199
+ });
200
+ const reasoning = await reasonAboutResults(currentQuery, results, question);
201
+ steps.push({
202
+ step,
203
+ query: currentQuery,
204
+ results,
205
+ reasoning: reasoning.thought
206
+ });
207
+ if (reasoning.hasAnswer) {
208
+ return {
209
+ answer: reasoning.answer,
210
+ steps
211
+ };
212
+ }
213
+ currentQuery = reasoning.nextQuery || question;
214
+ }
215
+ const finalAnswer = await synthesizeAnswer(question, steps);
216
+ return {
217
+ answer: finalAnswer,
218
+ steps
219
+ };
220
+ }
221
+ async function reasonAboutResults(query, results, originalQuestion) {
222
+ const prompt = `You are analyzing search results to answer a question.
223
+
224
+ **Original question:** ${originalQuestion}
225
+ **Current query:** ${query}
226
+
227
+ **Search results:**
228
+ ${results.map((r, i) => `${i + 1}. ${r.content} (relevance: ${r.relevance.toFixed(2)})`).join("\n")}
229
+
230
+ Analyze these results:
231
+ 1. Do they answer the original question?
232
+ 2. What information is still missing?
233
+ 3. What should be the next search query?
234
+
235
+ Return JSON:
236
+ {
237
+ "thought": "your analysis",
238
+ "hasAnswer": true or false,
239
+ "answer": "the answer if you have it" or null,
240
+ "nextQuery": "next search query" or null
241
+ }`;
242
+ const response = await openai.chat.completions.create({
243
+ model: "gpt-4o",
244
+ max_tokens: 1024,
245
+ temperature: 0,
246
+ messages: [{ role: "user", content: prompt }],
247
+ response_format: { type: "json_object" }
248
+ });
249
+ const text = response.choices[0]?.message?.content?.trim();
250
+ if (!text) {
251
+ return {
252
+ thought: "Analysis failed",
253
+ hasAnswer: false
254
+ };
255
+ }
256
+ const jsonMatch = text.match(/```json\n?([\s\S]*?)\n?```/) || text.match(/\{[\s\S]*\}/);
257
+ const jsonStr = jsonMatch ? jsonMatch[1] || jsonMatch[0] : text;
258
+ return JSON.parse(jsonStr);
259
+ }
260
+ async function synthesizeAnswer(question, steps) {
261
+ const prompt = `Synthesize a final answer from multiple research steps.
262
+
263
+ **Question:** ${question}
264
+
265
+ **Research steps:**
266
+ ${steps.map((s) => `Step ${s.step}: ${s.query}
267
+ ${s.reasoning}`).join("\n\n")}
268
+
269
+ Provide a comprehensive answer based on all the information gathered.`;
270
+ const response = await openai.chat.completions.create({
271
+ model: "gpt-4o",
272
+ max_tokens: 2048,
273
+ temperature: 0,
274
+ messages: [{ role: "user", content: prompt }]
275
+ });
276
+ return response.choices[0]?.message?.content || "Unable to synthesize answer";
277
+ }
278
+ export {
279
+ buildDocumentTree,
280
+ oracleResearch,
281
+ oracleSearch
282
+ };
@@ -0,0 +1,13 @@
1
+ import {
2
+ getSessionMemories,
3
+ getUserProfile,
4
+ searchMemories
5
+ } from "./chunk-T7KMSTWP.js";
6
+ import "./chunk-5KBZQHDL.js";
7
+ import "./chunk-3WGYBAYR.js";
8
+ import "./chunk-QGM4M3NI.js";
9
+ export {
10
+ getSessionMemories,
11
+ getUserProfile,
12
+ searchMemories
13
+ };
@@ -0,0 +1,13 @@
1
+ import {
2
+ getSessionMemories,
3
+ getUserProfile,
4
+ searchMemories
5
+ } from "./chunk-PPGYJJED.js";
6
+ import "./chunk-LMEYV4JD.js";
7
+ import "./chunk-3WGYBAYR.js";
8
+ import "./chunk-QGM4M3NI.js";
9
+ export {
10
+ getSessionMemories,
11
+ getUserProfile,
12
+ searchMemories
13
+ };
@@ -0,0 +1,13 @@
1
+ import {
2
+ getSessionMemories,
3
+ getUserProfile,
4
+ searchMemories
5
+ } from "./chunk-TWEIYHI6.js";
6
+ import "./chunk-5KBZQHDL.js";
7
+ import "./chunk-MEFLJ4PV.js";
8
+ import "./chunk-QGM4M3NI.js";
9
+ export {
10
+ getSessionMemories,
11
+ getUserProfile,
12
+ searchMemories
13
+ };