@agentic-robotics/mcp 0.1.3 → 0.2.1

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 (58) hide show
  1. package/dist/benchmark.d.ts +97 -0
  2. package/dist/benchmark.d.ts.map +1 -0
  3. package/dist/benchmark.js +330 -0
  4. package/dist/benchmark.js.map +1 -0
  5. package/dist/cli.d.ts +6 -0
  6. package/dist/cli.d.ts.map +1 -0
  7. package/dist/cli.js +79 -0
  8. package/dist/cli.js.map +1 -0
  9. package/dist/enhanced-memory.d.ts +118 -0
  10. package/dist/enhanced-memory.d.ts.map +1 -0
  11. package/dist/enhanced-memory.js +296 -0
  12. package/dist/enhanced-memory.js.map +1 -0
  13. package/dist/enhanced-server.d.ts +122 -0
  14. package/dist/enhanced-server.d.ts.map +1 -0
  15. package/dist/enhanced-server.js +361 -0
  16. package/dist/enhanced-server.js.map +1 -0
  17. package/dist/flow-orchestrator.d.ts +75 -0
  18. package/dist/flow-orchestrator.d.ts.map +1 -0
  19. package/dist/flow-orchestrator.js +350 -0
  20. package/dist/flow-orchestrator.js.map +1 -0
  21. package/dist/hybrid-benchmark.d.ts +44 -0
  22. package/dist/hybrid-benchmark.d.ts.map +1 -0
  23. package/dist/hybrid-benchmark.js +232 -0
  24. package/dist/hybrid-benchmark.js.map +1 -0
  25. package/dist/hybrid-memory.d.ts +81 -0
  26. package/dist/hybrid-memory.d.ts.map +1 -0
  27. package/dist/hybrid-memory.js +296 -0
  28. package/dist/hybrid-memory.js.map +1 -0
  29. package/dist/index.d.ts +10 -0
  30. package/dist/index.d.ts.map +1 -0
  31. package/{src/index.ts → dist/index.js} +1 -1
  32. package/dist/index.js.map +1 -0
  33. package/dist/interface.d.ts +38 -0
  34. package/dist/interface.d.ts.map +1 -0
  35. package/dist/interface.js +75 -0
  36. package/dist/interface.js.map +1 -0
  37. package/dist/memory.d.ts +52 -0
  38. package/dist/memory.d.ts.map +1 -0
  39. package/dist/memory.js +230 -0
  40. package/dist/memory.js.map +1 -0
  41. package/dist/server.d.ts +55 -0
  42. package/dist/server.d.ts.map +1 -0
  43. package/dist/server.js +147 -0
  44. package/dist/server.js.map +1 -0
  45. package/package.json +3 -2
  46. package/src/benchmark.ts +0 -434
  47. package/src/cli.ts +0 -89
  48. package/src/enhanced-memory.ts +0 -437
  49. package/src/enhanced-server.ts +0 -523
  50. package/src/flow-orchestrator.ts +0 -415
  51. package/src/hybrid-benchmark.ts +0 -291
  52. package/src/hybrid-memory.ts +0 -401
  53. package/src/interface.ts +0 -118
  54. package/src/memory.ts +0 -196
  55. package/src/optimized-benchmark.ts +0 -302
  56. package/src/optimized-memory.ts +0 -271
  57. package/src/server.ts +0 -213
  58. package/tsconfig.json +0 -20
