agentic-flow 3.3.0 → 3.4.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/CHANGELOG.md +36 -0
- package/dist/.tsbuildinfo +1 -1
- package/dist/config/claudeFlow.d.ts +1 -1
- package/dist/intelligence/RuVectorIntelligence.d.ts +4 -2
- package/dist/intelligence/RuVectorIntelligence.d.ts.map +1 -1
- package/dist/intelligence/RuVectorIntelligence.js +35 -10
- package/dist/intelligence/RuVectorIntelligence.js.map +1 -1
- package/dist/mcp/claudeFlowSdkServer.d.ts.map +1 -1
- package/dist/mcp/claudeFlowSdkServer.js +3 -1
- package/dist/mcp/claudeFlowSdkServer.js.map +1 -1
- package/dist/mcp/fastmcp/tools/swarm/p2p-swarm-tools.d.ts +29 -121
- package/dist/mcp/fastmcp/tools/swarm/p2p-swarm-tools.d.ts.map +1 -1
- package/dist/mcp/fastmcp/tools/swarm/p2p-swarm-tools.js +1 -1
- package/dist/mcp/fastmcp/tools/swarm/p2p-swarm-tools.js.map +1 -1
- package/dist/mcp/sdk-tool-schema.d.ts +20 -0
- package/dist/mcp/sdk-tool-schema.d.ts.map +1 -0
- package/dist/mcp/sdk-tool-schema.js +31 -0
- package/dist/mcp/sdk-tool-schema.js.map +1 -0
- package/dist/optimizations/configuration-tuning.d.ts +1 -1
- package/dist/utils/agentdb-runtime-patch.js +2 -2
- package/dist/utils/agentdb-runtime-patch.js.map +1 -1
- package/package.json +9 -6
|
@@ -26,7 +26,7 @@ export declare function getMemoryConfig(agentName?: string): {
|
|
|
26
26
|
* Initialize swarm coordination for multi-agent tasks
|
|
27
27
|
*/
|
|
28
28
|
export declare function getSwarmConfig(topology?: ClaudeFlowConfig['coordinationTopology']): {
|
|
29
|
-
topology: "
|
|
29
|
+
topology: "mesh" | "hierarchical" | "ring" | "star";
|
|
30
30
|
maxAgents: number;
|
|
31
31
|
strategy: "balanced";
|
|
32
32
|
};
|
|
@@ -301,9 +301,11 @@ export declare class RuVectorIntelligence {
|
|
|
301
301
|
*/
|
|
302
302
|
private getPatternsCount;
|
|
303
303
|
/**
|
|
304
|
-
* Compute attention asynchronously
|
|
304
|
+
* Compute attention asynchronously on a native worker thread
|
|
305
305
|
*
|
|
306
|
-
* Useful for large batches or when non-blocking is required
|
|
306
|
+
* Useful for large batches or when non-blocking is required. 'standard' (the
|
|
307
|
+
* default) is native scaled dot-product attention. The native functions take
|
|
308
|
+
* the embedding dimension (and flash block size) explicitly.
|
|
307
309
|
*/
|
|
308
310
|
computeAttentionAsync(query: Float32Array, keys: Float32Array[], values: Float32Array[], type?: 'flash' | 'hyperbolic' | 'standard'): Promise<Float32Array>;
|
|
309
311
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RuVectorIntelligence.d.ts","sourceRoot":"","sources":["../../src/intelligence/RuVectorIntelligence.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAIH,QAAA,IAAI,aAAa,SAAQ,CAAC;AAe1B,QAAA,IAAI,kBAAkB,SAAQ,CAAC;
|
|
1
|
+
{"version":3,"file":"RuVectorIntelligence.d.ts","sourceRoot":"","sources":["../../src/intelligence/RuVectorIntelligence.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAIH,QAAA,IAAI,aAAa,SAAQ,CAAC;AAe1B,QAAA,IAAI,kBAAkB,SAAQ,CAAC;AAmD/B,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,CAAC;AAG7C,MAAM,WAAW,YAAY;IAC3B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EA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AAa,IAAI,MAAM;IAcvB;;OAEG;IACH,OAAO,CAAC,uBAAuB;IAgB/B;;OAEG;IACH,OAAO,CAAC,gBAAgB;IAexB;;;;;;OAMG;IACG,qBAAqB,CACzB,KAAK,EAAE,YAAY,EACnB,IAAI,EAAE,YAAY,EAAE,EACpB,MAAM,EAAE,YAAY,EAAE,EACtB,IAAI,CAAC,EAAE,OAAO,GAAG,YAAY,GAAG,UAAU,GACzC,OAAO,CAAC,YAAY,CAAC;IAwBxB;;;;OAIG;IACH,gBAAgB,CAAC,CAAC,EAAE,YAAY,EAAE,CAAC,EAAE,YAAY,GAAG,MAAM;IAI1D;;OAEG;IACH,iBAAiB,CAAC,SAAS,EAAE,YAAY,GAAG,YAAY;IAQxD;;OAEG;IACH,QAAQ,IAAI,OAAO,IAAI,CAAC,KAAK,GAAG;QAAE,SAAS,CAAC,EAAE,GAAG,CAAA;KAAE;IAenD;;OAEG;IACH,UAAU,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI;IAMlC;;OAEG;IACH,SAAS,IAAI,OAAO;IAIpB;;OAEG;IACH,OAAO,IAAI,IAAI;CAsBhB;AAED;;GAEG;AACH,wBAAgB,uBAAuB,CACrC,MAAM,CAAC,EAAE,0BAA0B,GAClC,oBAAoB,CAEtB;AAED;;GAEG;AACH,eAAO,MAAM,mBAAmB;IAC9B,iDAAiD;;;;;;;;IASjD,wCAAwC;;;;;;;;;IAUxC,uCAAuC;;;;;;;;;;;;IAavC,kDAAkD;;;;;;IAOlD,4BAA4B;;;;;CAK7B,CAAC"}
|
|
@@ -47,6 +47,15 @@ let poincareDistance = null;
|
|
|
47
47
|
let projectToPoincareBall = null;
|
|
48
48
|
let AttentionType = null;
|
|
49
49
|
let attentionAvailable = false;
|
|
50
|
+
/**
|
|
51
|
+
* Tile size for native flash attention. @ruvector/attention 2.x requires it
|
|
52
|
+
* explicitly in both the FlashAttention constructor and
|
|
53
|
+
* computeFlashAttentionAsync (omitting it throws, which used to push every
|
|
54
|
+
* 'flash' route onto the JS fallback).
|
|
55
|
+
*/
|
|
56
|
+
const FLASH_ATTENTION_BLOCK_SIZE = 64;
|
|
57
|
+
/** Max graph position for GraphRoPeAttention's rotary table. */
|
|
58
|
+
const GRAPH_ROPE_MAX_POSITION = 10000;
|
|
50
59
|
// Try to load @ruvector/sona (through the loader, whose engines validate
|
|
51
60
|
// LoRA input lengths instead of letting a native panic abort the process)
|
|
52
61
|
try {
|
|
@@ -198,7 +207,7 @@ export class RuVectorIntelligence {
|
|
|
198
207
|
this.multiHeadAttention = new MultiHeadAttention(dim, this.config.numHeads ?? 8);
|
|
199
208
|
break;
|
|
200
209
|
case 'flash':
|
|
201
|
-
this.flashAttention = new FlashAttention(dim);
|
|
210
|
+
this.flashAttention = new FlashAttention(dim, FLASH_ATTENTION_BLOCK_SIZE);
|
|
202
211
|
break;
|
|
203
212
|
case 'hyperbolic':
|
|
204
213
|
this.hyperbolicAttention = new HyperbolicAttention(dim, this.config.curvature ?? 1.0);
|
|
@@ -212,12 +221,17 @@ export class RuVectorIntelligence {
|
|
|
212
221
|
this.moeAttention = new MoEAttention(moeConfig);
|
|
213
222
|
break;
|
|
214
223
|
case 'graph':
|
|
215
|
-
|
|
224
|
+
// 2.x takes a RoPEConfig object; positional args throw "Missing field `dim`"
|
|
225
|
+
this.graphAttention = new GraphRoPeAttention({ dim, maxPosition: GRAPH_ROPE_MAX_POSITION });
|
|
216
226
|
break;
|
|
217
227
|
case 'dual':
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
228
|
+
// 2.x takes a DualSpaceConfig object; positional args throw "Missing field `dim`"
|
|
229
|
+
this.dualSpaceAttention = new DualSpaceAttention({
|
|
230
|
+
dim,
|
|
231
|
+
curvature: this.config.curvature ?? 1.0,
|
|
232
|
+
euclideanWeight: 0.5,
|
|
233
|
+
hyperbolicWeight: 0.5,
|
|
234
|
+
});
|
|
221
235
|
break;
|
|
222
236
|
}
|
|
223
237
|
}
|
|
@@ -468,6 +482,14 @@ export class RuVectorIntelligence {
|
|
|
468
482
|
attentionOutput = this.computeFallbackAttention(transformedQuery, keys, values);
|
|
469
483
|
}
|
|
470
484
|
break;
|
|
485
|
+
case 'graph':
|
|
486
|
+
if (this.graphAttention) {
|
|
487
|
+
attentionOutput = this.graphAttention.compute(transformedQuery, keys, values);
|
|
488
|
+
}
|
|
489
|
+
else {
|
|
490
|
+
attentionOutput = this.computeFallbackAttention(transformedQuery, keys, values);
|
|
491
|
+
}
|
|
492
|
+
break;
|
|
471
493
|
case 'dual':
|
|
472
494
|
if (this.dualSpaceAttention) {
|
|
473
495
|
attentionOutput = this.dualSpaceAttention.compute(transformedQuery, keys, values);
|
|
@@ -755,18 +777,21 @@ export class RuVectorIntelligence {
|
|
|
755
777
|
// Async Attention (for large batches)
|
|
756
778
|
// ==========================================================================
|
|
757
779
|
/**
|
|
758
|
-
* Compute attention asynchronously
|
|
780
|
+
* Compute attention asynchronously on a native worker thread
|
|
759
781
|
*
|
|
760
|
-
* Useful for large batches or when non-blocking is required
|
|
782
|
+
* Useful for large batches or when non-blocking is required. 'standard' (the
|
|
783
|
+
* default) is native scaled dot-product attention. The native functions take
|
|
784
|
+
* the embedding dimension (and flash block size) explicitly.
|
|
761
785
|
*/
|
|
762
786
|
async computeAttentionAsync(query, keys, values, type) {
|
|
787
|
+
const dim = query.length;
|
|
763
788
|
switch (type) {
|
|
764
789
|
case 'flash':
|
|
765
|
-
return computeFlashAttentionAsync(query, keys, values);
|
|
790
|
+
return computeFlashAttentionAsync(query, keys, values, dim, FLASH_ATTENTION_BLOCK_SIZE);
|
|
766
791
|
case 'hyperbolic':
|
|
767
|
-
return computeHyperbolicAttentionAsync(query, keys, values, this.config.curvature);
|
|
792
|
+
return computeHyperbolicAttentionAsync(query, keys, values, dim, this.config.curvature ?? 1.0);
|
|
768
793
|
default:
|
|
769
|
-
return computeAttentionAsync(query, keys, values,
|
|
794
|
+
return computeAttentionAsync(query, keys, values, dim);
|
|
770
795
|
}
|
|
771
796
|
}
|
|
772
797
|
// ==========================================================================
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RuVectorIntelligence.js","sourceRoot":"","sources":["../../src/intelligence/RuVectorIntelligence.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,oFAAoF;AACpF,IAAI,UAAU,GAAQ,IAAI,CAAC;AAC3B,IAAI,aAAa,GAAG,KAAK,CAAC;AAE1B,IAAI,kBAAkB,GAAQ,IAAI,CAAC;AACnC,IAAI,cAAc,GAAQ,IAAI,CAAC;AAC/B,IAAI,mBAAmB,GAAQ,IAAI,CAAC;AACpC,IAAI,YAAY,GAAQ,IAAI,CAAC;AAC7B,IAAI,kBAAkB,GAAQ,IAAI,CAAC;AACnC,IAAI,kBAAkB,GAAQ,IAAI,CAAC;AACnC,IAAI,aAAa,GAAQ,IAAI,CAAC;AAC9B,IAAI,qBAAqB,GAAQ,IAAI,CAAC;AACtC,IAAI,0BAA0B,GAAQ,IAAI,CAAC;AAC3C,IAAI,+BAA+B,GAAQ,IAAI,CAAC;AAChD,IAAI,gBAAgB,GAAQ,IAAI,CAAC;AACjC,IAAI,qBAAqB,GAAQ,IAAI,CAAC;AACtC,IAAI,aAAa,GAAQ,IAAI,CAAC;AAC9B,IAAI,kBAAkB,GAAG,KAAK,CAAC;AAE/B,yEAAyE;AACzE,0EAA0E;AAC1E,IAAI,CAAC;IACH,UAAU,GAAG,iBAAiB,EAAE,CAAC;IACjC,aAAa,GAAG,IAAI,CAAC;AACvB,CAAC;AAAC,MAAM,CAAC;IACP,OAAO,CAAC,IAAI,CAAC,8EAA8E,CAAC,CAAC;AAC/F,CAAC;AAED,kCAAkC;AAClC,IAAI,CAAC;IACH,wEAAwE;IACxE,yEAAyE;IACzE,MAAM,YAAY,GAAQ,MAAM,MAAM,CAAC,qBAAqB,CAAC,CAAC;IAC9D,MAAM,eAAe,GAAG,YAAY,CAAC,OAAO,IAAI,YAAY,CAAC;IAC7D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,CAAC;AAC1C,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG;IACjC,iDAAiD;IACjD,IAAI,EAAE;QACJ,aAAa,EAAE,KAAc;QAC7B,UAAU,EAAE,CAAC;QACb,IAAI,EAAE,CAAC;QACP,kBAAkB,EAAE,KAAK;QACzB,oBAAoB,EAAE,MAAM,EAAE,QAAQ;KACvC;IAED,wCAAwC;IACxC,QAAQ,EAAE;QACR,aAAa,EAAE,KAAc;QAC7B,UAAU,EAAE,CAAC;QACb,IAAI,EAAE,CAAC;QACP,kBAAkB,EAAE,IAAI;QACxB,oBAAoB,EAAE,KAAK,EAAE,QAAQ;QACrC,gBAAgB,EAAE,GAAG;KACtB;IAED,uCAAuC;IACvC,QAAQ,EAAE;QACR,aAAa,EAAE,MAAe;QAC9B,kBAAkB,EAAE,IAAI;QACxB,oBAAoB,EAAE,KAAK,EAAE,SAAS;QACtC,gBAAgB,EAAE,GAAG;QACrB,UAAU,EAAE;YACV,aAAa,EAAE,CAAC;YAChB,YAAY,EAAE,EAAE;YAChB,kBAAkB,EAAE,KAAK;SAC1B;KACF;IAED,kDAAkD;IAClD,YAAY,EAAE;QACZ,aAAa,EAAE,YAAqB;QACpC,SAAS,EAAE,GAAG;QACd,kBAAkB,EAAE,IAAI;KACzB;IAED,4BAA4B;IAC5B,KAAK,EAAE;QACL,aAAa,EAAE,OAAgB;QAC/B,kBAAkB,EAAE,IAAI;KACzB;CACF,CAAC","sourcesContent":["/**\n * RuVector Unified Intelligence Layer\n *\n * Integrates the FULL power of RuVector ecosystem:\n *\n * @ruvector/sona - Self-Learning:\n * - Micro-LoRA: Ultra-fast rank-1/2 adaptations (~0.1ms)\n * - Base-LoRA: Deeper pattern adaptations\n * - EWC++: Elastic Weight Consolidation (catastrophic forgetting prevention)\n * - ReasoningBank: Pattern storage/retrieval via findPatterns\n * - Trajectory tracking: Learn from execution paths\n *\n * @ruvector/attention - Advanced Attention:\n * - MultiHeadAttention: Standard transformer attention\n * - FlashAttention: Memory-efficient O(n) attention\n * - HyperbolicAttention: Poincaré ball geometry for hierarchies\n * - MoEAttention: Mixture of Experts routing\n * - GraphRoPeAttention: Graph + Rotary Position Embeddings\n * - EdgeFeaturedAttention: Edge-aware graph attention\n * - DualSpaceAttention: Euclidean + Hyperbolic hybrid\n *\n * @ruvector/core - Vector Database:\n * - HNSW indexing: 150x faster than brute force\n * - Real vector similarity search\n * - Cosine/Euclidean/Dot product distance\n *\n * Performance:\n * - Micro-LoRA adaptation: ~0.1ms\n * - FlashAttention: O(n) complexity vs O(n²)\n * - HNSW search: O(log n) vs O(n)\n * - Background learning: Non-blocking\n */\n\n// Optional imports - graceful fallback on Windows/platforms without native binaries\nlet SonaEngine: any = null;\nlet sonaAvailable = false;\n\nlet MultiHeadAttention: any = null;\nlet FlashAttention: any = null;\nlet HyperbolicAttention: any = null;\nlet MoEAttention: any = null;\nlet GraphRoPeAttention: any = null;\nlet DualSpaceAttention: any = null;\nlet AdamOptimizer: any = null;\nlet computeAttentionAsync: any = null;\nlet computeFlashAttentionAsync: any = null;\nlet computeHyperbolicAttentionAsync: any = null;\nlet poincareDistance: any = null;\nlet projectToPoincareBall: any = null;\nlet AttentionType: any = null;\nlet attentionAvailable = false;\n\n// Try to load @ruvector/sona (through the loader, whose engines validate\n// LoRA input lengths instead of letting a native panic abort the process)\ntry {\n SonaEngine = requireSonaEngine();\n sonaAvailable = true;\n} catch {\n console.warn('[RuVectorIntelligence] @ruvector/sona not available - self-learning disabled');\n}\n\n// Try to load @ruvector/attention\ntry {\n // @ruvector/attention is CommonJS; from 0.1.32 its typings expose it as\n // `default` under ESM interop, while older builds surface named exports.\n const attentionMod: any = await import('@ruvector/attention');\n const attentionModule = attentionMod.default ?? attentionMod;\n MultiHeadAttention = attentionModule.MultiHeadAttention;\n FlashAttention = attentionModule.FlashAttention;\n HyperbolicAttention = attentionModule.HyperbolicAttention;\n MoEAttention = attentionModule.MoEAttention;\n GraphRoPeAttention = attentionModule.GraphRoPeAttention;\n DualSpaceAttention = attentionModule.DualSpaceAttention;\n AdamOptimizer = attentionModule.AdamOptimizer;\n computeAttentionAsync = attentionModule.computeAttentionAsync;\n computeFlashAttentionAsync = attentionModule.computeFlashAttentionAsync;\n computeHyperbolicAttentionAsync = attentionModule.computeHyperbolicAttentionAsync;\n poincareDistance = attentionModule.poincareDistance;\n projectToPoincareBall = attentionModule.projectToPoincareBall;\n AttentionType = attentionModule.AttentionType;\n attentionAvailable = true;\n} catch {\n console.warn('[RuVectorIntelligence] @ruvector/attention not available - attention features disabled');\n}\n\n// Import from ruvector core (for HNSW)\nimport { requireSonaEngine } from '../services/sona-loader.js';\nimport ruvector from 'ruvector';\n\n// Export availability flags\nexport { sonaAvailable, attentionAvailable };\n\n// Local type definitions (replaces imports from optional packages)\nexport interface JsSonaConfig {\n embeddingDim?: number;\n hiddenDim?: number;\n microLoraRank?: number;\n baseLoraRank?: number;\n ewcLambda?: number;\n microLoraLr?: number;\n baseLoraLr?: number;\n patternClusters?: number;\n [key: string]: any; // Allow additional properties\n}\n\nexport interface JsLearnedPattern {\n id: string;\n pattern: number[];\n confidence: number;\n timestamp: number;\n}\n\nexport interface MoEConfig {\n numExperts?: number;\n topK?: number;\n routerDim?: number;\n dim?: number;\n}\n\n/**\n * Intelligence Layer Configuration\n */\nexport interface RuVectorIntelligenceConfig {\n /** Embedding dimension (default: 384 for all-MiniLM-L6-v2) */\n embeddingDim?: number;\n\n /** Hidden dimension for SONA (default: 256) */\n hiddenDim?: number;\n\n /** Enable SONA self-learning (default: true) */\n enableSona?: boolean;\n\n /** SONA configuration */\n sonaConfig?: Partial<JsSonaConfig>;\n\n /** Attention type for agent routing (default: 'moe') */\n attentionType?: 'multi_head' | 'flash' | 'hyperbolic' | 'moe' | 'graph' | 'dual';\n\n /** Number of attention heads (default: 8) */\n numHeads?: number;\n\n /** Number of MoE experts (default: 4) */\n numExperts?: number;\n\n /** Top-K experts to use (default: 2) */\n topK?: number;\n\n /** Hyperbolic curvature for hierarchical structures (default: 1.0) */\n curvature?: number;\n\n /** Enable HNSW vector index (default: true) */\n enableHnsw?: boolean;\n\n /** HNSW M parameter - connections per node (default: 16) */\n hnswM?: number;\n\n /** HNSW ef_construction (default: 200) */\n hnswEfConstruction?: number;\n\n /** Enable trajectory tracking (default: true) */\n enableTrajectories?: boolean;\n\n /** Quality threshold for learning (default: 0.5) */\n qualityThreshold?: number;\n\n /** Background learning interval in ms (default: 60000 = 1 min) */\n backgroundIntervalMs?: number;\n\n /** Maximum trajectories to keep in memory (default: 1000, LRU eviction) */\n maxTrajectories?: number;\n\n /** Trajectory TTL in ms (default: 1800000 = 30 min) */\n trajectoryTTLMs?: number;\n\n /** Maximum agent embeddings to cache (default: 500, LRU eviction) */\n maxAgentEmbeddings?: number;\n}\n\n/**\n * Trajectory for learning\n */\nexport interface Trajectory {\n id: number;\n query: string;\n embedding: number[];\n steps: TrajectoryStep[];\n route?: string;\n contexts: string[];\n startTime: number;\n}\n\nexport interface TrajectoryStep {\n action: string;\n activations: number[];\n attentionWeights: number[];\n reward: number;\n timestamp: number;\n}\n\n/**\n * Agent routing result\n */\nexport interface AgentRoutingResult {\n agentId: string;\n confidence: number;\n attentionWeights: Float32Array;\n expertWeights?: number[];\n latencyMs: number;\n usedHnsw: boolean;\n usedSona: boolean;\n}\n\n/**\n * Learning outcome\n */\nexport interface LearningOutcome {\n trajectoryId: number;\n success: boolean;\n quality: number;\n patternsLearned: number;\n adaptations: {\n microLora: boolean;\n baseLora: boolean;\n ewc: boolean;\n };\n}\n\n/**\n * RuVector Unified Intelligence Layer\n *\n * Combines SONA self-learning, advanced attention mechanisms,\n * and HNSW vector search for intelligent agent orchestration.\n */\n/**\n * Result wrapper for operations that can fail\n */\nexport interface OperationResult<T> {\n success: boolean;\n value?: T;\n error?: string;\n}\n\nexport class RuVectorIntelligence {\n private config: Required<RuVectorIntelligenceConfig>;\n private initialized = false;\n private initPromise: Promise<void> | null = null;\n\n // SONA Engine for self-learning\n private sona: any = null;\n\n // Attention mechanisms\n private multiHeadAttention: any = null;\n private flashAttention: any = null;\n private hyperbolicAttention: any = null;\n private moeAttention: any = null;\n private graphAttention: any = null;\n private dualSpaceAttention: any = null;\n\n // Training (simplified - removed unused scheduler/loss)\n private optimizer: any = null;\n\n // HNSW index for vector search\n private hnswIndex: any = null;\n\n // Active trajectories with LRU tracking\n private trajectories: Map<number, Trajectory> = new Map();\n private trajectoryAccessOrder: number[] = []; // For LRU eviction\n private nextTrajectoryId = 0;\n\n // Agent embeddings with LRU tracking\n private agentEmbeddings: Map<string, Float32Array> = new Map();\n private agentAccessOrder: string[] = []; // For LRU eviction\n\n // Background learning timer\n private learningTimer: NodeJS.Timeout | null = null;\n\n // Cleanup timer for stale trajectories\n private cleanupTimer: NodeJS.Timeout | null = null;\n\n // Statistics\n private stats = {\n totalRoutings: 0,\n totalTrajectories: 0,\n totalLearningCycles: 0,\n avgRoutingLatencyMs: 0,\n patternsLearned: 0,\n hnswQueries: 0,\n sonaAdaptations: 0,\n evictedTrajectories: 0,\n evictedAgents: 0,\n };\n\n constructor(config?: RuVectorIntelligenceConfig) {\n this.config = {\n embeddingDim: config?.embeddingDim ?? 384,\n hiddenDim: config?.hiddenDim ?? 256,\n enableSona: config?.enableSona ?? true,\n sonaConfig: config?.sonaConfig ?? {},\n attentionType: config?.attentionType ?? 'moe',\n numHeads: config?.numHeads ?? 8,\n numExperts: config?.numExperts ?? 4,\n topK: config?.topK ?? 2,\n curvature: config?.curvature ?? 1.0,\n enableHnsw: config?.enableHnsw ?? true,\n hnswM: config?.hnswM ?? 16,\n hnswEfConstruction: config?.hnswEfConstruction ?? 200,\n enableTrajectories: config?.enableTrajectories ?? true,\n qualityThreshold: config?.qualityThreshold ?? 0.5,\n backgroundIntervalMs: config?.backgroundIntervalMs ?? 60000,\n // Memory limits with LRU eviction\n maxTrajectories: config?.maxTrajectories ?? 1000,\n trajectoryTTLMs: config?.trajectoryTTLMs ?? 1800000, // 30 min\n maxAgentEmbeddings: config?.maxAgentEmbeddings ?? 500,\n };\n\n // Initialize asynchronously to avoid race conditions\n this.initPromise = this.initializeAsync();\n }\n\n /**\n * Wait for initialization to complete\n */\n async waitForInit(): Promise<void> {\n if (this.initPromise) {\n await this.initPromise;\n }\n }\n\n /**\n * Initialize all components (async to avoid race conditions)\n */\n private async initializeAsync(): Promise<void> {\n if (this.initialized) return;\n\n const dim = this.config.embeddingDim;\n\n // Initialize SONA Engine\n if (this.config.enableSona) {\n try {\n // Ensure all values are explicitly defined (no undefined values)\n const sonaConfig: JsSonaConfig = {\n hiddenDim: this.config.hiddenDim ?? 256,\n embeddingDim: dim ?? 384,\n microLoraRank: 1, // Ultra-fast rank-1\n baseLoraRank: 8,\n microLoraLr: 0.001,\n baseLoraLr: 0.0001,\n ewcLambda: 1000.0, // EWC++ regularization\n patternClusters: 50,\n trajectoryCapacity: 10000,\n qualityThreshold: this.config.qualityThreshold ?? 0.5, // Ensure defined\n enableSimd: true,\n // Only spread defined values from sonaConfig\n ...(this.config.sonaConfig && Object.fromEntries(\n Object.entries(this.config.sonaConfig).filter(([, v]) => v !== undefined)\n )),\n };\n\n this.sona = SonaEngine.withConfig(sonaConfig);\n } catch (err) {\n console.warn('[RuVectorIntelligence] SONA init failed, using fallback:', err);\n this.sona = null;\n }\n }\n\n // Initialize attention mechanisms based on type\n try {\n switch (this.config.attentionType) {\n case 'multi_head':\n this.multiHeadAttention = new MultiHeadAttention(dim, this.config.numHeads ?? 8);\n break;\n\n case 'flash':\n this.flashAttention = new FlashAttention(dim);\n break;\n\n case 'hyperbolic':\n this.hyperbolicAttention = new HyperbolicAttention(dim, this.config.curvature ?? 1.0);\n break;\n\n case 'moe':\n const moeConfig: MoEConfig = {\n dim,\n numExperts: this.config.numExperts ?? 4,\n topK: this.config.topK ?? 2,\n };\n this.moeAttention = new MoEAttention(moeConfig);\n break;\n\n case 'graph':\n this.graphAttention = new GraphRoPeAttention(dim, 10000);\n break;\n\n case 'dual':\n this.dualSpaceAttention = new DualSpaceAttention(\n dim,\n this.config.curvature ?? 1.0,\n 0.5, // Euclidean weight\n 0.5 // Hyperbolic weight\n );\n break;\n }\n } catch (err) {\n console.warn('[RuVectorIntelligence] Attention init failed, using fallback:', err);\n }\n\n // Initialize training components (simplified - only optimizer needed)\n try {\n // AdamOptimizer requires: learning_rate, beta1, beta2, epsilon\n this.optimizer = new AdamOptimizer(0.001, 0.9, 0.999, 1e-8);\n } catch (err) {\n console.warn('[RuVectorIntelligence] Optimizer init failed:', err);\n }\n\n // Initialize HNSW index\n if (this.config.enableHnsw) {\n try {\n this.initializeHnsw();\n } catch (err) {\n console.warn('[RuVectorIntelligence] HNSW init failed:', err);\n }\n }\n\n // Start background learning\n if (this.config.enableSona) {\n this.startBackgroundLearning();\n }\n\n // Start cleanup timer for stale trajectories\n this.startCleanupTimer();\n\n this.initialized = true;\n }\n\n /**\n * Start cleanup timer for stale trajectories\n */\n private startCleanupTimer(): void {\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n }\n\n // Run cleanup every 5 minutes\n this.cleanupTimer = setInterval(() => {\n this.cleanupStaleTrajectories();\n }, 300000);\n }\n\n /**\n * Clean up trajectories older than TTL\n */\n private cleanupStaleTrajectories(): void {\n const now = Date.now();\n const ttl = this.config.trajectoryTTLMs;\n\n for (const [id, trajectory] of this.trajectories) {\n if (now - trajectory.startTime > ttl) {\n this.trajectories.delete(id);\n this.trajectoryAccessOrder = this.trajectoryAccessOrder.filter(t => t !== id);\n this.stats.evictedTrajectories++;\n }\n }\n }\n\n /**\n * LRU eviction for trajectories when limit exceeded\n */\n private evictOldestTrajectory(): void {\n if (this.trajectoryAccessOrder.length === 0) return;\n\n const oldestId = this.trajectoryAccessOrder.shift()!;\n this.trajectories.delete(oldestId);\n this.stats.evictedTrajectories++;\n }\n\n /**\n * LRU eviction for agent embeddings when limit exceeded\n */\n private evictOldestAgent(): void {\n if (this.agentAccessOrder.length === 0) return;\n\n const oldestId = this.agentAccessOrder.shift()!;\n this.agentEmbeddings.delete(oldestId);\n this.stats.evictedAgents++;\n }\n\n /**\n * Update LRU access order for trajectory\n */\n private touchTrajectory(id: number): void {\n const idx = this.trajectoryAccessOrder.indexOf(id);\n if (idx !== -1) {\n this.trajectoryAccessOrder.splice(idx, 1);\n }\n this.trajectoryAccessOrder.push(id);\n }\n\n /**\n * Update LRU access order for agent\n */\n private touchAgent(id: string): void {\n const idx = this.agentAccessOrder.indexOf(id);\n if (idx !== -1) {\n this.agentAccessOrder.splice(idx, 1);\n }\n this.agentAccessOrder.push(id);\n }\n\n /**\n * Initialize HNSW index for fast vector search\n */\n private initializeHnsw(): void {\n try {\n // Use ruvector core HNSW\n this.hnswIndex = new ruvector.HnswIndex({\n dim: this.config.embeddingDim,\n m: this.config.hnswM,\n efConstruction: this.config.hnswEfConstruction,\n distance: 'cosine',\n });\n } catch (error) {\n console.warn('HNSW initialization failed, falling back to brute force:', error);\n this.hnswIndex = null;\n }\n }\n\n /**\n * Register an agent with its embedding\n *\n * @param agentId - Unique agent identifier\n * @param embedding - Agent's semantic embedding\n * @param metadata - Optional metadata\n * @returns Operation result indicating success/failure\n */\n async registerAgent(\n agentId: string,\n embedding: number[] | Float32Array,\n metadata?: Record<string, any>\n ): Promise<OperationResult<void>> {\n await this.waitForInit();\n\n try {\n const embeddingArray = embedding instanceof Float32Array\n ? embedding\n : new Float32Array(embedding);\n\n // LRU eviction if at capacity\n while (this.agentEmbeddings.size >= this.config.maxAgentEmbeddings) {\n this.evictOldestAgent();\n }\n\n // Store in cache and update LRU order\n this.agentEmbeddings.set(agentId, embeddingArray);\n this.touchAgent(agentId);\n\n // Add to HNSW index\n if (this.hnswIndex) {\n try {\n await this.hnswIndex.add(agentId, embeddingArray);\n } catch (error) {\n console.warn(`Failed to add agent ${agentId} to HNSW:`, error);\n }\n }\n\n return { success: true };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Route a task to the best agent using full intelligence stack\n *\n * Uses:\n * - HNSW for fast candidate retrieval\n * - Attention mechanism for ranking\n * - SONA for adaptive learning\n *\n * @param taskEmbedding - Task's semantic embedding\n * @param candidates - Optional candidate agent IDs\n * @param topK - Number of results\n */\n async routeTask(\n taskEmbedding: number[] | Float32Array,\n candidates?: string[],\n topK: number = 5\n ): Promise<AgentRoutingResult[]> {\n const startTime = performance.now();\n const query = taskEmbedding instanceof Float32Array\n ? taskEmbedding\n : new Float32Array(taskEmbedding);\n\n let results: AgentRoutingResult[] = [];\n let usedHnsw = false;\n let usedSona = false;\n\n // Step 1: Get candidates via HNSW (150x faster than brute force)\n let candidateAgents: Array<{ id: string; embedding: Float32Array; score: number }> = [];\n\n if (this.hnswIndex && this.agentEmbeddings.size > 10) {\n try {\n const hnswResults = await this.hnswIndex.search(query, Math.min(topK * 2, 20));\n candidateAgents = hnswResults.map((r: any) => ({\n id: r.id,\n embedding: this.agentEmbeddings.get(r.id)!,\n score: r.score,\n }));\n usedHnsw = true;\n this.stats.hnswQueries++;\n } catch (error) {\n // Fallback to all agents\n }\n }\n\n // Fallback: use provided candidates or all agents\n if (candidateAgents.length === 0) {\n const agentIds = candidates || Array.from(this.agentEmbeddings.keys());\n candidateAgents = agentIds\n .filter(id => this.agentEmbeddings.has(id))\n .map(id => ({\n id,\n embedding: this.agentEmbeddings.get(id)!,\n score: 0,\n }));\n }\n\n if (candidateAgents.length === 0) {\n return [];\n }\n\n // Step 2: Apply SONA Micro-LoRA transformation (~0.1ms)\n let transformedQuery = query;\n if (this.sona) {\n try {\n const loraResult = this.sona.applyMicroLora(Array.from(query));\n transformedQuery = new Float32Array(loraResult);\n usedSona = true;\n this.stats.sonaAdaptations++;\n } catch (error) {\n // Use original query\n }\n }\n\n // Step 3: Compute attention scores\n const keys = candidateAgents.map(c => c.embedding);\n const values = candidateAgents.map(c => c.embedding);\n\n let attentionOutput: Float32Array;\n let expertWeights: number[] | undefined;\n\n switch (this.config.attentionType) {\n case 'moe':\n if (this.moeAttention) {\n attentionOutput = this.moeAttention.compute(transformedQuery, keys, values);\n // MoE provides expert routing weights\n expertWeights = Array.from(attentionOutput.slice(0, this.config.numExperts));\n } else {\n attentionOutput = this.computeFallbackAttention(transformedQuery, keys, values);\n }\n break;\n\n case 'flash':\n if (this.flashAttention) {\n attentionOutput = this.flashAttention.compute(transformedQuery, keys, values);\n } else {\n attentionOutput = this.computeFallbackAttention(transformedQuery, keys, values);\n }\n break;\n\n case 'hyperbolic':\n if (this.hyperbolicAttention) {\n attentionOutput = this.hyperbolicAttention.compute(transformedQuery, keys, values);\n } else {\n attentionOutput = this.computeFallbackAttention(transformedQuery, keys, values);\n }\n break;\n\n case 'dual':\n if (this.dualSpaceAttention) {\n attentionOutput = this.dualSpaceAttention.compute(transformedQuery, keys, values);\n } else {\n attentionOutput = this.computeFallbackAttention(transformedQuery, keys, values);\n }\n break;\n\n default:\n if (this.multiHeadAttention) {\n attentionOutput = this.multiHeadAttention.compute(transformedQuery, keys, values);\n } else {\n attentionOutput = this.computeFallbackAttention(transformedQuery, keys, values);\n }\n }\n\n // Step 4: Compute similarity scores for ranking\n const scores = candidateAgents.map((agent, i) => {\n // Combine HNSW score with attention-weighted score\n const attentionScore = this.cosineSimilarity(\n attentionOutput,\n agent.embedding\n );\n const hnswScore = agent.score || 0;\n\n // Weighted combination\n const finalScore = usedHnsw\n ? 0.3 * hnswScore + 0.7 * attentionScore\n : attentionScore;\n\n return {\n agentId: agent.id,\n confidence: finalScore,\n attentionWeights: attentionOutput,\n expertWeights,\n latencyMs: 0,\n usedHnsw,\n usedSona,\n };\n });\n\n // Sort by confidence\n results = scores\n .sort((a, b) => b.confidence - a.confidence)\n .slice(0, topK);\n\n // Update latency\n const latencyMs = performance.now() - startTime;\n results.forEach(r => (r.latencyMs = latencyMs));\n\n // Update stats\n this.stats.totalRoutings++;\n this.stats.avgRoutingLatencyMs =\n (this.stats.avgRoutingLatencyMs * (this.stats.totalRoutings - 1) + latencyMs) /\n this.stats.totalRoutings;\n\n return results;\n }\n\n /**\n * Fallback attention using dot product\n */\n private computeFallbackAttention(\n query: Float32Array,\n keys: Float32Array[],\n values: Float32Array[]\n ): Float32Array {\n const dim = query.length;\n const result = new Float32Array(dim);\n let totalWeight = 0;\n\n for (let i = 0; i < keys.length; i++) {\n const similarity = this.cosineSimilarity(query, keys[i]);\n const weight = Math.exp(similarity * 10); // Temperature scaling\n totalWeight += weight;\n\n for (let j = 0; j < dim; j++) {\n result[j] += weight * values[i][j];\n }\n }\n\n // Normalize\n if (totalWeight > 0) {\n for (let j = 0; j < dim; j++) {\n result[j] /= totalWeight;\n }\n }\n\n return result;\n }\n\n /**\n * Cosine similarity between two vectors\n */\n private cosineSimilarity(a: Float32Array, b: Float32Array): number {\n let dot = 0;\n let normA = 0;\n let normB = 0;\n\n for (let i = 0; i < a.length; i++) {\n dot += a[i] * b[i];\n normA += a[i] * a[i];\n normB += b[i] * b[i];\n }\n\n const norm = Math.sqrt(normA) * Math.sqrt(normB);\n return norm > 0 ? dot / norm : 0;\n }\n\n // ==========================================================================\n // Trajectory Learning (SONA)\n // ==========================================================================\n\n /**\n * Begin a new trajectory for learning\n *\n * @param query - The task query\n * @param embedding - Query embedding\n * @returns Operation result with trajectory ID\n */\n beginTrajectory(query: string, embedding: number[]): OperationResult<number> {\n if (!this.config.enableTrajectories) {\n return {\n success: false,\n error: 'Trajectories are disabled in config',\n };\n }\n\n if (!this.sona) {\n return {\n success: false,\n error: 'SONA engine not initialized',\n };\n }\n\n try {\n // LRU eviction if at capacity\n while (this.trajectories.size >= this.config.maxTrajectories) {\n this.evictOldestTrajectory();\n }\n\n const trajectoryId = this.nextTrajectoryId++;\n\n // Start SONA trajectory\n const sonaId = this.sona.beginTrajectory(embedding);\n\n // Store local trajectory\n this.trajectories.set(trajectoryId, {\n id: sonaId,\n query,\n embedding,\n steps: [],\n contexts: [],\n startTime: Date.now(),\n });\n\n // Update LRU order\n this.touchTrajectory(trajectoryId);\n\n this.stats.totalTrajectories++;\n return { success: true, value: trajectoryId };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Add a step to trajectory\n *\n * @param trajectoryId - Trajectory ID from beginTrajectory\n * @param action - Action taken (e.g., agent selected)\n * @param reward - Reward for this step (0-1)\n * @param activations - Optional activations\n * @param attentionWeights - Optional attention weights\n */\n addTrajectoryStep(\n trajectoryId: number,\n action: string,\n reward: number,\n activations?: number[],\n attentionWeights?: number[]\n ): void {\n const trajectory = this.trajectories.get(trajectoryId);\n if (!trajectory || !this.sona) {\n return;\n }\n\n const step: TrajectoryStep = {\n action,\n activations: activations || new Array(this.config.hiddenDim).fill(0),\n attentionWeights: attentionWeights || new Array(this.config.numHeads).fill(0),\n reward,\n timestamp: Date.now(),\n };\n\n trajectory.steps.push(step);\n\n // Add to SONA\n this.sona.addTrajectoryStep(\n trajectory.id,\n step.activations,\n step.attentionWeights,\n reward\n );\n }\n\n /**\n * Set the route (agent selected) for trajectory\n */\n setTrajectoryRoute(trajectoryId: number, route: string): void {\n const trajectory = this.trajectories.get(trajectoryId);\n if (!trajectory || !this.sona) {\n return;\n }\n\n trajectory.route = route;\n this.sona.setTrajectoryRoute(trajectory.id, route);\n }\n\n /**\n * Add context to trajectory\n */\n addTrajectoryContext(trajectoryId: number, contextId: string): void {\n const trajectory = this.trajectories.get(trajectoryId);\n if (!trajectory || !this.sona) {\n return;\n }\n\n trajectory.contexts.push(contextId);\n this.sona.addTrajectoryContext(trajectory.id, contextId);\n }\n\n /**\n * End trajectory and submit for learning\n *\n * @param trajectoryId - Trajectory ID\n * @param success - Whether the task succeeded\n * @param quality - Quality score (0-1)\n * @returns Learning outcome\n */\n endTrajectory(\n trajectoryId: number,\n success: boolean,\n quality: number\n ): LearningOutcome {\n const trajectory = this.trajectories.get(trajectoryId);\n if (!trajectory || !this.sona) {\n return {\n trajectoryId,\n success,\n quality,\n patternsLearned: 0,\n adaptations: { microLora: false, baseLora: false, ewc: false },\n };\n }\n\n // End SONA trajectory\n this.sona.endTrajectory(trajectory.id, quality);\n\n // Cleanup\n this.trajectories.delete(trajectoryId);\n\n return {\n trajectoryId,\n success,\n quality,\n patternsLearned: quality >= this.config.qualityThreshold ? 1 : 0,\n adaptations: {\n microLora: true, // Micro-LoRA always adapts\n baseLora: quality >= 0.7, // Base-LoRA for high quality\n ewc: quality >= 0.8, // EWC++ for very high quality\n },\n };\n }\n\n // ==========================================================================\n // Pattern Retrieval (ReasoningBank)\n // ==========================================================================\n\n /**\n * Find similar learned patterns\n *\n * Uses SONA's ReasoningBank for pattern retrieval\n *\n * @param embedding - Query embedding\n * @param k - Number of patterns to return\n */\n findPatterns(embedding: number[], k: number = 5): JsLearnedPattern[] {\n if (!this.sona) {\n return [];\n }\n\n return this.sona.findPatterns(embedding, k);\n }\n\n /**\n * Force a learning cycle\n */\n forceLearning(): string {\n if (!this.sona) {\n return 'SONA not enabled';\n }\n\n const result = this.sona.forceLearn();\n this.stats.totalLearningCycles++;\n return result;\n }\n\n // ==========================================================================\n // Background Learning\n // ==========================================================================\n\n /**\n * Start background learning timer\n */\n private startBackgroundLearning(): void {\n if (this.learningTimer) {\n clearInterval(this.learningTimer);\n }\n\n this.learningTimer = setInterval(() => {\n if (this.sona) {\n const result = this.sona.tick();\n if (result) {\n this.stats.totalLearningCycles++;\n this.stats.patternsLearned = this.getPatternsCount();\n }\n }\n }, this.config.backgroundIntervalMs);\n }\n\n /**\n * Get patterns count from SONA stats\n */\n private getPatternsCount(): number {\n if (!this.sona) return 0;\n\n try {\n const stats = JSON.parse(this.sona.getStats());\n return stats.patterns_count || 0;\n } catch {\n return 0;\n }\n }\n\n // ==========================================================================\n // Async Attention (for large batches)\n // ==========================================================================\n\n /**\n * Compute attention asynchronously\n *\n * Useful for large batches or when non-blocking is required\n */\n async computeAttentionAsync(\n query: Float32Array,\n keys: Float32Array[],\n values: Float32Array[],\n type?: 'flash' | 'hyperbolic' | 'standard'\n ): Promise<Float32Array> {\n switch (type) {\n case 'flash':\n return computeFlashAttentionAsync(query, keys, values);\n\n case 'hyperbolic':\n return computeHyperbolicAttentionAsync(\n query,\n keys,\n values,\n this.config.curvature\n );\n\n default:\n return computeAttentionAsync(query, keys, values, AttentionType.MultiHead);\n }\n }\n\n // ==========================================================================\n // Hyperbolic Operations (for hierarchical structures)\n // ==========================================================================\n\n /**\n * Compute Poincaré distance between two embeddings\n *\n * Useful for hierarchical agent structures\n */\n poincareDistance(a: Float32Array, b: Float32Array): number {\n return poincareDistance(a, b, this.config.curvature);\n }\n\n /**\n * Project embedding to Poincaré ball\n */\n projectToPoincare(embedding: Float32Array): Float32Array {\n return projectToPoincareBall(embedding, this.config.curvature);\n }\n\n // ==========================================================================\n // Statistics & Status\n // ==========================================================================\n\n /**\n * Get intelligence layer statistics\n */\n getStats(): typeof this.stats & { sonaStats?: any } {\n let sonaStats: any = null;\n\n if (this.sona) {\n try {\n sonaStats = JSON.parse(this.sona.getStats());\n } catch {}\n }\n\n return {\n ...this.stats,\n sonaStats,\n };\n }\n\n /**\n * Enable/disable the intelligence layer\n */\n setEnabled(enabled: boolean): void {\n if (this.sona) {\n this.sona.setEnabled(enabled);\n }\n }\n\n /**\n * Check if enabled\n */\n isEnabled(): boolean {\n return this.sona?.isEnabled() ?? false;\n }\n\n /**\n * Cleanup resources\n */\n dispose(): void {\n if (this.learningTimer) {\n clearInterval(this.learningTimer);\n this.learningTimer = null;\n }\n\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n this.cleanupTimer = null;\n }\n\n // Flush SONA\n if (this.sona) {\n this.sona.flush();\n }\n\n // Clear caches and LRU tracking\n this.trajectories.clear();\n this.trajectoryAccessOrder = [];\n this.agentEmbeddings.clear();\n this.agentAccessOrder = [];\n }\n}\n\n/**\n * Create a default intelligence layer\n */\nexport function createIntelligenceLayer(\n config?: RuVectorIntelligenceConfig\n): RuVectorIntelligence {\n return new RuVectorIntelligence(config);\n}\n\n/**\n * Presets for common configurations\n */\nexport const IntelligencePresets = {\n /** Fast routing with MoE and minimal learning */\n fast: {\n attentionType: 'moe' as const,\n numExperts: 4,\n topK: 2,\n enableTrajectories: false,\n backgroundIntervalMs: 300000, // 5 min\n },\n\n /** Balanced performance and learning */\n balanced: {\n attentionType: 'moe' as const,\n numExperts: 4,\n topK: 2,\n enableTrajectories: true,\n backgroundIntervalMs: 60000, // 1 min\n qualityThreshold: 0.5,\n },\n\n /** Maximum learning for development */\n learning: {\n attentionType: 'dual' as const,\n enableTrajectories: true,\n backgroundIntervalMs: 30000, // 30 sec\n qualityThreshold: 0.3,\n sonaConfig: {\n microLoraRank: 2,\n baseLoraRank: 16,\n trajectoryCapacity: 50000,\n },\n },\n\n /** Hierarchical structures (Poincaré geometry) */\n hierarchical: {\n attentionType: 'hyperbolic' as const,\n curvature: 1.0,\n enableTrajectories: true,\n },\n\n /** Graph-based reasoning */\n graph: {\n attentionType: 'graph' as const,\n enableTrajectories: true,\n },\n};\n"]}
|
|
1
|
+
{"version":3,"file":"RuVectorIntelligence.js","sourceRoot":"","sources":["../../src/intelligence/RuVectorIntelligence.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,oFAAoF;AACpF,IAAI,UAAU,GAAQ,IAAI,CAAC;AAC3B,IAAI,aAAa,GAAG,KAAK,CAAC;AAE1B,IAAI,kBAAkB,GAAQ,IAAI,CAAC;AACnC,IAAI,cAAc,GAAQ,IAAI,CAAC;AAC/B,IAAI,mBAAmB,GAAQ,IAAI,CAAC;AACpC,IAAI,YAAY,GAAQ,IAAI,CAAC;AAC7B,IAAI,kBAAkB,GAAQ,IAAI,CAAC;AACnC,IAAI,kBAAkB,GAAQ,IAAI,CAAC;AACnC,IAAI,aAAa,GAAQ,IAAI,CAAC;AAC9B,IAAI,qBAAqB,GAAQ,IAAI,CAAC;AACtC,IAAI,0BAA0B,GAAQ,IAAI,CAAC;AAC3C,IAAI,+BAA+B,GAAQ,IAAI,CAAC;AAChD,IAAI,gBAAgB,GAAQ,IAAI,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EAAE,KAAc;QAC7B,UAAU,EAAE,CAAC;QACb,IAAI,EAAE,CAAC;QACP,kBAAkB,EAAE,KAAK;QACzB,oBAAoB,EAAE,MAAM,EAAE,QAAQ;KACvC;IAED,wCAAwC;IACxC,QAAQ,EAAE;QACR,aAAa,EAAE,KAAc;QAC7B,UAAU,EAAE,CAAC;QACb,IAAI,EAAE,CAAC;QACP,kBAAkB,EAAE,IAAI;QACxB,oBAAoB,EAAE,KAAK,EAAE,QAAQ;QACrC,gBAAgB,EAAE,GAAG;KACtB;IAED,uCAAuC;IACvC,QAAQ,EAAE;QACR,aAAa,EAAE,MAAe;QAC9B,kBAAkB,EAAE,IAAI;QACxB,oBAAoB,EAAE,KAAK,EAAE,SAAS;QACtC,gBAAgB,EAAE,GAAG;QACrB,UAAU,EAAE;YACV,aAAa,EAAE,CAAC;YAChB,YAAY,EAAE,EAAE;YAChB,kBAAkB,EAAE,KAAK;SAC1B;KACF;IAED,kDAAkD;IAClD,YAAY,EAAE;QACZ,aAAa,EAAE,YAAqB;QACpC,SAAS,EAAE,GAAG;QACd,kBAAkB,EAAE,IAAI;KACzB;IAED,4BAA4B;IAC5B,KAAK,EAAE;QACL,aAAa,EAAE,OAAgB;QAC/B,kBAAkB,EAAE,IAAI;KACzB;CACF,CAAC","sourcesContent":["/**\n * RuVector Unified Intelligence Layer\n *\n * Integrates the FULL power of RuVector ecosystem:\n *\n * @ruvector/sona - Self-Learning:\n * - Micro-LoRA: Ultra-fast rank-1/2 adaptations (~0.1ms)\n * - Base-LoRA: Deeper pattern adaptations\n * - EWC++: Elastic Weight Consolidation (catastrophic forgetting prevention)\n * - ReasoningBank: Pattern storage/retrieval via findPatterns\n * - Trajectory tracking: Learn from execution paths\n *\n * @ruvector/attention - Advanced Attention:\n * - MultiHeadAttention: Standard transformer attention\n * - FlashAttention: Memory-efficient O(n) attention\n * - HyperbolicAttention: Poincaré ball geometry for hierarchies\n * - MoEAttention: Mixture of Experts routing\n * - GraphRoPeAttention: Graph + Rotary Position Embeddings\n * - EdgeFeaturedAttention: Edge-aware graph attention\n * - DualSpaceAttention: Euclidean + Hyperbolic hybrid\n *\n * @ruvector/core - Vector Database:\n * - HNSW indexing: 150x faster than brute force\n * - Real vector similarity search\n * - Cosine/Euclidean/Dot product distance\n *\n * Performance:\n * - Micro-LoRA adaptation: ~0.1ms\n * - FlashAttention: O(n) complexity vs O(n²)\n * - HNSW search: O(log n) vs O(n)\n * - Background learning: Non-blocking\n */\n\n// Optional imports - graceful fallback on Windows/platforms without native binaries\nlet SonaEngine: any = null;\nlet sonaAvailable = false;\n\nlet MultiHeadAttention: any = null;\nlet FlashAttention: any = null;\nlet HyperbolicAttention: any = null;\nlet MoEAttention: any = null;\nlet GraphRoPeAttention: any = null;\nlet DualSpaceAttention: any = null;\nlet AdamOptimizer: any = null;\nlet computeAttentionAsync: any = null;\nlet computeFlashAttentionAsync: any = null;\nlet computeHyperbolicAttentionAsync: any = null;\nlet poincareDistance: any = null;\nlet projectToPoincareBall: any = null;\nlet AttentionType: any = null;\nlet attentionAvailable = false;\n\n/**\n * Tile size for native flash attention. @ruvector/attention 2.x requires it\n * explicitly in both the FlashAttention constructor and\n * computeFlashAttentionAsync (omitting it throws, which used to push every\n * 'flash' route onto the JS fallback).\n */\nconst FLASH_ATTENTION_BLOCK_SIZE = 64;\n\n/** Max graph position for GraphRoPeAttention's rotary table. */\nconst GRAPH_ROPE_MAX_POSITION = 10000;\n\n// Try to load @ruvector/sona (through the loader, whose engines validate\n// LoRA input lengths instead of letting a native panic abort the process)\ntry {\n SonaEngine = requireSonaEngine();\n sonaAvailable = true;\n} catch {\n console.warn('[RuVectorIntelligence] @ruvector/sona not available - self-learning disabled');\n}\n\n// Try to load @ruvector/attention\ntry {\n // @ruvector/attention is CommonJS; from 0.1.32 its typings expose it as\n // `default` under ESM interop, while older builds surface named exports.\n const attentionMod: any = await import('@ruvector/attention');\n const attentionModule = attentionMod.default ?? attentionMod;\n MultiHeadAttention = attentionModule.MultiHeadAttention;\n FlashAttention = attentionModule.FlashAttention;\n HyperbolicAttention = attentionModule.HyperbolicAttention;\n MoEAttention = attentionModule.MoEAttention;\n GraphRoPeAttention = attentionModule.GraphRoPeAttention;\n DualSpaceAttention = attentionModule.DualSpaceAttention;\n AdamOptimizer = attentionModule.AdamOptimizer;\n computeAttentionAsync = attentionModule.computeAttentionAsync;\n computeFlashAttentionAsync = attentionModule.computeFlashAttentionAsync;\n computeHyperbolicAttentionAsync = attentionModule.computeHyperbolicAttentionAsync;\n poincareDistance = attentionModule.poincareDistance;\n projectToPoincareBall = attentionModule.projectToPoincareBall;\n AttentionType = attentionModule.AttentionType;\n attentionAvailable = true;\n} catch {\n console.warn('[RuVectorIntelligence] @ruvector/attention not available - attention features disabled');\n}\n\n// Import from ruvector core (for HNSW)\nimport { requireSonaEngine } from '../services/sona-loader.js';\nimport ruvector from 'ruvector';\n\n// Export availability flags\nexport { sonaAvailable, attentionAvailable };\n\n// Local type definitions (replaces imports from optional packages)\nexport interface JsSonaConfig {\n embeddingDim?: number;\n hiddenDim?: number;\n microLoraRank?: number;\n baseLoraRank?: number;\n ewcLambda?: number;\n microLoraLr?: number;\n baseLoraLr?: number;\n patternClusters?: number;\n [key: string]: any; // Allow additional properties\n}\n\nexport interface JsLearnedPattern {\n id: string;\n pattern: number[];\n confidence: number;\n timestamp: number;\n}\n\nexport interface MoEConfig {\n numExperts?: number;\n topK?: number;\n routerDim?: number;\n dim?: number;\n}\n\n/**\n * Intelligence Layer Configuration\n */\nexport interface RuVectorIntelligenceConfig {\n /** Embedding dimension (default: 384 for all-MiniLM-L6-v2) */\n embeddingDim?: number;\n\n /** Hidden dimension for SONA (default: 256) */\n hiddenDim?: number;\n\n /** Enable SONA self-learning (default: true) */\n enableSona?: boolean;\n\n /** SONA configuration */\n sonaConfig?: Partial<JsSonaConfig>;\n\n /** Attention type for agent routing (default: 'moe') */\n attentionType?: 'multi_head' | 'flash' | 'hyperbolic' | 'moe' | 'graph' | 'dual';\n\n /** Number of attention heads (default: 8) */\n numHeads?: number;\n\n /** Number of MoE experts (default: 4) */\n numExperts?: number;\n\n /** Top-K experts to use (default: 2) */\n topK?: number;\n\n /** Hyperbolic curvature for hierarchical structures (default: 1.0) */\n curvature?: number;\n\n /** Enable HNSW vector index (default: true) */\n enableHnsw?: boolean;\n\n /** HNSW M parameter - connections per node (default: 16) */\n hnswM?: number;\n\n /** HNSW ef_construction (default: 200) */\n hnswEfConstruction?: number;\n\n /** Enable trajectory tracking (default: true) */\n enableTrajectories?: boolean;\n\n /** Quality threshold for learning (default: 0.5) */\n qualityThreshold?: number;\n\n /** Background learning interval in ms (default: 60000 = 1 min) */\n backgroundIntervalMs?: number;\n\n /** Maximum trajectories to keep in memory (default: 1000, LRU eviction) */\n maxTrajectories?: number;\n\n /** Trajectory TTL in ms (default: 1800000 = 30 min) */\n trajectoryTTLMs?: number;\n\n /** Maximum agent embeddings to cache (default: 500, LRU eviction) */\n maxAgentEmbeddings?: number;\n}\n\n/**\n * Trajectory for learning\n */\nexport interface Trajectory {\n id: number;\n query: string;\n embedding: number[];\n steps: TrajectoryStep[];\n route?: string;\n contexts: string[];\n startTime: number;\n}\n\nexport interface TrajectoryStep {\n action: string;\n activations: number[];\n attentionWeights: number[];\n reward: number;\n timestamp: number;\n}\n\n/**\n * Agent routing result\n */\nexport interface AgentRoutingResult {\n agentId: string;\n confidence: number;\n attentionWeights: Float32Array;\n expertWeights?: number[];\n latencyMs: number;\n usedHnsw: boolean;\n usedSona: boolean;\n}\n\n/**\n * Learning outcome\n */\nexport interface LearningOutcome {\n trajectoryId: number;\n success: boolean;\n quality: number;\n patternsLearned: number;\n adaptations: {\n microLora: boolean;\n baseLora: boolean;\n ewc: boolean;\n };\n}\n\n/**\n * RuVector Unified Intelligence Layer\n *\n * Combines SONA self-learning, advanced attention mechanisms,\n * and HNSW vector search for intelligent agent orchestration.\n */\n/**\n * Result wrapper for operations that can fail\n */\nexport interface OperationResult<T> {\n success: boolean;\n value?: T;\n error?: string;\n}\n\nexport class RuVectorIntelligence {\n private config: Required<RuVectorIntelligenceConfig>;\n private initialized = false;\n private initPromise: Promise<void> | null = null;\n\n // SONA Engine for self-learning\n private sona: any = null;\n\n // Attention mechanisms\n private multiHeadAttention: any = null;\n private flashAttention: any = null;\n private hyperbolicAttention: any = null;\n private moeAttention: any = null;\n private graphAttention: any = null;\n private dualSpaceAttention: any = null;\n\n // Training (simplified - removed unused scheduler/loss)\n private optimizer: any = null;\n\n // HNSW index for vector search\n private hnswIndex: any = null;\n\n // Active trajectories with LRU tracking\n private trajectories: Map<number, Trajectory> = new Map();\n private trajectoryAccessOrder: number[] = []; // For LRU eviction\n private nextTrajectoryId = 0;\n\n // Agent embeddings with LRU tracking\n private agentEmbeddings: Map<string, Float32Array> = new Map();\n private agentAccessOrder: string[] = []; // For LRU eviction\n\n // Background learning timer\n private learningTimer: NodeJS.Timeout | null = null;\n\n // Cleanup timer for stale trajectories\n private cleanupTimer: NodeJS.Timeout | null = null;\n\n // Statistics\n private stats = {\n totalRoutings: 0,\n totalTrajectories: 0,\n totalLearningCycles: 0,\n avgRoutingLatencyMs: 0,\n patternsLearned: 0,\n hnswQueries: 0,\n sonaAdaptations: 0,\n evictedTrajectories: 0,\n evictedAgents: 0,\n };\n\n constructor(config?: RuVectorIntelligenceConfig) {\n this.config = {\n embeddingDim: config?.embeddingDim ?? 384,\n hiddenDim: config?.hiddenDim ?? 256,\n enableSona: config?.enableSona ?? true,\n sonaConfig: config?.sonaConfig ?? {},\n attentionType: config?.attentionType ?? 'moe',\n numHeads: config?.numHeads ?? 8,\n numExperts: config?.numExperts ?? 4,\n topK: config?.topK ?? 2,\n curvature: config?.curvature ?? 1.0,\n enableHnsw: config?.enableHnsw ?? true,\n hnswM: config?.hnswM ?? 16,\n hnswEfConstruction: config?.hnswEfConstruction ?? 200,\n enableTrajectories: config?.enableTrajectories ?? true,\n qualityThreshold: config?.qualityThreshold ?? 0.5,\n backgroundIntervalMs: config?.backgroundIntervalMs ?? 60000,\n // Memory limits with LRU eviction\n maxTrajectories: config?.maxTrajectories ?? 1000,\n trajectoryTTLMs: config?.trajectoryTTLMs ?? 1800000, // 30 min\n maxAgentEmbeddings: config?.maxAgentEmbeddings ?? 500,\n };\n\n // Initialize asynchronously to avoid race conditions\n this.initPromise = this.initializeAsync();\n }\n\n /**\n * Wait for initialization to complete\n */\n async waitForInit(): Promise<void> {\n if (this.initPromise) {\n await this.initPromise;\n }\n }\n\n /**\n * Initialize all components (async to avoid race conditions)\n */\n private async initializeAsync(): Promise<void> {\n if (this.initialized) return;\n\n const dim = this.config.embeddingDim;\n\n // Initialize SONA Engine\n if (this.config.enableSona) {\n try {\n // Ensure all values are explicitly defined (no undefined values)\n const sonaConfig: JsSonaConfig = {\n hiddenDim: this.config.hiddenDim ?? 256,\n embeddingDim: dim ?? 384,\n microLoraRank: 1, // Ultra-fast rank-1\n baseLoraRank: 8,\n microLoraLr: 0.001,\n baseLoraLr: 0.0001,\n ewcLambda: 1000.0, // EWC++ regularization\n patternClusters: 50,\n trajectoryCapacity: 10000,\n qualityThreshold: this.config.qualityThreshold ?? 0.5, // Ensure defined\n enableSimd: true,\n // Only spread defined values from sonaConfig\n ...(this.config.sonaConfig && Object.fromEntries(\n Object.entries(this.config.sonaConfig).filter(([, v]) => v !== undefined)\n )),\n };\n\n this.sona = SonaEngine.withConfig(sonaConfig);\n } catch (err) {\n console.warn('[RuVectorIntelligence] SONA init failed, using fallback:', err);\n this.sona = null;\n }\n }\n\n // Initialize attention mechanisms based on type\n try {\n switch (this.config.attentionType) {\n case 'multi_head':\n this.multiHeadAttention = new MultiHeadAttention(dim, this.config.numHeads ?? 8);\n break;\n\n case 'flash':\n this.flashAttention = new FlashAttention(dim, FLASH_ATTENTION_BLOCK_SIZE);\n break;\n\n case 'hyperbolic':\n this.hyperbolicAttention = new HyperbolicAttention(dim, this.config.curvature ?? 1.0);\n break;\n\n case 'moe':\n const moeConfig: MoEConfig = {\n dim,\n numExperts: this.config.numExperts ?? 4,\n topK: this.config.topK ?? 2,\n };\n this.moeAttention = new MoEAttention(moeConfig);\n break;\n\n case 'graph':\n // 2.x takes a RoPEConfig object; positional args throw \"Missing field `dim`\"\n this.graphAttention = new GraphRoPeAttention({ dim, maxPosition: GRAPH_ROPE_MAX_POSITION });\n break;\n\n case 'dual':\n // 2.x takes a DualSpaceConfig object; positional args throw \"Missing field `dim`\"\n this.dualSpaceAttention = new DualSpaceAttention({\n dim,\n curvature: this.config.curvature ?? 1.0,\n euclideanWeight: 0.5,\n hyperbolicWeight: 0.5,\n });\n break;\n }\n } catch (err) {\n console.warn('[RuVectorIntelligence] Attention init failed, using fallback:', err);\n }\n\n // Initialize training components (simplified - only optimizer needed)\n try {\n // AdamOptimizer requires: learning_rate, beta1, beta2, epsilon\n this.optimizer = new AdamOptimizer(0.001, 0.9, 0.999, 1e-8);\n } catch (err) {\n console.warn('[RuVectorIntelligence] Optimizer init failed:', err);\n }\n\n // Initialize HNSW index\n if (this.config.enableHnsw) {\n try {\n this.initializeHnsw();\n } catch (err) {\n console.warn('[RuVectorIntelligence] HNSW init failed:', err);\n }\n }\n\n // Start background learning\n if (this.config.enableSona) {\n this.startBackgroundLearning();\n }\n\n // Start cleanup timer for stale trajectories\n this.startCleanupTimer();\n\n this.initialized = true;\n }\n\n /**\n * Start cleanup timer for stale trajectories\n */\n private startCleanupTimer(): void {\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n }\n\n // Run cleanup every 5 minutes\n this.cleanupTimer = setInterval(() => {\n this.cleanupStaleTrajectories();\n }, 300000);\n }\n\n /**\n * Clean up trajectories older than TTL\n */\n private cleanupStaleTrajectories(): void {\n const now = Date.now();\n const ttl = this.config.trajectoryTTLMs;\n\n for (const [id, trajectory] of this.trajectories) {\n if (now - trajectory.startTime > ttl) {\n this.trajectories.delete(id);\n this.trajectoryAccessOrder = this.trajectoryAccessOrder.filter(t => t !== id);\n this.stats.evictedTrajectories++;\n }\n }\n }\n\n /**\n * LRU eviction for trajectories when limit exceeded\n */\n private evictOldestTrajectory(): void {\n if (this.trajectoryAccessOrder.length === 0) return;\n\n const oldestId = this.trajectoryAccessOrder.shift()!;\n this.trajectories.delete(oldestId);\n this.stats.evictedTrajectories++;\n }\n\n /**\n * LRU eviction for agent embeddings when limit exceeded\n */\n private evictOldestAgent(): void {\n if (this.agentAccessOrder.length === 0) return;\n\n const oldestId = this.agentAccessOrder.shift()!;\n this.agentEmbeddings.delete(oldestId);\n this.stats.evictedAgents++;\n }\n\n /**\n * Update LRU access order for trajectory\n */\n private touchTrajectory(id: number): void {\n const idx = this.trajectoryAccessOrder.indexOf(id);\n if (idx !== -1) {\n this.trajectoryAccessOrder.splice(idx, 1);\n }\n this.trajectoryAccessOrder.push(id);\n }\n\n /**\n * Update LRU access order for agent\n */\n private touchAgent(id: string): void {\n const idx = this.agentAccessOrder.indexOf(id);\n if (idx !== -1) {\n this.agentAccessOrder.splice(idx, 1);\n }\n this.agentAccessOrder.push(id);\n }\n\n /**\n * Initialize HNSW index for fast vector search\n */\n private initializeHnsw(): void {\n try {\n // Use ruvector core HNSW\n this.hnswIndex = new ruvector.HnswIndex({\n dim: this.config.embeddingDim,\n m: this.config.hnswM,\n efConstruction: this.config.hnswEfConstruction,\n distance: 'cosine',\n });\n } catch (error) {\n console.warn('HNSW initialization failed, falling back to brute force:', error);\n this.hnswIndex = null;\n }\n }\n\n /**\n * Register an agent with its embedding\n *\n * @param agentId - Unique agent identifier\n * @param embedding - Agent's semantic embedding\n * @param metadata - Optional metadata\n * @returns Operation result indicating success/failure\n */\n async registerAgent(\n agentId: string,\n embedding: number[] | Float32Array,\n metadata?: Record<string, any>\n ): Promise<OperationResult<void>> {\n await this.waitForInit();\n\n try {\n const embeddingArray = embedding instanceof Float32Array\n ? embedding\n : new Float32Array(embedding);\n\n // LRU eviction if at capacity\n while (this.agentEmbeddings.size >= this.config.maxAgentEmbeddings) {\n this.evictOldestAgent();\n }\n\n // Store in cache and update LRU order\n this.agentEmbeddings.set(agentId, embeddingArray);\n this.touchAgent(agentId);\n\n // Add to HNSW index\n if (this.hnswIndex) {\n try {\n await this.hnswIndex.add(agentId, embeddingArray);\n } catch (error) {\n console.warn(`Failed to add agent ${agentId} to HNSW:`, error);\n }\n }\n\n return { success: true };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Route a task to the best agent using full intelligence stack\n *\n * Uses:\n * - HNSW for fast candidate retrieval\n * - Attention mechanism for ranking\n * - SONA for adaptive learning\n *\n * @param taskEmbedding - Task's semantic embedding\n * @param candidates - Optional candidate agent IDs\n * @param topK - Number of results\n */\n async routeTask(\n taskEmbedding: number[] | Float32Array,\n candidates?: string[],\n topK: number = 5\n ): Promise<AgentRoutingResult[]> {\n const startTime = performance.now();\n const query = taskEmbedding instanceof Float32Array\n ? taskEmbedding\n : new Float32Array(taskEmbedding);\n\n let results: AgentRoutingResult[] = [];\n let usedHnsw = false;\n let usedSona = false;\n\n // Step 1: Get candidates via HNSW (150x faster than brute force)\n let candidateAgents: Array<{ id: string; embedding: Float32Array; score: number }> = [];\n\n if (this.hnswIndex && this.agentEmbeddings.size > 10) {\n try {\n const hnswResults = await this.hnswIndex.search(query, Math.min(topK * 2, 20));\n candidateAgents = hnswResults.map((r: any) => ({\n id: r.id,\n embedding: this.agentEmbeddings.get(r.id)!,\n score: r.score,\n }));\n usedHnsw = true;\n this.stats.hnswQueries++;\n } catch (error) {\n // Fallback to all agents\n }\n }\n\n // Fallback: use provided candidates or all agents\n if (candidateAgents.length === 0) {\n const agentIds = candidates || Array.from(this.agentEmbeddings.keys());\n candidateAgents = agentIds\n .filter(id => this.agentEmbeddings.has(id))\n .map(id => ({\n id,\n embedding: this.agentEmbeddings.get(id)!,\n score: 0,\n }));\n }\n\n if (candidateAgents.length === 0) {\n return [];\n }\n\n // Step 2: Apply SONA Micro-LoRA transformation (~0.1ms)\n let transformedQuery = query;\n if (this.sona) {\n try {\n const loraResult = this.sona.applyMicroLora(Array.from(query));\n transformedQuery = new Float32Array(loraResult);\n usedSona = true;\n this.stats.sonaAdaptations++;\n } catch (error) {\n // Use original query\n }\n }\n\n // Step 3: Compute attention scores\n const keys = candidateAgents.map(c => c.embedding);\n const values = candidateAgents.map(c => c.embedding);\n\n let attentionOutput: Float32Array;\n let expertWeights: number[] | undefined;\n\n switch (this.config.attentionType) {\n case 'moe':\n if (this.moeAttention) {\n attentionOutput = this.moeAttention.compute(transformedQuery, keys, values);\n // MoE provides expert routing weights\n expertWeights = Array.from(attentionOutput.slice(0, this.config.numExperts));\n } else {\n attentionOutput = this.computeFallbackAttention(transformedQuery, keys, values);\n }\n break;\n\n case 'flash':\n if (this.flashAttention) {\n attentionOutput = this.flashAttention.compute(transformedQuery, keys, values);\n } else {\n attentionOutput = this.computeFallbackAttention(transformedQuery, keys, values);\n }\n break;\n\n case 'hyperbolic':\n if (this.hyperbolicAttention) {\n attentionOutput = this.hyperbolicAttention.compute(transformedQuery, keys, values);\n } else {\n attentionOutput = this.computeFallbackAttention(transformedQuery, keys, values);\n }\n break;\n\n case 'graph':\n if (this.graphAttention) {\n attentionOutput = this.graphAttention.compute(transformedQuery, keys, values);\n } else {\n attentionOutput = this.computeFallbackAttention(transformedQuery, keys, values);\n }\n break;\n\n case 'dual':\n if (this.dualSpaceAttention) {\n attentionOutput = this.dualSpaceAttention.compute(transformedQuery, keys, values);\n } else {\n attentionOutput = this.computeFallbackAttention(transformedQuery, keys, values);\n }\n break;\n\n default:\n if (this.multiHeadAttention) {\n attentionOutput = this.multiHeadAttention.compute(transformedQuery, keys, values);\n } else {\n attentionOutput = this.computeFallbackAttention(transformedQuery, keys, values);\n }\n }\n\n // Step 4: Compute similarity scores for ranking\n const scores = candidateAgents.map((agent, i) => {\n // Combine HNSW score with attention-weighted score\n const attentionScore = this.cosineSimilarity(\n attentionOutput,\n agent.embedding\n );\n const hnswScore = agent.score || 0;\n\n // Weighted combination\n const finalScore = usedHnsw\n ? 0.3 * hnswScore + 0.7 * attentionScore\n : attentionScore;\n\n return {\n agentId: agent.id,\n confidence: finalScore,\n attentionWeights: attentionOutput,\n expertWeights,\n latencyMs: 0,\n usedHnsw,\n usedSona,\n };\n });\n\n // Sort by confidence\n results = scores\n .sort((a, b) => b.confidence - a.confidence)\n .slice(0, topK);\n\n // Update latency\n const latencyMs = performance.now() - startTime;\n results.forEach(r => (r.latencyMs = latencyMs));\n\n // Update stats\n this.stats.totalRoutings++;\n this.stats.avgRoutingLatencyMs =\n (this.stats.avgRoutingLatencyMs * (this.stats.totalRoutings - 1) + latencyMs) /\n this.stats.totalRoutings;\n\n return results;\n }\n\n /**\n * Fallback attention using dot product\n */\n private computeFallbackAttention(\n query: Float32Array,\n keys: Float32Array[],\n values: Float32Array[]\n ): Float32Array {\n const dim = query.length;\n const result = new Float32Array(dim);\n let totalWeight = 0;\n\n for (let i = 0; i < keys.length; i++) {\n const similarity = this.cosineSimilarity(query, keys[i]);\n const weight = Math.exp(similarity * 10); // Temperature scaling\n totalWeight += weight;\n\n for (let j = 0; j < dim; j++) {\n result[j] += weight * values[i][j];\n }\n }\n\n // Normalize\n if (totalWeight > 0) {\n for (let j = 0; j < dim; j++) {\n result[j] /= totalWeight;\n }\n }\n\n return result;\n }\n\n /**\n * Cosine similarity between two vectors\n */\n private cosineSimilarity(a: Float32Array, b: Float32Array): number {\n let dot = 0;\n let normA = 0;\n let normB = 0;\n\n for (let i = 0; i < a.length; i++) {\n dot += a[i] * b[i];\n normA += a[i] * a[i];\n normB += b[i] * b[i];\n }\n\n const norm = Math.sqrt(normA) * Math.sqrt(normB);\n return norm > 0 ? dot / norm : 0;\n }\n\n // ==========================================================================\n // Trajectory Learning (SONA)\n // ==========================================================================\n\n /**\n * Begin a new trajectory for learning\n *\n * @param query - The task query\n * @param embedding - Query embedding\n * @returns Operation result with trajectory ID\n */\n beginTrajectory(query: string, embedding: number[]): OperationResult<number> {\n if (!this.config.enableTrajectories) {\n return {\n success: false,\n error: 'Trajectories are disabled in config',\n };\n }\n\n if (!this.sona) {\n return {\n success: false,\n error: 'SONA engine not initialized',\n };\n }\n\n try {\n // LRU eviction if at capacity\n while (this.trajectories.size >= this.config.maxTrajectories) {\n this.evictOldestTrajectory();\n }\n\n const trajectoryId = this.nextTrajectoryId++;\n\n // Start SONA trajectory\n const sonaId = this.sona.beginTrajectory(embedding);\n\n // Store local trajectory\n this.trajectories.set(trajectoryId, {\n id: sonaId,\n query,\n embedding,\n steps: [],\n contexts: [],\n startTime: Date.now(),\n });\n\n // Update LRU order\n this.touchTrajectory(trajectoryId);\n\n this.stats.totalTrajectories++;\n return { success: true, value: trajectoryId };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Add a step to trajectory\n *\n * @param trajectoryId - Trajectory ID from beginTrajectory\n * @param action - Action taken (e.g., agent selected)\n * @param reward - Reward for this step (0-1)\n * @param activations - Optional activations\n * @param attentionWeights - Optional attention weights\n */\n addTrajectoryStep(\n trajectoryId: number,\n action: string,\n reward: number,\n activations?: number[],\n attentionWeights?: number[]\n ): void {\n const trajectory = this.trajectories.get(trajectoryId);\n if (!trajectory || !this.sona) {\n return;\n }\n\n const step: TrajectoryStep = {\n action,\n activations: activations || new Array(this.config.hiddenDim).fill(0),\n attentionWeights: attentionWeights || new Array(this.config.numHeads).fill(0),\n reward,\n timestamp: Date.now(),\n };\n\n trajectory.steps.push(step);\n\n // Add to SONA\n this.sona.addTrajectoryStep(\n trajectory.id,\n step.activations,\n step.attentionWeights,\n reward\n );\n }\n\n /**\n * Set the route (agent selected) for trajectory\n */\n setTrajectoryRoute(trajectoryId: number, route: string): void {\n const trajectory = this.trajectories.get(trajectoryId);\n if (!trajectory || !this.sona) {\n return;\n }\n\n trajectory.route = route;\n this.sona.setTrajectoryRoute(trajectory.id, route);\n }\n\n /**\n * Add context to trajectory\n */\n addTrajectoryContext(trajectoryId: number, contextId: string): void {\n const trajectory = this.trajectories.get(trajectoryId);\n if (!trajectory || !this.sona) {\n return;\n }\n\n trajectory.contexts.push(contextId);\n this.sona.addTrajectoryContext(trajectory.id, contextId);\n }\n\n /**\n * End trajectory and submit for learning\n *\n * @param trajectoryId - Trajectory ID\n * @param success - Whether the task succeeded\n * @param quality - Quality score (0-1)\n * @returns Learning outcome\n */\n endTrajectory(\n trajectoryId: number,\n success: boolean,\n quality: number\n ): LearningOutcome {\n const trajectory = this.trajectories.get(trajectoryId);\n if (!trajectory || !this.sona) {\n return {\n trajectoryId,\n success,\n quality,\n patternsLearned: 0,\n adaptations: { microLora: false, baseLora: false, ewc: false },\n };\n }\n\n // End SONA trajectory\n this.sona.endTrajectory(trajectory.id, quality);\n\n // Cleanup\n this.trajectories.delete(trajectoryId);\n\n return {\n trajectoryId,\n success,\n quality,\n patternsLearned: quality >= this.config.qualityThreshold ? 1 : 0,\n adaptations: {\n microLora: true, // Micro-LoRA always adapts\n baseLora: quality >= 0.7, // Base-LoRA for high quality\n ewc: quality >= 0.8, // EWC++ for very high quality\n },\n };\n }\n\n // ==========================================================================\n // Pattern Retrieval (ReasoningBank)\n // ==========================================================================\n\n /**\n * Find similar learned patterns\n *\n * Uses SONA's ReasoningBank for pattern retrieval\n *\n * @param embedding - Query embedding\n * @param k - Number of patterns to return\n */\n findPatterns(embedding: number[], k: number = 5): JsLearnedPattern[] {\n if (!this.sona) {\n return [];\n }\n\n return this.sona.findPatterns(embedding, k);\n }\n\n /**\n * Force a learning cycle\n */\n forceLearning(): string {\n if (!this.sona) {\n return 'SONA not enabled';\n }\n\n const result = this.sona.forceLearn();\n this.stats.totalLearningCycles++;\n return result;\n }\n\n // ==========================================================================\n // Background Learning\n // ==========================================================================\n\n /**\n * Start background learning timer\n */\n private startBackgroundLearning(): void {\n if (this.learningTimer) {\n clearInterval(this.learningTimer);\n }\n\n this.learningTimer = setInterval(() => {\n if (this.sona) {\n const result = this.sona.tick();\n if (result) {\n this.stats.totalLearningCycles++;\n this.stats.patternsLearned = this.getPatternsCount();\n }\n }\n }, this.config.backgroundIntervalMs);\n }\n\n /**\n * Get patterns count from SONA stats\n */\n private getPatternsCount(): number {\n if (!this.sona) return 0;\n\n try {\n const stats = JSON.parse(this.sona.getStats());\n return stats.patterns_count || 0;\n } catch {\n return 0;\n }\n }\n\n // ==========================================================================\n // Async Attention (for large batches)\n // ==========================================================================\n\n /**\n * Compute attention asynchronously on a native worker thread\n *\n * Useful for large batches or when non-blocking is required. 'standard' (the\n * default) is native scaled dot-product attention. The native functions take\n * the embedding dimension (and flash block size) explicitly.\n */\n async computeAttentionAsync(\n query: Float32Array,\n keys: Float32Array[],\n values: Float32Array[],\n type?: 'flash' | 'hyperbolic' | 'standard'\n ): Promise<Float32Array> {\n const dim = query.length;\n switch (type) {\n case 'flash':\n return computeFlashAttentionAsync(query, keys, values, dim, FLASH_ATTENTION_BLOCK_SIZE);\n\n case 'hyperbolic':\n return computeHyperbolicAttentionAsync(\n query,\n keys,\n values,\n dim,\n this.config.curvature ?? 1.0\n );\n\n default:\n return computeAttentionAsync(query, keys, values, dim);\n }\n }\n\n // ==========================================================================\n // Hyperbolic Operations (for hierarchical structures)\n // ==========================================================================\n\n /**\n * Compute Poincaré distance between two embeddings\n *\n * Useful for hierarchical agent structures\n */\n poincareDistance(a: Float32Array, b: Float32Array): number {\n return poincareDistance(a, b, this.config.curvature);\n }\n\n /**\n * Project embedding to Poincaré ball\n */\n projectToPoincare(embedding: Float32Array): Float32Array {\n return projectToPoincareBall(embedding, this.config.curvature);\n }\n\n // ==========================================================================\n // Statistics & Status\n // ==========================================================================\n\n /**\n * Get intelligence layer statistics\n */\n getStats(): typeof this.stats & { sonaStats?: any } {\n let sonaStats: any = null;\n\n if (this.sona) {\n try {\n sonaStats = JSON.parse(this.sona.getStats());\n } catch {}\n }\n\n return {\n ...this.stats,\n sonaStats,\n };\n }\n\n /**\n * Enable/disable the intelligence layer\n */\n setEnabled(enabled: boolean): void {\n if (this.sona) {\n this.sona.setEnabled(enabled);\n }\n }\n\n /**\n * Check if enabled\n */\n isEnabled(): boolean {\n return this.sona?.isEnabled() ?? false;\n }\n\n /**\n * Cleanup resources\n */\n dispose(): void {\n if (this.learningTimer) {\n clearInterval(this.learningTimer);\n this.learningTimer = null;\n }\n\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n this.cleanupTimer = null;\n }\n\n // Flush SONA\n if (this.sona) {\n this.sona.flush();\n }\n\n // Clear caches and LRU tracking\n this.trajectories.clear();\n this.trajectoryAccessOrder = [];\n this.agentEmbeddings.clear();\n this.agentAccessOrder = [];\n }\n}\n\n/**\n * Create a default intelligence layer\n */\nexport function createIntelligenceLayer(\n config?: RuVectorIntelligenceConfig\n): RuVectorIntelligence {\n return new RuVectorIntelligence(config);\n}\n\n/**\n * Presets for common configurations\n */\nexport const IntelligencePresets = {\n /** Fast routing with MoE and minimal learning */\n fast: {\n attentionType: 'moe' as const,\n numExperts: 4,\n topK: 2,\n enableTrajectories: false,\n backgroundIntervalMs: 300000, // 5 min\n },\n\n /** Balanced performance and learning */\n balanced: {\n attentionType: 'moe' as const,\n numExperts: 4,\n topK: 2,\n enableTrajectories: true,\n backgroundIntervalMs: 60000, // 1 min\n qualityThreshold: 0.5,\n },\n\n /** Maximum learning for development */\n learning: {\n attentionType: 'dual' as const,\n enableTrajectories: true,\n backgroundIntervalMs: 30000, // 30 sec\n qualityThreshold: 0.3,\n sonaConfig: {\n microLoraRank: 2,\n baseLoraRank: 16,\n trajectoryCapacity: 50000,\n },\n },\n\n /** Hierarchical structures (Poincaré geometry) */\n hierarchical: {\n attentionType: 'hyperbolic' as const,\n curvature: 1.0,\n enableTrajectories: true,\n },\n\n /** Graph-based reasoning */\n graph: {\n attentionType: 'graph' as const,\n enableTrajectories: true,\n },\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"claudeFlowSdkServer.d.ts","sourceRoot":"","sources":["../../src/mcp/claudeFlowSdkServer.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"claudeFlowSdkServer.d.ts","sourceRoot":"","sources":["../../src/mcp/claudeFlowSdkServer.ts"],"names":[],"mappings":"AAyEA;;;GAGG;AACH,eAAO,MAAM,mBAAmB,yEAmc9B,CAAC"}
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
// In-SDK MCP server for claude-flow tools (no subprocess required)
|
|
2
|
-
import { createSdkMcpServer, tool } from '@anthropic-ai/claude-agent-sdk';
|
|
2
|
+
import { createSdkMcpServer, tool as sdkTool } from '@anthropic-ai/claude-agent-sdk';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
import { readFileSync, writeFileSync } from 'fs';
|
|
5
5
|
import { extname } from 'path';
|
|
6
6
|
import { resolveInsideCwd } from '../utils/path-safety.js';
|
|
7
7
|
import { logger } from '../utils/logger.js';
|
|
8
8
|
import { execMemoryStore, execMemoryRetrieve, execMemorySearch, execAgentSpawn, safeExecNpx, } from '../utils/safe-exec.js';
|
|
9
|
+
import { withPortableDescriptions } from './sdk-tool-schema.js';
|
|
10
|
+
const tool = (name, description, inputSchema, handler) => sdkTool(name, description, withPortableDescriptions(inputSchema), handler);
|
|
9
11
|
let _AgentBooster = null;
|
|
10
12
|
async function loadAgentBooster() {
|
|
11
13
|
if (_AgentBooster)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"claudeFlowSdkServer.js","sourceRoot":"","sources":["../../src/mcp/claudeFlowSdkServer.ts"],"names":[],"mappings":"AAAA,mEAAmE;AACnE,OAAO,EAAE,kBAAkB,EAAE,IAAI,EAAE,MAAM,gCAAgC,CAAC;AAC1E,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,IAAI,CAAC;AACjD,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC/B,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,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AAC,IAAI,CAAC,EAAE;yBACvC;qBACF;iBACF,CAAC;YACJ,CAAC;YAAC,OAAO,KAAU,EAAE,CAAC;gBACpB,OAAO;oBACL,OAAO,EAAE;wBACP;4BACE,IAAI,EAAE,MAAM;4BACZ,IAAI,EAAE,wBAAwB,KAAK,CAAC,OAAO,EAAE;yBAC9C;qBACF;oBACD,OAAO,EAAE,IAAI;iBACd,CAAC;YACJ,CAAC;QACH,CAAC,CACF;KACF;CACF,CAAC,CAAC","sourcesContent":["// In-SDK MCP server for claude-flow tools (no subprocess required)\nimport { createSdkMcpServer, tool } from '@anthropic-ai/claude-agent-sdk';\nimport { z } from 'zod';\nimport { readFileSync, writeFileSync } from 'fs';\nimport { extname } from 'path';\nimport { resolveInsideCwd } from '../utils/path-safety.js';\nimport { logger } from '../utils/logger.js';\nimport {\n execMemoryStore,\n execMemoryRetrieve,\n execMemorySearch,\n execAgentSpawn,\n safeExecNpx,\n} from '../utils/safe-exec.js';\n\n// agent-booster is an optional sibling package — load it lazily so a missing\n// dep does not break top-level imports of agentic-flow (issue #102).\ntype AgentBoosterCtor = new (opts: { confidenceThreshold?: number }) => {\n apply(input: any): Promise<{\n success: boolean;\n output: string;\n latency: number;\n confidence: number;\n strategy: string;\n }>;\n};\n\nlet _AgentBooster: AgentBoosterCtor | null = null;\nasync function loadAgentBooster(): Promise<AgentBoosterCtor> {\n if (_AgentBooster) return _AgentBooster;\n try {\n const mod: any = await import('agent-booster');\n const ctor: AgentBoosterCtor | undefined =\n mod.AgentBooster ?? mod.default?.AgentBooster ?? mod.default;\n if (!ctor) {\n throw new Error(\"'agent-booster' loaded but does not export AgentBooster\");\n }\n _AgentBooster = ctor;\n return ctor;\n } catch (err: any) {\n throw new Error(\n `Agent Booster is unavailable (optional package 'agent-booster' not installed). ` +\n `Install it with: npm install agent-booster. Underlying: ${err?.message || err}`\n );\n }\n}\n\n/**\n * Validate a file path to prevent directory traversal.\n * Resolves to an absolute path and rejects paths that escape the working directory\n * (after following symlinks) or reference clearly sensitive locations.\n *\n * @param filePath - Caller-supplied file path\n * @returns Resolved absolute path\n * @throws Error if the path is unsafe\n */\nfunction validateFilePath(filePath: string): string {\n const resolved = resolveInsideCwd(filePath);\n\n // Block paths that are clearly sensitive system locations\n const blockedPrefixes = ['/etc/', '/proc/', '/sys/', '/dev/', '/root/'];\n for (const prefix of blockedPrefixes) {\n if (resolved.startsWith(prefix)) {\n throw new Error(`Access to path '${prefix}' is not permitted`);\n }\n }\n return resolved;\n}\n\n/**\n * Create an in-SDK MCP server that provides claude-flow memory and coordination tools\n * This runs in-process without spawning Claude Code CLI subprocess\n */\nexport const claudeFlowSdkServer = createSdkMcpServer({\n name: 'claude-flow-sdk',\n version: '1.0.0',\n\n tools: [\n // Memory storage tool\n tool(\n 'memory_store',\n 'Store a value in persistent memory with optional namespace and TTL',\n {\n key: z.string().describe('Memory key'),\n value: z.string().describe('Value to store'),\n namespace: z.string().optional().default('default').describe('Memory namespace'),\n ttl: z.number().optional().describe('Time-to-live in seconds'),\n },\n async ({ key, value, namespace, ttl }) => {\n try {\n logger.info('Storing memory', { key, namespace });\n // Use safe exec to prevent shell injection — inputs are validated inside execMemoryStore\n execMemoryStore(key, value, namespace, ttl);\n\n logger.info('Memory stored successfully', { key });\n return {\n content: [\n {\n type: 'text',\n text: `✅ Stored successfully\\n📝 Key: ${key}\\n📦 Namespace: ${namespace}\\n💾 Size: ${value.length} bytes`,\n },\n ],\n };\n } catch (error: any) {\n logger.error('Failed to store memory', { error: error.message });\n return {\n content: [\n {\n type: 'text',\n text: `❌ Failed to store: ${error.message}`,\n },\n ],\n isError: true,\n };\n }\n }\n ),\n\n // Memory retrieval tool\n tool(\n 'memory_retrieve',\n 'Retrieve a value from persistent memory',\n {\n key: z.string().describe('Memory key'),\n namespace: z.string().optional().default('default').describe('Memory namespace'),\n },\n async ({ key, namespace }) => {\n try {\n // Use safe exec to prevent shell injection — inputs are validated inside execMemoryRetrieve\n const result = execMemoryRetrieve(key, namespace);\n\n return {\n content: [\n {\n type: 'text',\n text: `✅ Retrieved:\\n${result}`,\n },\n ],\n };\n } catch (error: any) {\n return {\n content: [\n {\n type: 'text',\n text: `❌ Failed to retrieve: ${error.message}`,\n },\n ],\n isError: true,\n };\n }\n }\n ),\n\n // Memory search tool\n tool(\n 'memory_search',\n 'Search for keys matching a pattern in memory',\n {\n pattern: z.string().describe('Search pattern (supports wildcards)'),\n namespace: z.string().optional().describe('Memory namespace to search in'),\n limit: z.number().optional().default(10).describe('Maximum results to return'),\n },\n async ({ pattern, namespace, limit }) => {\n try {\n // Use safe exec to prevent shell injection — inputs are validated inside execMemorySearch\n const result = execMemorySearch(pattern, namespace, limit);\n\n return {\n content: [\n {\n type: 'text',\n text: `🔍 Search results:\\n${result}`,\n },\n ],\n };\n } catch (error: any) {\n return {\n content: [\n {\n type: 'text',\n text: `❌ Search failed: ${error.message}`,\n },\n ],\n isError: true,\n };\n }\n }\n ),\n\n // Swarm initialization tool\n tool(\n 'swarm_init',\n 'Initialize a multi-agent swarm with specified topology',\n {\n topology: z.enum(['mesh', 'hierarchical', 'ring', 'star']).describe('Swarm topology'),\n maxAgents: z.number().optional().default(8).describe('Maximum number of agents'),\n strategy: z\n .enum(['balanced', 'specialized', 'adaptive'])\n .optional()\n .default('balanced')\n .describe('Agent distribution strategy'),\n },\n async ({ topology, maxAgents, strategy }) => {\n try {\n // Use safe exec — topology and strategy come from z.enum() so are\n // already allowlisted, but execSwarmInit validates them again.\n // Pass a generated swarm ID so execSwarmInit is satisfied.\n const swarmId = `swarm-${Date.now()}`;\n const result = safeExecNpx('claude-flow@alpha', [\n 'swarm', 'init',\n '--topology', topology,\n '--max-agents', String(Math.min(Math.max(1, maxAgents), 100)),\n '--strategy', strategy,\n ]);\n\n return {\n content: [\n {\n type: 'text',\n text: `🚀 Swarm initialized:\\n${result}`,\n },\n ],\n };\n } catch (error: any) {\n return {\n content: [\n {\n type: 'text',\n text: `❌ Swarm init failed: ${error.message}`,\n },\n ],\n isError: true,\n };\n }\n }\n ),\n\n // Agent spawn tool\n tool(\n 'agent_spawn',\n 'Spawn a new agent in the swarm',\n {\n type: z\n .enum(['researcher', 'coder', 'analyst', 'optimizer', 'coordinator'])\n .describe('Agent type'),\n capabilities: z.array(z.string()).optional().describe('Agent capabilities'),\n name: z.string().optional().describe('Custom agent name'),\n },\n async ({ type, capabilities, name }) => {\n try {\n // Use safe exec — type comes from z.enum() but execAgentSpawn re-validates\n // against VALIDATION_PATTERNS.agentType. The optional `name` is also\n // validated against agentName pattern inside execAgentSpawn.\n const agentName = name ?? `${type}-${Date.now()}`;\n const result = execAgentSpawn(agentName, type, undefined, capabilities);\n\n return {\n content: [\n {\n type: 'text',\n text: `🤖 Agent spawned:\\n${result}`,\n },\n ],\n };\n } catch (error: any) {\n return {\n content: [\n {\n type: 'text',\n text: `❌ Agent spawn failed: ${error.message}`,\n },\n ],\n isError: true,\n };\n }\n }\n ),\n\n // Task orchestration tool\n tool(\n 'task_orchestrate',\n 'Orchestrate a complex task across the swarm',\n {\n task: z.string().describe('Task description or instructions'),\n strategy: z\n .enum(['parallel', 'sequential', 'adaptive'])\n .optional()\n .default('adaptive')\n .describe('Execution strategy'),\n priority: z\n .enum(['low', 'medium', 'high', 'critical'])\n .optional()\n .default('medium')\n .describe('Task priority'),\n maxAgents: z.number().optional().describe('Maximum agents to use for this task'),\n },\n async ({ task, strategy, priority, maxAgents }) => {\n try {\n // Use safe exec — task is passed as an array arg (no shell interpolation).\n // strategy and priority come from z.enum() and are re-validated inside\n // execTaskOrchestrate against VALIDATION_PATTERNS.\n const args = ['task', 'orchestrate', '--task', task, '--strategy', strategy, '--priority', priority];\n if (maxAgents !== undefined) {\n args.push('--max-agents', String(Math.min(Math.max(1, maxAgents), 100)));\n }\n const result = safeExecNpx('claude-flow@alpha', args);\n\n return {\n content: [\n {\n type: 'text',\n text: `⚡ Task orchestrated:\\n${result}`,\n },\n ],\n };\n } catch (error: any) {\n return {\n content: [\n {\n type: 'text',\n text: `❌ Task orchestration failed: ${error.message}`,\n },\n ],\n isError: true,\n };\n }\n }\n ),\n\n // Swarm status tool\n tool(\n 'swarm_status',\n 'Get current swarm status and metrics',\n {\n verbose: z.boolean().optional().default(false).describe('Include detailed metrics'),\n },\n async ({ verbose }) => {\n try {\n // verbose is a boolean from schema — no user string is interpolated into the command\n const args = ['swarm', 'status'];\n if (verbose) args.push('--verbose');\n const result = safeExecNpx('claude-flow@alpha', args);\n\n return {\n content: [\n {\n type: 'text',\n text: `📊 Swarm status:\\n${result}`,\n },\n ],\n };\n } catch (error: any) {\n return {\n content: [\n {\n type: 'text',\n text: `❌ Status check failed: ${error.message}`,\n },\n ],\n isError: true,\n };\n }\n }\n ),\n\n // Agent Booster - Ultra-fast code editing\n tool(\n 'agent_booster_edit_file',\n \"Ultra-fast code editing (352x faster than cloud APIs, $0 cost). Apply precise code edits using Agent Booster's local WASM engine.\",\n {\n target_filepath: z.string().describe('Path of the file to modify'),\n instructions: z.string().describe('Description of what changes to make'),\n code_edit: z.string().describe('The new code or edit to apply'),\n language: z\n .string()\n .optional()\n .describe('Programming language (auto-detected if not provided)'),\n },\n async ({ target_filepath, instructions, code_edit, language }) => {\n try {\n // Initialize Agent Booster (lazy load to keep top-level import safe)\n const Ctor = await loadAgentBooster();\n const booster = new Ctor({ confidenceThreshold: 0.5 });\n\n // Validate and resolve the path before any file I/O to prevent traversal attacks\n const safePath = validateFilePath(target_filepath);\n\n // Read original file\n const originalCode = readFileSync(safePath, 'utf8');\n\n // Auto-detect language if not provided\n const lang = language || extname(safePath).slice(1);\n\n // Apply edit - use any cast for flexible signature\n const result = await booster.apply({\n code: originalCode,\n edit: code_edit,\n language: lang,\n target_filepath: safePath,\n instructions: code_edit,\n code_edit,\n } as any);\n\n // Write if successful\n if (result.success) {\n writeFileSync(safePath, result.output, 'utf8');\n }\n\n return {\n content: [\n {\n type: 'text',\n text:\n `⚡ Agent Booster Edit Result:\\n` +\n `📁 File: ${safePath}\\n` +\n `✅ Success: ${result.success}\\n` +\n `⏱️ Latency: ${result.latency}ms\\n` +\n `🎯 Confidence: ${(result.confidence * 100).toFixed(1)}%\\n` +\n `🔧 Strategy: ${result.strategy}\\n` +\n `📊 Speedup: ~${Math.round(352 / result.latency)}x vs cloud APIs\\n` +\n `💰 Cost: $0 (vs ~$0.01 for cloud API)\\n\\n` +\n `${result.success ? '✨ Edit applied successfully!' : '❌ Edit failed - check confidence score'}`,\n },\n ],\n };\n } catch (error: any) {\n return {\n content: [\n {\n type: 'text',\n text: `❌ Agent Booster edit failed: ${error.message}`,\n },\n ],\n isError: true,\n };\n }\n }\n ),\n\n // Agent Booster - Batch editing\n tool(\n 'agent_booster_batch_edit',\n 'Apply multiple code edits in parallel using Agent Booster. Perfect for multi-file refactoring.',\n {\n edits: z\n .array(\n z.object({\n target_filepath: z.string(),\n instructions: z.string(),\n code_edit: z.string(),\n language: z.string().optional(),\n })\n )\n .describe('Array of edit operations to apply'),\n },\n async ({ edits }) => {\n try {\n const Ctor = await loadAgentBooster();\n const booster = new Ctor({ confidenceThreshold: 0.5 });\n let successCount = 0;\n let totalLatency = 0;\n const results: string[] = [];\n\n for (const edit of edits) {\n // Validate path for each entry before any file I/O\n const safePath = validateFilePath(edit.target_filepath);\n const originalCode = readFileSync(safePath, 'utf8');\n const lang = edit.language || extname(safePath).slice(1);\n\n const result = await booster.apply({\n code: originalCode,\n edit: edit.code_edit,\n language: lang,\n target_filepath: safePath,\n instructions: edit.code_edit,\n code_edit: edit.code_edit,\n } as any);\n\n if (result.success) {\n writeFileSync(safePath, result.output, 'utf8');\n successCount++;\n }\n\n totalLatency += result.latency;\n results.push(\n ` ${result.success ? '✅' : '❌'} ${safePath} (${result.latency}ms, ${(result.confidence * 100).toFixed(0)}%)`\n );\n }\n\n const avgLatency = totalLatency / edits.length;\n const avgSpeedup = Math.round(352 / avgLatency);\n\n return {\n content: [\n {\n type: 'text',\n text:\n `⚡ Agent Booster Batch Edit Results:\\n\\n` +\n `📊 Summary:\\n` +\n ` Total edits: ${edits.length}\\n` +\n ` Successful: ${successCount}\\n` +\n ` Failed: ${edits.length - successCount}\\n` +\n ` Total time: ${totalLatency.toFixed(1)}ms\\n` +\n ` Avg latency: ${avgLatency.toFixed(1)}ms\\n` +\n ` Avg speedup: ~${avgSpeedup}x vs cloud APIs\\n` +\n ` Cost savings: ~$${(edits.length * 0.01).toFixed(2)}\\n\\n` +\n `📁 Results:\\n${results.join('\\n')}`,\n },\n ],\n };\n } catch (error: any) {\n return {\n content: [\n {\n type: 'text',\n text: `❌ Batch edit failed: ${error.message}`,\n },\n ],\n isError: true,\n };\n }\n }\n ),\n ],\n});\n"]}
|
|
1
|
+
{"version":3,"file":"claudeFlowSdkServer.js","sourceRoot":"","sources":["../../src/mcp/claudeFlowSdkServer.ts"],"names":[],"mappings":"AAAA,mEAAmE;AACnE,OAAO,EAAE,kBAAkB,EAAE,IAAI,IAAI,OAAO,EAAE,MAAM,gCAAgC,CAAC;AACrF,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,IAAI,CAAC;AACjD,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC/B,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,OAAO,EACL,eAAe,EACf,kBAAkB,EAClB,gBAAgB,EAChB,cAAc,EACd,WAAW,GACZ,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAEhE,MAAM,IAAI,GAAmB,CAAC,IAAI,EAAE,WAAW,EAAE,WAAW,EAAE,OAAO,EAAE,EAAE,CACvE,OAAO,CAAC,IAAI,EAAE,WAAW,EAAE,wBAAwB,CAAC,WAAW,CAAC,EAAE,OAAO,CAAC,CAAC;AAc7E,IAAI,aAAa,GAA4B,IAAI,CAAC;AAClD,KAAK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E,MAAM;4BACZ,IAAI,EAAE,wBAAwB,KAAK,CAAC,OAAO,EAAE;yBAC9C;qBACF;oBACD,OAAO,EAAE,IAAI;iBACd,CAAC;YACJ,CAAC;QACH,CAAC,CACF;KACF;CACF,CAAC,CAAC","sourcesContent":["// In-SDK MCP server for claude-flow tools (no subprocess required)\nimport { createSdkMcpServer, tool as sdkTool } from '@anthropic-ai/claude-agent-sdk';\nimport { z } from 'zod';\nimport { readFileSync, writeFileSync } from 'fs';\nimport { extname } from 'path';\nimport { resolveInsideCwd } from '../utils/path-safety.js';\nimport { logger } from '../utils/logger.js';\nimport {\n execMemoryStore,\n execMemoryRetrieve,\n execMemorySearch,\n execAgentSpawn,\n safeExecNpx,\n} from '../utils/safe-exec.js';\nimport { withPortableDescriptions } from './sdk-tool-schema.js';\n\nconst tool: typeof sdkTool = (name, description, inputSchema, handler) =>\n sdkTool(name, description, withPortableDescriptions(inputSchema), handler);\n\n// agent-booster is an optional sibling package — load it lazily so a missing\n// dep does not break top-level imports of agentic-flow (issue #102).\ntype AgentBoosterCtor = new (opts: { confidenceThreshold?: number }) => {\n apply(input: any): Promise<{\n success: boolean;\n output: string;\n latency: number;\n confidence: number;\n strategy: string;\n }>;\n};\n\nlet _AgentBooster: AgentBoosterCtor | null = null;\nasync function loadAgentBooster(): Promise<AgentBoosterCtor> {\n if (_AgentBooster) return _AgentBooster;\n try {\n const mod: any = await import('agent-booster');\n const ctor: AgentBoosterCtor | undefined =\n mod.AgentBooster ?? mod.default?.AgentBooster ?? mod.default;\n if (!ctor) {\n throw new Error(\"'agent-booster' loaded but does not export AgentBooster\");\n }\n _AgentBooster = ctor;\n return ctor;\n } catch (err: any) {\n throw new Error(\n `Agent Booster is unavailable (optional package 'agent-booster' not installed). ` +\n `Install it with: npm install agent-booster. Underlying: ${err?.message || err}`\n );\n }\n}\n\n/**\n * Validate a file path to prevent directory traversal.\n * Resolves to an absolute path and rejects paths that escape the working directory\n * (after following symlinks) or reference clearly sensitive locations.\n *\n * @param filePath - Caller-supplied file path\n * @returns Resolved absolute path\n * @throws Error if the path is unsafe\n */\nfunction validateFilePath(filePath: string): string {\n const resolved = resolveInsideCwd(filePath);\n\n // Block paths that are clearly sensitive system locations\n const blockedPrefixes = ['/etc/', '/proc/', '/sys/', '/dev/', '/root/'];\n for (const prefix of blockedPrefixes) {\n if (resolved.startsWith(prefix)) {\n throw new Error(`Access to path '${prefix}' is not permitted`);\n }\n }\n return resolved;\n}\n\n/**\n * Create an in-SDK MCP server that provides claude-flow memory and coordination tools\n * This runs in-process without spawning Claude Code CLI subprocess\n */\nexport const claudeFlowSdkServer = createSdkMcpServer({\n name: 'claude-flow-sdk',\n version: '1.0.0',\n\n tools: [\n // Memory storage tool\n tool(\n 'memory_store',\n 'Store a value in persistent memory with optional namespace and TTL',\n {\n key: z.string().describe('Memory key'),\n value: z.string().describe('Value to store'),\n namespace: z.string().optional().default('default').describe('Memory namespace'),\n ttl: z.number().optional().describe('Time-to-live in seconds'),\n },\n async ({ key, value, namespace, ttl }) => {\n try {\n logger.info('Storing memory', { key, namespace });\n // Use safe exec to prevent shell injection — inputs are validated inside execMemoryStore\n execMemoryStore(key, value, namespace, ttl);\n\n logger.info('Memory stored successfully', { key });\n return {\n content: [\n {\n type: 'text',\n text: `✅ Stored successfully\\n📝 Key: ${key}\\n📦 Namespace: ${namespace}\\n💾 Size: ${value.length} bytes`,\n },\n ],\n };\n } catch (error: any) {\n logger.error('Failed to store memory', { error: error.message });\n return {\n content: [\n {\n type: 'text',\n text: `❌ Failed to store: ${error.message}`,\n },\n ],\n isError: true,\n };\n }\n }\n ),\n\n // Memory retrieval tool\n tool(\n 'memory_retrieve',\n 'Retrieve a value from persistent memory',\n {\n key: z.string().describe('Memory key'),\n namespace: z.string().optional().default('default').describe('Memory namespace'),\n },\n async ({ key, namespace }) => {\n try {\n // Use safe exec to prevent shell injection — inputs are validated inside execMemoryRetrieve\n const result = execMemoryRetrieve(key, namespace);\n\n return {\n content: [\n {\n type: 'text',\n text: `✅ Retrieved:\\n${result}`,\n },\n ],\n };\n } catch (error: any) {\n return {\n content: [\n {\n type: 'text',\n text: `❌ Failed to retrieve: ${error.message}`,\n },\n ],\n isError: true,\n };\n }\n }\n ),\n\n // Memory search tool\n tool(\n 'memory_search',\n 'Search for keys matching a pattern in memory',\n {\n pattern: z.string().describe('Search pattern (supports wildcards)'),\n namespace: z.string().optional().describe('Memory namespace to search in'),\n limit: z.number().optional().default(10).describe('Maximum results to return'),\n },\n async ({ pattern, namespace, limit }) => {\n try {\n // Use safe exec to prevent shell injection — inputs are validated inside execMemorySearch\n const result = execMemorySearch(pattern, namespace, limit);\n\n return {\n content: [\n {\n type: 'text',\n text: `🔍 Search results:\\n${result}`,\n },\n ],\n };\n } catch (error: any) {\n return {\n content: [\n {\n type: 'text',\n text: `❌ Search failed: ${error.message}`,\n },\n ],\n isError: true,\n };\n }\n }\n ),\n\n // Swarm initialization tool\n tool(\n 'swarm_init',\n 'Initialize a multi-agent swarm with specified topology',\n {\n topology: z.enum(['mesh', 'hierarchical', 'ring', 'star']).describe('Swarm topology'),\n maxAgents: z.number().optional().default(8).describe('Maximum number of agents'),\n strategy: z\n .enum(['balanced', 'specialized', 'adaptive'])\n .optional()\n .default('balanced')\n .describe('Agent distribution strategy'),\n },\n async ({ topology, maxAgents, strategy }) => {\n try {\n // Use safe exec — topology and strategy come from z.enum() so are\n // already allowlisted, but execSwarmInit validates them again.\n // Pass a generated swarm ID so execSwarmInit is satisfied.\n const swarmId = `swarm-${Date.now()}`;\n const result = safeExecNpx('claude-flow@alpha', [\n 'swarm', 'init',\n '--topology', topology,\n '--max-agents', String(Math.min(Math.max(1, maxAgents), 100)),\n '--strategy', strategy,\n ]);\n\n return {\n content: [\n {\n type: 'text',\n text: `🚀 Swarm initialized:\\n${result}`,\n },\n ],\n };\n } catch (error: any) {\n return {\n content: [\n {\n type: 'text',\n text: `❌ Swarm init failed: ${error.message}`,\n },\n ],\n isError: true,\n };\n }\n }\n ),\n\n // Agent spawn tool\n tool(\n 'agent_spawn',\n 'Spawn a new agent in the swarm',\n {\n type: z\n .enum(['researcher', 'coder', 'analyst', 'optimizer', 'coordinator'])\n .describe('Agent type'),\n capabilities: z.array(z.string()).optional().describe('Agent capabilities'),\n name: z.string().optional().describe('Custom agent name'),\n },\n async ({ type, capabilities, name }) => {\n try {\n // Use safe exec — type comes from z.enum() but execAgentSpawn re-validates\n // against VALIDATION_PATTERNS.agentType. The optional `name` is also\n // validated against agentName pattern inside execAgentSpawn.\n const agentName = name ?? `${type}-${Date.now()}`;\n const result = execAgentSpawn(agentName, type, undefined, capabilities);\n\n return {\n content: [\n {\n type: 'text',\n text: `🤖 Agent spawned:\\n${result}`,\n },\n ],\n };\n } catch (error: any) {\n return {\n content: [\n {\n type: 'text',\n text: `❌ Agent spawn failed: ${error.message}`,\n },\n ],\n isError: true,\n };\n }\n }\n ),\n\n // Task orchestration tool\n tool(\n 'task_orchestrate',\n 'Orchestrate a complex task across the swarm',\n {\n task: z.string().describe('Task description or instructions'),\n strategy: z\n .enum(['parallel', 'sequential', 'adaptive'])\n .optional()\n .default('adaptive')\n .describe('Execution strategy'),\n priority: z\n .enum(['low', 'medium', 'high', 'critical'])\n .optional()\n .default('medium')\n .describe('Task priority'),\n maxAgents: z.number().optional().describe('Maximum agents to use for this task'),\n },\n async ({ task, strategy, priority, maxAgents }) => {\n try {\n // Use safe exec — task is passed as an array arg (no shell interpolation).\n // strategy and priority come from z.enum() and are re-validated inside\n // execTaskOrchestrate against VALIDATION_PATTERNS.\n const args = ['task', 'orchestrate', '--task', task, '--strategy', strategy, '--priority', priority];\n if (maxAgents !== undefined) {\n args.push('--max-agents', String(Math.min(Math.max(1, maxAgents), 100)));\n }\n const result = safeExecNpx('claude-flow@alpha', args);\n\n return {\n content: [\n {\n type: 'text',\n text: `⚡ Task orchestrated:\\n${result}`,\n },\n ],\n };\n } catch (error: any) {\n return {\n content: [\n {\n type: 'text',\n text: `❌ Task orchestration failed: ${error.message}`,\n },\n ],\n isError: true,\n };\n }\n }\n ),\n\n // Swarm status tool\n tool(\n 'swarm_status',\n 'Get current swarm status and metrics',\n {\n verbose: z.boolean().optional().default(false).describe('Include detailed metrics'),\n },\n async ({ verbose }) => {\n try {\n // verbose is a boolean from schema — no user string is interpolated into the command\n const args = ['swarm', 'status'];\n if (verbose) args.push('--verbose');\n const result = safeExecNpx('claude-flow@alpha', args);\n\n return {\n content: [\n {\n type: 'text',\n text: `📊 Swarm status:\\n${result}`,\n },\n ],\n };\n } catch (error: any) {\n return {\n content: [\n {\n type: 'text',\n text: `❌ Status check failed: ${error.message}`,\n },\n ],\n isError: true,\n };\n }\n }\n ),\n\n // Agent Booster - Ultra-fast code editing\n tool(\n 'agent_booster_edit_file',\n \"Ultra-fast code editing (352x faster than cloud APIs, $0 cost). Apply precise code edits using Agent Booster's local WASM engine.\",\n {\n target_filepath: z.string().describe('Path of the file to modify'),\n instructions: z.string().describe('Description of what changes to make'),\n code_edit: z.string().describe('The new code or edit to apply'),\n language: z\n .string()\n .optional()\n .describe('Programming language (auto-detected if not provided)'),\n },\n async ({ target_filepath, instructions, code_edit, language }) => {\n try {\n // Initialize Agent Booster (lazy load to keep top-level import safe)\n const Ctor = await loadAgentBooster();\n const booster = new Ctor({ confidenceThreshold: 0.5 });\n\n // Validate and resolve the path before any file I/O to prevent traversal attacks\n const safePath = validateFilePath(target_filepath);\n\n // Read original file\n const originalCode = readFileSync(safePath, 'utf8');\n\n // Auto-detect language if not provided\n const lang = language || extname(safePath).slice(1);\n\n // Apply edit - use any cast for flexible signature\n const result = await booster.apply({\n code: originalCode,\n edit: code_edit,\n language: lang,\n target_filepath: safePath,\n instructions: code_edit,\n code_edit,\n } as any);\n\n // Write if successful\n if (result.success) {\n writeFileSync(safePath, result.output, 'utf8');\n }\n\n return {\n content: [\n {\n type: 'text',\n text:\n `⚡ Agent Booster Edit Result:\\n` +\n `📁 File: ${safePath}\\n` +\n `✅ Success: ${result.success}\\n` +\n `⏱️ Latency: ${result.latency}ms\\n` +\n `🎯 Confidence: ${(result.confidence * 100).toFixed(1)}%\\n` +\n `🔧 Strategy: ${result.strategy}\\n` +\n `📊 Speedup: ~${Math.round(352 / result.latency)}x vs cloud APIs\\n` +\n `💰 Cost: $0 (vs ~$0.01 for cloud API)\\n\\n` +\n `${result.success ? '✨ Edit applied successfully!' : '❌ Edit failed - check confidence score'}`,\n },\n ],\n };\n } catch (error: any) {\n return {\n content: [\n {\n type: 'text',\n text: `❌ Agent Booster edit failed: ${error.message}`,\n },\n ],\n isError: true,\n };\n }\n }\n ),\n\n // Agent Booster - Batch editing\n tool(\n 'agent_booster_batch_edit',\n 'Apply multiple code edits in parallel using Agent Booster. Perfect for multi-file refactoring.',\n {\n edits: z\n .array(\n z.object({\n target_filepath: z.string(),\n instructions: z.string(),\n code_edit: z.string(),\n language: z.string().optional(),\n })\n )\n .describe('Array of edit operations to apply'),\n },\n async ({ edits }) => {\n try {\n const Ctor = await loadAgentBooster();\n const booster = new Ctor({ confidenceThreshold: 0.5 });\n let successCount = 0;\n let totalLatency = 0;\n const results: string[] = [];\n\n for (const edit of edits) {\n // Validate path for each entry before any file I/O\n const safePath = validateFilePath(edit.target_filepath);\n const originalCode = readFileSync(safePath, 'utf8');\n const lang = edit.language || extname(safePath).slice(1);\n\n const result = await booster.apply({\n code: originalCode,\n edit: edit.code_edit,\n language: lang,\n target_filepath: safePath,\n instructions: edit.code_edit,\n code_edit: edit.code_edit,\n } as any);\n\n if (result.success) {\n writeFileSync(safePath, result.output, 'utf8');\n successCount++;\n }\n\n totalLatency += result.latency;\n results.push(\n ` ${result.success ? '✅' : '❌'} ${safePath} (${result.latency}ms, ${(result.confidence * 100).toFixed(0)}%)`\n );\n }\n\n const avgLatency = totalLatency / edits.length;\n const avgSpeedup = Math.round(352 / avgLatency);\n\n return {\n content: [\n {\n type: 'text',\n text:\n `⚡ Agent Booster Batch Edit Results:\\n\\n` +\n `📊 Summary:\\n` +\n ` Total edits: ${edits.length}\\n` +\n ` Successful: ${successCount}\\n` +\n ` Failed: ${edits.length - successCount}\\n` +\n ` Total time: ${totalLatency.toFixed(1)}ms\\n` +\n ` Avg latency: ${avgLatency.toFixed(1)}ms\\n` +\n ` Avg speedup: ~${avgSpeedup}x vs cloud APIs\\n` +\n ` Cost savings: ~$${(edits.length * 0.01).toFixed(2)}\\n\\n` +\n `📁 Results:\\n${results.join('\\n')}`,\n },\n ],\n };\n } catch (error: any) {\n return {\n content: [\n {\n type: 'text',\n text: `❌ Batch edit failed: ${error.message}`,\n },\n ],\n isError: true,\n };\n }\n }\n ),\n ],\n});\n"]}
|