@holoscript/framework 6.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (329) hide show
  1. package/ALL-test-results.json +1 -0
  2. package/CHANGELOG.md +8 -0
  3. package/LICENSE +21 -0
  4. package/ROADMAP.md +175 -0
  5. package/dist/AgentManifest-CB4xM-Ma.d.cts +704 -0
  6. package/dist/AgentManifest-CB4xM-Ma.d.ts +704 -0
  7. package/dist/BehaviorTree-BrBFECv5.d.cts +103 -0
  8. package/dist/BehaviorTree-BrBFECv5.d.ts +103 -0
  9. package/dist/InvisibleWallet-BB6tFvRA.d.cts +1732 -0
  10. package/dist/InvisibleWallet-rtRrBOA8.d.ts +1732 -0
  11. package/dist/OrchestratorAgent-BvWgf9uw.d.cts +798 -0
  12. package/dist/OrchestratorAgent-Q_CbVTmO.d.ts +798 -0
  13. package/dist/agents/index.cjs +4790 -0
  14. package/dist/agents/index.d.cts +1788 -0
  15. package/dist/agents/index.d.ts +1788 -0
  16. package/dist/agents/index.js +4695 -0
  17. package/dist/ai/index.cjs +5347 -0
  18. package/dist/ai/index.d.cts +1753 -0
  19. package/dist/ai/index.d.ts +1753 -0
  20. package/dist/ai/index.js +5244 -0
  21. package/dist/behavior.cjs +449 -0
  22. package/dist/behavior.d.cts +130 -0
  23. package/dist/behavior.d.ts +130 -0
  24. package/dist/behavior.js +407 -0
  25. package/dist/economy/index.cjs +3659 -0
  26. package/dist/economy/index.d.cts +747 -0
  27. package/dist/economy/index.d.ts +747 -0
  28. package/dist/economy/index.js +3617 -0
  29. package/dist/implementations-D9T3un9D.d.cts +236 -0
  30. package/dist/implementations-D9T3un9D.d.ts +236 -0
  31. package/dist/index.cjs +24550 -0
  32. package/dist/index.d.cts +1729 -0
  33. package/dist/index.d.ts +1729 -0
  34. package/dist/index.js +24277 -0
  35. package/dist/learning/index.cjs +219 -0
  36. package/dist/learning/index.d.cts +104 -0
  37. package/dist/learning/index.d.ts +104 -0
  38. package/dist/learning/index.js +189 -0
  39. package/dist/negotiation/index.cjs +970 -0
  40. package/dist/negotiation/index.d.cts +610 -0
  41. package/dist/negotiation/index.d.ts +610 -0
  42. package/dist/negotiation/index.js +931 -0
  43. package/dist/skills/index.cjs +1118 -0
  44. package/dist/skills/index.d.cts +289 -0
  45. package/dist/skills/index.d.ts +289 -0
  46. package/dist/skills/index.js +1079 -0
  47. package/dist/swarm/index.cjs +5268 -0
  48. package/dist/swarm/index.d.cts +2433 -0
  49. package/dist/swarm/index.d.ts +2433 -0
  50. package/dist/swarm/index.js +5221 -0
  51. package/dist/training/index.cjs +2745 -0
  52. package/dist/training/index.d.cts +1734 -0
  53. package/dist/training/index.d.ts +1734 -0
  54. package/dist/training/index.js +2687 -0
  55. package/extract-failures.js +10 -0
  56. package/package.json +82 -0
  57. package/src/__tests__/bounty-marketplace.test.ts +374 -0
  58. package/src/__tests__/delegation.test.ts +144 -0
  59. package/src/__tests__/distributed-claimer.test.ts +147 -0
  60. package/src/__tests__/done-log-audit.test.ts +342 -0
  61. package/src/__tests__/framework.test.ts +865 -0
  62. package/src/__tests__/goal-synthesizer.test.ts +236 -0
  63. package/src/__tests__/presence.test.ts +223 -0
  64. package/src/__tests__/protocol-agent.test.ts +254 -0
  65. package/src/__tests__/revenue-splitter.test.ts +114 -0
  66. package/src/__tests__/scenario-driven-todo.test.ts +197 -0
  67. package/src/__tests__/self-improve.test.ts +349 -0
  68. package/src/__tests__/service-lifecycle.test.ts +237 -0
  69. package/src/__tests__/skill-router.test.ts +121 -0
  70. package/src/agents/AgentManifest.ts +493 -0
  71. package/src/agents/AgentRegistry.ts +475 -0
  72. package/src/agents/AgentTypes.ts +585 -0
  73. package/src/agents/AgentWalletRegistry.ts +83 -0
  74. package/src/agents/AuthenticatedCRDT.ts +388 -0
  75. package/src/agents/CapabilityMatcher.ts +453 -0
  76. package/src/agents/CrossRealityHandoff.ts +305 -0
  77. package/src/agents/CulturalMemory.ts +454 -0
  78. package/src/agents/FederatedRegistryAdapter.ts +429 -0
  79. package/src/agents/NormEngine.ts +450 -0
  80. package/src/agents/OrchestratorAgent.ts +414 -0
  81. package/src/agents/SkillWorkflowEngine.ts +472 -0
  82. package/src/agents/TaskDelegationService.ts +551 -0
  83. package/src/agents/__tests__/AgentManifest.prod.test.ts +134 -0
  84. package/src/agents/__tests__/AgentManifest.test.ts +182 -0
  85. package/src/agents/__tests__/AgentModule.test.ts +864 -0
  86. package/src/agents/__tests__/AgentRegistry.prod.test.ts +125 -0
  87. package/src/agents/__tests__/AgentRegistry.test.ts +148 -0
  88. package/src/agents/__tests__/AgentTypes.test.ts +534 -0
  89. package/src/agents/__tests__/AgentWalletRegistry.test.ts +152 -0
  90. package/src/agents/__tests__/AuthenticatedCRDT.test.ts +558 -0
  91. package/src/agents/__tests__/CapabilityMatcher.prod.test.ts +117 -0
  92. package/src/agents/__tests__/CapabilityMatcher.test.ts +178 -0
  93. package/src/agents/__tests__/CrossRealityHandoff.test.ts +402 -0
  94. package/src/agents/__tests__/CulturalMemory.test.ts +200 -0
  95. package/src/agents/__tests__/FederatedRegistryAdapter.test.ts +409 -0
  96. package/src/agents/__tests__/NormEngine.test.ts +276 -0
  97. package/src/agents/__tests__/OrchestratorAgent.test.ts +182 -0
  98. package/src/agents/__tests__/SkillWorkflowEngine.test.ts +357 -0
  99. package/src/agents/__tests__/TaskDelegationService.test.ts +446 -0
  100. package/src/agents/index.ts +107 -0
  101. package/src/agents/spatial-comms/Layer1RealTime.ts +621 -0
  102. package/src/agents/spatial-comms/Layer2A2A.ts +661 -0
  103. package/src/agents/spatial-comms/Layer3MCP.ts +651 -0
  104. package/src/agents/spatial-comms/ProtocolTypes.ts +543 -0
  105. package/src/agents/spatial-comms/SpatialCommClient.ts +483 -0
  106. package/src/agents/spatial-comms/__tests__/performance-benchmark.test.ts +465 -0
  107. package/src/agents/spatial-comms/examples/multi-agent-world-creation.ts +409 -0
  108. package/src/agents/spatial-comms/index.ts +66 -0
  109. package/src/ai/AIAdapter.ts +313 -0
  110. package/src/ai/AICopilot.ts +331 -0
  111. package/src/ai/AIOutputValidator.ts +203 -0
  112. package/src/ai/BTNodes.ts +239 -0
  113. package/src/ai/BehaviorSelector.ts +135 -0
  114. package/src/ai/BehaviorTree.ts +153 -0
  115. package/src/ai/Blackboard.ts +165 -0
  116. package/src/ai/GenerationAnalytics.ts +461 -0
  117. package/src/ai/GenerationCache.ts +265 -0
  118. package/src/ai/GoalPlanner.ts +165 -0
  119. package/src/ai/HoloScriptGenerator.ts +580 -0
  120. package/src/ai/InfluenceMap.ts +180 -0
  121. package/src/ai/NavMesh.ts +168 -0
  122. package/src/ai/PerceptionSystem.ts +178 -0
  123. package/src/ai/PromptTemplates.ts +453 -0
  124. package/src/ai/SemanticSearchService.ts +80 -0
  125. package/src/ai/StateMachine.ts +196 -0
  126. package/src/ai/SteeringBehavior.ts +150 -0
  127. package/src/ai/SteeringBehaviors.ts +244 -0
  128. package/src/ai/TrainingDataGenerator.ts +1082 -0
  129. package/src/ai/UtilityAI.ts +145 -0
  130. package/src/ai/__tests__/AIAdapter.prod.test.ts +259 -0
  131. package/src/ai/__tests__/AIAdapter.test.ts +109 -0
  132. package/src/ai/__tests__/AICopilot.prod.test.ts +341 -0
  133. package/src/ai/__tests__/AICopilot.test.ts +178 -0
  134. package/src/ai/__tests__/AIOutputValidator.prod.test.ts +226 -0
  135. package/src/ai/__tests__/AIOutputValidator.test.ts +138 -0
  136. package/src/ai/__tests__/BTNodes.prod.test.ts +391 -0
  137. package/src/ai/__tests__/BTNodes.test.ts +263 -0
  138. package/src/ai/__tests__/BehaviorSelector.prod.test.ts +129 -0
  139. package/src/ai/__tests__/BehaviorSelector.test.ts +132 -0
  140. package/src/ai/__tests__/BehaviorTree.prod.test.ts +266 -0
  141. package/src/ai/__tests__/BehaviorTree.test.ts +216 -0
  142. package/src/ai/__tests__/Blackboard.prod.test.ts +339 -0
  143. package/src/ai/__tests__/Blackboard.test.ts +183 -0
  144. package/src/ai/__tests__/GenerationAnalytics.prod.test.ts +141 -0
  145. package/src/ai/__tests__/GenerationAnalytics.test.ts +165 -0
  146. package/src/ai/__tests__/GenerationCache.prod.test.ts +144 -0
  147. package/src/ai/__tests__/GenerationCache.test.ts +171 -0
  148. package/src/ai/__tests__/GoalPlanner.prod.test.ts +189 -0
  149. package/src/ai/__tests__/GoalPlanner.test.ts +137 -0
  150. package/src/ai/__tests__/GoalPlannerDepth.prod.test.ts +217 -0
  151. package/src/ai/__tests__/HoloScriptGenerator.test.ts +125 -0
  152. package/src/ai/__tests__/InfluenceMap.prod.test.ts +146 -0
  153. package/src/ai/__tests__/InfluenceMap.test.ts +149 -0
  154. package/src/ai/__tests__/NavMesh.prod.test.ts +141 -0
  155. package/src/ai/__tests__/NavMesh.test.ts +159 -0
  156. package/src/ai/__tests__/PerceptionSystem.prod.test.ts +135 -0
  157. package/src/ai/__tests__/PerceptionSystem.test.ts +250 -0
  158. package/src/ai/__tests__/PromptTemplates.prod.test.ts +313 -0
  159. package/src/ai/__tests__/PromptTemplates.test.ts +146 -0
  160. package/src/ai/__tests__/SemanticSearch.test.ts +37 -0
  161. package/src/ai/__tests__/StateMachine.prod.test.ts +162 -0
  162. package/src/ai/__tests__/StateMachine.test.ts +163 -0
  163. package/src/ai/__tests__/SteeringBehavior.prod.test.ts +251 -0
  164. package/src/ai/__tests__/SteeringBehavior.test.ts +135 -0
  165. package/src/ai/__tests__/SteeringBehaviors.prod.test.ts +133 -0
  166. package/src/ai/__tests__/SteeringBehaviors.test.ts +151 -0
  167. package/src/ai/__tests__/TrainingDataGenerator.prod.test.ts +286 -0
  168. package/src/ai/__tests__/TrainingDataGenerator.test.ts +286 -0
  169. package/src/ai/__tests__/UtilityAI.prod.test.ts +207 -0
  170. package/src/ai/__tests__/UtilityAI.test.ts +155 -0
  171. package/src/ai/__tests__/adapters.prod.test.ts +263 -0
  172. package/src/ai/__tests__/adapters.test.ts +320 -0
  173. package/src/ai/adapters.ts +1585 -0
  174. package/src/ai/index.ts +130 -0
  175. package/src/behavior/BehaviorPresets.ts +140 -0
  176. package/src/behavior/BehaviorTree.ts +236 -0
  177. package/src/behavior/StateMachine.ts +176 -0
  178. package/src/behavior/StateTrait.ts +67 -0
  179. package/src/behavior/index.ts +8 -0
  180. package/src/behavior.ts +8 -0
  181. package/src/board/audit.ts +284 -0
  182. package/src/board/board-ops.ts +336 -0
  183. package/src/board/board-types.ts +302 -0
  184. package/src/board/index.ts +69 -0
  185. package/src/define-agent.ts +46 -0
  186. package/src/define-team.ts +33 -0
  187. package/src/delegation.ts +265 -0
  188. package/src/distributed-claimer.ts +228 -0
  189. package/src/economy/AgentBudgetEnforcer.ts +464 -0
  190. package/src/economy/BountyManager.ts +185 -0
  191. package/src/economy/CreatorRevenueAggregator.ts +460 -0
  192. package/src/economy/InvisibleWallet.ts +82 -0
  193. package/src/economy/KnowledgeMarketplace.ts +193 -0
  194. package/src/economy/PaymentWebhookService.ts +512 -0
  195. package/src/economy/RevenueSplitter.ts +156 -0
  196. package/src/economy/SubscriptionManager.ts +546 -0
  197. package/src/economy/UnifiedBudgetOptimizer.ts +635 -0
  198. package/src/economy/UsageMeter.ts +440 -0
  199. package/src/economy/_core-stubs.ts +219 -0
  200. package/src/economy/index.ts +100 -0
  201. package/src/economy/x402-facilitator.ts +1978 -0
  202. package/src/index.ts +348 -0
  203. package/src/knowledge/__tests__/knowledge-consolidator.test.ts +444 -0
  204. package/src/knowledge/__tests__/knowledge-store-vector.test.ts +291 -0
  205. package/src/knowledge/brain.ts +167 -0
  206. package/src/knowledge/consolidation.ts +581 -0
  207. package/src/knowledge/knowledge-consolidator.ts +510 -0
  208. package/src/knowledge/knowledge-store.ts +616 -0
  209. package/src/learning/MemoryConsolidator.ts +102 -0
  210. package/src/learning/MemoryScorer.ts +69 -0
  211. package/src/learning/ProceduralCompiler.ts +45 -0
  212. package/src/learning/SemanticClusterer.ts +66 -0
  213. package/src/learning/index.ts +8 -0
  214. package/src/llm/llm-adapter.ts +159 -0
  215. package/src/mesh/index.ts +309 -0
  216. package/src/negotiation/NegotiationProtocol.ts +694 -0
  217. package/src/negotiation/NegotiationTypes.ts +473 -0
  218. package/src/negotiation/VotingMechanisms.ts +691 -0
  219. package/src/negotiation/index.ts +49 -0
  220. package/src/protocol/goal-synthesizer.ts +317 -0
  221. package/src/protocol/implementations.ts +474 -0
  222. package/src/protocol/micro-phase-decomposer.ts +299 -0
  223. package/src/protocol/micro-step-decomposer.test.ts +306 -0
  224. package/src/protocol-agent.test.ts +353 -0
  225. package/src/protocol-agent.ts +670 -0
  226. package/src/self-improve/absorb-scanner.ts +252 -0
  227. package/src/self-improve/evolution-engine.ts +149 -0
  228. package/src/self-improve/framework-absorber.ts +214 -0
  229. package/src/self-improve/index.ts +50 -0
  230. package/src/self-improve/prompt-optimizer.ts +212 -0
  231. package/src/self-improve/test-generator.ts +175 -0
  232. package/src/skill-router.ts +186 -0
  233. package/src/skills/index.ts +5 -0
  234. package/src/skills/skill-md-bridge.ts +1699 -0
  235. package/src/swarm/ACOEngine.ts +261 -0
  236. package/src/swarm/CollectiveIntelligence.ts +383 -0
  237. package/src/swarm/ContributionSynthesizer.ts +481 -0
  238. package/src/swarm/LeaderElection.ts +393 -0
  239. package/src/swarm/PSOEngine.ts +206 -0
  240. package/src/swarm/QuorumPolicy.ts +173 -0
  241. package/src/swarm/SwarmCoordinator.ts +335 -0
  242. package/src/swarm/SwarmManager.ts +442 -0
  243. package/src/swarm/SwarmMembership.ts +456 -0
  244. package/src/swarm/VotingRound.ts +255 -0
  245. package/src/swarm/__tests__/ACOEngine.prod.test.ts +164 -0
  246. package/src/swarm/__tests__/ACOEngine.test.ts +117 -0
  247. package/src/swarm/__tests__/CollectiveIntelligence.prod.test.ts +296 -0
  248. package/src/swarm/__tests__/CollectiveIntelligence.test.ts +457 -0
  249. package/src/swarm/__tests__/ContributionSynthesizer.prod.test.ts +269 -0
  250. package/src/swarm/__tests__/ContributionSynthesizer.test.ts +254 -0
  251. package/src/swarm/__tests__/LeaderElection.prod.test.ts +196 -0
  252. package/src/swarm/__tests__/LeaderElection.test.ts +151 -0
  253. package/src/swarm/__tests__/PSOEngine.prod.test.ts +162 -0
  254. package/src/swarm/__tests__/PSOEngine.test.ts +106 -0
  255. package/src/swarm/__tests__/QuorumPolicy.prod.test.ts +216 -0
  256. package/src/swarm/__tests__/QuorumPolicy.test.ts +177 -0
  257. package/src/swarm/__tests__/SwarmCoordinator.prod.test.ts +186 -0
  258. package/src/swarm/__tests__/SwarmCoordinator.test.ts +167 -0
  259. package/src/swarm/__tests__/SwarmManager.prod.test.ts +308 -0
  260. package/src/swarm/__tests__/SwarmManager.test.ts +373 -0
  261. package/src/swarm/__tests__/SwarmMembership.prod.test.ts +273 -0
  262. package/src/swarm/__tests__/SwarmMembership.test.ts +264 -0
  263. package/src/swarm/__tests__/VotingRound.prod.test.ts +233 -0
  264. package/src/swarm/__tests__/VotingRound.test.ts +174 -0
  265. package/src/swarm/analytics/SwarmInspector.ts +476 -0
  266. package/src/swarm/analytics/SwarmMetrics.ts +449 -0
  267. package/src/swarm/analytics/__tests__/SwarmInspector.prod.test.ts +366 -0
  268. package/src/swarm/analytics/__tests__/SwarmInspector.test.ts +454 -0
  269. package/src/swarm/analytics/__tests__/SwarmMetrics.prod.test.ts +254 -0
  270. package/src/swarm/analytics/__tests__/SwarmMetrics.test.ts +370 -0
  271. package/src/swarm/analytics/index.ts +7 -0
  272. package/src/swarm/index.ts +69 -0
  273. package/src/swarm/messaging/BroadcastChannel.ts +509 -0
  274. package/src/swarm/messaging/GossipProtocol.ts +565 -0
  275. package/src/swarm/messaging/SwarmEventBus.ts +443 -0
  276. package/src/swarm/messaging/__tests__/BroadcastChannel.prod.test.ts +331 -0
  277. package/src/swarm/messaging/__tests__/BroadcastChannel.test.ts +333 -0
  278. package/src/swarm/messaging/__tests__/GossipProtocol.prod.test.ts +356 -0
  279. package/src/swarm/messaging/__tests__/GossipProtocol.test.ts +437 -0
  280. package/src/swarm/messaging/__tests__/SwarmEventBus.prod.test.ts +191 -0
  281. package/src/swarm/messaging/__tests__/SwarmEventBus.test.ts +247 -0
  282. package/src/swarm/messaging/index.ts +8 -0
  283. package/src/swarm/spatial/FlockingBehavior.ts +462 -0
  284. package/src/swarm/spatial/FormationController.ts +500 -0
  285. package/src/swarm/spatial/Vector3.ts +170 -0
  286. package/src/swarm/spatial/ZoneClaiming.ts +509 -0
  287. package/src/swarm/spatial/__tests__/FlockingBehavior.prod.test.ts +239 -0
  288. package/src/swarm/spatial/__tests__/FlockingBehavior.test.ts +298 -0
  289. package/src/swarm/spatial/__tests__/FormationController.prod.test.ts +240 -0
  290. package/src/swarm/spatial/__tests__/FormationController.test.ts +297 -0
  291. package/src/swarm/spatial/__tests__/Vector3.prod.test.ts +283 -0
  292. package/src/swarm/spatial/__tests__/Vector3.test.ts +224 -0
  293. package/src/swarm/spatial/__tests__/ZoneClaiming.prod.test.ts +246 -0
  294. package/src/swarm/spatial/__tests__/ZoneClaiming.test.ts +374 -0
  295. package/src/swarm/spatial/index.ts +28 -0
  296. package/src/team.ts +1245 -0
  297. package/src/training/LRScheduler.ts +377 -0
  298. package/src/training/QualityScoringPipeline.ts +139 -0
  299. package/src/training/SoftDedup.ts +461 -0
  300. package/src/training/SparsityMonitor.ts +685 -0
  301. package/src/training/SparsityMonitorTypes.ts +209 -0
  302. package/src/training/SpatialTrainingDataGenerator.ts +1526 -0
  303. package/src/training/SpatialTrainingDataTypes.ts +216 -0
  304. package/src/training/TrainingPipelineConfig.ts +215 -0
  305. package/src/training/constants.ts +94 -0
  306. package/src/training/index.ts +138 -0
  307. package/src/training/schema.ts +147 -0
  308. package/src/training/scripts/generate-novel-use-cases-dataset.ts +272 -0
  309. package/src/training/scripts/generate-spatial-dataset.ts +521 -0
  310. package/src/training/training/data/novel-use-cases.jsonl +153 -0
  311. package/src/training/training/data/spatial-reasoning-10k.jsonl +9354 -0
  312. package/src/training/trainingmonkey/TrainingMonkeyIntegration.ts +477 -0
  313. package/src/training/trainingmonkey/TrainingMonkeyTypes.ts +230 -0
  314. package/src/training/trainingmonkey/index.ts +26 -0
  315. package/src/training/trait-mappings.ts +157 -0
  316. package/src/types/core-stubs.d.ts +113 -0
  317. package/src/types.ts +304 -0
  318. package/test-output.txt +0 -0
  319. package/test-result.json +1 -0
  320. package/tsc-errors.txt +4 -0
  321. package/tsc_output.txt +0 -0
  322. package/tsconfig.json +14 -0
  323. package/tsup-learning-esm.config.ts +12 -0
  324. package/tsup.config.ts +21 -0
  325. package/typescript-errors-2.txt +0 -0
  326. package/typescript-errors.txt +22 -0
  327. package/vitest-log-utf8.txt +268 -0
  328. package/vitest-log.txt +0 -0
  329. package/vitest.config.ts +8 -0
