agentic-flow 2.0.1-alpha.2 → 2.0.1-alpha.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/CHANGELOG.md +352 -0
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/agentdb/controllers/EmbeddingService.d.ts +37 -0
  4. package/dist/agentdb/controllers/EmbeddingService.d.ts.map +1 -0
  5. package/dist/agentdb/controllers/EmbeddingService.js +1 -0
  6. package/dist/agentdb/controllers/EmbeddingService.js.map +1 -0
  7. package/dist/billing/mcp/tools.d.ts.map +1 -1
  8. package/dist/billing/mcp/tools.js +2 -0
  9. package/dist/billing/mcp/tools.js.map +1 -1
  10. package/dist/cli/commands/hooks.d.ts +18 -0
  11. package/dist/cli/commands/hooks.d.ts.map +1 -0
  12. package/dist/cli/commands/hooks.js +755 -0
  13. package/dist/cli/commands/hooks.js.map +1 -0
  14. package/dist/cli-proxy.d.ts +1 -1
  15. package/dist/cli-proxy.d.ts.map +1 -1
  16. package/dist/cli-proxy.js +28 -1
  17. package/dist/cli-proxy.js.map +1 -1
  18. package/dist/core/agentdb-fast.js +3 -3
  19. package/dist/core/agentdb-fast.js.map +1 -1
  20. package/dist/core/agentdb-wrapper-enhanced.d.ts.map +1 -1
  21. package/dist/core/agentdb-wrapper-enhanced.js +32 -17
  22. package/dist/core/agentdb-wrapper-enhanced.js.map +1 -1
  23. package/dist/core/attention-native.d.ts +1 -0
  24. package/dist/core/attention-native.d.ts.map +1 -1
  25. package/dist/core/attention-native.js +6 -1
  26. package/dist/core/attention-native.js.map +1 -1
  27. package/dist/federation/integrations/supabase-adapter-debug.js +3 -3
  28. package/dist/federation/integrations/supabase-adapter-debug.js.map +1 -1
  29. package/dist/intelligence/EmbeddingCache.d.ts +112 -0
  30. package/dist/intelligence/EmbeddingCache.d.ts.map +1 -0
  31. package/dist/intelligence/EmbeddingCache.js +624 -0
  32. package/dist/intelligence/EmbeddingCache.js.map +1 -0
  33. package/dist/intelligence/EmbeddingService.d.ts +380 -0
  34. package/dist/intelligence/EmbeddingService.d.ts.map +1 -0
  35. package/dist/intelligence/EmbeddingService.js +1484 -0
  36. package/dist/intelligence/EmbeddingService.js.map +1 -0
  37. package/dist/intelligence/IntelligenceStore.d.ts +168 -0
  38. package/dist/intelligence/IntelligenceStore.d.ts.map +1 -0
  39. package/dist/intelligence/IntelligenceStore.js +364 -0
  40. package/dist/intelligence/IntelligenceStore.js.map +1 -0
  41. package/dist/intelligence/RuVectorIntelligence.d.ts +362 -0
  42. package/dist/intelligence/RuVectorIntelligence.d.ts.map +1 -0
  43. package/dist/intelligence/RuVectorIntelligence.js +853 -0
  44. package/dist/intelligence/RuVectorIntelligence.js.map +1 -0
  45. package/dist/intelligence/embedding-benchmark.d.ts +7 -0
  46. package/dist/intelligence/embedding-benchmark.d.ts.map +1 -0
  47. package/dist/intelligence/embedding-benchmark.js +155 -0
  48. package/dist/intelligence/embedding-benchmark.js.map +1 -0
  49. package/dist/intelligence/index.d.ts +14 -0
  50. package/dist/intelligence/index.d.ts.map +1 -0
  51. package/dist/intelligence/index.js +14 -0
  52. package/dist/intelligence/index.js.map +1 -0
  53. package/dist/llm/RuvLLMOrchestrator.d.ts +184 -0
  54. package/dist/llm/RuvLLMOrchestrator.d.ts.map +1 -0
  55. package/dist/llm/RuvLLMOrchestrator.js +442 -0
  56. package/dist/llm/RuvLLMOrchestrator.js.map +1 -0
  57. package/dist/llm/index.d.ts +9 -0
  58. package/dist/llm/index.d.ts.map +1 -0
  59. package/dist/llm/index.js +8 -0
  60. package/dist/llm/index.js.map +1 -0
  61. package/dist/mcp/claudeFlowSdkServer.d.ts.map +1 -1
  62. package/dist/mcp/claudeFlowSdkServer.js +86 -21
  63. package/dist/mcp/claudeFlowSdkServer.js.map +1 -1
  64. package/dist/mcp/fastmcp/servers/hooks-server.d.ts +15 -0
  65. package/dist/mcp/fastmcp/servers/hooks-server.d.ts.map +1 -0
  66. package/dist/mcp/fastmcp/servers/hooks-server.js +63 -0
  67. package/dist/mcp/fastmcp/servers/hooks-server.js.map +1 -0
  68. package/dist/mcp/fastmcp/tools/hooks/benchmark.d.ts +20 -0
  69. package/dist/mcp/fastmcp/tools/hooks/benchmark.d.ts.map +1 -0
  70. package/dist/mcp/fastmcp/tools/hooks/benchmark.js +110 -0
  71. package/dist/mcp/fastmcp/tools/hooks/benchmark.js.map +1 -0
  72. package/dist/mcp/fastmcp/tools/hooks/build-agents.d.ts +7 -0
  73. package/dist/mcp/fastmcp/tools/hooks/build-agents.d.ts.map +1 -0
  74. package/dist/mcp/fastmcp/tools/hooks/build-agents.js +276 -0
  75. package/dist/mcp/fastmcp/tools/hooks/build-agents.js.map +1 -0
  76. package/dist/mcp/fastmcp/tools/hooks/explain.d.ts +6 -0
  77. package/dist/mcp/fastmcp/tools/hooks/explain.d.ts.map +1 -0
  78. package/dist/mcp/fastmcp/tools/hooks/explain.js +164 -0
  79. package/dist/mcp/fastmcp/tools/hooks/explain.js.map +1 -0
  80. package/dist/mcp/fastmcp/tools/hooks/index.d.ts +28 -0
  81. package/dist/mcp/fastmcp/tools/hooks/index.d.ts.map +1 -0
  82. package/dist/mcp/fastmcp/tools/hooks/index.js +59 -0
  83. package/dist/mcp/fastmcp/tools/hooks/index.js.map +1 -0
  84. package/dist/mcp/fastmcp/tools/hooks/intelligence-bridge.d.ts +307 -0
  85. package/dist/mcp/fastmcp/tools/hooks/intelligence-bridge.d.ts.map +1 -0
  86. package/dist/mcp/fastmcp/tools/hooks/intelligence-bridge.js +714 -0
  87. package/dist/mcp/fastmcp/tools/hooks/intelligence-bridge.js.map +1 -0
  88. package/dist/mcp/fastmcp/tools/hooks/intelligence-tools.d.ts +58 -0
  89. package/dist/mcp/fastmcp/tools/hooks/intelligence-tools.d.ts.map +1 -0
  90. package/dist/mcp/fastmcp/tools/hooks/intelligence-tools.js +425 -0
  91. package/dist/mcp/fastmcp/tools/hooks/intelligence-tools.js.map +1 -0
  92. package/dist/mcp/fastmcp/tools/hooks/metrics.d.ts +6 -0
  93. package/dist/mcp/fastmcp/tools/hooks/metrics.d.ts.map +1 -0
  94. package/dist/mcp/fastmcp/tools/hooks/metrics.js +137 -0
  95. package/dist/mcp/fastmcp/tools/hooks/metrics.js.map +1 -0
  96. package/dist/mcp/fastmcp/tools/hooks/post-command.d.ts +7 -0
  97. package/dist/mcp/fastmcp/tools/hooks/post-command.d.ts.map +1 -0
  98. package/dist/mcp/fastmcp/tools/hooks/post-command.js +91 -0
  99. package/dist/mcp/fastmcp/tools/hooks/post-command.js.map +1 -0
  100. package/dist/mcp/fastmcp/tools/hooks/post-edit.d.ts +12 -0
  101. package/dist/mcp/fastmcp/tools/hooks/post-edit.d.ts.map +1 -0
  102. package/dist/mcp/fastmcp/tools/hooks/post-edit.js +146 -0
  103. package/dist/mcp/fastmcp/tools/hooks/post-edit.js.map +1 -0
  104. package/dist/mcp/fastmcp/tools/hooks/pre-command.d.ts +7 -0
  105. package/dist/mcp/fastmcp/tools/hooks/pre-command.d.ts.map +1 -0
  106. package/dist/mcp/fastmcp/tools/hooks/pre-command.js +70 -0
  107. package/dist/mcp/fastmcp/tools/hooks/pre-command.js.map +1 -0
  108. package/dist/mcp/fastmcp/tools/hooks/pre-edit.d.ts +14 -0
  109. package/dist/mcp/fastmcp/tools/hooks/pre-edit.d.ts.map +1 -0
  110. package/dist/mcp/fastmcp/tools/hooks/pre-edit.js +121 -0
  111. package/dist/mcp/fastmcp/tools/hooks/pre-edit.js.map +1 -0
  112. package/dist/mcp/fastmcp/tools/hooks/pretrain.d.ts +7 -0
  113. package/dist/mcp/fastmcp/tools/hooks/pretrain.d.ts.map +1 -0
  114. package/dist/mcp/fastmcp/tools/hooks/pretrain.js +171 -0
  115. package/dist/mcp/fastmcp/tools/hooks/pretrain.js.map +1 -0
  116. package/dist/mcp/fastmcp/tools/hooks/route.d.ts +12 -0
  117. package/dist/mcp/fastmcp/tools/hooks/route.d.ts.map +1 -0
  118. package/dist/mcp/fastmcp/tools/hooks/route.js +267 -0
  119. package/dist/mcp/fastmcp/tools/hooks/route.js.map +1 -0
  120. package/dist/mcp/fastmcp/tools/hooks/shared.d.ts +46 -0
  121. package/dist/mcp/fastmcp/tools/hooks/shared.d.ts.map +1 -0
  122. package/dist/mcp/fastmcp/tools/hooks/shared.js +159 -0
  123. package/dist/mcp/fastmcp/tools/hooks/shared.js.map +1 -0
  124. package/dist/mcp/fastmcp/tools/hooks/transfer.d.ts +7 -0
  125. package/dist/mcp/fastmcp/tools/hooks/transfer.d.ts.map +1 -0
  126. package/dist/mcp/fastmcp/tools/hooks/transfer.js +151 -0
  127. package/dist/mcp/fastmcp/tools/hooks/transfer.js.map +1 -0
  128. package/dist/mcp/tools/agent-booster-tools.d.ts +10 -1
  129. package/dist/mcp/tools/agent-booster-tools.d.ts.map +1 -1
  130. package/dist/mcp/tools/agent-booster-tools.js.map +1 -1
  131. package/dist/mcp/tools/sona-tools.d.ts.map +1 -1
  132. package/dist/mcp/tools/sona-tools.js +15 -3
  133. package/dist/mcp/tools/sona-tools.js.map +1 -1
  134. package/dist/memory/SharedMemoryPool.d.ts +16 -3
  135. package/dist/memory/SharedMemoryPool.d.ts.map +1 -1
  136. package/dist/memory/SharedMemoryPool.js +33 -1
  137. package/dist/memory/SharedMemoryPool.js.map +1 -1
  138. package/dist/middleware/auth.middleware.d.ts +114 -0
  139. package/dist/middleware/auth.middleware.d.ts.map +1 -0
  140. package/dist/middleware/auth.middleware.js +222 -0
  141. package/dist/middleware/auth.middleware.js.map +1 -0
  142. package/dist/optimizations/agent-booster-migration.d.ts.map +1 -1
  143. package/dist/optimizations/agent-booster-migration.js.map +1 -1
  144. package/dist/proxy/anthropic-to-gemini.d.ts.map +1 -1
  145. package/dist/proxy/anthropic-to-gemini.js.map +1 -1
  146. package/dist/proxy/anthropic-to-openrouter.d.ts.map +1 -1
  147. package/dist/proxy/anthropic-to-openrouter.js.map +1 -1
  148. package/dist/proxy/anthropic-to-requesty.d.ts.map +1 -1
  149. package/dist/proxy/anthropic-to-requesty.js.map +1 -1
  150. package/dist/proxy/quic-proxy.d.ts +0 -1
  151. package/dist/proxy/quic-proxy.d.ts.map +1 -1
  152. package/dist/proxy/quic-proxy.js +2 -1
  153. package/dist/proxy/quic-proxy.js.map +1 -1
  154. package/dist/reasoningbank/AdvancedMemory.d.ts.map +1 -1
  155. package/dist/reasoningbank/AdvancedMemory.js +12 -1
  156. package/dist/reasoningbank/AdvancedMemory.js.map +1 -1
  157. package/dist/reasoningbank/HybridBackend.d.ts +9 -0
  158. package/dist/reasoningbank/HybridBackend.d.ts.map +1 -1
  159. package/dist/reasoningbank/HybridBackend.js +48 -4
  160. package/dist/reasoningbank/HybridBackend.js.map +1 -1
  161. package/dist/reasoningbank/backend-selector.d.ts +1 -1
  162. package/dist/reasoningbank/backend-selector.d.ts.map +1 -1
  163. package/dist/reasoningbank/backend-selector.js.map +1 -1
  164. package/dist/reasoningbank/index-new.d.ts +0 -6
  165. package/dist/reasoningbank/index-new.d.ts.map +1 -1
  166. package/dist/reasoningbank/index-new.js +9 -7
  167. package/dist/reasoningbank/index-new.js.map +1 -1
  168. package/dist/reasoningbank/index.d.ts +1 -6
  169. package/dist/reasoningbank/index.d.ts.map +1 -1
  170. package/dist/reasoningbank/index.js +10 -7
  171. package/dist/reasoningbank/index.js.map +1 -1
  172. package/dist/router/providers/onnx-local.d.ts.map +1 -1
  173. package/dist/router/providers/onnx-local.js +3 -1
  174. package/dist/router/providers/onnx-local.js.map +1 -1
  175. package/dist/routing/CircuitBreakerRouter.d.ts +187 -0
  176. package/dist/routing/CircuitBreakerRouter.d.ts.map +1 -0
  177. package/dist/routing/CircuitBreakerRouter.js +460 -0
  178. package/dist/routing/CircuitBreakerRouter.js.map +1 -0
  179. package/dist/routing/SemanticRouter.d.ts +164 -0
  180. package/dist/routing/SemanticRouter.d.ts.map +1 -0
  181. package/dist/routing/SemanticRouter.js +291 -0
  182. package/dist/routing/SemanticRouter.js.map +1 -0
  183. package/dist/routing/index.d.ts +12 -0
  184. package/dist/routing/index.d.ts.map +1 -0
  185. package/dist/routing/index.js +10 -0
  186. package/dist/routing/index.js.map +1 -0
  187. package/dist/services/embedding-service.d.ts.map +1 -1
  188. package/dist/services/embedding-service.js +5 -2
  189. package/dist/services/embedding-service.js.map +1 -1
  190. package/dist/services/sona-agent-training.js +1 -1
  191. package/dist/services/sona-agent-training.js.map +1 -1
  192. package/dist/services/sona-agentdb-integration.d.ts.map +1 -1
  193. package/dist/services/sona-agentdb-integration.js +10 -5
  194. package/dist/services/sona-agentdb-integration.js.map +1 -1
  195. package/dist/services/sona-service.d.ts +6 -6
  196. package/dist/services/sona-service.d.ts.map +1 -1
  197. package/dist/services/sona-service.js +3 -1
  198. package/dist/services/sona-service.js.map +1 -1
  199. package/dist/utils/agentdb-runtime-patch.d.ts +1 -0
  200. package/dist/utils/agentdb-runtime-patch.d.ts.map +1 -1
  201. package/dist/utils/agentdb-runtime-patch.js +97 -2
  202. package/dist/utils/agentdb-runtime-patch.js.map +1 -1
  203. package/dist/utils/audit-logger.d.ts +115 -0
  204. package/dist/utils/audit-logger.d.ts.map +1 -0
  205. package/dist/utils/audit-logger.js +228 -0
  206. package/dist/utils/audit-logger.js.map +1 -0
  207. package/dist/utils/cli.d.ts +1 -1
  208. package/dist/utils/cli.d.ts.map +1 -1
  209. package/dist/utils/cli.js +5 -0
  210. package/dist/utils/cli.js.map +1 -1
  211. package/dist/utils/input-validator.d.ts +116 -0
  212. package/dist/utils/input-validator.d.ts.map +1 -0
  213. package/dist/utils/input-validator.js +299 -0
  214. package/dist/utils/input-validator.js.map +1 -0
  215. package/dist/utils/rate-limiter.js +2 -2
  216. package/dist/utils/rate-limiter.js.map +1 -1
  217. package/package.json +14 -3
  218. package/scripts/postinstall.js +72 -0