@@ -1,437 +0,0 @@
1
- /**
2
- * Enhanced AgentDB Memory Integration
3
- *
4
- * Uses ALL AgentDB features:
5
- * - Reflexion memory with self-critique
6
- * - Skill library with semantic search
7
- * - Causal reasoning
8
- * - Automated learning
9
- * - Performance optimization
10
- */
11
-
12
- import { spawn } from 'child_process';
13
- import { promisify } from 'util';
14
- import { exec } from 'child_process';
15
-
16
- const execAsync = promisify(exec);
17
-
18
- export interface Episode {
19
- sessionId: string;
20
- taskName: string;
21
- confidence: number;
22
- success: boolean;
23
- outcome: string;
24
- strategy?: string;
25
- metadata?: Record<string, any>;
26
- reasoning?: string; // NEW: Causal reasoning
27
- critique?: string; // NEW: Self-critique
28
- }
29
-
30
- export interface Memory {
31
- task: string;
32
- confidence: number;
33
- success: boolean;
34
- outcome: string;
35
- strategy?: string;
36
- timestamp: number;
37
- reasoning?: string;
38
- critique?: string;
39
- similarity?: number;
40
- }
41
-
42
- export interface Skill {
43
- name: string;
44
- description: string;
45
- successRate: number;
46
- avgReward: number;
47
- numAttempts: number;
48
- lastUsed: number;
49
- bestStrategy?: string;
50
- }
51
-
52
- export interface MemoryStats {
53
- totalEpisodes: number;
54
- totalSkills: number;
55
- avgRetrievalTime: number;
56
- cacheHitRate: number;
57
- dbSize: number;
58
- }
59
-
60
- export class EnhancedAgentDBMemory {
61
- private dbPath: string;
62
- private initialized: boolean = false;
63
- private performanceMetrics: {
64
- retrievalTimes: number[];
65
- storeTimes: number[];
66
- cacheHits: number;
67
- cacheMisses: number;
68
- } = {
69
- retrievalTimes: [],
70
- storeTimes: [],
71
- cacheHits: 0,
72
- cacheMisses: 0,
73
- };
74
-
75
- constructor(dbPath: string) {
76
- this.dbPath = dbPath;
77
- }
78
-
79
- async initialize(): Promise<void> {
80
- if (this.initialized) return;
81
-
82
- const startTime = Date.now();
83
-
84
- try {
85
- // Initialize with optimized settings
86
- const { stdout, stderr } = await execAsync(
87
- `npx agentdb init "${this.dbPath}" --dimension 768 --preset high-performance --enable-cache`
88
- );
89
-
90
- console.error('✅ AgentDB initialized:', this.dbPath);
91
- console.error(`⚡ Initialization time: ${Date.now() - startTime}ms`);
92
- this.initialized = true;
93
- } catch (error: any) {
94
- if (!error.message.includes('already exists')) {
95
- console.error('⚠️ AgentDB initialization warning:', error.message);
96
- }
97
- this.initialized = true;
98
- }
99
- }
100
-
101
- /**
102
- * Store episode with full context and self-critique
103
- */
104
- async storeEpisode(episode: Episode): Promise<void> {
105
- const startTime = Date.now();
106
-
107
- // Generate self-critique if success
108
- let critique = episode.critique;
109
- if (episode.success && !critique) {
110
- critique = await this.generateCritique(episode);
111
- }
112
-
113
- const cmd = [
114
- 'npx agentdb reflexion store',
115
- `"${episode.sessionId}"`,
116
- `"${episode.taskName}"`,
117
- episode.confidence.toString(),
118
- episode.success.toString(),
119
- episode.outcome ? `"${episode.outcome}"` : '""',
120
- episode.strategy ? `--strategy "${episode.strategy}"` : '',
121
- episode.reasoning ? `--reasoning "${episode.reasoning}"` : '',
122
- critique ? `--critique "${critique}"` : '',
123
- ].join(' ');
124
-
125
- try {
126
- await execAsync(`AGENTDB_PATH="${this.dbPath}" ${cmd}`);
127
-
128
- const storeTime = Date.now() - startTime;
129
- this.performanceMetrics.storeTimes.push(storeTime);
130
-
131
- console.error(`💾 Stored episode: ${episode.taskName} (${storeTime}ms)`);
132
- } catch (error: any) {
133
- console.error('❌ Error storing episode:', error.message);
134
- throw error;
135
- }
136
- }
137
-
138
- /**
139
- * Retrieve memories with semantic search and causal reasoning
140
- */
141
- async retrieveMemories(
142
- query: string,
143
- k: number = 5,
144
- options: {
145
- minReward?: number;
146
- onlySuccesses?: boolean;
147
- onlyFailures?: boolean;
148
- synthesizeContext?: boolean;
149
- enableReasoning?: boolean; // NEW
150
- timeWindow?: number; // NEW: in days
151
- } = {}
152
- ): Promise<Memory[]> {
153
- const startTime = Date.now();
154
-
155
- let cmd = `npx agentdb reflexion retrieve "${query}" --k ${k}`;
156
-
157
- if (options.minReward !== undefined) {
158
- cmd += ` --min-reward ${options.minReward}`;
159
- }
160
- if (options.onlySuccesses) {
161
- cmd += ' --only-successes';
162
- }
163
- if (options.onlyFailures) {
164
- cmd += ' --only-failures';
165
- }
166
- if (options.synthesizeContext) {
167
- cmd += ' --synthesize-context';
168
- }
169
- if (options.enableReasoning) {
170
- cmd += ' --enable-causal-reasoning';
171
- }
172
- if (options.timeWindow) {
173
- cmd += ` --time-window ${options.timeWindow}`;
174
- }
175
-
176
- try {
177
- const { stdout } = await execAsync(`AGENTDB_PATH="${this.dbPath}" ${cmd}`);
178
-
179
- const retrievalTime = Date.now() - startTime;
180
- this.performanceMetrics.retrievalTimes.push(retrievalTime);
181
-
182
- // Check if sub-millisecond (cache hit)
183
- if (retrievalTime < 1) {
184
- this.performanceMetrics.cacheHits++;
185
- } else {
186
- this.performanceMetrics.cacheMisses++;
187
- }
188
-
189
- const lines = stdout.trim().split('\n');
190
- const jsonLine = lines.find(line => line.startsWith('[') || line.startsWith('{'));
191
-
192
- if (jsonLine) {
193
- const data = JSON.parse(jsonLine);
194
- const memories = Array.isArray(data) ? data : [data];
195
-
196
- console.error(`⚡ Retrieved ${memories.length} memories in ${retrievalTime}ms`);
197
- return memories;
198
- }
199
-
200
- return [];
201
- } catch (error: any) {
202
- console.error('❌ Error retrieving memories:', error.message);
203
- return [];
204
- }
205
- }
206
-
207
- /**
208
- * Query with full context synthesis and reasoning
209
- */
210
- async queryWithContext(
211
- query: string,
212
- options: {
213
- k?: number;
214
- minConfidence?: number;
215
- domain?: string;
216
- synthesizeReasoning?: boolean; // NEW
217
- } = {}
218
- ): Promise<{ memories: Memory[]; context?: string; reasoning?: string }> {
219
- const startTime = Date.now();
220
- const { k = 5, minConfidence = 0.0, domain, synthesizeReasoning = true } = options;
221
-
222
- let cmd = `npx agentdb query --query "${query}" --k ${k} --min-confidence ${minConfidence}`;
223
-
224
- if (domain) {
225
- cmd += ` --domain "${domain}"`;
226
- }
227
-
228
- cmd += ' --synthesize-context';
229
-
230
- if (synthesizeReasoning) {
231
- cmd += ' --enable-causal-reasoning';
232
- }
233
-
234
- cmd += ' --format json';
235
-
236
- try {
237
- const { stdout } = await execAsync(`AGENTDB_PATH="${this.dbPath}" ${cmd}`);
238
-
239
- const retrievalTime = Date.now() - startTime;
240
- this.performanceMetrics.retrievalTimes.push(retrievalTime);
241
-
242
- const lines = stdout.trim().split('\n');
243
- const jsonLine = lines.find(line => line.startsWith('[') || line.startsWith('{'));
244
-
245
- if (jsonLine) {
246
- const data = JSON.parse(jsonLine);
247
- console.error(`🧠 Query with reasoning: ${retrievalTime}ms`);
248
-
249
- return {
250
- memories: Array.isArray(data) ? data : [data],
251
- context: data.context || data.summary,
252
- reasoning: data.reasoning || data.causal_chain,
253
- };
254
- }
255
-
256
- return { memories: [] };
257
- } catch (error: any) {
258
- console.error('❌ Error querying with context:', error.message);
259
- return { memories: [] };
260
- }
261
- }
262
-
263
- /**
264
- * Consolidate skills with advanced filtering
265
- */
266
- async consolidateSkills(options: {
267
- minAttempts?: number;
268
- minReward?: number;
269
- timeWindowDays?: number;
270
- enablePruning?: boolean; // NEW: Remove low-quality skills
271
- } = {}): Promise<number> {
272
- const startTime = Date.now();
273
- const {
274
- minAttempts = 3,
275
- minReward = 0.7,
276
- timeWindowDays = 7,
277
- enablePruning = true,
278
- } = options;
279
-
280
- const cmd = `npx agentdb skill consolidate ${minAttempts} ${minReward} ${timeWindowDays} ${enablePruning}`;
281
-
282
- try {
283
- const { stdout } = await execAsync(`AGENTDB_PATH="${this.dbPath}" ${cmd}`);
284
-
285
- const consolidationTime = Date.now() - startTime;
286
-
287
- // Parse number of skills consolidated
288
- const match = stdout.match(/(\d+)\s+skills?\s+consolidated/i);
289
- const skillsConsolidated = match ? parseInt(match[1]) : 0;
290
-
291
- console.error(`🎯 Consolidated ${skillsConsolidated} skills in ${consolidationTime}ms`);
292
- return skillsConsolidated;
293
- } catch (error: any) {
294
- console.error('❌ Error consolidating skills:', error.message);
295
- return 0;
296
- }
297
- }
298
-
299
- /**
300
- * Get skill library with semantic search
301
- */
302
- async searchSkills(
303
- query: string,
304
- options: {
305
- k?: number;
306
- minSuccessRate?: number;
307
- sortBy?: 'success_rate' | 'avg_reward' | 'num_attempts' | 'last_used';
308
- } = {}
309
- ): Promise<Skill[]> {
310
- const startTime = Date.now();
311
- const { k = 10, minSuccessRate = 0.5, sortBy = 'success_rate' } = options;
312
-
313
- const cmd = `npx agentdb skill search "${query}" --k ${k} --min-success-rate ${minSuccessRate} --sort-by ${sortBy} --format json`;
314
-
315
- try {
316
- const { stdout } = await execAsync(`AGENTDB_PATH="${this.dbPath}" ${cmd}`);
317
-
318
- const searchTime = Date.now() - startTime;
319
-
320
- const lines = stdout.trim().split('\n');
321
- const jsonLine = lines.find(line => line.startsWith('[') || line.startsWith('{'));
322
-
323
- if (jsonLine) {
324
- const data = JSON.parse(jsonLine);
325
- const skills = Array.isArray(data) ? data : [data];
326
-
327
- console.error(`🔍 Found ${skills.length} skills in ${searchTime}ms`);
328
- return skills;
329
- }
330
-
331
- return [];
332
- } catch (error: any) {
333
- console.error('❌ Error searching skills:', error.message);
334
- return [];
335
- }
336
- }
337
-
338
- /**
339
- * Generate self-critique for an episode
340
- */
341
- private async generateCritique(episode: Episode): Promise<string> {
342
- if (!episode.success) {
343
- return `Failed to complete ${episode.taskName}: ${episode.outcome}. Need to analyze failure modes.`;
344
- }
345
-
346
- const critiques = [
347
- `Successfully completed ${episode.taskName} with ${(episode.confidence * 100).toFixed(1)}% confidence. `,
348
- episode.strategy ? `Strategy "${episode.strategy}" was effective. ` : '',
349
- episode.metadata?.latency
350
- ? `Latency: ${episode.metadata.latency}ms. ${episode.metadata.latency < 100 ? 'Excellent response time.' : 'Consider optimization.'} `
351
- : '',
352
- 'Could explore alternative approaches for comparison.',
353
- ].join('');
354
-
355
- return critiques;
356
- }
357
-
358
- /**
359
- * Get comprehensive statistics with performance metrics
360
- */
361
- async getStats(): Promise<MemoryStats> {
362
- try {
363
- const { stdout } = await execAsync(`AGENTDB_PATH="${this.dbPath}" npx agentdb db stats --format json`);
364
-
365
- const lines = stdout.trim().split('\n');
366
- const jsonLine = lines.find(line => line.startsWith('{'));
367
-
368
- const dbStats = jsonLine ? JSON.parse(jsonLine) : {};
369
-
370
- // Calculate performance metrics
371
- const avgRetrievalTime = this.performanceMetrics.retrievalTimes.length > 0
372
- ? this.performanceMetrics.retrievalTimes.reduce((a, b) => a + b, 0) / this.performanceMetrics.retrievalTimes.length
373
- : 0;
374
-
375
- const totalCacheRequests = this.performanceMetrics.cacheHits + this.performanceMetrics.cacheMisses;
376
- const cacheHitRate = totalCacheRequests > 0
377
- ? this.performanceMetrics.cacheHits / totalCacheRequests
378
- : 0;
379
-
380
- return {
381
- totalEpisodes: dbStats.total_episodes || 0,
382
- totalSkills: dbStats.total_skills || 0,
383
- avgRetrievalTime: parseFloat(avgRetrievalTime.toFixed(3)),
384
- cacheHitRate: parseFloat((cacheHitRate * 100).toFixed(2)),
385
- dbSize: dbStats.db_size_bytes || 0,
386
- };
387
- } catch (error: any) {
388
- console.error('❌ Error getting stats:', error.message);
389
- return {
390
- totalEpisodes: 0,
391
- totalSkills: 0,
392
- avgRetrievalTime: 0,
393
- cacheHitRate: 0,
394
- dbSize: 0,
395
- };
396
- }
397
- }
398
-
399
- /**
400
- * Optimize database performance
401
- */
402
- async optimize(): Promise<void> {
403
- const startTime = Date.now();
404
-
405
- try {
406
- // Vacuum database
407
- await execAsync(`AGENTDB_PATH="${this.dbPath}" npx agentdb db vacuum`);
408
-
409
- // Rebuild indexes
410
- await execAsync(`AGENTDB_PATH="${this.dbPath}" npx agentdb db reindex`);
411
-
412
- // Optimize vector index
413
- await execAsync(`AGENTDB_PATH="${this.dbPath}" npx agentdb db optimize-vectors`);
414
-
415
- const optimizeTime = Date.now() - startTime;
416
- console.error(`⚙️ Database optimized in ${optimizeTime}ms`);
417
- } catch (error: any) {
418
- console.error('⚠️ Optimization warning:', error.message);
419
- }
420
- }
421
-
422
- /**
423
- * Clear performance metrics
424
- */
425
- clearMetrics(): void {
426
- this.performanceMetrics = {
427
- retrievalTimes: [],
428
- storeTimes: [],
429
- cacheHits: 0,
430
- cacheMisses: 0,
431
- };
432
- }
433
-
434
- async close(): Promise<void> {
435
- this.initialized = false;
436
- }
437
- }