@@ -0,0 +1,443 @@
1
+ /**
2
+ * SwarmEventBus - Central event coordination for swarm communication
3
+ * HoloScript v3.2 - Autonomous Agent Swarms
4
+ *
5
+ * Decoupled pub/sub messaging between swarm components
6
+ */
7
+
8
+ /**
9
+ * Event priority levels
10
+ */
11
+ export type EventPriority = 'low' | 'normal' | 'high' | 'critical';
12
+
13
+ /**
14
+ * Swarm event interface
15
+ */
16
+ export interface ISwarmEvent {
17
+ id: string;
18
+ type: string;
19
+ source: string;
20
+ target?: string | string[];
21
+ payload: unknown;
22
+ timestamp: number;
23
+ priority: EventPriority;
24
+ ttl?: number; // Time-to-live in milliseconds
25
+ metadata?: Record<string, unknown>;
26
+ }
27
+
28
+ /**
29
+ * Event subscription
30
+ */
31
+ export interface IEventSubscription {
32
+ id: string;
33
+ pattern: string | RegExp;
34
+ handler: EventHandler;
35
+ priority: EventPriority;
36
+ once: boolean;
37
+ }
38
+
39
+ /**
40
+ * Event handler function type
41
+ */
42
+ export type EventHandler = (event: ISwarmEvent) => void | Promise<void>;
43
+
44
+ /**
45
+ * Event bus configuration
46
+ */
47
+ export interface IEventBusConfig {
48
+ /** Maximum events in queue */
49
+ maxQueueSize: number;
50
+ /** Default TTL for events */
51
+ defaultTTL: number;
52
+ /** Enable async event processing */
53
+ asyncProcessing: boolean;
54
+ /** Max concurrent async handlers */
55
+ maxConcurrent: number;
56
+ /** Dead letter queue enabled */
57
+ enableDeadLetter: boolean;
58
+ }
59
+
60
+ /**
61
+ * Event bus statistics
62
+ */
63
+ export interface IEventBusStats {
64
+ eventsPublished: number;
65
+ eventsDelivered: number;
66
+ eventsDropped: number;
67
+ subscriptions: number;
68
+ pendingEvents: number;
69
+ deadLetterCount: number;
70
+ }
71
+
72
+ /**
73
+ * SwarmEventBus - Central pub/sub event bus for swarm communication
74
+ */
75
+ export class SwarmEventBus {
76
+ private subscriptions: Map<string, IEventSubscription> = new Map();
77
+ private eventQueue: ISwarmEvent[] = [];
78
+ private deadLetterQueue: ISwarmEvent[] = [];
79
+ private processing = false;
80
+ private config: IEventBusConfig;
81
+ private stats: IEventBusStats = {
82
+ eventsPublished: 0,
83
+ eventsDelivered: 0,
84
+ eventsDropped: 0,
85
+ subscriptions: 0,
86
+ pendingEvents: 0,
87
+ deadLetterCount: 0,
88
+ };
89
+ private nextId = 1;
90
+
91
+ constructor(config?: Partial<IEventBusConfig>) {
92
+ this.config = {
93
+ maxQueueSize: 10000,
94
+ defaultTTL: 30000,
95
+ asyncProcessing: true,
96
+ maxConcurrent: 10,
97
+ enableDeadLetter: true,
98
+ ...config,
99
+ };
100
+ }
101
+
102
+ /**
103
+ * Publish an event to the bus
104
+ */
105
+ publish(
106
+ type: string,
107
+ source: string,
108
+ payload: unknown,
109
+ options: {
110
+ target?: string | string[];
111
+ priority?: EventPriority;
112
+ ttl?: number;
113
+ metadata?: Record<string, unknown>;
114
+ } = {}
115
+ ): string {
116
+ const id = `evt-${this.nextId++}-${Date.now()}`;
117
+
118
+ const event: ISwarmEvent = {
119
+ id,
120
+ type,
121
+ source,
122
+ target: options.target,
123
+ payload,
124
+ timestamp: Date.now(),
125
+ priority: options.priority ?? 'normal',
126
+ ttl: options.ttl ?? this.config.defaultTTL,
127
+ metadata: options.metadata,
128
+ };
129
+
130
+ this.stats.eventsPublished++;
131
+
132
+ // Check queue size
133
+ if (this.eventQueue.length >= this.config.maxQueueSize) {
134
+ this.stats.eventsDropped++;
135
+ if (this.config.enableDeadLetter) {
136
+ this.deadLetterQueue.push(event);
137
+ this.stats.deadLetterCount++;
138
+ }
139
+ return id;
140
+ }
141
+
142
+ // Insert by priority
143
+ this.insertByPriority(event);
144
+ this.stats.pendingEvents = this.eventQueue.length;
145
+
146
+ // Process if not already processing
147
+ if (this.config.asyncProcessing && !this.processing) {
148
+ this.processQueue().catch(() => {});
149
+ }
150
+
151
+ return id;
152
+ }
153
+
154
+ /**
155
+ * Insert event maintaining priority order
156
+ */
157
+ private insertByPriority(event: ISwarmEvent): void {
158
+ const priorityOrder = ['low', 'normal', 'high', 'critical'];
159
+ const eventPriority = priorityOrder.indexOf(event.priority);
160
+
161
+ // Find insertion point
162
+ let insertIndex = this.eventQueue.length;
163
+ for (let i = 0; i < this.eventQueue.length; i++) {
164
+ const queuedPriority = priorityOrder.indexOf(this.eventQueue[i].priority);
165
+ if (eventPriority > queuedPriority) {
166
+ insertIndex = i;
167
+ break;
168
+ }
169
+ }
170
+
171
+ this.eventQueue.splice(insertIndex, 0, event);
172
+ }
173
+
174
+ /**
175
+ * Subscribe to events matching a pattern
176
+ */
177
+ subscribe(
178
+ pattern: string | RegExp,
179
+ handler: EventHandler,
180
+ options: {
181
+ priority?: EventPriority;
182
+ once?: boolean;
183
+ } = {}
184
+ ): string {
185
+ const id = `sub-${this.nextId++}`;
186
+
187
+ const subscription: IEventSubscription = {
188
+ id,
189
+ pattern,
190
+ handler,
191
+ priority: options.priority ?? 'normal',
192
+ once: options.once ?? false,
193
+ };
194
+
195
+ this.subscriptions.set(id, subscription);
196
+ this.stats.subscriptions = this.subscriptions.size;
197
+
198
+ return id;
199
+ }
200
+
201
+ /**
202
+ * Subscribe to an event type once
203
+ */
204
+ once(pattern: string | RegExp, handler: EventHandler): string {
205
+ return this.subscribe(pattern, handler, { once: true });
206
+ }
207
+
208
+ /**
209
+ * Unsubscribe from events
210
+ */
211
+ unsubscribe(subscriptionId: string): boolean {
212
+ const result = this.subscriptions.delete(subscriptionId);
213
+ this.stats.subscriptions = this.subscriptions.size;
214
+ return result;
215
+ }
216
+
217
+ /**
218
+ * Clear all subscriptions
219
+ */
220
+ clearSubscriptions(): void {
221
+ this.subscriptions.clear();
222
+ this.stats.subscriptions = 0;
223
+ }
224
+
225
+ /**
226
+ * Process the event queue (public for testing)
227
+ */
228
+ async processQueue(): Promise<void> {
229
+ if (this.processing) return;
230
+ this.processing = true;
231
+
232
+ try {
233
+ while (this.eventQueue.length > 0) {
234
+ const event = this.eventQueue.shift()!;
235
+ this.stats.pendingEvents = this.eventQueue.length;
236
+
237
+ // Check TTL
238
+ if (event.ttl && Date.now() - event.timestamp > event.ttl) {
239
+ this.stats.eventsDropped++;
240
+ continue;
241
+ }
242
+
243
+ await this.deliverEvent(event);
244
+ }
245
+ } finally {
246
+ this.processing = false;
247
+ }
248
+ }
249
+
250
+ /**
251
+ * Deliver event to matching subscribers
252
+ */
253
+ private async deliverEvent(event: ISwarmEvent): Promise<void> {
254
+ const toRemove: string[] = [];
255
+ const matchingHandlers: Array<{ sub: IEventSubscription; handler: EventHandler }> = [];
256
+
257
+ for (const [id, sub] of this.subscriptions) {
258
+ if (this.matchesPattern(event.type, sub.pattern)) {
259
+ // Check if targeted and matches
260
+ if (event.target) {
261
+ const _targets = Array.isArray(event.target) ? event.target : [event.target];
262
+ // Target filtering could be applied here if needed
263
+ }
264
+
265
+ matchingHandlers.push({ sub, handler: sub.handler });
266
+
267
+ if (sub.once) {
268
+ toRemove.push(id);
269
+ }
270
+ }
271
+ }
272
+
273
+ // Sort by priority
274
+ const priorityOrder = ['low', 'normal', 'high', 'critical'];
275
+ matchingHandlers.sort(
276
+ (a, b) => priorityOrder.indexOf(b.sub.priority) - priorityOrder.indexOf(a.sub.priority)
277
+ );
278
+
279
+ // Execute handlers
280
+ let delivered = false;
281
+ for (const { handler } of matchingHandlers) {
282
+ try {
283
+ await handler(event);
284
+ delivered = true;
285
+ } catch (error) {
286
+ // Handler error - continue to next
287
+ console.error('Event handler error:', error);
288
+ }
289
+ }
290
+
291
+ if (delivered) {
292
+ this.stats.eventsDelivered++;
293
+ } else if (this.config.enableDeadLetter) {
294
+ this.deadLetterQueue.push(event);
295
+ this.stats.deadLetterCount++;
296
+ }
297
+
298
+ // Remove once subscriptions
299
+ for (const id of toRemove) {
300
+ this.subscriptions.delete(id);
301
+ }
302
+ this.stats.subscriptions = this.subscriptions.size;
303
+ }
304
+
305
+ /**
306
+ * Check if event type matches pattern
307
+ */
308
+ private matchesPattern(type: string, pattern: string | RegExp): boolean {
309
+ if (pattern instanceof RegExp) {
310
+ return pattern.test(type);
311
+ }
312
+
313
+ // Wildcard support: "swarm.*" matches "swarm.joined", "swarm.left", etc.
314
+ if (pattern.includes('*')) {
315
+ const regexPattern = pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*');
316
+ return new RegExp(`^${regexPattern}$`).test(type);
317
+ }
318
+
319
+ return type === pattern;
320
+ }
321
+
322
+ /**
323
+ * Emit synchronously (bypass queue)
324
+ */
325
+ emit(
326
+ type: string,
327
+ source: string,
328
+ payload: unknown,
329
+ options: {
330
+ target?: string | string[];
331
+ priority?: EventPriority;
332
+ metadata?: Record<string, unknown>;
333
+ } = {}
334
+ ): void {
335
+ const event: ISwarmEvent = {
336
+ id: `evt-${this.nextId++}-${Date.now()}`,
337
+ type,
338
+ source,
339
+ target: options.target,
340
+ payload,
341
+ timestamp: Date.now(),
342
+ priority: options.priority ?? 'normal',
343
+ metadata: options.metadata,
344
+ };
345
+
346
+ this.stats.eventsPublished++;
347
+
348
+ for (const [id, sub] of this.subscriptions) {
349
+ if (this.matchesPattern(type, sub.pattern)) {
350
+ try {
351
+ sub.handler(event);
352
+ this.stats.eventsDelivered++;
353
+
354
+ if (sub.once) {
355
+ this.subscriptions.delete(id);
356
+ }
357
+ } catch (_error) {
358
+ // Handler error - continue
359
+ }
360
+ }
361
+ }
362
+
363
+ this.stats.subscriptions = this.subscriptions.size;
364
+ }
365
+
366
+ /**
367
+ * Get pending events in queue
368
+ */
369
+ getPendingEvents(): ISwarmEvent[] {
370
+ return [...this.eventQueue];
371
+ }
372
+
373
+ /**
374
+ * Get dead letter queue
375
+ */
376
+ getDeadLetterQueue(): ISwarmEvent[] {
377
+ return [...this.deadLetterQueue];
378
+ }
379
+
380
+ /**
381
+ * Clear dead letter queue
382
+ */
383
+ clearDeadLetterQueue(): ISwarmEvent[] {
384
+ const events = [...this.deadLetterQueue];
385
+ this.deadLetterQueue = [];
386
+ this.stats.deadLetterCount = 0;
387
+ return events;
388
+ }
389
+
390
+ /**
391
+ * Replay dead letter events
392
+ */
393
+ replayDeadLetters(): number {
394
+ const events = this.clearDeadLetterQueue();
395
+ for (const event of events) {
396
+ // Reset timestamp for TTL
397
+ event.timestamp = Date.now();
398
+ this.insertByPriority(event);
399
+ }
400
+ this.stats.pendingEvents = this.eventQueue.length;
401
+
402
+ if (this.config.asyncProcessing && !this.processing) {
403
+ this.processQueue();
404
+ }
405
+
406
+ return events.length;
407
+ }
408
+
409
+ /**
410
+ * Get event bus statistics
411
+ */
412
+ getStats(): IEventBusStats {
413
+ return { ...this.stats };
414
+ }
415
+
416
+ /**
417
+ * Reset statistics
418
+ */
419
+ resetStats(): void {
420
+ this.stats = {
421
+ eventsPublished: 0,
422
+ eventsDelivered: 0,
423
+ eventsDropped: 0,
424
+ subscriptions: this.subscriptions.size,
425
+ pendingEvents: this.eventQueue.length,
426
+ deadLetterCount: this.deadLetterQueue.length,
427
+ };
428
+ }
429
+
430
+ /**
431
+ * Get configuration
432
+ */
433
+ getConfig(): IEventBusConfig {
434
+ return { ...this.config };
435
+ }
436
+
437
+ /**
438
+ * Update configuration
439
+ */
440
+ setConfig(config: Partial<IEventBusConfig>): void {
441
+ this.config = { ...this.config, ...config };
442
+ }
443
+ }