@usewhisper/mcp-server 0.1.0 → 0.2.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.
Files changed (45) hide show
  1. package/README.md +3 -1
  2. package/dist/autosubscribe-6EDKPBE2.js +4068 -0
  3. package/dist/autosubscribe-ISDETQIB.js +436 -0
  4. package/dist/autosubscribe-ISDETQIB.js.map +1 -0
  5. package/dist/chunk-3WGYBAYR.js +8387 -0
  6. package/dist/chunk-5KIJNY6Z.js +370 -0
  7. package/dist/chunk-B3VWOHUA.js +271 -0
  8. package/dist/chunk-C57DHKTL.js +459 -0
  9. package/dist/chunk-FTWUJBAH.js +387 -0
  10. package/dist/chunk-FTWUJBAH.js.map +1 -0
  11. package/dist/chunk-H3HSKH2P.js +4841 -0
  12. package/dist/chunk-L6DXSM2U.js +457 -0
  13. package/dist/chunk-L6DXSM2U.js.map +1 -0
  14. package/dist/chunk-OBLI4FE4.js +276 -0
  15. package/dist/chunk-OBLI4FE4.js.map +1 -0
  16. package/dist/chunk-QGM4M3NI.js +37 -0
  17. package/dist/chunk-UYWE7HSU.js +369 -0
  18. package/dist/chunk-UYWE7HSU.js.map +1 -0
  19. package/dist/chunk-X2DL2GWT.js +33 -0
  20. package/dist/chunk-X2DL2GWT.js.map +1 -0
  21. package/dist/chunk-X7HNNNJJ.js +1079 -0
  22. package/dist/consolidation-FOVQTWNQ.js +222 -0
  23. package/dist/consolidation-IFQ52E44.js +210 -0
  24. package/dist/consolidation-IFQ52E44.js.map +1 -0
  25. package/dist/context-sharing-6CCFIAKL.js +276 -0
  26. package/dist/context-sharing-6CCFIAKL.js.map +1 -0
  27. package/dist/context-sharing-PH64JTXS.js +308 -0
  28. package/dist/cost-optimization-6OIKRSBV.js +196 -0
  29. package/dist/cost-optimization-6OIKRSBV.js.map +1 -0
  30. package/dist/cost-optimization-BH5NAX33.js +287 -0
  31. package/dist/cost-optimization-BH5NAX33.js.map +1 -0
  32. package/dist/cost-optimization-F3L5BS5F.js +303 -0
  33. package/dist/ingest-2LPTWUUM.js +16 -0
  34. package/dist/ingest-QE2BTV72.js +15 -0
  35. package/dist/ingest-QE2BTV72.js.map +1 -0
  36. package/dist/oracle-J47QCSEW.js +263 -0
  37. package/dist/oracle-MDP5MZRC.js +257 -0
  38. package/dist/oracle-MDP5MZRC.js.map +1 -0
  39. package/dist/search-BLVHWLWC.js +14 -0
  40. package/dist/search-CZ5NYL5B.js +13 -0
  41. package/dist/search-CZ5NYL5B.js.map +1 -0
  42. package/dist/server.d.ts +2 -0
  43. package/dist/server.js +686 -1000
  44. package/dist/server.js.map +1 -1
  45. package/package.json +5 -2