@@ -0,0 +1,853 @@
1
+ /**
2
+ * RuVector Unified Intelligence Layer
3
+ *
4
+ * Integrates the FULL power of RuVector ecosystem:
5
+ *
6
+ * @ruvector/sona - Self-Learning:
7
+ * - Micro-LoRA: Ultra-fast rank-1/2 adaptations (~0.1ms)
8
+ * - Base-LoRA: Deeper pattern adaptations
9
+ * - EWC++: Elastic Weight Consolidation (catastrophic forgetting prevention)
10
+ * - ReasoningBank: Pattern storage/retrieval via findPatterns
11
+ * - Trajectory tracking: Learn from execution paths
12
+ *
13
+ * @ruvector/attention - Advanced Attention:
14
+ * - MultiHeadAttention: Standard transformer attention
15
+ * - FlashAttention: Memory-efficient O(n) attention
16
+ * - HyperbolicAttention: Poincaré ball geometry for hierarchies
17
+ * - MoEAttention: Mixture of Experts routing
18
+ * - GraphRoPeAttention: Graph + Rotary Position Embeddings
19
+ * - EdgeFeaturedAttention: Edge-aware graph attention
20
+ * - DualSpaceAttention: Euclidean + Hyperbolic hybrid
21
+ *
22
+ * @ruvector/core - Vector Database:
23
+ * - HNSW indexing: 150x faster than brute force
24
+ * - Real vector similarity search
25
+ * - Cosine/Euclidean/Dot product distance
26
+ *
27
+ * Performance:
28
+ * - Micro-LoRA adaptation: ~0.1ms
29
+ * - FlashAttention: O(n) complexity vs O(n²)
30
+ * - HNSW search: O(log n) vs O(n)
31
+ * - Background learning: Non-blocking
32
+ */
33
+ // Import from @ruvector/sona
34
+ import { SonaEngine } from '@ruvector/sona';
35
+ // Import from @ruvector/attention
36
+ import { MultiHeadAttention, FlashAttention, HyperbolicAttention, MoEAttention, GraphRoPeAttention, DualSpaceAttention,
37
+ // Training (simplified - only AdamOptimizer needed)
38
+ AdamOptimizer,
39
+ // Utilities
40
+ computeAttentionAsync, computeFlashAttentionAsync, computeHyperbolicAttentionAsync,
41
+ // Hyperbolic math
42
+ poincareDistance, projectToPoincareBall, AttentionType, } from '@ruvector/attention';
43
+ // Import from ruvector core (for HNSW)
44
+ import ruvector from 'ruvector';
45
+ export class RuVectorIntelligence {
46
+ config;
47
+ initialized = false;
48
+ initPromise = null;
49
+ // SONA Engine for self-learning
50
+ sona = null;
51
+ // Attention mechanisms
52
+ multiHeadAttention = null;
53
+ flashAttention = null;
54
+ hyperbolicAttention = null;
55
+ moeAttention = null;
56
+ graphAttention = null;
57
+ dualSpaceAttention = null;
58
+ // Training (simplified - removed unused scheduler/loss)
59
+ optimizer = null;
60
+ // HNSW index for vector search
61
+ hnswIndex = null;
62
+ // Active trajectories with LRU tracking
63
+ trajectories = new Map();
64
+ trajectoryAccessOrder = []; // For LRU eviction
65
+ nextTrajectoryId = 0;
66
+ // Agent embeddings with LRU tracking
67
+ agentEmbeddings = new Map();
68
+ agentAccessOrder = []; // For LRU eviction
69
+ // Background learning timer
70
+ learningTimer = null;
71
+ // Cleanup timer for stale trajectories
72
+ cleanupTimer = null;
73
+ // Statistics
74
+ stats = {
75
+ totalRoutings: 0,
76
+ totalTrajectories: 0,
77
+ totalLearningCycles: 0,
78
+ avgRoutingLatencyMs: 0,
79
+ patternsLearned: 0,
80
+ hnswQueries: 0,
81
+ sonaAdaptations: 0,
82
+ evictedTrajectories: 0,
83
+ evictedAgents: 0,
84
+ };
85
+ constructor(config) {
86
+ this.config = {
87
+ embeddingDim: config?.embeddingDim ?? 384,
88
+ hiddenDim: config?.hiddenDim ?? 256,
89
+ enableSona: config?.enableSona ?? true,
90
+ sonaConfig: config?.sonaConfig ?? {},
91
+ attentionType: config?.attentionType ?? 'moe',
92
+ numHeads: config?.numHeads ?? 8,
93
+ numExperts: config?.numExperts ?? 4,
94
+ topK: config?.topK ?? 2,
95
+ curvature: config?.curvature ?? 1.0,
96
+ enableHnsw: config?.enableHnsw ?? true,
97
+ hnswM: config?.hnswM ?? 16,
98
+ hnswEfConstruction: config?.hnswEfConstruction ?? 200,
99
+ enableTrajectories: config?.enableTrajectories ?? true,
100
+ qualityThreshold: config?.qualityThreshold ?? 0.5,
101
+ backgroundIntervalMs: config?.backgroundIntervalMs ?? 60000,
102
+ // Memory limits with LRU eviction
103
+ maxTrajectories: config?.maxTrajectories ?? 1000,
104
+ trajectoryTTLMs: config?.trajectoryTTLMs ?? 1800000, // 30 min
105
+ maxAgentEmbeddings: config?.maxAgentEmbeddings ?? 500,
106
+ };
107
+ // Initialize asynchronously to avoid race conditions
108
+ this.initPromise = this.initializeAsync();
109
+ }
110
+ /**
111
+ * Wait for initialization to complete
112
+ */
113
+ async waitForInit() {
114
+ if (this.initPromise) {
115
+ await this.initPromise;
116
+ }
117
+ }
118
+ /**
119
+ * Initialize all components (async to avoid race conditions)
120
+ */
121
+ async initializeAsync() {
122
+ if (this.initialized)
123
+ return;
124
+ const dim = this.config.embeddingDim;
125
+ // Initialize SONA Engine
126
+ if (this.config.enableSona) {
127
+ try {
128
+ // Ensure all values are explicitly defined (no undefined values)
129
+ const sonaConfig = {
130
+ hiddenDim: this.config.hiddenDim ?? 256,
131
+ embeddingDim: dim ?? 384,
132
+ microLoraRank: 1, // Ultra-fast rank-1
133
+ baseLoraRank: 8,
134
+ microLoraLr: 0.001,
135
+ baseLoraLr: 0.0001,
136
+ ewcLambda: 1000.0, // EWC++ regularization
137
+ patternClusters: 50,
138
+ trajectoryCapacity: 10000,
139
+ qualityThreshold: this.config.qualityThreshold ?? 0.5, // Ensure defined
140
+ enableSimd: true,
141
+ // Only spread defined values from sonaConfig
142
+ ...(this.config.sonaConfig && Object.fromEntries(Object.entries(this.config.sonaConfig).filter(([, v]) => v !== undefined))),
143
+ };
144
+ this.sona = SonaEngine.withConfig(sonaConfig);
145
+ }
146
+ catch (err) {
147
+ console.warn('[RuVectorIntelligence] SONA init failed, using fallback:', err);
148
+ this.sona = null;
149
+ }
150
+ }
151
+ // Initialize attention mechanisms based on type
152
+ try {
153
+ switch (this.config.attentionType) {
154
+ case 'multi_head':
155
+ this.multiHeadAttention = new MultiHeadAttention(dim, this.config.numHeads ?? 8);
156
+ break;
157
+ case 'flash':
158
+ this.flashAttention = new FlashAttention(dim);
159
+ break;
160
+ case 'hyperbolic':
161
+ this.hyperbolicAttention = new HyperbolicAttention(dim, this.config.curvature ?? 1.0);
162
+ break;
163
+ case 'moe':
164
+ const moeConfig = {
165
+ dim,
166
+ numExperts: this.config.numExperts ?? 4,
167
+ topK: this.config.topK ?? 2,
168
+ };
169
+ this.moeAttention = new MoEAttention(moeConfig);
170
+ break;
171
+ case 'graph':
172
+ this.graphAttention = new GraphRoPeAttention(dim, 10000);
173
+ break;
174
+ case 'dual':
175
+ this.dualSpaceAttention = new DualSpaceAttention(dim, this.config.curvature ?? 1.0, 0.5, // Euclidean weight
176
+ 0.5 // Hyperbolic weight
177
+ );
178
+ break;
179
+ }
180
+ }
181
+ catch (err) {
182
+ console.warn('[RuVectorIntelligence] Attention init failed, using fallback:', err);
183
+ }
184
+ // Initialize training components (simplified - only optimizer needed)
185
+ try {
186
+ // AdamOptimizer requires: learning_rate, beta1, beta2, epsilon
187
+ this.optimizer = new AdamOptimizer(0.001, 0.9, 0.999, 1e-8);
188
+ }
189
+ catch (err) {
190
+ console.warn('[RuVectorIntelligence] Optimizer init failed:', err);
191
+ }
192
+ // Initialize HNSW index
193
+ if (this.config.enableHnsw) {
194
+ try {
195
+ this.initializeHnsw();
196
+ }
197
+ catch (err) {
198
+ console.warn('[RuVectorIntelligence] HNSW init failed:', err);
199
+ }
200
+ }
201
+ // Start background learning
202
+ if (this.config.enableSona) {
203
+ this.startBackgroundLearning();
204
+ }
205
+ // Start cleanup timer for stale trajectories
206
+ this.startCleanupTimer();
207
+ this.initialized = true;
208
+ }
209
+ /**
210
+ * Start cleanup timer for stale trajectories
211
+ */
212
+ startCleanupTimer() {
213
+ if (this.cleanupTimer) {
214
+ clearInterval(this.cleanupTimer);
215
+ }
216
+ // Run cleanup every 5 minutes
217
+ this.cleanupTimer = setInterval(() => {
218
+ this.cleanupStaleTrajectories();
219
+ }, 300000);
220
+ }
221
+ /**
222
+ * Clean up trajectories older than TTL
223
+ */
224
+ cleanupStaleTrajectories() {
225
+ const now = Date.now();
226
+ const ttl = this.config.trajectoryTTLMs;
227
+ for (const [id, trajectory] of this.trajectories) {
228
+ if (now - trajectory.startTime > ttl) {
229
+ this.trajectories.delete(id);
230
+ this.trajectoryAccessOrder = this.trajectoryAccessOrder.filter(t => t !== id);
231
+ this.stats.evictedTrajectories++;
232
+ }
233
+ }
234
+ }
235
+ /**
236
+ * LRU eviction for trajectories when limit exceeded
237
+ */
238
+ evictOldestTrajectory() {
239
+ if (this.trajectoryAccessOrder.length === 0)
240
+ return;
241
+ const oldestId = this.trajectoryAccessOrder.shift();
242
+ this.trajectories.delete(oldestId);
243
+ this.stats.evictedTrajectories++;
244
+ }
245
+ /**
246
+ * LRU eviction for agent embeddings when limit exceeded
247
+ */
248
+ evictOldestAgent() {
249
+ if (this.agentAccessOrder.length === 0)
250
+ return;
251
+ const oldestId = this.agentAccessOrder.shift();
252
+ this.agentEmbeddings.delete(oldestId);
253
+ this.stats.evictedAgents++;
254
+ }
255
+ /**
256
+ * Update LRU access order for trajectory
257
+ */
258
+ touchTrajectory(id) {
259
+ const idx = this.trajectoryAccessOrder.indexOf(id);
260
+ if (idx !== -1) {
261
+ this.trajectoryAccessOrder.splice(idx, 1);
262
+ }
263
+ this.trajectoryAccessOrder.push(id);
264
+ }
265
+ /**
266
+ * Update LRU access order for agent
267
+ */
268
+ touchAgent(id) {
269
+ const idx = this.agentAccessOrder.indexOf(id);
270
+ if (idx !== -1) {
271
+ this.agentAccessOrder.splice(idx, 1);
272
+ }
273
+ this.agentAccessOrder.push(id);
274
+ }
275
+ /**
276
+ * Initialize HNSW index for fast vector search
277
+ */
278
+ initializeHnsw() {
279
+ try {
280
+ // Use ruvector core HNSW
281
+ this.hnswIndex = new ruvector.HnswIndex({
282
+ dim: this.config.embeddingDim,
283
+ m: this.config.hnswM,
284
+ efConstruction: this.config.hnswEfConstruction,
285
+ distance: 'cosine',
286
+ });
287
+ }
288
+ catch (error) {
289
+ console.warn('HNSW initialization failed, falling back to brute force:', error);
290
+ this.hnswIndex = null;
291
+ }
292
+ }
293
+ /**
294
+ * Register an agent with its embedding
295
+ *
296
+ * @param agentId - Unique agent identifier
297
+ * @param embedding - Agent's semantic embedding
298
+ * @param metadata - Optional metadata
299
+ * @returns Operation result indicating success/failure
300
+ */
301
+ async registerAgent(agentId, embedding, metadata) {
302
+ await this.waitForInit();
303
+ try {
304
+ const embeddingArray = embedding instanceof Float32Array
305
+ ? embedding
306
+ : new Float32Array(embedding);
307
+ // LRU eviction if at capacity
308
+ while (this.agentEmbeddings.size >= this.config.maxAgentEmbeddings) {
309
+ this.evictOldestAgent();
310
+ }
311
+ // Store in cache and update LRU order
312
+ this.agentEmbeddings.set(agentId, embeddingArray);
313
+ this.touchAgent(agentId);
314
+ // Add to HNSW index
315
+ if (this.hnswIndex) {
316
+ try {
317
+ await this.hnswIndex.add(agentId, embeddingArray);
318
+ }
319
+ catch (error) {
320
+ console.warn(`Failed to add agent ${agentId} to HNSW:`, error);
321
+ }
322
+ }
323
+ return { success: true };
324
+ }
325
+ catch (error) {
326
+ return {
327
+ success: false,
328
+ error: error instanceof Error ? error.message : String(error),
329
+ };
330
+ }
331
+ }
332
+ /**
333
+ * Route a task to the best agent using full intelligence stack
334
+ *
335
+ * Uses:
336
+ * - HNSW for fast candidate retrieval
337
+ * - Attention mechanism for ranking
338
+ * - SONA for adaptive learning
339
+ *
340
+ * @param taskEmbedding - Task's semantic embedding
341
+ * @param candidates - Optional candidate agent IDs
342
+ * @param topK - Number of results
343
+ */
344
+ async routeTask(taskEmbedding, candidates, topK = 5) {
345
+ const startTime = performance.now();
346
+ const query = taskEmbedding instanceof Float32Array
347
+ ? taskEmbedding
348
+ : new Float32Array(taskEmbedding);
349
+ let results = [];
350
+ let usedHnsw = false;
351
+ let usedSona = false;
352
+ // Step 1: Get candidates via HNSW (150x faster than brute force)
353
+ let candidateAgents = [];
354
+ if (this.hnswIndex && this.agentEmbeddings.size > 10) {
355
+ try {
356
+ const hnswResults = await this.hnswIndex.search(query, Math.min(topK * 2, 20));
357
+ candidateAgents = hnswResults.map((r) => ({
358
+ id: r.id,
359
+ embedding: this.agentEmbeddings.get(r.id),
360
+ score: r.score,
361
+ }));
362
+ usedHnsw = true;
363
+ this.stats.hnswQueries++;
364
+ }
365
+ catch (error) {
366
+ // Fallback to all agents
367
+ }
368
+ }
369
+ // Fallback: use provided candidates or all agents
370
+ if (candidateAgents.length === 0) {
371
+ const agentIds = candidates || Array.from(this.agentEmbeddings.keys());
372
+ candidateAgents = agentIds
373
+ .filter(id => this.agentEmbeddings.has(id))
374
+ .map(id => ({
375
+ id,
376
+ embedding: this.agentEmbeddings.get(id),
377
+ score: 0,
378
+ }));
379
+ }
380
+ if (candidateAgents.length === 0) {
381
+ return [];
382
+ }
383
+ // Step 2: Apply SONA Micro-LoRA transformation (~0.1ms)
384
+ let transformedQuery = query;
385
+ if (this.sona) {
386
+ try {
387
+ const loraResult = this.sona.applyMicroLora(Array.from(query));
388
+ transformedQuery = new Float32Array(loraResult);
389
+ usedSona = true;
390
+ this.stats.sonaAdaptations++;
391
+ }
392
+ catch (error) {
393
+ // Use original query
394
+ }
395
+ }
396
+ // Step 3: Compute attention scores
397
+ const keys = candidateAgents.map(c => c.embedding);
398
+ const values = candidateAgents.map(c => c.embedding);
399
+ let attentionOutput;
400
+ let expertWeights;
401
+ switch (this.config.attentionType) {
402
+ case 'moe':
403
+ if (this.moeAttention) {
404
+ attentionOutput = this.moeAttention.compute(transformedQuery, keys, values);
405
+ // MoE provides expert routing weights
406
+ expertWeights = Array.from(attentionOutput.slice(0, this.config.numExperts));
407
+ }
408
+ else {
409
+ attentionOutput = this.computeFallbackAttention(transformedQuery, keys, values);
410
+ }
411
+ break;
412
+ case 'flash':
413
+ if (this.flashAttention) {
414
+ attentionOutput = this.flashAttention.compute(transformedQuery, keys, values);
415
+ }
416
+ else {
417
+ attentionOutput = this.computeFallbackAttention(transformedQuery, keys, values);
418
+ }
419
+ break;
420
+ case 'hyperbolic':
421
+ if (this.hyperbolicAttention) {
422
+ attentionOutput = this.hyperbolicAttention.compute(transformedQuery, keys, values);
423
+ }
424
+ else {
425
+ attentionOutput = this.computeFallbackAttention(transformedQuery, keys, values);
426
+ }
427
+ break;
428
+ case 'dual':
429
+ if (this.dualSpaceAttention) {
430
+ attentionOutput = this.dualSpaceAttention.compute(transformedQuery, keys, values);
431
+ }
432
+ else {
433
+ attentionOutput = this.computeFallbackAttention(transformedQuery, keys, values);
434
+ }
435
+ break;
436
+ default:
437
+ if (this.multiHeadAttention) {
438
+ attentionOutput = this.multiHeadAttention.compute(transformedQuery, keys, values);
439
+ }
440
+ else {
441
+ attentionOutput = this.computeFallbackAttention(transformedQuery, keys, values);
442
+ }
443
+ }
444
+ // Step 4: Compute similarity scores for ranking
445
+ const scores = candidateAgents.map((agent, i) => {
446
+ // Combine HNSW score with attention-weighted score
447
+ const attentionScore = this.cosineSimilarity(attentionOutput, agent.embedding);
448
+ const hnswScore = agent.score || 0;
449
+ // Weighted combination
450
+ const finalScore = usedHnsw
451
+ ? 0.3 * hnswScore + 0.7 * attentionScore
452
+ : attentionScore;
453
+ return {
454
+ agentId: agent.id,
455
+ confidence: finalScore,
456
+ attentionWeights: attentionOutput,
457
+ expertWeights,
458
+ latencyMs: 0,
459
+ usedHnsw,
460
+ usedSona,
461
+ };
462
+ });
463
+ // Sort by confidence
464
+ results = scores
465
+ .sort((a, b) => b.confidence - a.confidence)
466
+ .slice(0, topK);
467
+ // Update latency
468
+ const latencyMs = performance.now() - startTime;
469
+ results.forEach(r => (r.latencyMs = latencyMs));
470
+ // Update stats
471
+ this.stats.totalRoutings++;
472
+ this.stats.avgRoutingLatencyMs =
473
+ (this.stats.avgRoutingLatencyMs * (this.stats.totalRoutings - 1) + latencyMs) /
474
+ this.stats.totalRoutings;
475
+ return results;
476
+ }
477
+ /**
478
+ * Fallback attention using dot product
479
+ */
480
+ computeFallbackAttention(query, keys, values) {
481
+ const dim = query.length;
482
+ const result = new Float32Array(dim);
483
+ let totalWeight = 0;
484
+ for (let i = 0; i < keys.length; i++) {
485
+ const similarity = this.cosineSimilarity(query, keys[i]);
486
+ const weight = Math.exp(similarity * 10); // Temperature scaling
487
+ totalWeight += weight;
488
+ for (let j = 0; j < dim; j++) {
489
+ result[j] += weight * values[i][j];
490
+ }
491
+ }
492
+ // Normalize
493
+ if (totalWeight > 0) {
494
+ for (let j = 0; j < dim; j++) {
495
+ result[j] /= totalWeight;
496
+ }
497
+ }
498
+ return result;
499
+ }
500
+ /**
501
+ * Cosine similarity between two vectors
502
+ */
503
+ cosineSimilarity(a, b) {
504
+ let dot = 0;
505
+ let normA = 0;
506
+ let normB = 0;
507
+ for (let i = 0; i < a.length; i++) {
508
+ dot += a[i] * b[i];
509
+ normA += a[i] * a[i];
510
+ normB += b[i] * b[i];
511
+ }
512
+ const norm = Math.sqrt(normA) * Math.sqrt(normB);
513
+ return norm > 0 ? dot / norm : 0;
514
+ }
515
+ // ==========================================================================
516
+ // Trajectory Learning (SONA)
517
+ // ==========================================================================
518
+ /**
519
+ * Begin a new trajectory for learning
520
+ *
521
+ * @param query - The task query
522
+ * @param embedding - Query embedding
523
+ * @returns Operation result with trajectory ID
524
+ */
525
+ beginTrajectory(query, embedding) {
526
+ if (!this.config.enableTrajectories) {
527
+ return {
528
+ success: false,
529
+ error: 'Trajectories are disabled in config',
530
+ };
531
+ }
532
+ if (!this.sona) {
533
+ return {
534
+ success: false,
535
+ error: 'SONA engine not initialized',
536
+ };
537
+ }
538
+ try {
539
+ // LRU eviction if at capacity
540
+ while (this.trajectories.size >= this.config.maxTrajectories) {
541
+ this.evictOldestTrajectory();
542
+ }
543
+ const trajectoryId = this.nextTrajectoryId++;
544
+ // Start SONA trajectory
545
+ const sonaId = this.sona.beginTrajectory(embedding);
546
+ // Store local trajectory
547
+ this.trajectories.set(trajectoryId, {
548
+ id: sonaId,
549
+ query,
550
+ embedding,
551
+ steps: [],
552
+ contexts: [],
553
+ startTime: Date.now(),
554
+ });
555
+ // Update LRU order
556
+ this.touchTrajectory(trajectoryId);
557
+ this.stats.totalTrajectories++;
558
+ return { success: true, value: trajectoryId };
559
+ }
560
+ catch (error) {
561
+ return {
562
+ success: false,
563
+ error: error instanceof Error ? error.message : String(error),
564
+ };
565
+ }
566
+ }
567
+ /**
568
+ * Add a step to trajectory
569
+ *
570
+ * @param trajectoryId - Trajectory ID from beginTrajectory
571
+ * @param action - Action taken (e.g., agent selected)
572
+ * @param reward - Reward for this step (0-1)
573
+ * @param activations - Optional activations
574
+ * @param attentionWeights - Optional attention weights
575
+ */
576
+ addTrajectoryStep(trajectoryId, action, reward, activations, attentionWeights) {
577
+ const trajectory = this.trajectories.get(trajectoryId);
578
+ if (!trajectory || !this.sona) {
579
+ return;
580
+ }
581
+ const step = {
582
+ action,
583
+ activations: activations || new Array(this.config.hiddenDim).fill(0),
584
+ attentionWeights: attentionWeights || new Array(this.config.numHeads).fill(0),
585
+ reward,
586
+ timestamp: Date.now(),
587
+ };
588
+ trajectory.steps.push(step);
589
+ // Add to SONA
590
+ this.sona.addTrajectoryStep(trajectory.id, step.activations, step.attentionWeights, reward);
591
+ }
592
+ /**
593
+ * Set the route (agent selected) for trajectory
594
+ */
595
+ setTrajectoryRoute(trajectoryId, route) {
596
+ const trajectory = this.trajectories.get(trajectoryId);
597
+ if (!trajectory || !this.sona) {
598
+ return;
599
+ }
600
+ trajectory.route = route;
601
+ this.sona.setTrajectoryRoute(trajectory.id, route);
602
+ }
603
+ /**
604
+ * Add context to trajectory
605
+ */
606
+ addTrajectoryContext(trajectoryId, contextId) {
607
+ const trajectory = this.trajectories.get(trajectoryId);
608
+ if (!trajectory || !this.sona) {
609
+ return;
610
+ }
611
+ trajectory.contexts.push(contextId);
612
+ this.sona.addTrajectoryContext(trajectory.id, contextId);
613
+ }
614
+ /**
615
+ * End trajectory and submit for learning
616
+ *
617
+ * @param trajectoryId - Trajectory ID
618
+ * @param success - Whether the task succeeded
619
+ * @param quality - Quality score (0-1)
620
+ * @returns Learning outcome
621
+ */
622
+ endTrajectory(trajectoryId, success, quality) {
623
+ const trajectory = this.trajectories.get(trajectoryId);
624
+ if (!trajectory || !this.sona) {
625
+ return {
626
+ trajectoryId,
627
+ success,
628
+ quality,
629
+ patternsLearned: 0,
630
+ adaptations: { microLora: false, baseLora: false, ewc: false },
631
+ };
632
+ }
633
+ // End SONA trajectory
634
+ this.sona.endTrajectory(trajectory.id, quality);
635
+ // Cleanup
636
+ this.trajectories.delete(trajectoryId);
637
+ return {
638
+ trajectoryId,
639
+ success,
640
+ quality,
641
+ patternsLearned: quality >= this.config.qualityThreshold ? 1 : 0,
642
+ adaptations: {
643
+ microLora: true, // Micro-LoRA always adapts
644
+ baseLora: quality >= 0.7, // Base-LoRA for high quality
645
+ ewc: quality >= 0.8, // EWC++ for very high quality
646
+ },
647
+ };
648
+ }
649
+ // ==========================================================================
650
+ // Pattern Retrieval (ReasoningBank)
651
+ // ==========================================================================
652
+ /**
653
+ * Find similar learned patterns
654
+ *
655
+ * Uses SONA's ReasoningBank for pattern retrieval
656
+ *
657
+ * @param embedding - Query embedding
658
+ * @param k - Number of patterns to return
659
+ */
660
+ findPatterns(embedding, k = 5) {
661
+ if (!this.sona) {
662
+ return [];
663
+ }
664
+ return this.sona.findPatterns(embedding, k);
665
+ }
666
+ /**
667
+ * Force a learning cycle
668
+ */
669
+ forceLearning() {
670
+ if (!this.sona) {
671
+ return 'SONA not enabled';
672
+ }
673
+ const result = this.sona.forceLearn();
674
+ this.stats.totalLearningCycles++;
675
+ return result;
676
+ }
677
+ // ==========================================================================
678
+ // Background Learning
679
+ // ==========================================================================
680
+ /**
681
+ * Start background learning timer
682
+ */
683
+ startBackgroundLearning() {
684
+ if (this.learningTimer) {
685
+ clearInterval(this.learningTimer);
686
+ }
687
+ this.learningTimer = setInterval(() => {
688
+ if (this.sona) {
689
+ const result = this.sona.tick();
690
+ if (result) {
691
+ this.stats.totalLearningCycles++;
692
+ this.stats.patternsLearned = this.getPatternsCount();
693
+ }
694
+ }
695
+ }, this.config.backgroundIntervalMs);
696
+ }
697
+ /**
698
+ * Get patterns count from SONA stats
699
+ */
700
+ getPatternsCount() {
701
+ if (!this.sona)
702
+ return 0;
703
+ try {
704
+ const stats = JSON.parse(this.sona.getStats());
705
+ return stats.patterns_count || 0;
706
+ }
707
+ catch {
708
+ return 0;
709
+ }
710
+ }
711
+ // ==========================================================================
712
+ // Async Attention (for large batches)
713
+ // ==========================================================================
714
+ /**
715
+ * Compute attention asynchronously
716
+ *
717
+ * Useful for large batches or when non-blocking is required
718
+ */
719
+ async computeAttentionAsync(query, keys, values, type) {
720
+ switch (type) {
721
+ case 'flash':
722
+ return computeFlashAttentionAsync(query, keys, values);
723
+ case 'hyperbolic':
724
+ return computeHyperbolicAttentionAsync(query, keys, values, this.config.curvature);
725
+ default:
726
+ return computeAttentionAsync(query, keys, values, AttentionType.MultiHead);
727
+ }
728
+ }
729
+ // ==========================================================================
730
+ // Hyperbolic Operations (for hierarchical structures)
731
+ // ==========================================================================
732
+ /**
733
+ * Compute Poincaré distance between two embeddings
734
+ *
735
+ * Useful for hierarchical agent structures
736
+ */
737
+ poincareDistance(a, b) {
738
+ return poincareDistance(a, b, this.config.curvature);
739
+ }
740
+ /**
741
+ * Project embedding to Poincaré ball
742
+ */
743
+ projectToPoincare(embedding) {
744
+ return projectToPoincareBall(embedding, this.config.curvature);
745
+ }
746
+ // ==========================================================================
747
+ // Statistics & Status
748
+ // ==========================================================================
749
+ /**
750
+ * Get intelligence layer statistics
751
+ */
752
+ getStats() {
753
+ let sonaStats = null;
754
+ if (this.sona) {
755
+ try {
756
+ sonaStats = JSON.parse(this.sona.getStats());
757
+ }
758
+ catch { }
759
+ }
760
+ return {
761
+ ...this.stats,
762
+ sonaStats,
763
+ };
764
+ }
765
+ /**
766
+ * Enable/disable the intelligence layer
767
+ */
768
+ setEnabled(enabled) {
769
+ if (this.sona) {
770
+ this.sona.setEnabled(enabled);
771
+ }
772
+ }
773
+ /**
774
+ * Check if enabled
775
+ */
776
+ isEnabled() {
777
+ return this.sona?.isEnabled() ?? false;
778
+ }
779
+ /**
780
+ * Cleanup resources
781
+ */
782
+ dispose() {
783
+ if (this.learningTimer) {
784
+ clearInterval(this.learningTimer);
785
+ this.learningTimer = null;
786
+ }
787
+ if (this.cleanupTimer) {
788
+ clearInterval(this.cleanupTimer);
789
+ this.cleanupTimer = null;
790
+ }
791
+ // Flush SONA
792
+ if (this.sona) {
793
+ this.sona.flush();
794
+ }
795
+ // Clear caches and LRU tracking
796
+ this.trajectories.clear();
797
+ this.trajectoryAccessOrder = [];
798
+ this.agentEmbeddings.clear();
799
+ this.agentAccessOrder = [];
800
+ }
801
+ }
802
+ /**
803
+ * Create a default intelligence layer
804
+ */
805
+ export function createIntelligenceLayer(config) {
806
+ return new RuVectorIntelligence(config);
807
+ }
808
+ /**
809
+ * Presets for common configurations
810
+ */
811
+ export const IntelligencePresets = {
812
+ /** Fast routing with MoE and minimal learning */
813
+ fast: {
814
+ attentionType: 'moe',
815
+ numExperts: 4,
816
+ topK: 2,
817
+ enableTrajectories: false,
818
+ backgroundIntervalMs: 300000, // 5 min
819
+ },
820
+ /** Balanced performance and learning */
821
+ balanced: {
822
+ attentionType: 'moe',
823
+ numExperts: 4,
824
+ topK: 2,
825
+ enableTrajectories: true,
826
+ backgroundIntervalMs: 60000, // 1 min
827
+ qualityThreshold: 0.5,
828
+ },
829
+ /** Maximum learning for development */
830
+ learning: {
831
+ attentionType: 'dual',
832
+ enableTrajectories: true,
833
+ backgroundIntervalMs: 30000, // 30 sec
834
+ qualityThreshold: 0.3,
835
+ sonaConfig: {
836
+ microLoraRank: 2,
837
+ baseLoraRank: 16,
838
+ trajectoryCapacity: 50000,
839
+ },
840
+ },
841
+ /** Hierarchical structures (Poincaré geometry) */
842
+ hierarchical: {
843
+ attentionType: 'hyperbolic',
844
+ curvature: 1.0,
845
+ enableTrajectories: true,
846
+ },
847
+ /** Graph-based reasoning */
848
+ graph: {
849
+ attentionType: 'graph',
850
+ enableTrajectories: true,
851
+ },
852
+ };
853
+ //# sourceMappingURL=RuVectorIntelligence.js.map