agentic-flow 2.0.1-alpha.5 → 2.0.1-alpha.8

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