@@ -0,0 +1,303 @@
1
+ import {
2
+ Anthropic
3
+ } from "./chunk-H3HSKH2P.js";
4
+ import "./chunk-QGM4M3NI.js";
5
+
6
+ // ../src/engine/cost-optimization.ts
7
+ var MODELS = {
8
+ haiku: {
9
+ model: "claude-haiku-4.5",
10
+ maxTokens: 4096,
11
+ temperature: 0,
12
+ costPerMillion: 0.25
13
+ // $0.25 per million input tokens
14
+ },
15
+ sonnet: {
16
+ model: "claude-sonnet-4.5",
17
+ maxTokens: 8192,
18
+ temperature: 0,
19
+ costPerMillion: 3
20
+ // $3.00 per million input tokens
21
+ },
22
+ opus: {
23
+ model: "claude-opus-4.5",
24
+ maxTokens: 16384,
25
+ temperature: 0,
26
+ costPerMillion: 15
27
+ // $15.00 per million input tokens
28
+ }
29
+ };
30
+ var TASK_MODEL_MAP = {
31
+ temporal_parsing: "haiku",
32
+ // Fast, simple parsing
33
+ simple_classification: "haiku",
34
+ // Fast classification
35
+ memory_extraction: "sonnet",
36
+ // Needs accuracy for disambiguation
37
+ relation_detection: "sonnet",
38
+ // Needs reasoning
39
+ consolidation: "sonnet",
40
+ // Needs to merge intelligently
41
+ summarization: "haiku",
42
+ // Fast summarization
43
+ complex_reasoning: "opus"
44
+ // Deep reasoning tasks
45
+ };
46
+ function getOptimalModel(taskType, options = {}) {
47
+ if (options.forceModel) {
48
+ return MODELS[options.forceModel];
49
+ }
50
+ let tier = TASK_MODEL_MAP[taskType];
51
+ if (options.minQuality && tier === "haiku") {
52
+ tier = "sonnet";
53
+ }
54
+ return MODELS[tier];
55
+ }
56
+ function estimateCost(params) {
57
+ const modelConfig = getOptimalModel(params.taskType, { forceModel: params.model });
58
+ const inputCost = params.inputTokens / 1e6 * modelConfig.costPerMillion;
59
+ const outputCostPerMillion = modelConfig.costPerMillion * 5;
60
+ const outputCost = params.outputTokens / 1e6 * outputCostPerMillion;
61
+ return {
62
+ model: modelConfig.model,
63
+ inputCost,
64
+ outputCost,
65
+ totalCost: inputCost + outputCost
66
+ };
67
+ }
68
+ async function smartLLMCall(params) {
69
+ const { taskType, prompt, systemPrompt, maxTokens, temperature, forceModel } = params;
70
+ const modelConfig = getOptimalModel(taskType, { forceModel });
71
+ const anthropic = new Anthropic({
72
+ apiKey: process.env.ANTHROPIC_API_KEY || ""
73
+ });
74
+ const messages = [{ role: "user", content: prompt }];
75
+ if (systemPrompt) {
76
+ }
77
+ const response = await anthropic.messages.create({
78
+ model: modelConfig.model,
79
+ max_tokens: maxTokens || modelConfig.maxTokens,
80
+ temperature: temperature !== void 0 ? temperature : modelConfig.temperature,
81
+ messages
82
+ });
83
+ const textContent = response.content.find((c) => c.type === "text");
84
+ const responseText = textContent && textContent.type === "text" ? textContent.text : "";
85
+ const tokensUsed = {
86
+ input: response.usage.input_tokens,
87
+ output: response.usage.output_tokens
88
+ };
89
+ const cost = estimateCost({
90
+ taskType,
91
+ inputTokens: tokensUsed.input,
92
+ outputTokens: tokensUsed.output,
93
+ model: forceModel
94
+ });
95
+ return {
96
+ response: responseText,
97
+ model: modelConfig.model,
98
+ tokensUsed,
99
+ cost: cost.totalCost
100
+ };
101
+ }
102
+ async function batchOptimize(params) {
103
+ const { items, processFn, batchSize = 10, delayMs = 100 } = params;
104
+ const results = [];
105
+ for (let i = 0; i < items.length; i += batchSize) {
106
+ const batch = items.slice(i, i + batchSize);
107
+ const batchResults = await Promise.all(batch.map(processFn));
108
+ results.push(...batchResults);
109
+ if (i + batchSize < items.length) {
110
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
111
+ }
112
+ }
113
+ return results;
114
+ }
115
+ var costRecords = [];
116
+ function trackCost(record) {
117
+ costRecords.push({
118
+ ...record,
119
+ timestamp: /* @__PURE__ */ new Date()
120
+ });
121
+ }
122
+ async function getCostSummary(params) {
123
+ const { startDate, endDate } = params;
124
+ let filtered = [...costRecords];
125
+ if (startDate) {
126
+ filtered = filtered.filter((r) => r.timestamp >= startDate);
127
+ }
128
+ if (endDate) {
129
+ filtered = filtered.filter((r) => r.timestamp <= endDate);
130
+ }
131
+ const period = {
132
+ start: filtered.length > 0 ? filtered[0].timestamp : /* @__PURE__ */ new Date(),
133
+ end: filtered.length > 0 ? filtered[filtered.length - 1].timestamp : /* @__PURE__ */ new Date()
134
+ };
135
+ const totalCost = filtered.reduce((sum, r) => sum + r.cost, 0);
136
+ const totalRequests = filtered.length;
137
+ const costByModel = {};
138
+ const costByTask = {};
139
+ for (const record of filtered) {
140
+ costByModel[record.model] = (costByModel[record.model] || 0) + record.cost;
141
+ costByTask[record.taskType] = (costByTask[record.taskType] || 0) + record.cost;
142
+ }
143
+ const avgCostPerRequest = totalRequests > 0 ? totalCost / totalRequests : 0;
144
+ const daysDiff = period.end.getTime() - period.start.getTime();
145
+ const days = daysDiff > 0 ? daysDiff / (1e3 * 60 * 60 * 24) : 1;
146
+ const estimatedMonthlyCost = totalCost / days * 30;
147
+ return {
148
+ period,
149
+ totalCost,
150
+ totalRequests,
151
+ costByModel,
152
+ costByTask,
153
+ avgCostPerRequest,
154
+ estimatedMonthlyCost
155
+ };
156
+ }
157
+ function calculateSavings(params) {
158
+ const { since } = params;
159
+ const filtered = since ? costRecords.filter((r) => r.timestamp >= since) : costRecords;
160
+ const actualCost = filtered.reduce((sum, r) => sum + r.cost, 0);
161
+ const opusCost = filtered.reduce((sum, r) => {
162
+ const cost = estimateCost({
163
+ taskType: r.taskType,
164
+ inputTokens: r.inputTokens,
165
+ outputTokens: r.outputTokens,
166
+ model: "opus"
167
+ });
168
+ return sum + cost.totalCost;
169
+ }, 0);
170
+ const savings = opusCost - actualCost;
171
+ const savingsPercent = opusCost > 0 ? savings / opusCost * 100 : 0;
172
+ return {
173
+ actualCost,
174
+ opusCost,
175
+ savings,
176
+ savingsPercent
177
+ };
178
+ }
179
+ function recommendModelUpgrades(params) {
180
+ const { errorRates, threshold = 0.05 } = params;
181
+ const recommendations = [];
182
+ for (const [taskType, errorRate] of Object.entries(errorRates)) {
183
+ if (errorRate > threshold) {
184
+ const currentModel = TASK_MODEL_MAP[taskType];
185
+ let recommendedModel;
186
+ if (currentModel === "haiku") {
187
+ recommendedModel = "sonnet";
188
+ } else if (currentModel === "sonnet") {
189
+ recommendedModel = "opus";
190
+ } else {
191
+ continue;
192
+ }
193
+ recommendations.push({
194
+ taskType,
195
+ currentModel,
196
+ recommendedModel
197
+ });
198
+ }
199
+ }
200
+ return recommendations;
201
+ }
202
+ async function getCostBreakdown(params) {
203
+ const { groupBy, startDate, endDate } = params;
204
+ let filtered = [...costRecords];
205
+ if (startDate) {
206
+ filtered = filtered.filter((r) => r.timestamp >= startDate);
207
+ }
208
+ if (endDate) {
209
+ filtered = filtered.filter((r) => r.timestamp <= endDate);
210
+ }
211
+ const groups = {};
212
+ for (const record of filtered) {
213
+ let key;
214
+ switch (groupBy) {
215
+ case "model":
216
+ key = record.model;
217
+ break;
218
+ case "task":
219
+ key = record.taskType;
220
+ break;
221
+ case "day":
222
+ key = record.timestamp.toISOString().split("T")[0];
223
+ break;
224
+ case "hour":
225
+ key = record.timestamp.toISOString().slice(0, 13) + ":00";
226
+ break;
227
+ default:
228
+ key = record.taskType;
229
+ }
230
+ if (!groups[key]) {
231
+ groups[key] = { cost: 0, requests: 0 };
232
+ }
233
+ groups[key].cost += record.cost;
234
+ groups[key].requests += 1;
235
+ }
236
+ const totalCost = filtered.reduce((sum, r) => sum + r.cost, 0);
237
+ const totalRequests = filtered.length;
238
+ return { groups, totalCost, totalRequests };
239
+ }
240
+ async function getSavingsReport(params) {
241
+ const { startDate, endDate } = params;
242
+ let filtered = [...costRecords];
243
+ if (startDate) {
244
+ filtered = filtered.filter((r) => r.timestamp >= startDate);
245
+ }
246
+ if (endDate) {
247
+ filtered = filtered.filter((r) => r.timestamp <= endDate);
248
+ }
249
+ const period = {
250
+ start: filtered.length > 0 ? filtered[0].timestamp : /* @__PURE__ */ new Date(),
251
+ end: filtered.length > 0 ? filtered[filtered.length - 1].timestamp : /* @__PURE__ */ new Date()
252
+ };
253
+ const actualCost = filtered.reduce((sum, r) => sum + r.cost, 0);
254
+ let opusOnlyCost = 0;
255
+ const requests = { total: filtered.length, haiku: 0, sonnet: 0, opus: 0 };
256
+ for (const record of filtered) {
257
+ opusOnlyCost += estimateCost({
258
+ taskType: record.taskType,
259
+ inputTokens: record.inputTokens,
260
+ outputTokens: record.outputTokens,
261
+ model: "opus"
262
+ }).totalCost;
263
+ if (record.model.includes("haiku")) {
264
+ requests.haiku++;
265
+ } else if (record.model.includes("sonnet")) {
266
+ requests.sonnet++;
267
+ } else if (record.model.includes("opus")) {
268
+ requests.opus++;
269
+ }
270
+ }
271
+ const savings = opusOnlyCost - actualCost;
272
+ const savingsPercentage = opusOnlyCost > 0 ? savings / opusOnlyCost * 100 : 0;
273
+ let recommendation = "";
274
+ if (savingsPercentage > 50) {
275
+ recommendation = "Excellent! Your model selection is highly optimized.";
276
+ } else if (savingsPercentage > 30) {
277
+ recommendation = "Good savings. Consider using Haiku for simpler tasks.";
278
+ } else {
279
+ recommendation = "Consider reviewing task complexity to better match models.";
280
+ }
281
+ return {
282
+ period,
283
+ actualCost,
284
+ opusOnlyCost,
285
+ savings,
286
+ savingsPercentage,
287
+ requests,
288
+ recommendation
289
+ };
290
+ }
291
+ export {
292
+ MODELS,
293
+ batchOptimize,
294
+ calculateSavings,
295
+ estimateCost,
296
+ getCostBreakdown,
297
+ getCostSummary,
298
+ getOptimalModel,
299
+ getSavingsReport,
300
+ recommendModelUpgrades,
301
+ smartLLMCall,
302
+ trackCost
303
+ };
@@ -0,0 +1,16 @@
1
+ import {
2
+ ingestChunk,
3
+ ingestChunksBatch,
4
+ ingestSession,
5
+ updateMemory
6
+ } from "./chunk-C57DHKTL.js";
7
+ import "./chunk-5KIJNY6Z.js";
8
+ import "./chunk-3WGYBAYR.js";
9
+ import "./chunk-H3HSKH2P.js";
10
+ import "./chunk-QGM4M3NI.js";
11
+ export {
12
+ ingestChunk,
13
+ ingestChunksBatch,
14
+ ingestSession,
15
+ updateMemory
16
+ };
@@ -0,0 +1,15 @@
1
+ import {
2
+ ingestChunk,
3
+ ingestChunksBatch,
4
+ ingestSession,
5
+ updateMemory
6
+ } from "./chunk-L6DXSM2U.js";
7
+ import "./chunk-UYWE7HSU.js";
8
+ import "./chunk-X2DL2GWT.js";
9
+ export {
10
+ ingestChunk,
11
+ ingestChunksBatch,
12
+ ingestSession,
13
+ updateMemory
14
+ };
15
+ //# sourceMappingURL=ingest-QE2BTV72.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,263 @@
1
+ import {
2
+ db,
3
+ embedSingle
4
+ } from "./chunk-3WGYBAYR.js";
5
+ import {
6
+ Anthropic
7
+ } from "./chunk-H3HSKH2P.js";
8
+ import "./chunk-QGM4M3NI.js";
9
+
10
+ // ../src/engine/oracle.ts
11
+ var anthropic = new Anthropic({
12
+ apiKey: process.env.ANTHROPIC_API_KEY || ""
13
+ });
14
+ var MAX_DOCUMENT_CHUNKS = 500;
15
+ async function buildDocumentTree(documentId) {
16
+ const document = await db.document.findUnique({
17
+ where: { id: documentId },
18
+ include: {
19
+ chunks: {
20
+ orderBy: { chunkOrder: "asc" },
21
+ take: MAX_DOCUMENT_CHUNKS
22
+ }
23
+ }
24
+ });
25
+ if (!document) {
26
+ throw new Error("Document not found");
27
+ }
28
+ const root = {
29
+ id: document.id,
30
+ content: document.title,
31
+ type: "document",
32
+ children: [],
33
+ metadata: document.metadata
34
+ };
35
+ const sectionMap = /* @__PURE__ */ new Map();
36
+ for (const chunk of document.chunks) {
37
+ const sectionPath = chunk.metadata?.sectionPath || chunk.sectionPath || "root";
38
+ if (!sectionMap.has(sectionPath)) {
39
+ const sectionNode = {
40
+ id: `${documentId}::${sectionPath}`,
41
+ content: sectionPath,
42
+ type: "section",
43
+ children: [],
44
+ metadata: { path: sectionPath }
45
+ };
46
+ sectionMap.set(sectionPath, sectionNode);
47
+ root.children.push(sectionNode);
48
+ }
49
+ const section = sectionMap.get(sectionPath);
50
+ section.children.push({
51
+ id: chunk.id,
52
+ content: chunk.content,
53
+ type: "chunk",
54
+ children: [],
55
+ metadata: chunk.metadata,
56
+ embedding: chunk.embedding
57
+ });
58
+ }
59
+ return {
60
+ root,
61
+ depth: calculateDepth(root),
62
+ nodeCount: countNodes(root)
63
+ };
64
+ }
65
+ function calculateDepth(node) {
66
+ if (node.children.length === 0) return 1;
67
+ return 1 + Math.max(...node.children.map(calculateDepth));
68
+ }
69
+ function countNodes(node) {
70
+ return 1 + node.children.reduce((sum, child) => sum + countNodes(child), 0);
71
+ }
72
+ async function oracleSearch(params) {
73
+ const { query, projectId, topK = 5, maxDepth = 3 } = params;
74
+ console.log(`\u{1F52E} Oracle search: "${query}"`);
75
+ const queryEmbedding = await embedSingle(query);
76
+ const documents = await db.document.findMany({
77
+ where: { projectId },
78
+ take: 10
79
+ });
80
+ const results = [];
81
+ for (const doc of documents) {
82
+ const tree = await buildDocumentTree(doc.id);
83
+ const traversalResults = await guidedTraversal({
84
+ tree,
85
+ query,
86
+ queryEmbedding,
87
+ maxDepth,
88
+ topK
89
+ });
90
+ results.push(...traversalResults);
91
+ }
92
+ results.sort((a, b) => b.relevance - a.relevance);
93
+ return results.slice(0, topK);
94
+ }
95
+ async function guidedTraversal(params) {
96
+ const {
97
+ tree,
98
+ query,
99
+ queryEmbedding,
100
+ maxDepth,
101
+ topK,
102
+ currentNode = tree.root,
103
+ currentDepth = 0,
104
+ path = ""
105
+ } = params;
106
+ const results = [];
107
+ if (currentDepth >= maxDepth) {
108
+ return results;
109
+ }
110
+ if (currentNode.type === "chunk") {
111
+ const relevance = currentNode.embedding ? cosineSimilarity(queryEmbedding, currentNode.embedding) : 0;
112
+ if (relevance > 0.3) {
113
+ results.push({
114
+ content: currentNode.content,
115
+ path,
116
+ relevance
117
+ });
118
+ }
119
+ return results;
120
+ }
121
+ const childScores = await Promise.all(
122
+ currentNode.children.map(async (child) => {
123
+ const score = await scoreNode(child, query, queryEmbedding);
124
+ return { child, score };
125
+ })
126
+ );
127
+ childScores.sort((a, b) => b.score - a.score);
128
+ const topChildren = childScores.slice(0, Math.min(3, childScores.length));
129
+ for (const { child, score } of topChildren) {
130
+ if (score > 0.2) {
131
+ const childPath = path ? `${path} > ${child.content.substring(0, 30)}` : child.content;
132
+ const childResults = await guidedTraversal({
133
+ tree,
134
+ query,
135
+ queryEmbedding,
136
+ maxDepth,
137
+ topK,
138
+ currentNode: child,
139
+ currentDepth: currentDepth + 1,
140
+ path: childPath
141
+ });
142
+ results.push(...childResults);
143
+ }
144
+ }
145
+ return results;
146
+ }
147
+ async function scoreNode(node, query, queryEmbedding) {
148
+ if (node.embedding) {
149
+ return cosineSimilarity(queryEmbedding, node.embedding);
150
+ }
151
+ const queryWords = query.toLowerCase().split(/\s+/);
152
+ const nodeWords = node.content.toLowerCase().split(/\s+/);
153
+ const overlap = queryWords.filter((w) => nodeWords.includes(w)).length;
154
+ return overlap / queryWords.length;
155
+ }
156
+ function cosineSimilarity(a, b) {
157
+ if (a.length !== b.length) return 0;
158
+ let dotProduct = 0;
159
+ let normA = 0;
160
+ let normB = 0;
161
+ for (let i = 0; i < a.length; i++) {
162
+ dotProduct += a[i] * b[i];
163
+ normA += a[i] * a[i];
164
+ normB += b[i] * b[i];
165
+ }
166
+ return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
167
+ }
168
+ async function oracleResearch(params) {
169
+ const { question, projectId, maxSteps = 5 } = params;
170
+ const steps = [];
171
+ let currentQuery = question;
172
+ for (let step = 1; step <= maxSteps; step++) {
173
+ console.log(`\u{1F52E} Oracle step ${step}: ${currentQuery}`);
174
+ const results = await oracleSearch({
175
+ query: currentQuery,
176
+ projectId,
177
+ topK: 5
178
+ });
179
+ const reasoning = await reasonAboutResults(currentQuery, results, question);
180
+ steps.push({
181
+ step,
182
+ query: currentQuery,
183
+ results,
184
+ reasoning: reasoning.thought
185
+ });
186
+ if (reasoning.hasAnswer) {
187
+ return {
188
+ answer: reasoning.answer,
189
+ steps
190
+ };
191
+ }
192
+ currentQuery = reasoning.nextQuery || question;
193
+ }
194
+ const finalAnswer = await synthesizeAnswer(question, steps);
195
+ return {
196
+ answer: finalAnswer,
197
+ steps
198
+ };
199
+ }
200
+ async function reasonAboutResults(query, results, originalQuestion) {
201
+ const prompt = `You are analyzing search results to answer a question.
202
+
203
+ **Original question:** ${originalQuestion}
204
+ **Current query:** ${query}
205
+
206
+ **Search results:**
207
+ ${results.map((r, i) => `${i + 1}. ${r.content} (relevance: ${r.relevance.toFixed(2)})`).join("\n")}
208
+
209
+ Analyze these results:
210
+ 1. Do they answer the original question?
211
+ 2. What information is still missing?
212
+ 3. What should be the next search query?
213
+
214
+ Return JSON:
215
+ {
216
+ "thought": "your analysis",
217
+ "hasAnswer": true or false,
218
+ "answer": "the answer if you have it" or null,
219
+ "nextQuery": "next search query" or null
220
+ }`;
221
+ const response = await anthropic.messages.create({
222
+ model: "claude-sonnet-4-5-20250929",
223
+ // Fixed: was "claude-sonnet-4.5" (wrong format)
224
+ max_tokens: 1024,
225
+ temperature: 0,
226
+ messages: [{ role: "user", content: prompt }]
227
+ });
228
+ const text = response.content.find((c) => c.type === "text");
229
+ if (!text || text.type !== "text") {
230
+ return {
231
+ thought: "Analysis failed",
232
+ hasAnswer: false
233
+ };
234
+ }
235
+ const jsonMatch = text.text.match(/```json\n?([\s\S]*?)\n?```/) || text.text.match(/\{[\s\S]*\}/);
236
+ const jsonStr = jsonMatch ? jsonMatch[1] || jsonMatch[0] : text.text;
237
+ return JSON.parse(jsonStr);
238
+ }
239
+ async function synthesizeAnswer(question, steps) {
240
+ const prompt = `Synthesize a final answer from multiple research steps.
241
+
242
+ **Question:** ${question}
243
+
244
+ **Research steps:**
245
+ ${steps.map((s) => `Step ${s.step}: ${s.query}
246
+ ${s.reasoning}`).join("\n\n")}
247
+
248
+ Provide a comprehensive answer based on all the information gathered.`;
249
+ const response = await anthropic.messages.create({
250
+ model: "claude-sonnet-4-5-20250929",
251
+ // Fixed: was "claude-sonnet-4.5" (wrong format)
252
+ max_tokens: 2048,
253
+ temperature: 0,
254
+ messages: [{ role: "user", content: prompt }]
255
+ });
256
+ const text = response.content.find((c) => c.type === "text");
257
+ return text && text.type === "text" ? text.text : "Unable to synthesize answer";
258
+ }
259
+ export {
260
+ buildDocumentTree,
261
+ oracleResearch,
262
+ oracleSearch
263
+ };