@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,4790 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/agents/index.ts
31
+ var agents_exports = {};
32
+ __export(agents_exports, {
33
+ AgentManifestBuilder: () => AgentManifestBuilder,
34
+ AgentRegistry: () => AgentRegistry,
35
+ AgentWalletRegistry: () => AgentWalletRegistry,
36
+ BUILTIN_NORMS: () => BUILTIN_NORMS,
37
+ CapabilityMatcher: () => CapabilityMatcher,
38
+ CulturalMemory: () => CulturalMemory,
39
+ DEFAULT_A2A_CONFIG: () => DEFAULT_A2A_CONFIG,
40
+ DEFAULT_MCP_CONFIG: () => DEFAULT_MCP_CONFIG,
41
+ DEFAULT_PHASE_TIMINGS: () => DEFAULT_PHASE_TIMINGS,
42
+ DEFAULT_REALTIME_CONFIG: () => DEFAULT_REALTIME_CONFIG,
43
+ DEFAULT_REGISTRY_CONFIG: () => DEFAULT_REGISTRY_CONFIG,
44
+ DEFAULT_SPATIAL_COMM_CONFIG: () => DEFAULT_SPATIAL_COMM_CONFIG,
45
+ EffectRow: () => EffectRow,
46
+ FederatedRegistryAdapter: () => FederatedRegistryAdapter,
47
+ FrameBudgetTracker: () => FrameBudgetTracker,
48
+ GCounter: () => GCounter,
49
+ LATENCY_THRESHOLDS: () => LATENCY_THRESHOLDS,
50
+ LWWRegister: () => LWWRegister,
51
+ Layer1RealTimeClient: () => Layer1RealTimeClient,
52
+ Layer2A2AClient: () => Layer2A2AClient,
53
+ Layer3MCPClient: () => Layer3MCPClient,
54
+ Layer3MCPServer: () => Layer3MCPServer,
55
+ NormEngine: () => NormEngine,
56
+ ORSet: () => ORSet,
57
+ OrchestratorAgent: () => OrchestratorAgent,
58
+ PHASE_ORDER: () => PHASE_ORDER,
59
+ PLATFORM_CAPABILITIES: () => PLATFORM_CAPABILITIES,
60
+ PROTOCOL_COMPATIBILITY: () => PROTOCOL_COMPATIBILITY,
61
+ PROTOCOL_VERSION: () => PROTOCOL_VERSION,
62
+ SPATIAL_MCP_TOOLS: () => SPATIAL_MCP_TOOLS,
63
+ SkillWorkflowEngine: () => SkillWorkflowEngine,
64
+ SpatialCommClient: () => SpatialCommClient,
65
+ TaskDelegationService: () => TaskDelegationService,
66
+ UDPRealTimeTransport: () => UDPRealTimeTransport,
67
+ WebRTCRealTimeTransport: () => WebRTCRealTimeTransport,
68
+ createAgentManifest: () => createManifest,
69
+ createAgentState: () => createAgentState,
70
+ createMVCPayload: () => createMVCPayload,
71
+ criticalMassForChange: () => criticalMassForChange,
72
+ decodeRealTimeMessage: () => decodeRealTimeMessage,
73
+ defaultMatcher: () => defaultMatcher,
74
+ embodimentFor: () => embodimentFor,
75
+ encodeRealTimeMessage: () => encodeRealTimeMessage,
76
+ estimatePayloadSize: () => estimatePayloadSize,
77
+ findAgents: () => findAgents,
78
+ findBestAgent: () => findBestAgent,
79
+ getCounter: () => getCounter,
80
+ getDefaultRegistry: () => getDefaultRegistry,
81
+ getRegister: () => getRegister,
82
+ incrementCounter: () => incrementCounter,
83
+ mergeStates: () => mergeStates,
84
+ negotiateHandoff: () => negotiateHandoff,
85
+ platformCategory: () => platformCategory,
86
+ resetDefaultRegistry: () => resetDefaultRegistry,
87
+ setRegister: () => setRegister,
88
+ signOperation: () => signOperation,
89
+ validateManifest: () => validateManifest,
90
+ validatePayloadBudget: () => validatePayloadBudget,
91
+ verifyOperation: () => verifyOperation
92
+ });
93
+ module.exports = __toCommonJS(agents_exports);
94
+
95
+ // src/agents/AgentTypes.ts
96
+ var PHASE_ORDER = [
97
+ "INTAKE",
98
+ "REFLECT",
99
+ "EXECUTE",
100
+ "COMPRESS",
101
+ "REINTAKE",
102
+ "GROW",
103
+ "EVOLVE"
104
+ ];
105
+ var DEFAULT_PHASE_TIMINGS = {
106
+ INTAKE: 1e3,
107
+ REFLECT: 2e3,
108
+ EXECUTE: 5e3,
109
+ COMPRESS: 1e3,
110
+ REINTAKE: 1e3,
111
+ GROW: 2e3,
112
+ EVOLVE: 1e3
113
+ };
114
+
115
+ // src/agents/AgentManifest.ts
116
+ var LATENCY_THRESHOLDS = {
117
+ instant: 10,
118
+ fast: 100,
119
+ medium: 1e3,
120
+ slow: 1e4,
121
+ background: Infinity
122
+ };
123
+ var AgentManifestBuilder = class {
124
+ manifest = {
125
+ capabilities: [],
126
+ endpoints: [],
127
+ trustLevel: "local",
128
+ status: "unknown"
129
+ };
130
+ /**
131
+ * Set agent identity
132
+ */
133
+ identity(id, name, version) {
134
+ this.manifest.id = id;
135
+ this.manifest.name = name;
136
+ this.manifest.version = version;
137
+ return this;
138
+ }
139
+ /**
140
+ * Set agent description
141
+ */
142
+ description(desc) {
143
+ this.manifest.description = desc;
144
+ return this;
145
+ }
146
+ /**
147
+ * Set classification
148
+ */
149
+ classify(categories, position, section) {
150
+ this.manifest.categories = categories;
151
+ this.manifest.position = position;
152
+ this.manifest.section = section;
153
+ return this;
154
+ }
155
+ /**
156
+ * Add a capability
157
+ */
158
+ addCapability(capability) {
159
+ this.manifest.capabilities.push(capability);
160
+ return this;
161
+ }
162
+ /**
163
+ * Add multiple capabilities
164
+ */
165
+ addCapabilities(capabilities) {
166
+ this.manifest.capabilities.push(...capabilities);
167
+ return this;
168
+ }
169
+ /**
170
+ * Add an endpoint
171
+ */
172
+ addEndpoint(endpoint) {
173
+ this.manifest.endpoints.push(endpoint);
174
+ return this;
175
+ }
176
+ /**
177
+ * Set spatial scope
178
+ */
179
+ spatial(scope) {
180
+ this.manifest.spatialScope = scope;
181
+ return this;
182
+ }
183
+ /**
184
+ * Set trust level
185
+ */
186
+ trust(level, verification) {
187
+ this.manifest.trustLevel = level;
188
+ this.manifest.verification = verification;
189
+ return this;
190
+ }
191
+ /**
192
+ * Set health check interval
193
+ */
194
+ healthCheck(intervalMs) {
195
+ this.manifest.healthCheckInterval = intervalMs;
196
+ return this;
197
+ }
198
+ /**
199
+ * Add custom tags
200
+ */
201
+ tags(...tags) {
202
+ this.manifest.tags = [...this.manifest.tags || [], ...tags];
203
+ return this;
204
+ }
205
+ /**
206
+ * Set metadata
207
+ */
208
+ metadata(data) {
209
+ this.manifest.metadata = { ...this.manifest.metadata, ...data };
210
+ return this;
211
+ }
212
+ /**
213
+ * Build the manifest
214
+ */
215
+ build() {
216
+ if (!this.manifest.id || !this.manifest.name || !this.manifest.version) {
217
+ throw new Error("AgentManifest requires id, name, and version");
218
+ }
219
+ if (this.manifest.capabilities.length === 0) {
220
+ throw new Error("AgentManifest requires at least one capability");
221
+ }
222
+ if (this.manifest.endpoints.length === 0) {
223
+ throw new Error("AgentManifest requires at least one endpoint");
224
+ }
225
+ const now = Date.now();
226
+ return {
227
+ ...this.manifest,
228
+ registeredAt: now,
229
+ updatedAt: now,
230
+ status: "online"
231
+ };
232
+ }
233
+ };
234
+ function createManifest() {
235
+ return new AgentManifestBuilder();
236
+ }
237
+ function validateManifest(manifest) {
238
+ const errors = [];
239
+ const warnings = [];
240
+ if (!manifest.id) errors.push("Missing required field: id");
241
+ if (!manifest.name) errors.push("Missing required field: name");
242
+ if (!manifest.version) errors.push("Missing required field: version");
243
+ if (!manifest.capabilities || manifest.capabilities.length === 0) {
244
+ errors.push("At least one capability is required");
245
+ }
246
+ if (!manifest.endpoints || manifest.endpoints.length === 0) {
247
+ errors.push("At least one endpoint is required");
248
+ }
249
+ manifest.capabilities?.forEach((cap, i) => {
250
+ if (!cap.type) errors.push(`Capability ${i}: missing type`);
251
+ if (!cap.domain) errors.push(`Capability ${i}: missing domain`);
252
+ });
253
+ manifest.endpoints?.forEach((ep, i) => {
254
+ if (!ep.protocol) errors.push(`Endpoint ${i}: missing protocol`);
255
+ if (!ep.address) errors.push(`Endpoint ${i}: missing address`);
256
+ });
257
+ if (!manifest.description) {
258
+ warnings.push("Consider adding a description for better discovery");
259
+ }
260
+ if (!manifest.healthCheckInterval) {
261
+ warnings.push("No health check interval set, agent health may not be tracked");
262
+ }
263
+ if (manifest.trustLevel === "untrusted") {
264
+ warnings.push("Untrusted agents have limited capabilities");
265
+ }
266
+ return {
267
+ valid: errors.length === 0,
268
+ errors,
269
+ warnings
270
+ };
271
+ }
272
+
273
+ // src/agents/CapabilityMatcher.ts
274
+ var TRUST_LEVELS = ["local", "verified", "known", "external", "untrusted"];
275
+ function getTrustScore(level) {
276
+ const index = TRUST_LEVELS.indexOf(level);
277
+ return index >= 0 ? (TRUST_LEVELS.length - index) / TRUST_LEVELS.length : 0;
278
+ }
279
+ function meetsMinTrust(agentTrust, minTrust) {
280
+ return TRUST_LEVELS.indexOf(agentTrust) <= TRUST_LEVELS.indexOf(minTrust);
281
+ }
282
+ var LATENCY_ORDER = ["instant", "fast", "medium", "slow", "background"];
283
+ function getLatencyScore(profile) {
284
+ const index = LATENCY_ORDER.indexOf(profile);
285
+ return index >= 0 ? (LATENCY_ORDER.length - index) / LATENCY_ORDER.length : 0;
286
+ }
287
+ function meetsMaxLatency(capLatency, maxLatency) {
288
+ if (!capLatency) return true;
289
+ return LATENCY_ORDER.indexOf(capLatency) <= LATENCY_ORDER.indexOf(maxLatency);
290
+ }
291
+ function pointInBounds(point, min, max) {
292
+ return point.x >= min.x && point.x <= max.x && point.y >= min.y && point.y <= max.y && point.z >= min.z && point.z <= max.z;
293
+ }
294
+ function boundsOverlap(a, b) {
295
+ return a.min.x <= b.max.x && a.max.x >= b.min.x && a.min.y <= b.max.y && a.max.y >= b.min.y && a.min.z <= b.max.z && a.max.z >= b.min.z;
296
+ }
297
+ function matchesSpatialQuery(scope, query) {
298
+ if (scope?.global) return true;
299
+ if (!scope) return query.requireGlobal !== true;
300
+ if (query.point && scope.bounds) {
301
+ if (!pointInBounds(query.point, scope.bounds.min, scope.bounds.max)) {
302
+ return false;
303
+ }
304
+ }
305
+ if (query.point && scope.radius) {
306
+ const dx = query.point.x - scope.radius.center.x;
307
+ const dy = query.point.y - scope.radius.center.y;
308
+ const dz = query.point.z - scope.radius.center.z;
309
+ const distance = Math.sqrt(dx * dx + dy * dy + dz * dz);
310
+ if (distance > scope.radius.distance) return false;
311
+ }
312
+ if (query.scene && scope.scene && scope.scene !== query.scene) {
313
+ return false;
314
+ }
315
+ if (query.nodes && scope.nodes) {
316
+ const hasOverlap = query.nodes.some((n) => scope.nodes.includes(n));
317
+ if (!hasOverlap) return false;
318
+ }
319
+ if (query.overlaps && scope.bounds) {
320
+ if (!boundsOverlap(scope.bounds, query.overlaps)) {
321
+ return false;
322
+ }
323
+ }
324
+ return true;
325
+ }
326
+ var CapabilityMatcher = class {
327
+ /**
328
+ * Check if a capability matches the query
329
+ */
330
+ matchCapability(capability, query) {
331
+ const matchedCriteria = [];
332
+ let score = 0;
333
+ let criteriaCount = 0;
334
+ if (query.type) {
335
+ criteriaCount++;
336
+ const types = Array.isArray(query.type) ? query.type : [query.type];
337
+ if (types.includes(capability.type)) {
338
+ matchedCriteria.push("type");
339
+ score += 1;
340
+ } else {
341
+ return null;
342
+ }
343
+ }
344
+ if (query.domain) {
345
+ criteriaCount++;
346
+ const domains = Array.isArray(query.domain) ? query.domain : [query.domain];
347
+ if (domains.includes(capability.domain)) {
348
+ matchedCriteria.push("domain");
349
+ score += 1;
350
+ } else {
351
+ return null;
352
+ }
353
+ }
354
+ if (query.maxLatency && capability.latency) {
355
+ criteriaCount++;
356
+ if (meetsMaxLatency(capability.latency, query.maxLatency)) {
357
+ matchedCriteria.push("latency");
358
+ score += getLatencyScore(capability.latency);
359
+ } else {
360
+ return null;
361
+ }
362
+ }
363
+ if (capability.available === false) {
364
+ return null;
365
+ }
366
+ if (criteriaCount > 0 && matchedCriteria.length === 0) {
367
+ return null;
368
+ }
369
+ const normalizedScore = criteriaCount > 0 ? score / criteriaCount : 1;
370
+ const priorityBonus = (capability.priority || 0) / 100;
371
+ return {
372
+ capability,
373
+ score: Math.min(normalizedScore + priorityBonus, 1),
374
+ matchedCriteria
375
+ };
376
+ }
377
+ /**
378
+ * Check if an agent matches the query
379
+ */
380
+ matchAgent(manifest, query) {
381
+ const reasons = [];
382
+ if (!query.includeOffline && manifest.status === "offline") {
383
+ return null;
384
+ }
385
+ if (query.minTrust && !meetsMinTrust(manifest.trustLevel, query.minTrust)) {
386
+ return null;
387
+ }
388
+ if (query.spatial && !matchesSpatialQuery(manifest.spatialScope, query.spatial)) {
389
+ return null;
390
+ }
391
+ if (query.tags && query.tags.length > 0) {
392
+ const agentTags = manifest.tags || [];
393
+ const hasAllTags = query.tags.every((t) => agentTags.includes(t));
394
+ if (!hasAllTags) {
395
+ return null;
396
+ }
397
+ reasons.push("tags matched");
398
+ }
399
+ const capabilityMatches = [];
400
+ for (const capability of manifest.capabilities) {
401
+ const match = this.matchCapability(capability, query);
402
+ if (match) {
403
+ capabilityMatches.push(match);
404
+ }
405
+ }
406
+ if (capabilityMatches.length === 0) {
407
+ return null;
408
+ }
409
+ const avgCapabilityScore = capabilityMatches.reduce((sum, m) => sum + m.score, 0) / capabilityMatches.length;
410
+ const trustScore = getTrustScore(manifest.trustLevel);
411
+ const overallScore = avgCapabilityScore * 0.7 + trustScore * 0.3;
412
+ reasons.push(`${capabilityMatches.length} capability match(es)`);
413
+ reasons.push(`trust: ${manifest.trustLevel}`);
414
+ if (manifest.status === "online") {
415
+ reasons.push("online");
416
+ }
417
+ return {
418
+ manifest,
419
+ score: overallScore,
420
+ capabilities: capabilityMatches,
421
+ reasons
422
+ };
423
+ }
424
+ /**
425
+ * Find all matching agents from a list
426
+ */
427
+ findMatches(manifests, query) {
428
+ const matches = [];
429
+ for (const manifest of manifests) {
430
+ const match = this.matchAgent(manifest, query);
431
+ if (match) {
432
+ matches.push(match);
433
+ }
434
+ }
435
+ this.sortMatches(matches, query.sortBy || "score", query.sortOrder || "desc");
436
+ if (query.limit && query.limit > 0) {
437
+ return matches.slice(0, query.limit);
438
+ }
439
+ return matches;
440
+ }
441
+ /**
442
+ * Find the best matching agent
443
+ */
444
+ findBest(manifests, query) {
445
+ const matches = this.findMatches(manifests, { ...query, limit: 1 });
446
+ return matches.length > 0 ? matches[0] : null;
447
+ }
448
+ /**
449
+ * Sort matches by criteria
450
+ */
451
+ sortMatches(matches, sortBy, sortOrder) {
452
+ const multiplier = sortOrder === "asc" ? 1 : -1;
453
+ matches.sort((a, b) => {
454
+ switch (sortBy) {
455
+ case "latency": {
456
+ const aLatency = this.getFastestLatency(a.capabilities);
457
+ const bLatency = this.getFastestLatency(b.capabilities);
458
+ return multiplier * (LATENCY_ORDER.indexOf(aLatency) - LATENCY_ORDER.indexOf(bLatency));
459
+ }
460
+ case "trust":
461
+ return multiplier * (TRUST_LEVELS.indexOf(a.manifest.trustLevel) - TRUST_LEVELS.indexOf(b.manifest.trustLevel));
462
+ case "priority": {
463
+ const aPriority = this.getHighestPriority(a.capabilities);
464
+ const bPriority = this.getHighestPriority(b.capabilities);
465
+ return multiplier * (bPriority - aPriority);
466
+ }
467
+ case "name":
468
+ return multiplier * a.manifest.name.localeCompare(b.manifest.name);
469
+ case "score":
470
+ default:
471
+ return multiplier * (a.score - b.score);
472
+ }
473
+ });
474
+ }
475
+ getFastestLatency(capabilities) {
476
+ let fastest = "background";
477
+ for (const cap of capabilities) {
478
+ if (cap.capability.latency) {
479
+ const idx = LATENCY_ORDER.indexOf(cap.capability.latency);
480
+ if (idx < LATENCY_ORDER.indexOf(fastest)) {
481
+ fastest = cap.capability.latency;
482
+ }
483
+ }
484
+ }
485
+ return fastest;
486
+ }
487
+ getHighestPriority(capabilities) {
488
+ return Math.max(...capabilities.map((c) => c.capability.priority || 0));
489
+ }
490
+ };
491
+ var defaultMatcher = new CapabilityMatcher();
492
+ function findAgents(manifests, query) {
493
+ return defaultMatcher.findMatches(manifests, query);
494
+ }
495
+ function findBestAgent(manifests, query) {
496
+ return defaultMatcher.findBest(manifests, query);
497
+ }
498
+
499
+ // src/agents/AgentRegistry.ts
500
+ var import_events = require("events");
501
+ var DEFAULT_REGISTRY_CONFIG = {
502
+ mode: "central",
503
+ defaultTTL: 3e5,
504
+ // 5 minutes
505
+ healthCheckInterval: 1e4,
506
+ // 10 seconds
507
+ offlineThreshold: 3e4,
508
+ // 30 seconds
509
+ autoCleanup: true,
510
+ cleanupInterval: 6e4,
511
+ // 1 minute
512
+ maxAgents: 1e3,
513
+ minTrustForRegistration: "external"
514
+ };
515
+ var AgentRegistry = class extends import_events.EventEmitter {
516
+ agents = /* @__PURE__ */ new Map();
517
+ matcher = new CapabilityMatcher();
518
+ config;
519
+ healthCheckTimer;
520
+ cleanupTimer;
521
+ isShuttingDown = false;
522
+ constructor(config = {}) {
523
+ super();
524
+ this.config = { ...DEFAULT_REGISTRY_CONFIG, ...config };
525
+ }
526
+ // ==========================================================================
527
+ // LIFECYCLE
528
+ // ==========================================================================
529
+ /**
530
+ * Start the registry (begins health checks and cleanup)
531
+ */
532
+ start() {
533
+ if (this.isShuttingDown) {
534
+ throw new Error("Registry is shutting down");
535
+ }
536
+ this.healthCheckTimer = setInterval(() => {
537
+ this.performHealthCheck();
538
+ }, this.config.healthCheckInterval);
539
+ if (this.config.autoCleanup) {
540
+ this.cleanupTimer = setInterval(() => {
541
+ this.cleanup();
542
+ }, this.config.cleanupInterval);
543
+ }
544
+ }
545
+ /**
546
+ * Stop the registry
547
+ */
548
+ stop() {
549
+ this.isShuttingDown = true;
550
+ if (this.healthCheckTimer) {
551
+ clearInterval(this.healthCheckTimer);
552
+ this.healthCheckTimer = void 0;
553
+ }
554
+ if (this.cleanupTimer) {
555
+ clearInterval(this.cleanupTimer);
556
+ this.cleanupTimer = void 0;
557
+ }
558
+ }
559
+ /**
560
+ * Clear all agents and reset
561
+ */
562
+ clear() {
563
+ this.agents.clear();
564
+ }
565
+ // ==========================================================================
566
+ // REGISTRATION
567
+ // ==========================================================================
568
+ /**
569
+ * Register an agent
570
+ */
571
+ async register(manifest) {
572
+ if (this.isShuttingDown) {
573
+ throw new Error("Registry is shutting down");
574
+ }
575
+ const validation = validateManifest(manifest);
576
+ if (!validation.valid) {
577
+ throw new Error(`Invalid manifest: ${validation.errors.join(", ")}`);
578
+ }
579
+ const trustLevels = ["local", "verified", "known", "external", "untrusted"];
580
+ const minTrustIndex = trustLevels.indexOf(this.config.minTrustForRegistration);
581
+ const agentTrustIndex = trustLevels.indexOf(manifest.trustLevel);
582
+ if (agentTrustIndex > minTrustIndex) {
583
+ throw new Error(
584
+ `Trust level ${manifest.trustLevel} does not meet minimum ${this.config.minTrustForRegistration}`
585
+ );
586
+ }
587
+ if (this.agents.size >= this.config.maxAgents && !this.agents.has(manifest.id)) {
588
+ throw new Error(`Registry full: maximum ${this.config.maxAgents} agents`);
589
+ }
590
+ const now = Date.now();
591
+ const entry = {
592
+ manifest: {
593
+ ...manifest,
594
+ registeredAt: now,
595
+ updatedAt: now,
596
+ lastHeartbeat: now,
597
+ status: "online"
598
+ },
599
+ registeredAt: now,
600
+ lastHeartbeat: now,
601
+ heartbeatCount: 0,
602
+ missedHeartbeats: 0,
603
+ ttl: manifest.healthCheckInterval || this.config.defaultTTL
604
+ };
605
+ const isUpdate = this.agents.has(manifest.id);
606
+ this.agents.set(manifest.id, entry);
607
+ if (isUpdate) {
608
+ this.emit("agent:updated", entry.manifest);
609
+ } else {
610
+ this.emit("agent:registered", entry.manifest);
611
+ }
612
+ }
613
+ /**
614
+ * Deregister an agent
615
+ */
616
+ async deregister(agentId) {
617
+ const entry = this.agents.get(agentId);
618
+ if (entry) {
619
+ this.agents.delete(agentId);
620
+ this.emit("agent:deregistered", agentId, "explicit");
621
+ }
622
+ }
623
+ /**
624
+ * Update an agent's heartbeat
625
+ */
626
+ async heartbeat(agentId) {
627
+ const entry = this.agents.get(agentId);
628
+ if (!entry) {
629
+ throw new Error(`Agent not found: ${agentId}`);
630
+ }
631
+ const now = Date.now();
632
+ const wasOffline = entry.manifest.status === "offline";
633
+ entry.lastHeartbeat = now;
634
+ entry.heartbeatCount++;
635
+ entry.missedHeartbeats = 0;
636
+ entry.manifest.lastHeartbeat = now;
637
+ entry.manifest.status = "online";
638
+ if (wasOffline) {
639
+ this.emit("agent:online", agentId);
640
+ }
641
+ }
642
+ // ==========================================================================
643
+ // DISCOVERY
644
+ // ==========================================================================
645
+ /**
646
+ * Discover agents matching a capability query
647
+ */
648
+ async discover(query) {
649
+ const manifests = this.getAllManifests();
650
+ const matches = this.matcher.findMatches(manifests, query);
651
+ return matches.map((m) => m.manifest);
652
+ }
653
+ /**
654
+ * Discover agents with full match details
655
+ */
656
+ async discoverWithScores(query) {
657
+ const manifests = this.getAllManifests();
658
+ return this.matcher.findMatches(manifests, query);
659
+ }
660
+ /**
661
+ * Find the best agent for a query
662
+ */
663
+ async findBest(query) {
664
+ const manifests = this.getAllManifests();
665
+ const match = this.matcher.findBest(manifests, query);
666
+ return match?.manifest || null;
667
+ }
668
+ /**
669
+ * Get a specific agent by ID
670
+ */
671
+ get(agentId) {
672
+ return this.agents.get(agentId)?.manifest;
673
+ }
674
+ /**
675
+ * Check if an agent is registered
676
+ */
677
+ has(agentId) {
678
+ return this.agents.has(agentId);
679
+ }
680
+ /**
681
+ * Get all registered manifests
682
+ */
683
+ getAllManifests() {
684
+ return Array.from(this.agents.values()).map((e) => e.manifest);
685
+ }
686
+ /**
687
+ * Get count of registered agents
688
+ */
689
+ get size() {
690
+ return this.agents.size;
691
+ }
692
+ /**
693
+ * Get count by status
694
+ */
695
+ getStatusCounts() {
696
+ const counts = {
697
+ online: 0,
698
+ offline: 0,
699
+ degraded: 0,
700
+ unknown: 0
701
+ };
702
+ for (const entry of this.agents.values()) {
703
+ const status = entry.manifest.status || "unknown";
704
+ counts[status] = (counts[status] || 0) + 1;
705
+ }
706
+ return counts;
707
+ }
708
+ // ==========================================================================
709
+ // HEALTH CHECKS
710
+ // ==========================================================================
711
+ /**
712
+ * Perform health check on all agents
713
+ */
714
+ performHealthCheck() {
715
+ const now = Date.now();
716
+ for (const [agentId, entry] of this.agents) {
717
+ const timeSinceHeartbeat = now - entry.lastHeartbeat;
718
+ if (timeSinceHeartbeat > this.config.offlineThreshold) {
719
+ const wasOnline = entry.manifest.status === "online";
720
+ entry.manifest.status = "offline";
721
+ entry.missedHeartbeats++;
722
+ if (wasOnline) {
723
+ this.emit("agent:offline", agentId);
724
+ }
725
+ } else if (timeSinceHeartbeat > this.config.healthCheckInterval * 2) {
726
+ const wasOnline = entry.manifest.status === "online";
727
+ entry.manifest.status = "degraded";
728
+ if (wasOnline) {
729
+ this.emit("agent:degraded", agentId);
730
+ }
731
+ }
732
+ }
733
+ }
734
+ /**
735
+ * Cleanup expired/offline agents
736
+ */
737
+ cleanup() {
738
+ const now = Date.now();
739
+ let removedCount = 0;
740
+ for (const [agentId, entry] of this.agents) {
741
+ const _age = now - entry.registeredAt;
742
+ const timeSinceHeartbeat = now - entry.lastHeartbeat;
743
+ if (entry.manifest.status === "offline" && timeSinceHeartbeat > entry.ttl) {
744
+ this.agents.delete(agentId);
745
+ this.emit("agent:deregistered", agentId, "ttl-expired");
746
+ removedCount++;
747
+ }
748
+ }
749
+ if (removedCount > 0) {
750
+ this.emit("registry:cleanup", removedCount);
751
+ }
752
+ }
753
+ // ==========================================================================
754
+ // QUERIES
755
+ // ==========================================================================
756
+ /**
757
+ * Find agents by trust level
758
+ */
759
+ findByTrust(trustLevel) {
760
+ return this.getAllManifests().filter((m) => m.trustLevel === trustLevel);
761
+ }
762
+ /**
763
+ * Find agents by tag
764
+ */
765
+ findByTag(tag) {
766
+ return this.getAllManifests().filter((m) => m.tags?.includes(tag));
767
+ }
768
+ /**
769
+ * Find online agents
770
+ */
771
+ findOnline() {
772
+ return this.getAllManifests().filter((m) => m.status === "online");
773
+ }
774
+ /**
775
+ * Find agents in a scene
776
+ */
777
+ findInScene(scene) {
778
+ return this.getAllManifests().filter(
779
+ (m) => m.spatialScope?.scene === scene || m.spatialScope?.global
780
+ );
781
+ }
782
+ // ==========================================================================
783
+ // SERIALIZATION
784
+ // ==========================================================================
785
+ /**
786
+ * Export registry state
787
+ */
788
+ export() {
789
+ return {
790
+ agents: this.getAllManifests(),
791
+ config: this.config,
792
+ timestamp: Date.now()
793
+ };
794
+ }
795
+ /**
796
+ * Import registry state
797
+ */
798
+ async import(data) {
799
+ for (const manifest of data.agents) {
800
+ await this.register(manifest);
801
+ }
802
+ }
803
+ };
804
+ var defaultRegistry = null;
805
+ function getDefaultRegistry(config) {
806
+ if (!defaultRegistry) {
807
+ defaultRegistry = new AgentRegistry(config);
808
+ }
809
+ return defaultRegistry;
810
+ }
811
+ function resetDefaultRegistry() {
812
+ if (defaultRegistry) {
813
+ defaultRegistry.stop();
814
+ defaultRegistry.clear();
815
+ defaultRegistry = null;
816
+ }
817
+ }
818
+
819
+ // src/agents/FederatedRegistryAdapter.ts
820
+ var DEFAULT_CONFIG = {
821
+ seedUrls: [],
822
+ pollIntervalMs: 6e4,
823
+ maxRemoteAgents: 100,
824
+ trustRemoteAs: "external",
825
+ timeout: 5e3
826
+ };
827
+ var TAG_TO_TYPE = {
828
+ parsing: "analyze",
829
+ validation: "validate",
830
+ compilation: "transform",
831
+ generation: "generate",
832
+ rendering: "render",
833
+ analysis: "analyze",
834
+ optimization: "optimize",
835
+ storage: "store",
836
+ retrieval: "retrieve",
837
+ orchestration: "orchestrate",
838
+ detection: "detect",
839
+ communication: "communicate"
840
+ };
841
+ var TAG_TO_DOMAIN = {
842
+ spatial: "spatial",
843
+ "3d": "spatial",
844
+ vr: "spatial",
845
+ ar: "spatial",
846
+ nlp: "nlp",
847
+ language: "nlp",
848
+ vision: "vision",
849
+ blockchain: "blockchain",
850
+ web3: "blockchain",
851
+ audio: "audio",
852
+ video: "video",
853
+ physics: "physics",
854
+ network: "networking",
855
+ security: "security",
856
+ trading: "trading",
857
+ social: "social",
858
+ gaming: "gaming"
859
+ };
860
+ var FederatedRegistryAdapter = class {
861
+ registry;
862
+ config;
863
+ pollTimer;
864
+ remoteAgentIds = /* @__PURE__ */ new Set();
865
+ lastPollResults = /* @__PURE__ */ new Map();
866
+ constructor(registry, config = {}) {
867
+ this.registry = registry;
868
+ this.config = { ...DEFAULT_CONFIG, ...config };
869
+ }
870
+ // ===========================================================================
871
+ // CORE: FETCH & REGISTER
872
+ // ===========================================================================
873
+ /**
874
+ * Fetch a remote agent card and register it into the local registry.
875
+ * Returns the converted manifest on success, null on failure.
876
+ */
877
+ async fetchAndRegister(url) {
878
+ try {
879
+ const card = await this.fetchAgentCard(url);
880
+ if (!card || !card.id || !card.name) {
881
+ this.lastPollResults.set(url, { timestamp: Date.now(), success: false });
882
+ return null;
883
+ }
884
+ if (this.remoteAgentIds.size >= this.config.maxRemoteAgents && !this.remoteAgentIds.has(card.id)) {
885
+ this.lastPollResults.set(url, { timestamp: Date.now(), success: false });
886
+ return null;
887
+ }
888
+ const manifest = this.a2aCardToManifest(card, url);
889
+ await this.registry.register(manifest);
890
+ this.remoteAgentIds.add(card.id);
891
+ this.lastPollResults.set(url, { timestamp: Date.now(), success: true });
892
+ return manifest;
893
+ } catch {
894
+ this.lastPollResults.set(url, { timestamp: Date.now(), success: false });
895
+ return null;
896
+ }
897
+ }
898
+ /**
899
+ * Poll all seed URLs once. Returns summary of results.
900
+ */
901
+ async pollAll() {
902
+ let added = 0;
903
+ let updated = 0;
904
+ const failed = [];
905
+ const results = await Promise.allSettled(
906
+ this.config.seedUrls.map(async (url) => {
907
+ const wasKnown = this.isKnownUrl(url);
908
+ const manifest = await this.fetchAndRegister(url);
909
+ if (manifest) {
910
+ if (wasKnown) {
911
+ updated++;
912
+ } else {
913
+ added++;
914
+ }
915
+ } else {
916
+ failed.push(url);
917
+ }
918
+ })
919
+ );
920
+ return { added, updated, failed };
921
+ }
922
+ // ===========================================================================
923
+ // POLLING LIFECYCLE
924
+ // ===========================================================================
925
+ /**
926
+ * Start periodic polling of seed URLs.
927
+ */
928
+ startPolling() {
929
+ if (this.pollTimer) return;
930
+ this.pollTimer = setInterval(() => {
931
+ void this.pollAll();
932
+ }, this.config.pollIntervalMs);
933
+ }
934
+ /**
935
+ * Stop periodic polling.
936
+ */
937
+ stopPolling() {
938
+ if (this.pollTimer) {
939
+ clearInterval(this.pollTimer);
940
+ this.pollTimer = void 0;
941
+ }
942
+ }
943
+ /**
944
+ * Whether polling is currently active.
945
+ */
946
+ get isPolling() {
947
+ return this.pollTimer !== void 0;
948
+ }
949
+ // ===========================================================================
950
+ // CONVERSION: A2A AgentCard → AgentManifest
951
+ // ===========================================================================
952
+ /**
953
+ * Convert an A2A AgentCard to an AgentManifest.
954
+ */
955
+ a2aCardToManifest(card, sourceUrl) {
956
+ const capabilities = this.extractCapabilities(card);
957
+ const endpoint = this.extractEndpoint(card);
958
+ return {
959
+ id: card.id,
960
+ name: card.name,
961
+ version: card.version || "0.0.0",
962
+ description: card.description,
963
+ capabilities,
964
+ endpoints: [endpoint],
965
+ trustLevel: this.config.trustRemoteAs,
966
+ tags: ["remote", "a2a", ...card.provider?.organization ? [card.provider.organization] : []],
967
+ status: "online",
968
+ metadata: {
969
+ sourceUrl,
970
+ a2aEndpoint: card.endpoint,
971
+ provider: card.provider,
972
+ a2aCapabilities: card.capabilities,
973
+ skillCount: card.skills?.length ?? 0
974
+ }
975
+ };
976
+ }
977
+ // ===========================================================================
978
+ // FEDERATED DISCOVERY
979
+ // ===========================================================================
980
+ /**
981
+ * Discover agents across local registry + remote seeds.
982
+ * Ensures all seed URLs are polled before querying.
983
+ */
984
+ async discoverFederated(query) {
985
+ if (this.remoteAgentIds.size === 0 && this.config.seedUrls.length > 0) {
986
+ await this.pollAll();
987
+ }
988
+ return this.registry.discoverWithScores(query);
989
+ }
990
+ // ===========================================================================
991
+ // QUERIES
992
+ // ===========================================================================
993
+ /**
994
+ * Get all remote agent IDs tracked by this adapter.
995
+ */
996
+ getRemoteAgentIds() {
997
+ return Array.from(this.remoteAgentIds);
998
+ }
999
+ /**
1000
+ * Get the number of remote agents currently tracked.
1001
+ */
1002
+ get remoteAgentCount() {
1003
+ return this.remoteAgentIds.size;
1004
+ }
1005
+ /**
1006
+ * Get poll results for a specific URL.
1007
+ */
1008
+ getPollResult(url) {
1009
+ return this.lastPollResults.get(url);
1010
+ }
1011
+ /**
1012
+ * Add a seed URL dynamically (does not trigger immediate poll).
1013
+ */
1014
+ addSeedUrl(url) {
1015
+ if (!this.config.seedUrls.includes(url)) {
1016
+ this.config.seedUrls.push(url);
1017
+ }
1018
+ }
1019
+ /**
1020
+ * Remove a seed URL and optionally deregister its agent.
1021
+ */
1022
+ async removeSeedUrl(url, deregister = true) {
1023
+ this.config.seedUrls = this.config.seedUrls.filter((u) => u !== url);
1024
+ if (deregister) {
1025
+ for (const agentId of this.remoteAgentIds) {
1026
+ const manifest = this.registry.get(agentId);
1027
+ if (manifest?.metadata?.sourceUrl === url) {
1028
+ await this.registry.deregister(agentId);
1029
+ this.remoteAgentIds.delete(agentId);
1030
+ break;
1031
+ }
1032
+ }
1033
+ }
1034
+ }
1035
+ // ===========================================================================
1036
+ // PRIVATE HELPERS
1037
+ // ===========================================================================
1038
+ /**
1039
+ * Fetch an agent card from a URL.
1040
+ */
1041
+ async fetchAgentCard(url) {
1042
+ const fetchFn = this.config.fetchFn || globalThis.fetch;
1043
+ const controller = new AbortController();
1044
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
1045
+ try {
1046
+ const response = await fetchFn(url, {
1047
+ signal: controller.signal,
1048
+ headers: { Accept: "application/json" }
1049
+ });
1050
+ if (!response.ok) {
1051
+ return null;
1052
+ }
1053
+ const data = await response.json();
1054
+ return data;
1055
+ } catch {
1056
+ return null;
1057
+ } finally {
1058
+ clearTimeout(timeoutId);
1059
+ }
1060
+ }
1061
+ /**
1062
+ * Extract capabilities from an A2A AgentCard's skills.
1063
+ */
1064
+ extractCapabilities(card) {
1065
+ if (!card.skills || card.skills.length === 0) {
1066
+ return [{ type: "custom", domain: "general", name: card.name }];
1067
+ }
1068
+ const capMap = /* @__PURE__ */ new Map();
1069
+ for (const skill of card.skills) {
1070
+ const tags = skill.tags || [];
1071
+ const type = this.deriveType(tags);
1072
+ const domain = this.deriveDomain(tags);
1073
+ const key = `${type}:${domain}`;
1074
+ if (!capMap.has(key)) {
1075
+ capMap.set(key, {
1076
+ type,
1077
+ domain,
1078
+ name: skill.name,
1079
+ description: skill.description,
1080
+ available: true
1081
+ });
1082
+ }
1083
+ }
1084
+ return Array.from(capMap.values());
1085
+ }
1086
+ /**
1087
+ * Extract endpoint from an A2A AgentCard.
1088
+ */
1089
+ extractEndpoint(card) {
1090
+ const url = card.endpoint || "";
1091
+ const isSecure = url.startsWith("https");
1092
+ return {
1093
+ protocol: isSecure ? "https" : "http",
1094
+ address: url,
1095
+ primary: true,
1096
+ formats: ["json"]
1097
+ };
1098
+ }
1099
+ /**
1100
+ * Derive capability type from A2A skill tags.
1101
+ */
1102
+ deriveType(tags) {
1103
+ for (const tag of tags) {
1104
+ const mapped = TAG_TO_TYPE[tag.toLowerCase()];
1105
+ if (mapped) return mapped;
1106
+ }
1107
+ return "custom";
1108
+ }
1109
+ /**
1110
+ * Derive capability domain from A2A skill tags.
1111
+ */
1112
+ deriveDomain(tags) {
1113
+ for (const tag of tags) {
1114
+ const mapped = TAG_TO_DOMAIN[tag.toLowerCase()];
1115
+ if (mapped) return mapped;
1116
+ }
1117
+ return "general";
1118
+ }
1119
+ /**
1120
+ * Check if a URL has been successfully polled before.
1121
+ */
1122
+ isKnownUrl(url) {
1123
+ const result = this.lastPollResults.get(url);
1124
+ return !!result?.success;
1125
+ }
1126
+ };
1127
+
1128
+ // src/agents/TaskDelegationService.ts
1129
+ var import_crypto = require("crypto");
1130
+ var CANONICAL_TASK_BRIDGE_SCHEMA = "holoscript.task-bridge.v1";
1131
+ function createCanonicalTaskEnvelope(task) {
1132
+ return {
1133
+ schema: CANONICAL_TASK_BRIDGE_SCHEMA,
1134
+ task
1135
+ };
1136
+ }
1137
+ function canonicalTaskToA2ASendMessage(envelope, requestId, timestamp = (/* @__PURE__ */ new Date()).toISOString()) {
1138
+ return {
1139
+ jsonrpc: "2.0",
1140
+ id: requestId,
1141
+ method: "a2a.sendMessage",
1142
+ params: {
1143
+ message: {
1144
+ role: "user",
1145
+ parts: [
1146
+ {
1147
+ type: "data",
1148
+ mimeType: "application/json",
1149
+ data: {
1150
+ schema: envelope.schema,
1151
+ task: envelope.task,
1152
+ skillId: envelope.task.skillId,
1153
+ arguments: envelope.task.input,
1154
+ idempotencyKey: envelope.task.idempotency_key
1155
+ }
1156
+ }
1157
+ ],
1158
+ timestamp
1159
+ }
1160
+ }
1161
+ };
1162
+ }
1163
+ var DEFAULT_CONFIG2 = {
1164
+ defaultTimeout: 3e4,
1165
+ maxHistory: 1e3
1166
+ };
1167
+ var TaskDelegationService = class {
1168
+ registry;
1169
+ adapter;
1170
+ config;
1171
+ history = [];
1172
+ traceHistory = [];
1173
+ requestHistory = /* @__PURE__ */ new Map();
1174
+ constructor(registry, adapter, config = {}) {
1175
+ this.registry = registry;
1176
+ this.adapter = adapter;
1177
+ this.config = { ...DEFAULT_CONFIG2, ...config };
1178
+ }
1179
+ // ===========================================================================
1180
+ // DELEGATION
1181
+ // ===========================================================================
1182
+ /**
1183
+ * Delegate a task to a specific agent by ID.
1184
+ */
1185
+ async delegateTo(request) {
1186
+ const startTime = Date.now();
1187
+ const taskId = (0, import_crypto.randomUUID)();
1188
+ const timeout = request.timeout ?? this.config.defaultTimeout;
1189
+ const maxRetries = request.retries ?? 0;
1190
+ this.requestHistory.set(taskId, { ...request, arguments: { ...request.arguments } });
1191
+ this.emitTrace(taskId, "start", {
1192
+ targetAgentId: request.targetAgentId,
1193
+ skillId: request.skillId,
1194
+ timeout,
1195
+ maxRetries
1196
+ });
1197
+ const manifest = this.registry.get(request.targetAgentId);
1198
+ if (!manifest) {
1199
+ const result2 = {
1200
+ taskId,
1201
+ status: "rejected",
1202
+ error: `Agent not found: ${request.targetAgentId}`,
1203
+ durationMs: Date.now() - startTime,
1204
+ delegatedTo: { agentId: request.targetAgentId, endpoint: "unknown" }
1205
+ };
1206
+ this.addToHistory(result2);
1207
+ this.emitTrace(taskId, "rejected", { reason: result2.error });
1208
+ return result2;
1209
+ }
1210
+ const endpoint = this.getPrimaryEndpoint(manifest);
1211
+ const delegatedTo = { agentId: manifest.id, endpoint: endpoint?.address || "local" };
1212
+ let lastError = "";
1213
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
1214
+ this.emitTrace(taskId, "attempt", { attempt, maxRetries });
1215
+ if (attempt > 0) {
1216
+ const delay = Math.min(1e3 * Math.pow(2, attempt - 1) + Math.random() * 200, 1e4);
1217
+ this.emitTrace(taskId, "retry", { attempt, delayMs: delay });
1218
+ await this.sleep(delay);
1219
+ }
1220
+ try {
1221
+ const result2 = await this.executeWithTimeout(
1222
+ () => this.executeOnAgent(manifest, request.skillId, request.arguments, taskId, attempt),
1223
+ timeout
1224
+ );
1225
+ const delegationResult = {
1226
+ taskId,
1227
+ status: "completed",
1228
+ result: result2,
1229
+ durationMs: Date.now() - startTime,
1230
+ delegatedTo
1231
+ };
1232
+ this.addToHistory(delegationResult);
1233
+ this.emitTrace(taskId, "success", { attempt });
1234
+ return delegationResult;
1235
+ } catch (err) {
1236
+ lastError = err instanceof Error ? err.message : String(err);
1237
+ if (lastError === "TIMEOUT") {
1238
+ const result2 = {
1239
+ taskId,
1240
+ status: "timeout",
1241
+ error: `Delegation timed out after ${timeout}ms`,
1242
+ durationMs: Date.now() - startTime,
1243
+ delegatedTo
1244
+ };
1245
+ this.addToHistory(result2);
1246
+ this.emitTrace(taskId, "timeout", { attempt, timeoutMs: timeout });
1247
+ return result2;
1248
+ }
1249
+ this.emitTrace(taskId, "failure", { attempt, error: lastError });
1250
+ }
1251
+ }
1252
+ const result = {
1253
+ taskId,
1254
+ status: "failed",
1255
+ error: lastError || "Unknown error",
1256
+ durationMs: Date.now() - startTime,
1257
+ delegatedTo
1258
+ };
1259
+ this.addToHistory(result);
1260
+ this.emitTrace(taskId, "failure", { retriesExhausted: true, error: result.error });
1261
+ return result;
1262
+ }
1263
+ /**
1264
+ * Auto-delegate: find the best agent for a capability then delegate.
1265
+ */
1266
+ async autoDelegate(query, skillId, args, options) {
1267
+ const bestAgent = await this.registry.findBest({
1268
+ ...query,
1269
+ includeOffline: false
1270
+ });
1271
+ if (!bestAgent) {
1272
+ const startTime = Date.now();
1273
+ const result = {
1274
+ taskId: (0, import_crypto.randomUUID)(),
1275
+ status: "rejected",
1276
+ error: `No agent found matching query: ${JSON.stringify(query)}`,
1277
+ durationMs: Date.now() - startTime,
1278
+ delegatedTo: { agentId: "none", endpoint: "none" }
1279
+ };
1280
+ this.addToHistory(result);
1281
+ return result;
1282
+ }
1283
+ return this.delegateTo({
1284
+ targetAgentId: bestAgent.id,
1285
+ skillId,
1286
+ arguments: args,
1287
+ timeout: options?.timeout,
1288
+ retries: options?.retries
1289
+ });
1290
+ }
1291
+ /**
1292
+ * Get the status of a previously delegated task from history.
1293
+ */
1294
+ getStatus(taskId) {
1295
+ return this.history.find((r) => r.taskId === taskId);
1296
+ }
1297
+ /**
1298
+ * Get the full delegation history.
1299
+ */
1300
+ getDelegationHistory() {
1301
+ return [...this.history];
1302
+ }
1303
+ /**
1304
+ * Get observability trace events for delegations (optionally filtered by taskId).
1305
+ */
1306
+ getTraceHistory(taskId) {
1307
+ if (!taskId) return [...this.traceHistory];
1308
+ return this.traceHistory.filter((event) => event.taskId === taskId);
1309
+ }
1310
+ /**
1311
+ * Replay a previously delegated task using its original request payload.
1312
+ */
1313
+ async replay(taskId, overrides = {}) {
1314
+ const original = this.requestHistory.get(taskId);
1315
+ if (!original) {
1316
+ throw new Error(`Replay unavailable for taskId: ${taskId}`);
1317
+ }
1318
+ const replayRequest = {
1319
+ ...original,
1320
+ ...overrides,
1321
+ arguments: {
1322
+ ...original.arguments,
1323
+ ...overrides.arguments ?? {}
1324
+ }
1325
+ };
1326
+ this.emitTrace(taskId, "replay_requested", {
1327
+ targetAgentId: replayRequest.targetAgentId,
1328
+ skillId: replayRequest.skillId
1329
+ });
1330
+ try {
1331
+ const replayResult = await this.delegateTo(replayRequest);
1332
+ this.emitTrace(taskId, "replay_completed", { replayTaskId: replayResult.taskId });
1333
+ return replayResult;
1334
+ } catch (error) {
1335
+ const message = error instanceof Error ? error.message : String(error);
1336
+ this.emitTrace(taskId, "replay_failed", { error: message });
1337
+ throw error;
1338
+ }
1339
+ }
1340
+ /**
1341
+ * Get delegation stats.
1342
+ */
1343
+ getStats() {
1344
+ return {
1345
+ total: this.history.length,
1346
+ completed: this.history.filter((r) => r.status === "completed").length,
1347
+ failed: this.history.filter((r) => r.status === "failed").length,
1348
+ timeout: this.history.filter((r) => r.status === "timeout").length,
1349
+ rejected: this.history.filter((r) => r.status === "rejected").length
1350
+ };
1351
+ }
1352
+ // ===========================================================================
1353
+ // PRIVATE HELPERS
1354
+ // ===========================================================================
1355
+ /**
1356
+ * Execute a skill on an agent (local or remote).
1357
+ */
1358
+ async executeOnAgent(manifest, skillId, args, taskId, attempt) {
1359
+ const endpoint = this.getPrimaryEndpoint(manifest);
1360
+ if (!endpoint || endpoint.protocol === "local") {
1361
+ if (this.config.localExecutor) {
1362
+ return this.config.localExecutor(skillId, args);
1363
+ }
1364
+ throw new Error(`No local executor configured for agent ${manifest.id}`);
1365
+ }
1366
+ if (endpoint.protocol === "http" || endpoint.protocol === "https") {
1367
+ return this.executeRemote(endpoint.address, skillId, args, taskId, attempt);
1368
+ }
1369
+ throw new Error(`Unsupported endpoint protocol: ${endpoint.protocol}`);
1370
+ }
1371
+ /**
1372
+ * Execute via remote A2A JSON-RPC.
1373
+ */
1374
+ async executeRemote(endpointUrl, skillId, args, taskId, attempt) {
1375
+ const fetchFn = this.config.fetchFn || globalThis.fetch;
1376
+ const idempotencyKey = this.config.idempotencyKeyFactory?.({
1377
+ taskId,
1378
+ attempt,
1379
+ endpointUrl,
1380
+ skillId
1381
+ }) ?? `hs-delegation-${taskId}-attempt-${attempt}`;
1382
+ const envelope = createCanonicalTaskEnvelope({
1383
+ id: taskId,
1384
+ intent: skillId,
1385
+ skillId,
1386
+ input: args,
1387
+ idempotency_key: idempotencyKey,
1388
+ timeout: this.config.defaultTimeout
1389
+ });
1390
+ const jsonRpcRequest = canonicalTaskToA2ASendMessage(envelope, (0, import_crypto.randomUUID)());
1391
+ if (this.config.transportAdapter) {
1392
+ return this.config.transportAdapter.send({
1393
+ endpointUrl,
1394
+ requestBody: jsonRpcRequest,
1395
+ idempotencyKey,
1396
+ fetchFn
1397
+ });
1398
+ }
1399
+ const response = await fetchFn(endpointUrl, {
1400
+ method: "POST",
1401
+ headers: {
1402
+ "Content-Type": "application/json",
1403
+ "Idempotency-Key": idempotencyKey
1404
+ },
1405
+ body: JSON.stringify(jsonRpcRequest)
1406
+ });
1407
+ if (!response.ok) {
1408
+ throw new Error(`Remote agent returned HTTP ${response.status}`);
1409
+ }
1410
+ const data = await response.json();
1411
+ if (data.error) {
1412
+ throw new Error(data.error.message);
1413
+ }
1414
+ return data.result;
1415
+ }
1416
+ /**
1417
+ * Execute a function with a timeout.
1418
+ */
1419
+ async executeWithTimeout(fn, timeoutMs) {
1420
+ return Promise.race([
1421
+ fn(),
1422
+ new Promise((_, reject) => {
1423
+ setTimeout(() => reject(new Error("TIMEOUT")), timeoutMs);
1424
+ })
1425
+ ]);
1426
+ }
1427
+ /**
1428
+ * Get the primary endpoint from a manifest.
1429
+ */
1430
+ getPrimaryEndpoint(manifest) {
1431
+ return manifest.endpoints.find((e) => e.primary) || manifest.endpoints[0];
1432
+ }
1433
+ /**
1434
+ * Add a result to history with LRU eviction.
1435
+ */
1436
+ addToHistory(result) {
1437
+ this.history.push(result);
1438
+ while (this.history.length > this.config.maxHistory) {
1439
+ const evicted = this.history.shift();
1440
+ if (evicted) {
1441
+ this.requestHistory.delete(evicted.taskId);
1442
+ }
1443
+ }
1444
+ }
1445
+ /**
1446
+ * Emit and store delegation observability traces.
1447
+ */
1448
+ emitTrace(taskId, phase, metadata) {
1449
+ const event = {
1450
+ taskId,
1451
+ phase,
1452
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1453
+ ...metadata ? { metadata } : {}
1454
+ };
1455
+ this.traceHistory.push(event);
1456
+ this.config.traceHook?.(event);
1457
+ }
1458
+ /**
1459
+ * Sleep utility.
1460
+ */
1461
+ sleep(ms) {
1462
+ return new Promise((resolve) => setTimeout(resolve, ms));
1463
+ }
1464
+ };
1465
+
1466
+ // src/agents/SkillWorkflowEngine.ts
1467
+ var SkillWorkflowEngine = class {
1468
+ // ===========================================================================
1469
+ // VALIDATION
1470
+ // ===========================================================================
1471
+ /**
1472
+ * Validate a workflow definition.
1473
+ */
1474
+ validate(definition, availableSkills) {
1475
+ const errors = [];
1476
+ const warnings = [];
1477
+ const stepIds = new Set(definition.steps.map((s) => s.id));
1478
+ if (definition.steps.length === 0) {
1479
+ errors.push("Workflow must have at least one step");
1480
+ return { valid: false, errors, warnings, executionPlan: { groups: [], estimatedSteps: 0 } };
1481
+ }
1482
+ if (stepIds.size !== definition.steps.length) {
1483
+ errors.push("Duplicate step IDs detected");
1484
+ }
1485
+ for (const step of definition.steps) {
1486
+ if (!step.id) {
1487
+ errors.push('Step missing required "id" field');
1488
+ }
1489
+ if (!step.skillId) {
1490
+ errors.push(`Step "${step.id}": missing required "skillId" field`);
1491
+ } else if (availableSkills && !availableSkills.includes(step.skillId)) {
1492
+ errors.push(`Step "${step.id}": skill "${step.skillId}" not found in available skills`);
1493
+ }
1494
+ if (step.dependsOn) {
1495
+ for (const depId of step.dependsOn) {
1496
+ if (!stepIds.has(depId)) {
1497
+ errors.push(`Step "${step.id}": dependency "${depId}" does not exist`);
1498
+ }
1499
+ }
1500
+ }
1501
+ for (const [paramName, input] of Object.entries(step.inputs || {})) {
1502
+ if (input.type === "ref") {
1503
+ if (!stepIds.has(input.stepId)) {
1504
+ errors.push(
1505
+ `Step "${step.id}": input "${paramName}" references non-existent step "${input.stepId}"`
1506
+ );
1507
+ }
1508
+ if (!step.dependsOn || !step.dependsOn.includes(input.stepId)) {
1509
+ warnings.push(
1510
+ `Step "${step.id}": input "${paramName}" references step "${input.stepId}" which is not in dependsOn \u2014 adding implicit dependency`
1511
+ );
1512
+ }
1513
+ }
1514
+ }
1515
+ if (step.onError === "fallback" && !step.fallbackSkillId) {
1516
+ warnings.push(`Step "${step.id}": onError='fallback' but no fallbackSkillId specified`);
1517
+ }
1518
+ }
1519
+ const cycleCheck = this.detectCycles(definition.steps);
1520
+ if (cycleCheck) {
1521
+ errors.push(`Cycle detected: ${cycleCheck}`);
1522
+ }
1523
+ const groups = errors.length === 0 ? this.buildExecutionGroups(definition.steps) : [];
1524
+ return {
1525
+ valid: errors.length === 0,
1526
+ errors,
1527
+ warnings,
1528
+ executionPlan: {
1529
+ groups,
1530
+ estimatedSteps: definition.steps.length
1531
+ }
1532
+ };
1533
+ }
1534
+ // ===========================================================================
1535
+ // EXECUTION
1536
+ // ===========================================================================
1537
+ /**
1538
+ * Execute a workflow using the provided executor function.
1539
+ */
1540
+ async execute(definition, executor, onProgress) {
1541
+ const startTime = Date.now();
1542
+ const stepResults = [];
1543
+ const stepOutputs = /* @__PURE__ */ new Map();
1544
+ const context = definition.context || {};
1545
+ const groups = this.buildExecutionGroups(definition.steps);
1546
+ const stepMap = new Map(definition.steps.map((s) => [s.id, s]));
1547
+ let hasFailed = false;
1548
+ for (const group of groups) {
1549
+ const groupResults = await Promise.all(
1550
+ group.map(async (stepId) => {
1551
+ const step = stepMap.get(stepId);
1552
+ if (hasFailed && step.onError !== "skip") {
1553
+ const result = {
1554
+ stepId,
1555
+ status: "skipped",
1556
+ output: {},
1557
+ durationMs: 0,
1558
+ error: "Skipped due to previous failure"
1559
+ };
1560
+ return result;
1561
+ }
1562
+ onProgress?.(stepId, "starting");
1563
+ const resolvedInputs = this.resolveInputs(step, stepOutputs, context);
1564
+ const stepStart = Date.now();
1565
+ try {
1566
+ const output = await this.executeStep(step, resolvedInputs, executor);
1567
+ stepOutputs.set(stepId, output);
1568
+ onProgress?.(stepId, "completed");
1569
+ return {
1570
+ stepId,
1571
+ status: "completed",
1572
+ output,
1573
+ durationMs: Date.now() - stepStart
1574
+ };
1575
+ } catch (err) {
1576
+ const error = err instanceof Error ? err.message : String(err);
1577
+ onProgress?.(stepId, "failed");
1578
+ if (step.onError === "skip") {
1579
+ stepOutputs.set(stepId, {});
1580
+ return {
1581
+ stepId,
1582
+ status: "skipped",
1583
+ output: {},
1584
+ durationMs: Date.now() - stepStart,
1585
+ error
1586
+ };
1587
+ }
1588
+ hasFailed = true;
1589
+ return {
1590
+ stepId,
1591
+ status: "failed",
1592
+ output: {},
1593
+ durationMs: Date.now() - stepStart,
1594
+ error
1595
+ };
1596
+ }
1597
+ })
1598
+ );
1599
+ stepResults.push(...groupResults);
1600
+ }
1601
+ const completedCount = stepResults.filter((r) => r.status === "completed").length;
1602
+ let status;
1603
+ if (completedCount === definition.steps.length) {
1604
+ status = "completed";
1605
+ } else if (completedCount > 0) {
1606
+ status = "partial";
1607
+ } else {
1608
+ status = "failed";
1609
+ }
1610
+ return {
1611
+ workflowId: definition.id,
1612
+ status,
1613
+ stepResults,
1614
+ totalDurationMs: Date.now() - startTime
1615
+ };
1616
+ }
1617
+ // ===========================================================================
1618
+ // PRIVATE HELPERS
1619
+ // ===========================================================================
1620
+ /**
1621
+ * Execute a single step with optional fallback.
1622
+ */
1623
+ async executeStep(step, resolvedInputs, executor) {
1624
+ try {
1625
+ if (step.timeout) {
1626
+ return await Promise.race([
1627
+ executor(step.skillId, resolvedInputs),
1628
+ new Promise(
1629
+ (_, reject) => setTimeout(
1630
+ () => reject(new Error(`Step "${step.id}" timed out after ${step.timeout}ms`)),
1631
+ step.timeout
1632
+ )
1633
+ )
1634
+ ]);
1635
+ }
1636
+ return await executor(step.skillId, resolvedInputs);
1637
+ } catch (err) {
1638
+ if (step.onError === "fallback" && step.fallbackSkillId) {
1639
+ return executor(step.fallbackSkillId, resolvedInputs);
1640
+ }
1641
+ throw err;
1642
+ }
1643
+ }
1644
+ /**
1645
+ * Resolve step inputs from literal values, step outputs, or context.
1646
+ */
1647
+ resolveInputs(step, stepOutputs, context) {
1648
+ const resolved = {};
1649
+ for (const [paramName, input] of Object.entries(step.inputs || {})) {
1650
+ switch (input.type) {
1651
+ case "literal":
1652
+ resolved[paramName] = input.value;
1653
+ break;
1654
+ case "ref": {
1655
+ const outputs = stepOutputs.get(input.stepId);
1656
+ resolved[paramName] = outputs?.[input.outputKey];
1657
+ break;
1658
+ }
1659
+ case "context":
1660
+ resolved[paramName] = context[input.key];
1661
+ break;
1662
+ }
1663
+ }
1664
+ return resolved;
1665
+ }
1666
+ /**
1667
+ * Detect cycles in the step dependency graph.
1668
+ * Returns a cycle description string, or null if no cycles.
1669
+ */
1670
+ detectCycles(steps) {
1671
+ const visited = /* @__PURE__ */ new Set();
1672
+ const inStack = /* @__PURE__ */ new Set();
1673
+ const adjList = /* @__PURE__ */ new Map();
1674
+ for (const step of steps) {
1675
+ const deps = [...step.dependsOn || []];
1676
+ for (const input of Object.values(step.inputs || {})) {
1677
+ if (input.type === "ref" && !deps.includes(input.stepId)) {
1678
+ deps.push(input.stepId);
1679
+ }
1680
+ }
1681
+ adjList.set(step.id, deps);
1682
+ }
1683
+ const dfs = (nodeId, path) => {
1684
+ if (inStack.has(nodeId)) {
1685
+ return path.concat(nodeId).join(" \u2192 ");
1686
+ }
1687
+ if (visited.has(nodeId)) return null;
1688
+ visited.add(nodeId);
1689
+ inStack.add(nodeId);
1690
+ for (const dep of adjList.get(nodeId) || []) {
1691
+ const cycle = dfs(dep, [...path, nodeId]);
1692
+ if (cycle) return cycle;
1693
+ }
1694
+ inStack.delete(nodeId);
1695
+ return null;
1696
+ };
1697
+ for (const step of steps) {
1698
+ if (!visited.has(step.id)) {
1699
+ const cycle = dfs(step.id, []);
1700
+ if (cycle) return cycle;
1701
+ }
1702
+ }
1703
+ return null;
1704
+ }
1705
+ /**
1706
+ * Build parallel execution groups via topological sort.
1707
+ * Each group contains steps that can run concurrently.
1708
+ */
1709
+ buildExecutionGroups(steps) {
1710
+ const inDegree = /* @__PURE__ */ new Map();
1711
+ const dependents = /* @__PURE__ */ new Map();
1712
+ for (const step of steps) {
1713
+ if (!inDegree.has(step.id)) inDegree.set(step.id, 0);
1714
+ if (!dependents.has(step.id)) dependents.set(step.id, []);
1715
+ const allDeps = this.getAllDependencies(step);
1716
+ for (const dep of allDeps) {
1717
+ inDegree.set(step.id, (inDegree.get(step.id) || 0) + 1);
1718
+ if (!dependents.has(dep)) dependents.set(dep, []);
1719
+ dependents.get(dep).push(step.id);
1720
+ }
1721
+ }
1722
+ const groups = [];
1723
+ let ready = [...inDegree.entries()].filter(([, deg]) => deg === 0).map(([id]) => id);
1724
+ while (ready.length > 0) {
1725
+ groups.push([...ready]);
1726
+ const nextReady = [];
1727
+ for (const id of ready) {
1728
+ for (const dependent of dependents.get(id) || []) {
1729
+ const newDeg = (inDegree.get(dependent) || 1) - 1;
1730
+ inDegree.set(dependent, newDeg);
1731
+ if (newDeg === 0) {
1732
+ nextReady.push(dependent);
1733
+ }
1734
+ }
1735
+ }
1736
+ ready = nextReady;
1737
+ }
1738
+ return groups;
1739
+ }
1740
+ /**
1741
+ * Get all dependencies for a step (explicit + implicit from ref inputs).
1742
+ */
1743
+ getAllDependencies(step) {
1744
+ const deps = new Set(step.dependsOn || []);
1745
+ for (const input of Object.values(step.inputs || {})) {
1746
+ if (input.type === "ref") {
1747
+ deps.add(input.stepId);
1748
+ }
1749
+ }
1750
+ return Array.from(deps);
1751
+ }
1752
+ };
1753
+
1754
+ // src/protocol/implementations.ts
1755
+ var BaseAgent = class {
1756
+ /**
1757
+ * Execute a complete 7-phase cycle
1758
+ */
1759
+ async runCycle(task, context = {}) {
1760
+ const startedAt = Date.now();
1761
+ const cycleId = `cycle_${startedAt}_${Math.random().toString(36).slice(2, 8)}`;
1762
+ const phases = [];
1763
+ const runPhase = async (phase, fn, input) => {
1764
+ const start = Date.now();
1765
+ try {
1766
+ const result = await fn.call(this, input);
1767
+ result.durationMs = Date.now() - start;
1768
+ phases.push(result);
1769
+ return result;
1770
+ } catch (err) {
1771
+ const failResult = {
1772
+ phase,
1773
+ status: "failure",
1774
+ data: err instanceof Error ? err.message : String(err),
1775
+ durationMs: Date.now() - start,
1776
+ timestamp: Date.now()
1777
+ };
1778
+ phases.push(failResult);
1779
+ return failResult;
1780
+ }
1781
+ };
1782
+ const intakeResult = await runPhase(0 /* INTAKE */, this.intake, { task, ...context });
1783
+ const reflectResult = await runPhase(1 /* REFLECT */, this.reflect, intakeResult.data);
1784
+ const executeResult = await runPhase(2 /* EXECUTE */, this.execute, reflectResult.data);
1785
+ const compressResult = await runPhase(
1786
+ 3 /* COMPRESS */,
1787
+ this.compress,
1788
+ executeResult.data
1789
+ );
1790
+ const reintakeResult = await runPhase(
1791
+ 4 /* REINTAKE */,
1792
+ this.reintake,
1793
+ compressResult.data
1794
+ );
1795
+ const growResult = await runPhase(5 /* GROW */, this.grow, reintakeResult.data);
1796
+ await runPhase(6 /* EVOLVE */, this.evolve, growResult.data);
1797
+ const failed = phases.some((p) => p.status === "failure");
1798
+ return {
1799
+ cycleId,
1800
+ task,
1801
+ domain: this.identity.domain,
1802
+ phases,
1803
+ status: failed ? "partial" : "complete",
1804
+ totalDurationMs: Date.now() - startedAt,
1805
+ startedAt,
1806
+ completedAt: Date.now()
1807
+ };
1808
+ }
1809
+ };
1810
+
1811
+ // src/agents/OrchestratorAgent.ts
1812
+ var OrchestratorAgent = class extends BaseAgent {
1813
+ identity;
1814
+ registry;
1815
+ adapter;
1816
+ delegator;
1817
+ workflowEngine;
1818
+ config;
1819
+ /** Learned delegation patterns (GROW phase) */
1820
+ patterns = /* @__PURE__ */ new Map();
1821
+ /** Routing preferences (EVOLVE phase) */
1822
+ preferences = /* @__PURE__ */ new Map();
1823
+ // skillId → preferred agentId
1824
+ /** Last discovered agents */
1825
+ lastDiscovery = [];
1826
+ constructor(config) {
1827
+ super();
1828
+ this.config = config;
1829
+ this.identity = {
1830
+ id: `orchestrator-${config.name.toLowerCase().replace(/\s+/g, "-")}`,
1831
+ name: config.name,
1832
+ domain: config.domain,
1833
+ version: "1.0.0",
1834
+ capabilities: ["orchestrate", "delegate", "discover", "workflow"]
1835
+ };
1836
+ this.registry = getDefaultRegistry();
1837
+ this.adapter = new FederatedRegistryAdapter(this.registry, {
1838
+ seedUrls: config.seedUrls || [],
1839
+ pollIntervalMs: config.discoveryIntervalMs || 6e4,
1840
+ fetchFn: config.fetchFn
1841
+ });
1842
+ this.delegator = new TaskDelegationService(this.registry, this.adapter, {
1843
+ localExecutor: config.localExecutor
1844
+ });
1845
+ this.workflowEngine = new SkillWorkflowEngine();
1846
+ }
1847
+ // ===========================================================================
1848
+ // PHASE 0: INTAKE — Discover available agents
1849
+ // ===========================================================================
1850
+ async intake(input) {
1851
+ const startTime = Date.now();
1852
+ const data = input;
1853
+ if (this.config.autoDiscovery !== false) {
1854
+ await this.adapter.pollAll();
1855
+ }
1856
+ const allAgents = this.registry.getAllManifests();
1857
+ const onlineAgents = allAgents.filter((a) => a.status === "online");
1858
+ return {
1859
+ phase: 0 /* INTAKE */,
1860
+ status: "success",
1861
+ data: {
1862
+ task: data.task || "orchestrate",
1863
+ context: data,
1864
+ totalAgents: allAgents.length,
1865
+ onlineAgents: onlineAgents.length,
1866
+ remoteAgents: this.adapter.remoteAgentCount,
1867
+ agents: onlineAgents.map((a) => ({
1868
+ id: a.id,
1869
+ name: a.name,
1870
+ capabilities: a.capabilities.map((c) => `${c.type}:${c.domain}`)
1871
+ }))
1872
+ },
1873
+ durationMs: Date.now() - startTime,
1874
+ timestamp: Date.now()
1875
+ };
1876
+ }
1877
+ // ===========================================================================
1878
+ // PHASE 1: REFLECT — Match capabilities to task requirements
1879
+ // ===========================================================================
1880
+ async reflect(data) {
1881
+ const startTime = Date.now();
1882
+ const intakeData = data;
1883
+ const task = intakeData.task || "";
1884
+ const query = this.taskToQuery(task, intakeData.context);
1885
+ this.lastDiscovery = await this.registry.discoverWithScores(query);
1886
+ const preferredAgents = this.getPreferredAgents(task);
1887
+ return {
1888
+ phase: 1 /* REFLECT */,
1889
+ status: "success",
1890
+ data: {
1891
+ task,
1892
+ matchingAgents: this.lastDiscovery.length,
1893
+ topAgent: this.lastDiscovery[0] ? { id: this.lastDiscovery[0].manifest.id, score: this.lastDiscovery[0].score } : null,
1894
+ preferredAgents,
1895
+ query
1896
+ },
1897
+ durationMs: Date.now() - startTime,
1898
+ timestamp: Date.now()
1899
+ };
1900
+ }
1901
+ // ===========================================================================
1902
+ // PHASE 2: EXECUTE — Delegate tasks or run workflows
1903
+ // ===========================================================================
1904
+ async execute(plan) {
1905
+ const startTime = Date.now();
1906
+ const reflectData = plan;
1907
+ const task = reflectData.task || "";
1908
+ let result = null;
1909
+ let executionType = "none";
1910
+ if (this.lastDiscovery.length > 0) {
1911
+ const bestAgent = this.lastDiscovery[0].manifest;
1912
+ result = await this.delegator.delegateTo({
1913
+ targetAgentId: bestAgent.id,
1914
+ skillId: task,
1915
+ arguments: reflectData.query || {}
1916
+ });
1917
+ executionType = "delegation";
1918
+ }
1919
+ return {
1920
+ phase: 2 /* EXECUTE */,
1921
+ status: "success",
1922
+ data: {
1923
+ executionType,
1924
+ result,
1925
+ task
1926
+ },
1927
+ durationMs: Date.now() - startTime,
1928
+ timestamp: Date.now()
1929
+ };
1930
+ }
1931
+ // ===========================================================================
1932
+ // PHASE 3: COMPRESS — Summarize results
1933
+ // ===========================================================================
1934
+ async compress(results) {
1935
+ const startTime = Date.now();
1936
+ const execData = results;
1937
+ const result = execData.result;
1938
+ return {
1939
+ phase: 3 /* COMPRESS */,
1940
+ status: "success",
1941
+ data: {
1942
+ summary: {
1943
+ executionType: execData.executionType,
1944
+ status: result?.status || "no-execution",
1945
+ task: execData.task,
1946
+ durationMs: result?.durationMs
1947
+ }
1948
+ },
1949
+ durationMs: Date.now() - startTime,
1950
+ timestamp: Date.now()
1951
+ };
1952
+ }
1953
+ // ===========================================================================
1954
+ // PHASE 4: REINTAKE — Check delegation results
1955
+ // ===========================================================================
1956
+ async reintake(compressed) {
1957
+ const startTime = Date.now();
1958
+ const summary = compressed.summary;
1959
+ const stats = this.delegator.getStats();
1960
+ return {
1961
+ phase: 4 /* REINTAKE */,
1962
+ status: "success",
1963
+ data: {
1964
+ delegationStats: stats,
1965
+ lastResult: summary,
1966
+ registryHealth: this.registry.getStatusCounts()
1967
+ },
1968
+ durationMs: Date.now() - startTime,
1969
+ timestamp: Date.now()
1970
+ };
1971
+ }
1972
+ // ===========================================================================
1973
+ // PHASE 5: GROW — Learn patterns from delegations
1974
+ // ===========================================================================
1975
+ async grow(learnings) {
1976
+ const startTime = Date.now();
1977
+ const data = learnings;
1978
+ const lastResult = data.lastResult;
1979
+ if (lastResult?.status === "completed") {
1980
+ const key = `${lastResult.task}`;
1981
+ const existing = this.patterns.get(key);
1982
+ if (existing) {
1983
+ existing.successCount++;
1984
+ existing.avgDurationMs = (existing.avgDurationMs + (lastResult.durationMs || 0)) / 2;
1985
+ existing.lastUsed = Date.now();
1986
+ } else {
1987
+ this.patterns.set(key, {
1988
+ agentId: "unknown",
1989
+ skillId: key,
1990
+ successCount: 1,
1991
+ failureCount: 0,
1992
+ avgDurationMs: lastResult.durationMs || 0,
1993
+ lastUsed: Date.now()
1994
+ });
1995
+ }
1996
+ }
1997
+ return {
1998
+ phase: 5 /* GROW */,
1999
+ status: "success",
2000
+ data: {
2001
+ totalPatterns: this.patterns.size,
2002
+ newPattern: lastResult?.task || null
2003
+ },
2004
+ durationMs: Date.now() - startTime,
2005
+ timestamp: Date.now()
2006
+ };
2007
+ }
2008
+ // ===========================================================================
2009
+ // PHASE 6: EVOLVE — Optimize routing preferences
2010
+ // ===========================================================================
2011
+ async evolve(adaptations) {
2012
+ const startTime = Date.now();
2013
+ for (const [skillId, pattern] of this.patterns) {
2014
+ if (pattern.successCount > pattern.failureCount) {
2015
+ this.preferences.set(skillId, pattern.agentId);
2016
+ }
2017
+ }
2018
+ return {
2019
+ phase: 6 /* EVOLVE */,
2020
+ status: "success",
2021
+ data: {
2022
+ totalPreferences: this.preferences.size,
2023
+ totalPatterns: this.patterns.size
2024
+ },
2025
+ durationMs: Date.now() - startTime,
2026
+ timestamp: Date.now()
2027
+ };
2028
+ }
2029
+ // ===========================================================================
2030
+ // CONVENIENCE METHODS
2031
+ // ===========================================================================
2032
+ /**
2033
+ * Delegate a task without running a full cycle.
2034
+ */
2035
+ async delegateTask(skillId, args) {
2036
+ const preferredAgentId = this.preferences.get(skillId);
2037
+ if (preferredAgentId && this.registry.has(preferredAgentId)) {
2038
+ return this.delegator.delegateTo({
2039
+ targetAgentId: preferredAgentId,
2040
+ skillId,
2041
+ arguments: args
2042
+ });
2043
+ }
2044
+ return this.delegator.autoDelegate({}, skillId, args);
2045
+ }
2046
+ /**
2047
+ * Run a workflow without running a full cycle.
2048
+ */
2049
+ async runWorkflow(definition) {
2050
+ const executor = this.config.localExecutor ? async (skillId, inputs) => {
2051
+ const result = await this.config.localExecutor(skillId, inputs);
2052
+ return typeof result === "object" && result !== null ? result : { result };
2053
+ } : async (skillId, inputs) => {
2054
+ return { skillId, inputs, note: "No executor configured" };
2055
+ };
2056
+ return this.workflowEngine.execute(definition, executor);
2057
+ }
2058
+ /**
2059
+ * Get all discovered agents.
2060
+ */
2061
+ getDiscoveredAgents() {
2062
+ return this.registry.getAllManifests();
2063
+ }
2064
+ /**
2065
+ * Get learned patterns.
2066
+ */
2067
+ getPatterns() {
2068
+ return Array.from(this.patterns.values());
2069
+ }
2070
+ /**
2071
+ * Stop polling and cleanup.
2072
+ */
2073
+ shutdown() {
2074
+ this.adapter.stopPolling();
2075
+ }
2076
+ // ===========================================================================
2077
+ // PRIVATE HELPERS
2078
+ // ===========================================================================
2079
+ taskToQuery(task, context) {
2080
+ const query = { includeOffline: false };
2081
+ if (context?.type) query.type = context.type;
2082
+ if (context?.domain) query.domain = context.domain;
2083
+ if (context?.tags) query.tags = context.tags;
2084
+ return query;
2085
+ }
2086
+ getPreferredAgents(task) {
2087
+ const preferred = [];
2088
+ const agentId = this.preferences.get(task);
2089
+ if (agentId) preferred.push(agentId);
2090
+ return preferred;
2091
+ }
2092
+ };
2093
+
2094
+ // src/agents/AgentWalletRegistry.ts
2095
+ var AgentWalletRegistry = class _AgentWalletRegistry {
2096
+ static instance;
2097
+ wallets = /* @__PURE__ */ new Map();
2098
+ constructor() {
2099
+ }
2100
+ static getInstance() {
2101
+ if (!_AgentWalletRegistry.instance) {
2102
+ _AgentWalletRegistry.instance = new _AgentWalletRegistry();
2103
+ }
2104
+ return _AgentWalletRegistry.instance;
2105
+ }
2106
+ /**
2107
+ * Registers a new agent wallet mapping
2108
+ */
2109
+ registerWallet(agentId, walletAddress, networkId = 8453) {
2110
+ const wallet = {
2111
+ agentId,
2112
+ walletAddress,
2113
+ networkId,
2114
+ balanceThreshold: 1e-3
2115
+ // 0.001 ETH
2116
+ };
2117
+ this.wallets.set(agentId, wallet);
2118
+ return wallet;
2119
+ }
2120
+ /**
2121
+ * Retrieves an agent's registered wallet
2122
+ */
2123
+ getWallet(agentId) {
2124
+ return this.wallets.get(agentId);
2125
+ }
2126
+ /**
2127
+ * Removes an agent's wallet from the registry
2128
+ */
2129
+ unregisterWallet(agentId) {
2130
+ return this.wallets.delete(agentId);
2131
+ }
2132
+ /**
2133
+ * Authorizes an agent transaction using EIP-712 signature fallback
2134
+ * (Placeholder for Coinbase AgentKit KMS signing)
2135
+ */
2136
+ async authorizeTransaction(agentId, payload) {
2137
+ const wallet = this.getWallet(agentId);
2138
+ if (!wallet) {
2139
+ throw new Error(`[AgentWalletRegistry] No wallet registered for agent ${agentId}`);
2140
+ }
2141
+ const mockHash = "0x" + Buffer.from(JSON.stringify(payload)).toString("hex").slice(0, 64);
2142
+ return mockHash;
2143
+ }
2144
+ };
2145
+
2146
+ // src/agents/AuthenticatedCRDT.ts
2147
+ function computeSignature(payload, signer, timestamp) {
2148
+ const data = JSON.stringify({ payload, signer: signer.id, timestamp });
2149
+ let hash = 0;
2150
+ for (let i = 0; i < data.length; i++) {
2151
+ hash = (hash << 5) - hash + data.charCodeAt(i) | 0;
2152
+ }
2153
+ return Math.abs(hash).toString(16).padStart(8, "0");
2154
+ }
2155
+ function signOperation(payload, signer, scopeTag, timestamp) {
2156
+ return {
2157
+ payload,
2158
+ signer,
2159
+ timestamp,
2160
+ signature: computeSignature(payload, signer, timestamp),
2161
+ scopeTag
2162
+ };
2163
+ }
2164
+ function verifyOperation(op) {
2165
+ if (op.signer.revoked) return { valid: false, reason: "Signer DID revoked" };
2166
+ if (!op.signer.scope.includes(op.scopeTag) && !op.signer.scope.includes("*")) {
2167
+ return { valid: false, reason: `Signer lacks scope '${op.scopeTag}'` };
2168
+ }
2169
+ const expected = computeSignature(op.payload, op.signer, op.timestamp);
2170
+ if (op.signature !== expected) return { valid: false, reason: "Signature mismatch" };
2171
+ return { valid: true };
2172
+ }
2173
+ var LWWRegister = class {
2174
+ value;
2175
+ timestamp;
2176
+ lastSigner;
2177
+ history = [];
2178
+ constructor(initialValue) {
2179
+ this.value = initialValue;
2180
+ this.timestamp = 0;
2181
+ this.lastSigner = null;
2182
+ }
2183
+ /** Get current value */
2184
+ get() {
2185
+ return this.value;
2186
+ }
2187
+ /** Get last write timestamp */
2188
+ getTimestamp() {
2189
+ return this.timestamp;
2190
+ }
2191
+ /** Set value with a signed operation */
2192
+ set(op) {
2193
+ const verification = verifyOperation(op);
2194
+ if (!verification.valid) return { accepted: false, reason: verification.reason };
2195
+ if (op.timestamp <= this.timestamp) return { accepted: false, reason: "Stale timestamp" };
2196
+ this.value = op.payload;
2197
+ this.timestamp = op.timestamp;
2198
+ this.lastSigner = op.signer;
2199
+ this.history.push(op);
2200
+ return { accepted: true };
2201
+ }
2202
+ /** Merge with another register (LWW semantics) */
2203
+ merge(other) {
2204
+ if (other.timestamp > this.timestamp) {
2205
+ this.value = other.value;
2206
+ this.timestamp = other.timestamp;
2207
+ this.lastSigner = other.lastSigner;
2208
+ }
2209
+ }
2210
+ /** Get operation history */
2211
+ getHistory() {
2212
+ return [...this.history];
2213
+ }
2214
+ };
2215
+ var GCounter = class _GCounter {
2216
+ counts = /* @__PURE__ */ new Map();
2217
+ // nodeId → count
2218
+ /** Increment for a specific node */
2219
+ increment(nodeId, amount = 1) {
2220
+ this.counts.set(nodeId, (this.counts.get(nodeId) || 0) + amount);
2221
+ }
2222
+ /** Get the total value */
2223
+ value() {
2224
+ let total = 0;
2225
+ for (const v of this.counts.values()) total += v;
2226
+ return total;
2227
+ }
2228
+ /** Get the count for a specific node */
2229
+ nodeValue(nodeId) {
2230
+ return this.counts.get(nodeId) || 0;
2231
+ }
2232
+ /** Merge with another counter (take max per node) */
2233
+ merge(other) {
2234
+ for (const [nodeId, count] of other.counts) {
2235
+ this.counts.set(nodeId, Math.max(this.counts.get(nodeId) || 0, count));
2236
+ }
2237
+ }
2238
+ /** Export state */
2239
+ toJSON() {
2240
+ const obj = {};
2241
+ for (const [k, v] of this.counts) obj[k] = v;
2242
+ return obj;
2243
+ }
2244
+ /** Import state */
2245
+ static fromJSON(data) {
2246
+ const counter = new _GCounter();
2247
+ for (const [k, v] of Object.entries(data)) counter.counts.set(k, v);
2248
+ return counter;
2249
+ }
2250
+ };
2251
+ var ORSet = class {
2252
+ elements = /* @__PURE__ */ new Map();
2253
+ // tag → element
2254
+ tombstones = /* @__PURE__ */ new Set();
2255
+ // removed tags
2256
+ tagCounter = 0;
2257
+ /** Add an element with a signed operation */
2258
+ add(value, signer, timestamp) {
2259
+ if (signer.revoked) return "";
2260
+ const tag = `${signer.id}_${timestamp}_${this.tagCounter++}`;
2261
+ this.elements.set(tag, { value, tag, signer, timestamp });
2262
+ return tag;
2263
+ }
2264
+ /** Remove an element by value (removes all copies) */
2265
+ remove(value, _signer) {
2266
+ let removed = 0;
2267
+ for (const [tag, elem] of this.elements) {
2268
+ if (this.valueEquals(elem.value, value)) {
2269
+ this.tombstones.add(tag);
2270
+ this.elements.delete(tag);
2271
+ removed++;
2272
+ }
2273
+ }
2274
+ return removed;
2275
+ }
2276
+ /** Check if the set contains a value */
2277
+ has(value) {
2278
+ for (const elem of this.elements.values()) {
2279
+ if (this.valueEquals(elem.value, value)) return true;
2280
+ }
2281
+ return false;
2282
+ }
2283
+ /** Get all current values (deduplicated) */
2284
+ values() {
2285
+ const seen = /* @__PURE__ */ new Set();
2286
+ const result = [];
2287
+ for (const elem of this.elements.values()) {
2288
+ const key = JSON.stringify(elem.value);
2289
+ if (!seen.has(key)) {
2290
+ seen.add(key);
2291
+ result.push(elem.value);
2292
+ }
2293
+ }
2294
+ return result;
2295
+ }
2296
+ /** Size of the set (unique values) */
2297
+ get size() {
2298
+ return this.values().length;
2299
+ }
2300
+ /** Merge with another OR-Set (adds win over concurrent removes) */
2301
+ merge(other) {
2302
+ for (const [tag, elem] of other.elements) {
2303
+ if (!this.tombstones.has(tag) && !this.elements.has(tag)) {
2304
+ if (!elem.signer.revoked) {
2305
+ this.elements.set(tag, elem);
2306
+ }
2307
+ }
2308
+ }
2309
+ for (const tag of other.tombstones) {
2310
+ this.tombstones.add(tag);
2311
+ this.elements.delete(tag);
2312
+ }
2313
+ }
2314
+ valueEquals(a, b) {
2315
+ return JSON.stringify(a) === JSON.stringify(b);
2316
+ }
2317
+ };
2318
+ function createAgentState(agentDID) {
2319
+ return {
2320
+ agentDID,
2321
+ registers: /* @__PURE__ */ new Map(),
2322
+ counters: /* @__PURE__ */ new Map(),
2323
+ sets: /* @__PURE__ */ new Map(),
2324
+ lastSync: 0
2325
+ };
2326
+ }
2327
+ function setRegister(state, key, value, signer, timestamp) {
2328
+ if (!state.registers.has(key)) {
2329
+ state.registers.set(key, new LWWRegister(void 0));
2330
+ }
2331
+ const op = signOperation(value, signer, `state:${key}`, timestamp);
2332
+ return state.registers.get(key).set(op);
2333
+ }
2334
+ function getRegister(state, key) {
2335
+ return state.registers.get(key)?.get();
2336
+ }
2337
+ function incrementCounter(state, key, nodeId, amount = 1) {
2338
+ if (!state.counters.has(key)) state.counters.set(key, new GCounter());
2339
+ state.counters.get(key).increment(nodeId, amount);
2340
+ }
2341
+ function getCounter(state, key) {
2342
+ return state.counters.get(key)?.value() ?? 0;
2343
+ }
2344
+ function mergeStates(local, remote) {
2345
+ for (const [key, reg] of remote.registers) {
2346
+ if (local.registers.has(key)) {
2347
+ local.registers.get(key).merge(reg);
2348
+ } else {
2349
+ local.registers.set(key, reg);
2350
+ }
2351
+ }
2352
+ for (const [key, counter] of remote.counters) {
2353
+ if (local.counters.has(key)) {
2354
+ local.counters.get(key).merge(counter);
2355
+ } else {
2356
+ local.counters.set(key, counter);
2357
+ }
2358
+ }
2359
+ for (const [key, set] of remote.sets) {
2360
+ if (local.sets.has(key)) {
2361
+ local.sets.get(key).merge(set);
2362
+ } else {
2363
+ local.sets.set(key, set);
2364
+ }
2365
+ }
2366
+ local.lastSync = Math.max(local.lastSync, remote.lastSync);
2367
+ }
2368
+
2369
+ // src/agents/CrossRealityHandoff.ts
2370
+ var PLATFORM_CAPABILITIES = {};
2371
+ var embodimentFor = (platform) => {
2372
+ if (platform === "quest3" || platform === "pcvr") return "Avatar3D";
2373
+ if (platform === "android-auto") return "VoiceHUD";
2374
+ return "UI2D";
2375
+ };
2376
+ var platformCategory = (platform) => {
2377
+ if (platform.includes("android-auto")) return "automotive";
2378
+ if (platform.includes("android") || platform.includes("ios")) return "mobile";
2379
+ if (platform.includes("quest") || platform.includes("pcvr")) return "vr";
2380
+ return "desktop";
2381
+ };
2382
+ function negotiateHandoff(source, target) {
2383
+ const gained = [];
2384
+ const lost = [];
2385
+ const boolCaps = [
2386
+ "spatialTracking",
2387
+ "handTracking",
2388
+ "eyeTracking",
2389
+ "haptics",
2390
+ "spatialAudio",
2391
+ "gpu3D",
2392
+ "arCamera",
2393
+ "gps",
2394
+ "npu",
2395
+ "webxrSupport"
2396
+ ];
2397
+ for (const cap of boolCaps) {
2398
+ const srcHas = !!source.capabilities[cap];
2399
+ const tgtHas = !!target.capabilities[cap];
2400
+ if (!srcHas && tgtHas) gained.push(cap);
2401
+ if (srcHas && !tgtHas) lost.push(cap);
2402
+ }
2403
+ const srcCat = platformCategory(source.platform);
2404
+ const tgtCat = platformCategory(target.platform);
2405
+ let latency = 200;
2406
+ if (srcCat === tgtCat) latency = 100;
2407
+ if (tgtCat === "automotive") latency = 500;
2408
+ const feasible = target.available;
2409
+ return {
2410
+ sourceDevice: source,
2411
+ targetDevice: target,
2412
+ gained,
2413
+ lost,
2414
+ transition: { from: source.embodiment, to: target.embodiment },
2415
+ estimatedLatencyMs: latency,
2416
+ feasible,
2417
+ reason: feasible ? void 0 : "Target device not available"
2418
+ };
2419
+ }
2420
+ function createMVCPayload(agentDID, sessionId, source, data) {
2421
+ const trimmedDecisions = data.decisions.slice(-10);
2422
+ const trimmedEvidence = data.evidence.sort((a, b) => b.relevance - a.relevance).slice(0, 15);
2423
+ return {
2424
+ version: "1.0",
2425
+ agentDID,
2426
+ sessionId,
2427
+ decisions: trimmedDecisions,
2428
+ task: data.task,
2429
+ preferences: data.preferences,
2430
+ spatial: data.spatial,
2431
+ evidence: trimmedEvidence,
2432
+ handoff: {
2433
+ sourceDevice: source.deviceId,
2434
+ sourcePlatform: source.platform,
2435
+ sourceEmbodiment: embodimentFor(source.platform),
2436
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2437
+ }
2438
+ };
2439
+ }
2440
+ function estimatePayloadSize(payload) {
2441
+ return new TextEncoder().encode(JSON.stringify(payload)).length;
2442
+ }
2443
+ function validatePayloadBudget(payload) {
2444
+ const BUDGET = 10 * 1024;
2445
+ const size = estimatePayloadSize(payload);
2446
+ return { valid: size <= BUDGET, sizeBytes: size, budgetBytes: BUDGET };
2447
+ }
2448
+
2449
+ // src/agents/CulturalMemory.ts
2450
+ var DEFAULT_CONFIG3 = {
2451
+ episodicCapacity: 100,
2452
+ episodicDecayRate: 0.01,
2453
+ stigmergicCapacity: 500,
2454
+ traceDecayRate: 5e-3,
2455
+ consolidationThreshold: 5,
2456
+ sopRetentionThreshold: 0.3
2457
+ };
2458
+ var CulturalMemory = class {
2459
+ config;
2460
+ episodic = /* @__PURE__ */ new Map();
2461
+ // agentId → memories
2462
+ stigmergic = /* @__PURE__ */ new Map();
2463
+ // zoneId → traces
2464
+ sops = /* @__PURE__ */ new Map();
2465
+ // sopId → SOP
2466
+ currentTick = 0;
2467
+ constructor(config = {}) {
2468
+ this.config = { ...DEFAULT_CONFIG3, ...config };
2469
+ }
2470
+ // ── Episodic Memory ──────────────────────────────────────────────────────
2471
+ /**
2472
+ * Record an episodic memory for an agent.
2473
+ */
2474
+ record(agentId, event, opts = {}) {
2475
+ const memories = this.episodic.get(agentId) || [];
2476
+ const memory = {
2477
+ id: `ep_${agentId}_${this.currentTick}_${memories.length}`,
2478
+ agentId,
2479
+ event,
2480
+ participants: opts.participants || [],
2481
+ valence: opts.valence ?? 0,
2482
+ importance: opts.importance ?? 0.5,
2483
+ timestamp: this.currentTick,
2484
+ strength: 1,
2485
+ normId: opts.normId,
2486
+ tags: opts.tags || []
2487
+ };
2488
+ memories.push(memory);
2489
+ if (memories.length > this.config.episodicCapacity) {
2490
+ memories.sort((a, b) => b.strength * b.importance - a.strength * a.importance);
2491
+ memories.length = this.config.episodicCapacity;
2492
+ }
2493
+ this.episodic.set(agentId, memories);
2494
+ return memory;
2495
+ }
2496
+ /**
2497
+ * Recall memories for an agent, optionally filtered.
2498
+ */
2499
+ recall(agentId, filter) {
2500
+ const memories = this.episodic.get(agentId) || [];
2501
+ return memories.filter((m) => {
2502
+ if (filter?.minStrength && m.strength < filter.minStrength) return false;
2503
+ if (filter?.normId && m.normId !== filter.normId) return false;
2504
+ if (filter?.tags && !filter.tags.some((t) => m.tags.includes(t))) return false;
2505
+ return true;
2506
+ }).sort((a, b) => b.strength * b.importance - a.strength * a.importance);
2507
+ }
2508
+ /**
2509
+ * Get the number of memories for an agent.
2510
+ */
2511
+ memoryCount(agentId) {
2512
+ return (this.episodic.get(agentId) || []).length;
2513
+ }
2514
+ // ── Stigmergic Memory ────────────────────────────────────────────────────
2515
+ /**
2516
+ * Leave a stigmergic trace in the environment.
2517
+ */
2518
+ leaveTrace(creatorId, zoneId, label, position, opts = {}) {
2519
+ const traces = this.stigmergic.get(zoneId) || [];
2520
+ const intensity = opts.intensity ?? opts.initialIntensity ?? 1;
2521
+ const trace = {
2522
+ id: `st_${zoneId}_${this.currentTick}_${traces.length}`,
2523
+ creatorId,
2524
+ position,
2525
+ zoneId,
2526
+ type: opts.type || "marker",
2527
+ label,
2528
+ intensity,
2529
+ initialIntensity: intensity,
2530
+ decayRate: opts.decayRate ?? this.config.traceDecayRate,
2531
+ radius: opts.radius ?? 10,
2532
+ timestamp: this.currentTick,
2533
+ reinforcements: 0
2534
+ };
2535
+ traces.push(trace);
2536
+ if (traces.length > this.config.stigmergicCapacity) {
2537
+ traces.sort((a, b) => b.intensity - a.intensity);
2538
+ traces.length = this.config.stigmergicCapacity;
2539
+ }
2540
+ this.stigmergic.set(zoneId, traces);
2541
+ return trace;
2542
+ }
2543
+ /**
2544
+ * Perceive nearby traces from a position.
2545
+ */
2546
+ perceiveTraces(zoneId, position) {
2547
+ const traces = this.stigmergic.get(zoneId) || [];
2548
+ return traces.filter((t) => {
2549
+ const dx = t.position.x - position.x;
2550
+ const dy = t.position.y - position.y;
2551
+ const dz = t.position.z - position.z;
2552
+ const dist = Math.sqrt(dx * dx + dy * dy + dz * dz);
2553
+ return dist <= t.radius && t.intensity > 0.01;
2554
+ }).sort((a, b) => b.intensity - a.intensity);
2555
+ }
2556
+ /**
2557
+ * Reinforce a trace (another agent validates it).
2558
+ * Increases intensity and slows decay.
2559
+ */
2560
+ reinforceTrace(traceId, zoneId) {
2561
+ const traces = this.stigmergic.get(zoneId) || [];
2562
+ const trace = traces.find((t) => t.id === traceId);
2563
+ if (!trace) return false;
2564
+ trace.reinforcements++;
2565
+ trace.intensity = Math.min(trace.initialIntensity * 2, trace.intensity + 0.1);
2566
+ trace.decayRate *= 0.95;
2567
+ return true;
2568
+ }
2569
+ /**
2570
+ * Get all traces in a zone.
2571
+ */
2572
+ zoneTraces(zoneId) {
2573
+ return (this.stigmergic.get(zoneId) || []).filter((t) => t.intensity > 0.01);
2574
+ }
2575
+ // ── Semantic SOPs ────────────────────────────────────────────────────────
2576
+ /**
2577
+ * Attempt to consolidate episodic memories into a semantic SOP.
2578
+ * Finds repeated patterns (same normId, high frequency) and forms SOPs.
2579
+ */
2580
+ consolidate(agentId) {
2581
+ const memories = this.episodic.get(agentId) || [];
2582
+ const newSops = [];
2583
+ const byNorm = /* @__PURE__ */ new Map();
2584
+ for (const m of memories) {
2585
+ if (m.normId) {
2586
+ const group = byNorm.get(m.normId) || [];
2587
+ group.push(m);
2588
+ byNorm.set(m.normId, group);
2589
+ }
2590
+ }
2591
+ for (const [normId, episodes] of byNorm) {
2592
+ if (episodes.length < this.config.consolidationThreshold) continue;
2593
+ const existing = this.sops.get(`sop_${agentId}_${normId}`);
2594
+ if (existing) {
2595
+ existing.episodeCount = episodes.length;
2596
+ existing.confidence = Math.min(
2597
+ 1,
2598
+ episodes.length / (this.config.consolidationThreshold * 3)
2599
+ );
2600
+ existing.updatedAt = this.currentTick;
2601
+ continue;
2602
+ }
2603
+ const avgValence = episodes.reduce((s, e) => s + e.valence, 0) / episodes.length;
2604
+ const sop = {
2605
+ id: `sop_${agentId}_${normId}`,
2606
+ normId,
2607
+ description: `Learned behavior for norm '${normId}' from ${episodes.length} experiences (avg valence: ${avgValence.toFixed(2)})`,
2608
+ conditions: [...new Set(episodes.flatMap((e) => e.tags))],
2609
+ actions: avgValence > 0 ? ["comply", "reinforce"] : ["avoid", "report"],
2610
+ confidence: Math.min(1, episodes.length / (this.config.consolidationThreshold * 3)),
2611
+ episodeCount: episodes.length,
2612
+ createdAt: this.currentTick,
2613
+ updatedAt: this.currentTick
2614
+ };
2615
+ this.sops.set(sop.id, sop);
2616
+ newSops.push(sop);
2617
+ }
2618
+ return newSops;
2619
+ }
2620
+ /**
2621
+ * Get all SOPs for an agent.
2622
+ */
2623
+ getSOPs(agentId) {
2624
+ const prefix = `sop_${agentId}_`;
2625
+ return [...this.sops.values()].filter((s) => s.id.startsWith(prefix));
2626
+ }
2627
+ /**
2628
+ * Get a specific SOP by agent and norm.
2629
+ */
2630
+ getSOP(agentId, normId) {
2631
+ return this.sops.get(`sop_${agentId}_${normId}`);
2632
+ }
2633
+ // ── Tick / Lifecycle ─────────────────────────────────────────────────────
2634
+ /**
2635
+ * Advance one tick: decay memories and traces, prune dead entries.
2636
+ */
2637
+ tick() {
2638
+ this.currentTick++;
2639
+ let decayedMemories = 0;
2640
+ let evaporatedTraces = 0;
2641
+ for (const [agentId, memories] of this.episodic) {
2642
+ for (const m of memories) {
2643
+ m.strength *= 1 - this.config.episodicDecayRate;
2644
+ }
2645
+ const before = memories.length;
2646
+ const alive = memories.filter((m) => m.strength > 0.01);
2647
+ decayedMemories += before - alive.length;
2648
+ this.episodic.set(agentId, alive);
2649
+ }
2650
+ for (const [zoneId, traces] of this.stigmergic) {
2651
+ for (const t of traces) {
2652
+ t.intensity -= t.decayRate;
2653
+ }
2654
+ const before = traces.length;
2655
+ const alive = traces.filter((t) => t.intensity > 0.01);
2656
+ evaporatedTraces += before - alive.length;
2657
+ this.stigmergic.set(zoneId, alive);
2658
+ }
2659
+ for (const [id, sop] of this.sops) {
2660
+ if (sop.confidence < this.config.sopRetentionThreshold) {
2661
+ this.sops.delete(id);
2662
+ }
2663
+ }
2664
+ return { decayedMemories, evaporatedTraces };
2665
+ }
2666
+ /**
2667
+ * Get current tick.
2668
+ */
2669
+ getTick() {
2670
+ return this.currentTick;
2671
+ }
2672
+ /**
2673
+ * Get global statistics.
2674
+ */
2675
+ stats() {
2676
+ let totalMemories = 0;
2677
+ let totalTraces = 0;
2678
+ for (const mems of this.episodic.values()) totalMemories += mems.length;
2679
+ for (const traces of this.stigmergic.values()) totalTraces += traces.length;
2680
+ return {
2681
+ agents: this.episodic.size,
2682
+ totalMemories,
2683
+ totalTraces,
2684
+ totalSOPs: this.sops.size,
2685
+ zones: this.stigmergic.size
2686
+ };
2687
+ }
2688
+ /**
2689
+ * Export full state for persistence / cross-session continuity.
2690
+ */
2691
+ exportState() {
2692
+ const episodic = {};
2693
+ for (const [k, v] of this.episodic) episodic[k] = v;
2694
+ const stigmergic = {};
2695
+ for (const [k, v] of this.stigmergic) stigmergic[k] = v;
2696
+ return { episodic, stigmergic, sops: [...this.sops.values()], tick: this.currentTick };
2697
+ }
2698
+ /**
2699
+ * Import state from persistence.
2700
+ */
2701
+ importState(state) {
2702
+ for (const [k, v] of Object.entries(state.episodic)) this.episodic.set(k, v);
2703
+ for (const [k, v] of Object.entries(state.stigmergic)) this.stigmergic.set(k, v);
2704
+ for (const sop of state.sops) this.sops.set(sop.id, sop);
2705
+ this.currentTick = state.tick;
2706
+ }
2707
+ };
2708
+
2709
+ // src/agents/NormEngine.ts
2710
+ var BUILTIN_NORMS = [
2711
+ {
2712
+ id: "no_griefing",
2713
+ name: "No Griefing",
2714
+ category: "safety",
2715
+ description: "Do not cause harm to others",
2716
+ enforcement: "hard",
2717
+ scope: "world",
2718
+ activationThreshold: 0.1,
2719
+ strength: "strong",
2720
+ forbiddenEffects: ["agent:kill", "inventory:steal"]
2721
+ },
2722
+ {
2723
+ id: "resource_sharing",
2724
+ name: "Resource Sharing",
2725
+ category: "cooperation",
2726
+ description: "Share resources when abundant",
2727
+ enforcement: "soft",
2728
+ scope: "world",
2729
+ activationThreshold: 0.5,
2730
+ strength: "moderate",
2731
+ forbiddenEffects: ["inventory:hoard", "inventory:horde"]
2732
+ },
2733
+ {
2734
+ id: "fair_trade",
2735
+ name: "Fair Trade",
2736
+ category: "economy",
2737
+ description: "Trade at mutually agreeable values",
2738
+ enforcement: "soft",
2739
+ scope: "world",
2740
+ activationThreshold: 0.3,
2741
+ strength: "weak",
2742
+ forbiddenEffects: ["trade:scam", "trade:extort"]
2743
+ }
2744
+ ];
2745
+ function criticalMassForChange(norm, populationSize) {
2746
+ if (norm.strength === "strong") return populationSize * 0.5;
2747
+ if (norm.strength === "moderate") return populationSize * 0.25;
2748
+ return populationSize * 0.02;
2749
+ }
2750
+ var EffectRow = class {
2751
+ effects;
2752
+ constructor(effects) {
2753
+ this.effects = new Set(effects);
2754
+ }
2755
+ has(effect) {
2756
+ return this.effects.has(effect);
2757
+ }
2758
+ };
2759
+ var DEFAULT_CONFIG4 = {
2760
+ activationThreshold: 0.3,
2761
+ complianceReward: 0.05,
2762
+ violationPenalty: 0.15,
2763
+ proposalThreshold: 0.6,
2764
+ enableMetanorms: true
2765
+ };
2766
+ var NormEngine = class {
2767
+ config;
2768
+ norms = /* @__PURE__ */ new Map();
2769
+ agents = /* @__PURE__ */ new Map();
2770
+ proposals = /* @__PURE__ */ new Map();
2771
+ violationLog = [];
2772
+ adoptionHistory = [];
2773
+ currentTick = 0;
2774
+ constructor(config = {}) {
2775
+ this.config = { ...DEFAULT_CONFIG4, ...config };
2776
+ for (const norm of BUILTIN_NORMS) {
2777
+ this.norms.set(norm.id, norm);
2778
+ }
2779
+ }
2780
+ // ── C: Creation ──────────────────────────────────────────────────────────
2781
+ /**
2782
+ * Register a custom norm.
2783
+ */
2784
+ registerNorm(norm) {
2785
+ this.norms.set(norm.id, norm);
2786
+ }
2787
+ /**
2788
+ * Agent proposes a new norm.
2789
+ */
2790
+ proposeNorm(proposerId, norm) {
2791
+ const proposal = {
2792
+ id: `prop_${this.currentTick}_${proposerId}`,
2793
+ proposerId,
2794
+ norm,
2795
+ votes: /* @__PURE__ */ new Map(),
2796
+ timestamp: this.currentTick,
2797
+ status: "pending"
2798
+ };
2799
+ this.proposals.set(proposal.id, proposal);
2800
+ const state = this.getOrCreateAgent(proposerId);
2801
+ state.proposed.add(proposal.id);
2802
+ return proposal;
2803
+ }
2804
+ /**
2805
+ * Vote on a pending proposal.
2806
+ */
2807
+ vote(proposalId, agentId, approve) {
2808
+ const proposal = this.proposals.get(proposalId);
2809
+ if (!proposal || proposal.status !== "pending") return false;
2810
+ proposal.votes.set(agentId, approve);
2811
+ const totalAgents = this.agents.size;
2812
+ if (totalAgents === 0) return true;
2813
+ const approvals = [...proposal.votes.values()].filter((v) => v).length;
2814
+ const ratio = approvals / totalAgents;
2815
+ if (ratio >= this.config.proposalThreshold) {
2816
+ proposal.status = "adopted";
2817
+ this.norms.set(proposal.norm.id, proposal.norm);
2818
+ } else if (proposal.votes.size >= totalAgents) {
2819
+ proposal.status = "rejected";
2820
+ }
2821
+ return true;
2822
+ }
2823
+ // ── R: Representation ────────────────────────────────────────────────────
2824
+ /**
2825
+ * Get a norm by ID.
2826
+ */
2827
+ getNorm(normId) {
2828
+ return this.norms.get(normId);
2829
+ }
2830
+ /**
2831
+ * List all registered norms.
2832
+ */
2833
+ listNorms() {
2834
+ return [...this.norms.values()];
2835
+ }
2836
+ // ── S: Spreading ─────────────────────────────────────────────────────────
2837
+ /**
2838
+ * Agent adopts a norm.
2839
+ */
2840
+ adopt(agentId, normId) {
2841
+ if (!this.norms.has(normId)) return false;
2842
+ const state = this.getOrCreateAgent(agentId);
2843
+ state.adopted.add(normId);
2844
+ state.compliance.set(normId, 1);
2845
+ return true;
2846
+ }
2847
+ /**
2848
+ * Agent abandons a norm.
2849
+ */
2850
+ abandon(agentId, normId) {
2851
+ const state = this.agents.get(agentId);
2852
+ if (!state) return false;
2853
+ state.adopted.delete(normId);
2854
+ state.compliance.delete(normId);
2855
+ return true;
2856
+ }
2857
+ /**
2858
+ * Get adoption rate for a norm (0-1).
2859
+ */
2860
+ adoptionRate(normId) {
2861
+ if (this.agents.size === 0) return 0;
2862
+ let adopters = 0;
2863
+ for (const state of this.agents.values()) {
2864
+ if (state.adopted.has(normId)) adopters++;
2865
+ }
2866
+ return adopters / this.agents.size;
2867
+ }
2868
+ /**
2869
+ * Check if a norm is active (adoption > threshold).
2870
+ */
2871
+ isActive(normId) {
2872
+ const norm = this.norms.get(normId);
2873
+ if (!norm) return false;
2874
+ return this.adoptionRate(normId) >= (norm.activationThreshold || this.config.activationThreshold);
2875
+ }
2876
+ // ── E: Evaluation ────────────────────────────────────────────────────────
2877
+ /**
2878
+ * Check if an agent's intended effects comply with active norms.
2879
+ * Returns violations found.
2880
+ */
2881
+ evaluate(agentId, effects, zoneId) {
2882
+ const violations = [];
2883
+ const effectRow = new EffectRow(effects);
2884
+ for (const norm of this.norms.values()) {
2885
+ if (!this.isActive(norm.id)) continue;
2886
+ if (norm.scope === "zone" && !zoneId) continue;
2887
+ if (norm.forbiddenEffects) {
2888
+ for (const forbidden of norm.forbiddenEffects) {
2889
+ if (effectRow.has(forbidden)) {
2890
+ violations.push({
2891
+ normId: norm.id,
2892
+ agentId,
2893
+ effect: forbidden,
2894
+ timestamp: this.currentTick,
2895
+ severity: norm.enforcement,
2896
+ witnessed: this.witnessesIn(zoneId)
2897
+ });
2898
+ }
2899
+ }
2900
+ }
2901
+ }
2902
+ return violations;
2903
+ }
2904
+ // ── C: Compliance ────────────────────────────────────────────────────────
2905
+ /**
2906
+ * Record that an agent complied with a norm.
2907
+ */
2908
+ recordCompliance(agentId, normId) {
2909
+ const state = this.getOrCreateAgent(agentId);
2910
+ const current = state.compliance.get(normId) || 0.5;
2911
+ state.compliance.set(normId, Math.min(1, current + this.config.complianceReward));
2912
+ state.violations.delete(normId);
2913
+ }
2914
+ /**
2915
+ * Record that an agent violated a norm.
2916
+ */
2917
+ recordViolation(violation) {
2918
+ const state = this.getOrCreateAgent(violation.agentId);
2919
+ const current = state.compliance.get(violation.normId) || 0.5;
2920
+ state.compliance.set(violation.normId, Math.max(0, current - this.config.violationPenalty));
2921
+ state.violations.add(violation.normId);
2922
+ this.violationLog.push(violation);
2923
+ if (this.config.enableMetanorms) {
2924
+ for (const witnessId of violation.witnessed) {
2925
+ const witnessState = this.getOrCreateAgent(witnessId);
2926
+ witnessState.enforcementCount++;
2927
+ }
2928
+ }
2929
+ }
2930
+ /**
2931
+ * Get compliance score for an agent on a norm.
2932
+ */
2933
+ getCompliance(agentId, normId) {
2934
+ return this.agents.get(agentId)?.compliance.get(normId) ?? 0.5;
2935
+ }
2936
+ // ── Lifecycle ────────────────────────────────────────────────────────────
2937
+ /**
2938
+ * Register an agent in the norm engine.
2939
+ */
2940
+ registerAgent(agentId, adoptNorms) {
2941
+ const state = this.getOrCreateAgent(agentId);
2942
+ if (adoptNorms) {
2943
+ for (const normId of adoptNorms) this.adopt(agentId, normId);
2944
+ }
2945
+ return state;
2946
+ }
2947
+ /**
2948
+ * Advance one tick: record adoption history, snapshot state.
2949
+ */
2950
+ tick() {
2951
+ this.currentTick++;
2952
+ for (const norm of this.norms.values()) {
2953
+ this.adoptionHistory.push({
2954
+ normId: norm.id,
2955
+ tick: this.currentTick,
2956
+ rate: this.adoptionRate(norm.id)
2957
+ });
2958
+ }
2959
+ }
2960
+ /**
2961
+ * Get adoption curve data for a norm.
2962
+ */
2963
+ adoptionCurve(normId) {
2964
+ return this.adoptionHistory.filter((h) => h.normId === normId);
2965
+ }
2966
+ /**
2967
+ * Get the cultural health score for the whole population (0-1).
2968
+ * High = norms well-adopted, low violations. Low = cultural breakdown.
2969
+ */
2970
+ culturalHealth() {
2971
+ if (this.agents.size === 0) return 1;
2972
+ let totalCompliance = 0;
2973
+ let count = 0;
2974
+ for (const state of this.agents.values()) {
2975
+ for (const score of state.compliance.values()) {
2976
+ totalCompliance += score;
2977
+ count++;
2978
+ }
2979
+ }
2980
+ return count > 0 ? totalCompliance / count : 1;
2981
+ }
2982
+ /**
2983
+ * Get statistics.
2984
+ */
2985
+ stats() {
2986
+ return {
2987
+ norms: this.norms.size,
2988
+ agents: this.agents.size,
2989
+ activeNorms: [...this.norms.keys()].filter((id) => this.isActive(id)).length,
2990
+ violations: this.violationLog.length,
2991
+ proposals: this.proposals.size,
2992
+ culturalHealth: this.culturalHealth()
2993
+ };
2994
+ }
2995
+ // ── Internal ─────────────────────────────────────────────────────────────
2996
+ getOrCreateAgent(agentId) {
2997
+ let state = this.agents.get(agentId);
2998
+ if (!state) {
2999
+ state = {
3000
+ agentId,
3001
+ adopted: /* @__PURE__ */ new Set(),
3002
+ compliance: /* @__PURE__ */ new Map(),
3003
+ violations: /* @__PURE__ */ new Set(),
3004
+ proposed: /* @__PURE__ */ new Set(),
3005
+ enforcementCount: 0
3006
+ };
3007
+ this.agents.set(agentId, state);
3008
+ }
3009
+ return state;
3010
+ }
3011
+ witnessesIn(zoneId) {
3012
+ return [...this.agents.keys()].slice(0, 5);
3013
+ }
3014
+ };
3015
+
3016
+ // src/agents/spatial-comms/ProtocolTypes.ts
3017
+ var DEFAULT_REALTIME_CONFIG = {
3018
+ binary: true,
3019
+ maxMessageSize: 512,
3020
+ // 512 bytes max
3021
+ targetLatency: 1,
3022
+ // <1ms target
3023
+ messagesPerSecond: 90,
3024
+ // 90fps coordination
3025
+ compression: false,
3026
+ // No compression for minimal latency
3027
+ udpPort: 9001
3028
+ };
3029
+ var DEFAULT_A2A_CONFIG = {
3030
+ endpoint: "http://localhost:3002/a2a",
3031
+ timeout: 5e3,
3032
+ // 5 seconds
3033
+ maxRetries: 3,
3034
+ retryBackoffBase: 100,
3035
+ // 100ms, 200ms, 400ms
3036
+ requireAck: true,
3037
+ enableBatching: true,
3038
+ batchSize: 10
3039
+ };
3040
+ var DEFAULT_MCP_CONFIG = {
3041
+ endpoint: "http://localhost:5567",
3042
+ apiKey: process.env.MCP_API_KEY || "",
3043
+ timeout: 3e4
3044
+ // 30 seconds
3045
+ };
3046
+ var DEFAULT_SPATIAL_COMM_CONFIG = {
3047
+ layer1: DEFAULT_REALTIME_CONFIG,
3048
+ layer2: DEFAULT_A2A_CONFIG,
3049
+ layer3: DEFAULT_MCP_CONFIG
3050
+ };
3051
+ var PROTOCOL_VERSION = "1.0.0";
3052
+ var PROTOCOL_COMPATIBILITY = {
3053
+ version: PROTOCOL_VERSION,
3054
+ minVersion: "1.0.0",
3055
+ maxVersion: "1.x.x"
3056
+ };
3057
+
3058
+ // src/agents/spatial-comms/Layer1RealTime.ts
3059
+ var import_events2 = require("events");
3060
+ var HEADER_SIZE = 12;
3061
+ function encodeRealTimeMessage(message) {
3062
+ const agentIdBytes = Buffer.from(message.agent_id, "utf-8");
3063
+ const agentIdLen = agentIdBytes.length;
3064
+ let typeCode;
3065
+ switch (message.type) {
3066
+ case "position_sync":
3067
+ typeCode = 1 /* POSITION_SYNC */;
3068
+ break;
3069
+ case "frame_budget":
3070
+ typeCode = 2 /* FRAME_BUDGET */;
3071
+ break;
3072
+ case "spatial_conflict":
3073
+ typeCode = 3 /* SPATIAL_CONFLICT */;
3074
+ break;
3075
+ case "performance_metric":
3076
+ typeCode = 4 /* PERFORMANCE_METRIC */;
3077
+ break;
3078
+ default:
3079
+ throw new Error(
3080
+ `Unknown message type: ${message.type}`
3081
+ );
3082
+ }
3083
+ if (message.type === "position_sync") {
3084
+ const msg = message;
3085
+ const bodySize = agentIdLen + 12 + 16 + 12 + (msg.velocity ? 12 : 0);
3086
+ const buffer = Buffer.allocUnsafe(HEADER_SIZE + bodySize);
3087
+ let offset = 0;
3088
+ buffer.writeUInt8(typeCode, offset);
3089
+ offset += 1;
3090
+ buffer.writeUInt8(agentIdLen, offset);
3091
+ offset += 1;
3092
+ buffer.writeBigInt64BE(BigInt(msg.timestamp), offset);
3093
+ offset += 8;
3094
+ buffer.writeUInt16BE(0, offset);
3095
+ offset += 2;
3096
+ agentIdBytes.copy(buffer, offset);
3097
+ offset += agentIdLen;
3098
+ buffer.writeFloatBE(msg.position[0], offset);
3099
+ offset += 4;
3100
+ buffer.writeFloatBE(msg.position[1], offset);
3101
+ offset += 4;
3102
+ buffer.writeFloatBE(msg.position[2], offset);
3103
+ offset += 4;
3104
+ buffer.writeFloatBE(msg.rotation[0], offset);
3105
+ offset += 4;
3106
+ buffer.writeFloatBE(msg.rotation[1], offset);
3107
+ offset += 4;
3108
+ buffer.writeFloatBE(msg.rotation[2], offset);
3109
+ offset += 4;
3110
+ buffer.writeFloatBE(msg.rotation[3], offset);
3111
+ offset += 4;
3112
+ buffer.writeFloatBE(msg.scale[0], offset);
3113
+ offset += 4;
3114
+ buffer.writeFloatBE(msg.scale[1], offset);
3115
+ offset += 4;
3116
+ buffer.writeFloatBE(msg.scale[2], offset);
3117
+ offset += 4;
3118
+ if (msg.velocity) {
3119
+ buffer.writeFloatBE(msg.velocity[0], offset);
3120
+ offset += 4;
3121
+ buffer.writeFloatBE(msg.velocity[1], offset);
3122
+ offset += 4;
3123
+ buffer.writeFloatBE(msg.velocity[2], offset);
3124
+ offset += 4;
3125
+ }
3126
+ return buffer;
3127
+ } else if (message.type === "frame_budget") {
3128
+ const msg = message;
3129
+ const bodySize = agentIdLen + 17;
3130
+ const buffer = Buffer.allocUnsafe(HEADER_SIZE + bodySize);
3131
+ let offset = 0;
3132
+ buffer.writeUInt8(typeCode, offset);
3133
+ offset += 1;
3134
+ buffer.writeUInt8(agentIdLen, offset);
3135
+ offset += 1;
3136
+ buffer.writeBigInt64BE(BigInt(msg.timestamp), offset);
3137
+ offset += 8;
3138
+ buffer.writeUInt16BE(0, offset);
3139
+ offset += 2;
3140
+ agentIdBytes.copy(buffer, offset);
3141
+ offset += agentIdLen;
3142
+ buffer.writeFloatBE(msg.frame_time_ms, offset);
3143
+ offset += 4;
3144
+ buffer.writeFloatBE(msg.budget_remaining_ms, offset);
3145
+ offset += 4;
3146
+ buffer.writeFloatBE(msg.target_fps, offset);
3147
+ offset += 4;
3148
+ buffer.writeFloatBE(msg.actual_fps, offset);
3149
+ offset += 4;
3150
+ const qualityCode = { high: 0, medium: 1, low: 2, minimal: 3 }[msg.quality_level];
3151
+ buffer.writeUInt8(qualityCode, offset);
3152
+ offset += 1;
3153
+ return buffer;
3154
+ } else {
3155
+ const json = JSON.stringify(message);
3156
+ const jsonBytes = Buffer.from(json, "utf-8");
3157
+ const buffer = Buffer.allocUnsafe(HEADER_SIZE + agentIdLen + jsonBytes.length);
3158
+ let offset = 0;
3159
+ buffer.writeUInt8(typeCode, offset);
3160
+ offset += 1;
3161
+ buffer.writeUInt8(agentIdLen, offset);
3162
+ offset += 1;
3163
+ buffer.writeBigInt64BE(BigInt(message.timestamp), offset);
3164
+ offset += 8;
3165
+ buffer.writeUInt16BE(0, offset);
3166
+ offset += 2;
3167
+ agentIdBytes.copy(buffer, offset);
3168
+ offset += agentIdLen;
3169
+ jsonBytes.copy(buffer, offset);
3170
+ return buffer;
3171
+ }
3172
+ }
3173
+ function decodeRealTimeMessage(buffer) {
3174
+ let offset = 0;
3175
+ const typeCode = buffer.readUInt8(offset);
3176
+ offset += 1;
3177
+ const agentIdLen = buffer.readUInt8(offset);
3178
+ offset += 1;
3179
+ const timestamp = Number(buffer.readBigInt64BE(offset));
3180
+ offset += 8;
3181
+ offset += 2;
3182
+ const agentId = buffer.toString("utf-8", offset, offset + agentIdLen);
3183
+ offset += agentIdLen;
3184
+ if (typeCode === 1 /* POSITION_SYNC */) {
3185
+ const px = buffer.readFloatBE(offset);
3186
+ offset += 4;
3187
+ const py = buffer.readFloatBE(offset);
3188
+ offset += 4;
3189
+ const pz = buffer.readFloatBE(offset);
3190
+ offset += 4;
3191
+ const position = [px, py, pz];
3192
+ const rx = buffer.readFloatBE(offset);
3193
+ offset += 4;
3194
+ const ry = buffer.readFloatBE(offset);
3195
+ offset += 4;
3196
+ const rz = buffer.readFloatBE(offset);
3197
+ offset += 4;
3198
+ const rw = buffer.readFloatBE(offset);
3199
+ offset += 4;
3200
+ const rotation = [rx, ry, rz, rw];
3201
+ const sx = buffer.readFloatBE(offset);
3202
+ offset += 4;
3203
+ const sy = buffer.readFloatBE(offset);
3204
+ offset += 4;
3205
+ const sz = buffer.readFloatBE(offset);
3206
+ offset += 4;
3207
+ const scale = [sx, sy, sz];
3208
+ let velocity;
3209
+ if (offset < buffer.length) {
3210
+ const vx = buffer.readFloatBE(offset);
3211
+ offset += 4;
3212
+ const vy = buffer.readFloatBE(offset);
3213
+ offset += 4;
3214
+ const vz = buffer.readFloatBE(offset);
3215
+ offset += 4;
3216
+ velocity = [vx, vy, vz];
3217
+ }
3218
+ return {
3219
+ type: "position_sync",
3220
+ agent_id: agentId,
3221
+ timestamp,
3222
+ position,
3223
+ rotation,
3224
+ scale,
3225
+ velocity
3226
+ };
3227
+ } else if (typeCode === 2 /* FRAME_BUDGET */) {
3228
+ const frame_time_ms = buffer.readFloatBE(offset);
3229
+ offset += 4;
3230
+ const budget_remaining_ms = buffer.readFloatBE(offset);
3231
+ offset += 4;
3232
+ const target_fps = buffer.readFloatBE(offset);
3233
+ offset += 4;
3234
+ const actual_fps = buffer.readFloatBE(offset);
3235
+ offset += 4;
3236
+ const qualityCode = buffer.readUInt8(offset);
3237
+ offset += 1;
3238
+ const qualityLevels = [
3239
+ "high",
3240
+ "medium",
3241
+ "low",
3242
+ "minimal"
3243
+ ];
3244
+ const quality_level = qualityLevels[qualityCode] ?? "medium";
3245
+ return {
3246
+ type: "frame_budget",
3247
+ agent_id: agentId,
3248
+ timestamp,
3249
+ frame_time_ms,
3250
+ budget_remaining_ms,
3251
+ target_fps,
3252
+ actual_fps,
3253
+ quality_level
3254
+ };
3255
+ } else {
3256
+ const json = buffer.toString("utf-8", offset);
3257
+ return JSON.parse(json);
3258
+ }
3259
+ }
3260
+ var UDPRealTimeTransport = class {
3261
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- dgram.Socket dynamically imported at runtime
3262
+ socket;
3263
+ port;
3264
+ targetHost = "localhost";
3265
+ constructor(port) {
3266
+ this.port = port;
3267
+ }
3268
+ async init() {
3269
+ const dgram = await import("dgram");
3270
+ this.socket = dgram.createSocket("udp4");
3271
+ return new Promise((resolve, reject) => {
3272
+ this.socket.bind(this.port, () => {
3273
+ this.socket.setBroadcast(true);
3274
+ resolve();
3275
+ });
3276
+ this.socket.on("error", (err) => {
3277
+ reject(err);
3278
+ });
3279
+ });
3280
+ }
3281
+ async send(buffer, _targetAgent) {
3282
+ if (!this.socket) throw new Error("Transport not initialized");
3283
+ return new Promise((resolve, reject) => {
3284
+ this.socket.send(buffer, this.port, this.targetHost, (err) => {
3285
+ if (err) reject(err);
3286
+ else resolve();
3287
+ });
3288
+ });
3289
+ }
3290
+ async broadcast(buffer) {
3291
+ if (!this.socket) throw new Error("Transport not initialized");
3292
+ return new Promise((resolve, reject) => {
3293
+ this.socket.send(buffer, this.port, "255.255.255.255", (err) => {
3294
+ if (err) reject(err);
3295
+ else resolve();
3296
+ });
3297
+ });
3298
+ }
3299
+ async close() {
3300
+ if (this.socket) {
3301
+ return new Promise((resolve) => {
3302
+ this.socket.close(() => resolve());
3303
+ });
3304
+ }
3305
+ }
3306
+ onMessage(callback) {
3307
+ if (!this.socket) throw new Error("Transport not initialized");
3308
+ this.socket.on("message", callback);
3309
+ }
3310
+ };
3311
+ var WebRTCRealTimeTransport = class {
3312
+ constructor(config) {
3313
+ this.config = config;
3314
+ }
3315
+ dataChannel;
3316
+ peerConnection;
3317
+ async init(remoteDescription) {
3318
+ this.peerConnection = new RTCPeerConnection(this.config);
3319
+ this.dataChannel = this.peerConnection.createDataChannel("realtime", {
3320
+ ordered: false,
3321
+ // Unordered for minimal latency
3322
+ maxRetransmits: 0
3323
+ // No retransmits (UDP-like)
3324
+ });
3325
+ this.dataChannel.bufferedAmountLowThreshold = 0;
3326
+ if (remoteDescription) {
3327
+ await this.peerConnection.setRemoteDescription(remoteDescription);
3328
+ }
3329
+ }
3330
+ async send(buffer, _targetAgent) {
3331
+ if (!this.dataChannel || this.dataChannel.readyState !== "open") {
3332
+ throw new Error("Data channel not ready");
3333
+ }
3334
+ this.dataChannel.send(new Uint8Array(buffer));
3335
+ }
3336
+ async broadcast(buffer) {
3337
+ return this.send(buffer);
3338
+ }
3339
+ async close() {
3340
+ if (this.dataChannel) {
3341
+ this.dataChannel.close();
3342
+ }
3343
+ if (this.peerConnection) {
3344
+ this.peerConnection.close();
3345
+ }
3346
+ }
3347
+ onMessage(callback) {
3348
+ if (!this.dataChannel) throw new Error("Data channel not initialized");
3349
+ this.dataChannel.onmessage = (event) => {
3350
+ const buffer = Buffer.from(event.data);
3351
+ callback(buffer);
3352
+ };
3353
+ }
3354
+ async createOffer() {
3355
+ if (!this.peerConnection) throw new Error("Peer connection not initialized");
3356
+ const offer = await this.peerConnection.createOffer();
3357
+ await this.peerConnection.setLocalDescription(offer);
3358
+ return offer;
3359
+ }
3360
+ async createAnswer() {
3361
+ if (!this.peerConnection) throw new Error("Peer connection not initialized");
3362
+ const answer = await this.peerConnection.createAnswer();
3363
+ await this.peerConnection.setLocalDescription(answer);
3364
+ return answer;
3365
+ }
3366
+ };
3367
+ var Layer1RealTimeClient = class extends import_events2.EventEmitter {
3368
+ config;
3369
+ transport;
3370
+ agentId;
3371
+ messageCount = 0;
3372
+ lastMessageTime = 0;
3373
+ _messageBuffer = [];
3374
+ constructor(agentId, config) {
3375
+ super();
3376
+ this.agentId = agentId;
3377
+ this.config = { ...DEFAULT_REALTIME_CONFIG, ...config };
3378
+ }
3379
+ /**
3380
+ * Initialize transport and start listening
3381
+ */
3382
+ async init(useWebRTC = false) {
3383
+ if (useWebRTC) {
3384
+ const transport = new WebRTCRealTimeTransport(
3385
+ this.config.webrtc?.iceServers ? { iceServers: this.config.webrtc.iceServers } : {}
3386
+ );
3387
+ await transport.init();
3388
+ this.transport = transport;
3389
+ transport.onMessage((buffer) => {
3390
+ this.handleIncomingMessage(buffer);
3391
+ });
3392
+ } else {
3393
+ const transport = new UDPRealTimeTransport(this.config.udpPort || 9001);
3394
+ await transport.init();
3395
+ this.transport = transport;
3396
+ transport.onMessage((buffer) => {
3397
+ this.handleIncomingMessage(buffer);
3398
+ });
3399
+ }
3400
+ }
3401
+ /**
3402
+ * Send real-time message
3403
+ */
3404
+ async send(message, targetAgent) {
3405
+ if (!this.transport) throw new Error("Transport not initialized");
3406
+ const fullMessage = {
3407
+ ...message,
3408
+ agent_id: this.agentId,
3409
+ timestamp: this.getMicroseconds()
3410
+ };
3411
+ const buffer = this.config.binary ? encodeRealTimeMessage(fullMessage) : Buffer.from(JSON.stringify(fullMessage), "utf-8");
3412
+ if (buffer.length > this.config.maxMessageSize) {
3413
+ throw new Error(`Message size ${buffer.length} exceeds max ${this.config.maxMessageSize}`);
3414
+ }
3415
+ await this.enforceRateLimit();
3416
+ if (targetAgent) {
3417
+ await this.transport.send(buffer, targetAgent);
3418
+ } else {
3419
+ await this.transport.broadcast(buffer);
3420
+ }
3421
+ this.messageCount++;
3422
+ this.lastMessageTime = Date.now();
3423
+ }
3424
+ /**
3425
+ * Send position sync message
3426
+ */
3427
+ async sendPositionSync(position, rotation, scale, velocity) {
3428
+ await this.send({
3429
+ type: "position_sync",
3430
+ position,
3431
+ rotation,
3432
+ scale,
3433
+ velocity
3434
+ });
3435
+ }
3436
+ /**
3437
+ * Send frame budget message
3438
+ */
3439
+ async sendFrameBudget(frameTimeMs, budgetRemainingMs, targetFps, actualFps, qualityLevel) {
3440
+ await this.send({
3441
+ type: "frame_budget",
3442
+ frame_time_ms: frameTimeMs,
3443
+ budget_remaining_ms: budgetRemainingMs,
3444
+ target_fps: targetFps,
3445
+ actual_fps: actualFps,
3446
+ quality_level: qualityLevel
3447
+ });
3448
+ }
3449
+ /**
3450
+ * Close transport
3451
+ */
3452
+ async close() {
3453
+ if (this.transport) {
3454
+ await this.transport.close();
3455
+ }
3456
+ }
3457
+ /**
3458
+ * Handle incoming message
3459
+ */
3460
+ handleIncomingMessage(buffer) {
3461
+ try {
3462
+ const message = this.config.binary ? decodeRealTimeMessage(buffer) : JSON.parse(buffer.toString("utf-8"));
3463
+ this.emit("message", message);
3464
+ this.emit(message.type, message);
3465
+ const latency = (this.getMicroseconds() - message.timestamp) / 1e3;
3466
+ this.emit("latency", latency);
3467
+ if (latency > this.config.targetLatency) {
3468
+ this.emit("latency_warning", { message, latency });
3469
+ }
3470
+ } catch (err) {
3471
+ this.emit("error", err);
3472
+ }
3473
+ }
3474
+ /**
3475
+ * Enforce rate limiting
3476
+ */
3477
+ async enforceRateLimit() {
3478
+ const now = Date.now();
3479
+ const timeSinceLastMessage = now - this.lastMessageTime;
3480
+ const minInterval = 1e3 / this.config.messagesPerSecond;
3481
+ if (timeSinceLastMessage < minInterval) {
3482
+ const delay = minInterval - timeSinceLastMessage;
3483
+ await new Promise((resolve) => setTimeout(resolve, delay));
3484
+ }
3485
+ }
3486
+ /**
3487
+ * Get current time in microseconds
3488
+ */
3489
+ getMicroseconds() {
3490
+ const hrTime = process.hrtime ? process.hrtime() : [Date.now() / 1e3, 0];
3491
+ return hrTime[0] * 1e6 + Math.floor(hrTime[1] / 1e3);
3492
+ }
3493
+ };
3494
+
3495
+ // src/agents/spatial-comms/Layer2A2A.ts
3496
+ var import_events3 = require("events");
3497
+ var MessageQueue = class {
3498
+ queue = /* @__PURE__ */ new Map();
3499
+ retryTimers = /* @__PURE__ */ new Map();
3500
+ /**
3501
+ * Add message to queue
3502
+ */
3503
+ add(message, maxRetries, backoffBase) {
3504
+ return new Promise((resolve, reject) => {
3505
+ this.queue.set(message.message_id, {
3506
+ message,
3507
+ attempt: 0,
3508
+ maxRetries,
3509
+ backoffBase,
3510
+ resolve,
3511
+ reject
3512
+ });
3513
+ });
3514
+ }
3515
+ /**
3516
+ * Get message from queue
3517
+ */
3518
+ get(messageId) {
3519
+ return this.queue.get(messageId);
3520
+ }
3521
+ /**
3522
+ * Remove message from queue
3523
+ */
3524
+ remove(messageId) {
3525
+ const timer = this.retryTimers.get(messageId);
3526
+ if (timer) {
3527
+ clearTimeout(timer);
3528
+ this.retryTimers.delete(messageId);
3529
+ }
3530
+ this.queue.delete(messageId);
3531
+ }
3532
+ /**
3533
+ * Schedule retry for message
3534
+ */
3535
+ scheduleRetry(messageId, callback) {
3536
+ const queued = this.queue.get(messageId);
3537
+ if (!queued) return;
3538
+ queued.attempt++;
3539
+ const delay = queued.backoffBase * Math.pow(2, queued.attempt - 1);
3540
+ const timer = setTimeout(() => {
3541
+ this.retryTimers.delete(messageId);
3542
+ callback();
3543
+ }, delay);
3544
+ this.retryTimers.set(messageId, timer);
3545
+ }
3546
+ /**
3547
+ * Check if message should retry
3548
+ */
3549
+ shouldRetry(messageId) {
3550
+ const queued = this.queue.get(messageId);
3551
+ if (!queued) return false;
3552
+ return queued.attempt < queued.maxRetries;
3553
+ }
3554
+ /**
3555
+ * Get queue size
3556
+ */
3557
+ get size() {
3558
+ return this.queue.size;
3559
+ }
3560
+ /**
3561
+ * Clear all queued messages
3562
+ */
3563
+ clear() {
3564
+ for (const timer of this.retryTimers.values()) {
3565
+ clearTimeout(timer);
3566
+ }
3567
+ this.retryTimers.clear();
3568
+ this.queue.clear();
3569
+ }
3570
+ };
3571
+ var SpatialClaimManager = class {
3572
+ claims = /* @__PURE__ */ new Map();
3573
+ /**
3574
+ * Add spatial claim
3575
+ */
3576
+ addClaim(claim) {
3577
+ this.claims.set(claim.claim_id, claim);
3578
+ }
3579
+ /**
3580
+ * Remove spatial claim
3581
+ */
3582
+ removeClaim(claimId) {
3583
+ this.claims.delete(claimId);
3584
+ }
3585
+ /**
3586
+ * Get claims by agent
3587
+ */
3588
+ getClaimsByAgent(agentId) {
3589
+ return Array.from(this.claims.values()).filter((c) => c.agent_id === agentId);
3590
+ }
3591
+ /**
3592
+ * Check for conflicts with new claim
3593
+ */
3594
+ checkConflicts(newClaim) {
3595
+ const conflicts = [];
3596
+ for (const existingClaim of this.claims.values()) {
3597
+ if (existingClaim.agent_id === newClaim.agent_id) continue;
3598
+ if (this.boundingBoxesOverlap(newClaim.bounding_box, existingClaim.bounding_box)) {
3599
+ if (newClaim.exclusive || existingClaim.exclusive) {
3600
+ conflicts.push(existingClaim);
3601
+ }
3602
+ }
3603
+ }
3604
+ return conflicts;
3605
+ }
3606
+ /**
3607
+ * Check if two bounding boxes overlap
3608
+ */
3609
+ boundingBoxesOverlap(box1, box2) {
3610
+ return box1.min[0] <= box2.max[0] && box1.max[0] >= box2.min[0] && box1.min[1] <= box2.max[1] && box1.max[1] >= box2.min[1] && box1.min[2] <= box2.max[2] && box1.max[2] >= box2.min[2];
3611
+ }
3612
+ /**
3613
+ * Cleanup expired claims
3614
+ */
3615
+ cleanup() {
3616
+ const now = Date.now();
3617
+ for (const [claimId, claim] of this.claims) {
3618
+ if (claim.expires_at && claim.expires_at < now) {
3619
+ this.claims.delete(claimId);
3620
+ }
3621
+ }
3622
+ }
3623
+ /**
3624
+ * Get all claims
3625
+ */
3626
+ getAllClaims() {
3627
+ return Array.from(this.claims.values());
3628
+ }
3629
+ /**
3630
+ * Clear all claims
3631
+ */
3632
+ clear() {
3633
+ this.claims.clear();
3634
+ }
3635
+ };
3636
+ var Layer2A2AClient = class extends import_events3.EventEmitter {
3637
+ config;
3638
+ agentId;
3639
+ messageQueue = new MessageQueue();
3640
+ claimManager = new SpatialClaimManager();
3641
+ messageHandlers = /* @__PURE__ */ new Map();
3642
+ batchBuffer = [];
3643
+ batchTimer;
3644
+ constructor(agentId, config) {
3645
+ super();
3646
+ this.agentId = agentId;
3647
+ this.config = { ...DEFAULT_A2A_CONFIG, ...config };
3648
+ setInterval(() => {
3649
+ this.claimManager.cleanup();
3650
+ }, 6e4);
3651
+ }
3652
+ /**
3653
+ * Send A2A message with retry
3654
+ */
3655
+ async send(message) {
3656
+ const fullMessage = {
3657
+ ...message,
3658
+ message_id: this.generateMessageId(),
3659
+ from_agent: this.agentId,
3660
+ timestamp: Date.now()
3661
+ };
3662
+ if (this.config.enableBatching) {
3663
+ return this.addToBatch(fullMessage);
3664
+ }
3665
+ return this.sendMessage(fullMessage);
3666
+ }
3667
+ /**
3668
+ * Send task assignment
3669
+ */
3670
+ async assignTask(toAgent, task) {
3671
+ return this.send({
3672
+ type: "task_assignment",
3673
+ to_agent: toAgent,
3674
+ task
3675
+ });
3676
+ }
3677
+ /**
3678
+ * Send task completion
3679
+ */
3680
+ async completeTask(taskId, success, result, error, performanceMetrics) {
3681
+ return this.send({
3682
+ type: "task_complete",
3683
+ task_id: taskId,
3684
+ success,
3685
+ result,
3686
+ error,
3687
+ performance_metrics: performanceMetrics
3688
+ });
3689
+ }
3690
+ /**
3691
+ * Claim spatial region
3692
+ */
3693
+ async claimSpatialRegion(claimId, boundingBox, priority, durationMs, exclusive = true) {
3694
+ const claim = {
3695
+ claim_id: claimId,
3696
+ agent_id: this.agentId,
3697
+ bounding_box: boundingBox,
3698
+ priority,
3699
+ exclusive,
3700
+ expires_at: durationMs ? Date.now() + durationMs : void 0
3701
+ };
3702
+ const conflicts = this.claimManager.checkConflicts(claim);
3703
+ if (conflicts.length > 0) {
3704
+ this.emit("spatial_conflict", {
3705
+ claim,
3706
+ conflicts
3707
+ });
3708
+ const hasHigherPriority = conflicts.some((c) => {
3709
+ const priorities = ["low", "medium", "high", "critical"];
3710
+ return priorities.indexOf(c.priority) >= priorities.indexOf(priority);
3711
+ });
3712
+ if (hasHigherPriority) {
3713
+ return {
3714
+ message_id: this.generateMessageId(),
3715
+ success: false,
3716
+ error: "Spatial conflict with higher priority claim",
3717
+ data: { conflicts },
3718
+ timestamp: Date.now()
3719
+ };
3720
+ }
3721
+ }
3722
+ this.claimManager.addClaim(claim);
3723
+ return this.send({
3724
+ type: "spatial_claim",
3725
+ claim_id: claimId,
3726
+ bounding_box: boundingBox,
3727
+ priority,
3728
+ duration_ms: durationMs,
3729
+ exclusive
3730
+ });
3731
+ }
3732
+ /**
3733
+ * Resolve spatial conflict
3734
+ */
3735
+ async resolveConflict(conflictId, involvedAgents, strategy, resolutionParams) {
3736
+ return this.send({
3737
+ type: "conflict_resolution",
3738
+ conflict_id: conflictId,
3739
+ strategy,
3740
+ involved_agents: involvedAgents,
3741
+ resolution_params: resolutionParams
3742
+ });
3743
+ }
3744
+ /**
3745
+ * Request resource
3746
+ */
3747
+ async requestResource(resourceId, resourceType, amount, priority = "medium") {
3748
+ return this.send({
3749
+ type: "resource_request",
3750
+ resource_id: resourceId,
3751
+ resource_type: resourceType,
3752
+ amount,
3753
+ priority
3754
+ });
3755
+ }
3756
+ /**
3757
+ * Release resource
3758
+ */
3759
+ async releaseResource(resourceId) {
3760
+ return this.send({
3761
+ type: "resource_release",
3762
+ resource_id: resourceId
3763
+ });
3764
+ }
3765
+ /**
3766
+ * Perform agent handshake
3767
+ */
3768
+ async handshake(toAgent, capabilities, protocolVersion) {
3769
+ return this.send({
3770
+ type: "agent_handshake",
3771
+ to_agent: toAgent,
3772
+ capabilities,
3773
+ protocol_version: protocolVersion
3774
+ });
3775
+ }
3776
+ /**
3777
+ * Register message handler
3778
+ */
3779
+ onMessage(messageType, handler) {
3780
+ this.messageHandlers.set(messageType, handler);
3781
+ }
3782
+ /**
3783
+ * Handle incoming message
3784
+ */
3785
+ async handleIncoming(message) {
3786
+ this.emit("message", message);
3787
+ this.emit(message.type, message);
3788
+ const handler = this.messageHandlers.get(message.type);
3789
+ if (handler) {
3790
+ return handler(message);
3791
+ }
3792
+ return {
3793
+ message_id: message.message_id,
3794
+ success: true,
3795
+ timestamp: Date.now()
3796
+ };
3797
+ }
3798
+ /**
3799
+ * Get spatial claims for this agent
3800
+ */
3801
+ getMyClaims() {
3802
+ return this.claimManager.getClaimsByAgent(this.agentId);
3803
+ }
3804
+ /**
3805
+ * Get all spatial claims
3806
+ */
3807
+ getAllClaims() {
3808
+ return this.claimManager.getAllClaims();
3809
+ }
3810
+ /**
3811
+ * Send message with retry logic
3812
+ */
3813
+ async sendMessage(message) {
3814
+ const responsePromise = this.messageQueue.add(
3815
+ message,
3816
+ this.config.maxRetries,
3817
+ this.config.retryBackoffBase
3818
+ );
3819
+ this.attemptSend(message);
3820
+ return responsePromise;
3821
+ }
3822
+ /**
3823
+ * Attempt to send message
3824
+ */
3825
+ async attemptSend(message) {
3826
+ try {
3827
+ const response = await this.httpRequest(message);
3828
+ const queued = this.messageQueue.get(message.message_id);
3829
+ if (!queued) return;
3830
+ queued.resolve(response);
3831
+ this.messageQueue.remove(message.message_id);
3832
+ this.emit("message_sent", { message, response });
3833
+ } catch (error) {
3834
+ const queued = this.messageQueue.get(message.message_id);
3835
+ if (!queued) return;
3836
+ if (this.messageQueue.shouldRetry(message.message_id)) {
3837
+ this.emit("retry", { message, attempt: queued.attempt });
3838
+ this.messageQueue.scheduleRetry(message.message_id, () => {
3839
+ this.attemptSend(message);
3840
+ });
3841
+ } else {
3842
+ queued.reject(error);
3843
+ this.messageQueue.remove(message.message_id);
3844
+ this.emit("message_failed", { message, error });
3845
+ }
3846
+ }
3847
+ }
3848
+ /**
3849
+ * HTTP/2 request
3850
+ */
3851
+ async httpRequest(message) {
3852
+ const controller = new AbortController();
3853
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
3854
+ try {
3855
+ const response = await fetch(this.config.endpoint, {
3856
+ method: "POST",
3857
+ headers: {
3858
+ "Content-Type": "application/json"
3859
+ },
3860
+ body: JSON.stringify(message),
3861
+ signal: controller.signal
3862
+ });
3863
+ if (!response.ok) {
3864
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
3865
+ }
3866
+ const data = await response.json();
3867
+ return data;
3868
+ } finally {
3869
+ clearTimeout(timeoutId);
3870
+ }
3871
+ }
3872
+ /**
3873
+ * Add message to batch
3874
+ */
3875
+ addToBatch(message) {
3876
+ this.batchBuffer.push(message);
3877
+ const responsePromise = new Promise((resolve, reject) => {
3878
+ this.messageQueue.add(message, this.config.maxRetries, this.config.retryBackoffBase).then(resolve).catch(reject);
3879
+ });
3880
+ if (!this.batchTimer) {
3881
+ this.batchTimer = setTimeout(() => {
3882
+ this.flushBatch();
3883
+ }, 10);
3884
+ }
3885
+ if (this.batchBuffer.length >= this.config.batchSize) {
3886
+ this.flushBatch();
3887
+ }
3888
+ return responsePromise;
3889
+ }
3890
+ /**
3891
+ * Flush batch of messages
3892
+ */
3893
+ flushBatch() {
3894
+ if (this.batchTimer) {
3895
+ clearTimeout(this.batchTimer);
3896
+ this.batchTimer = void 0;
3897
+ }
3898
+ if (this.batchBuffer.length === 0) return;
3899
+ const batch = this.batchBuffer.splice(0);
3900
+ for (const message of batch) {
3901
+ this.attemptSend(message);
3902
+ }
3903
+ }
3904
+ /**
3905
+ * Generate unique message ID
3906
+ */
3907
+ generateMessageId() {
3908
+ return `${this.agentId}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
3909
+ }
3910
+ /**
3911
+ * Get queue statistics
3912
+ */
3913
+ getQueueStats() {
3914
+ return {
3915
+ queueSize: this.messageQueue.size,
3916
+ claimCount: this.getAllClaims().length
3917
+ };
3918
+ }
3919
+ /**
3920
+ * Shutdown client
3921
+ */
3922
+ async shutdown() {
3923
+ this.flushBatch();
3924
+ this.claimManager.clear();
3925
+ this.messageQueue.clear();
3926
+ this.emit("shutdown");
3927
+ }
3928
+ };
3929
+
3930
+ // src/agents/spatial-comms/Layer3MCP.ts
3931
+ var import_events4 = require("events");
3932
+ var SPATIAL_MCP_TOOLS = [
3933
+ {
3934
+ name: "create_world",
3935
+ description: "Create a new VR world with multi-agent support",
3936
+ parameters: {
3937
+ type: "object",
3938
+ properties: {
3939
+ world_spec: {
3940
+ type: "object",
3941
+ description: "World specification including dimensions, features, and agent roles"
3942
+ }
3943
+ },
3944
+ required: ["world_spec"]
3945
+ }
3946
+ },
3947
+ {
3948
+ name: "get_world_status",
3949
+ description: "Get current status of a VR world including agent activity and performance",
3950
+ parameters: {
3951
+ type: "object",
3952
+ properties: {
3953
+ world_id: {
3954
+ type: "string",
3955
+ description: "ID of the world to query"
3956
+ }
3957
+ },
3958
+ required: ["world_id"]
3959
+ }
3960
+ },
3961
+ {
3962
+ name: "export_world",
3963
+ description: "Export VR world to specified format",
3964
+ parameters: {
3965
+ type: "object",
3966
+ properties: {
3967
+ world_id: {
3968
+ type: "string",
3969
+ description: "ID of the world to export"
3970
+ },
3971
+ format: {
3972
+ type: "string",
3973
+ enum: ["gltf", "fbx", "usdz", "vrm", "json", "holoscript"],
3974
+ description: "Export format"
3975
+ }
3976
+ },
3977
+ required: ["world_id", "format"]
3978
+ }
3979
+ },
3980
+ {
3981
+ name: "get_agent_registry",
3982
+ description: "Get all registered agents in the spatial communication system",
3983
+ parameters: {
3984
+ type: "object",
3985
+ properties: {
3986
+ filter: {
3987
+ type: "object",
3988
+ description: "Optional filter criteria (status, role, etc.)"
3989
+ }
3990
+ }
3991
+ }
3992
+ },
3993
+ {
3994
+ name: "get_performance_metrics",
3995
+ description: "Get real-time performance metrics for agents and system",
3996
+ parameters: {
3997
+ type: "object",
3998
+ properties: {
3999
+ world_id: {
4000
+ type: "string",
4001
+ description: "Optional world ID to filter metrics"
4002
+ },
4003
+ agent_id: {
4004
+ type: "string",
4005
+ description: "Optional agent ID to filter metrics"
4006
+ }
4007
+ }
4008
+ }
4009
+ },
4010
+ {
4011
+ name: "set_global_config",
4012
+ description: "Set global configuration for spatial communication system",
4013
+ parameters: {
4014
+ type: "object",
4015
+ properties: {
4016
+ config: {
4017
+ type: "object",
4018
+ description: "Configuration object with settings to update"
4019
+ }
4020
+ },
4021
+ required: ["config"]
4022
+ }
4023
+ },
4024
+ {
4025
+ name: "trigger_event",
4026
+ description: "Trigger a system-wide event for agent coordination",
4027
+ parameters: {
4028
+ type: "object",
4029
+ properties: {
4030
+ event_type: {
4031
+ type: "string",
4032
+ description: "Type of event to trigger"
4033
+ },
4034
+ event_data: {
4035
+ type: "object",
4036
+ description: "Event payload data"
4037
+ }
4038
+ },
4039
+ required: ["event_type"]
4040
+ }
4041
+ }
4042
+ ];
4043
+ var Layer3MCPClient = class extends import_events4.EventEmitter {
4044
+ config;
4045
+ agentId;
4046
+ constructor(agentId, config) {
4047
+ super();
4048
+ this.agentId = agentId;
4049
+ this.config = { ...DEFAULT_MCP_CONFIG, ...config };
4050
+ }
4051
+ /**
4052
+ * Execute MCP command
4053
+ */
4054
+ async execute(command, params) {
4055
+ const request = {
4056
+ command,
4057
+ params
4058
+ };
4059
+ try {
4060
+ const response = await this.sendMCPRequest(request);
4061
+ this.emit("command_success", { command, params, response });
4062
+ return response;
4063
+ } catch (error) {
4064
+ this.emit("command_error", { command, params, error });
4065
+ throw error;
4066
+ }
4067
+ }
4068
+ /**
4069
+ * Create new VR world
4070
+ */
4071
+ async createWorld(worldSpec) {
4072
+ const response = await this.execute("create_world", { world_spec: worldSpec });
4073
+ if (!response.success) {
4074
+ throw new Error(response.error || "Failed to create world");
4075
+ }
4076
+ return response.data;
4077
+ }
4078
+ /**
4079
+ * Get world status
4080
+ */
4081
+ async getWorldStatus(worldId) {
4082
+ const response = await this.execute("get_world_status", { world_id: worldId });
4083
+ if (!response.success) {
4084
+ throw new Error(response.error || "Failed to get world status");
4085
+ }
4086
+ return response.data;
4087
+ }
4088
+ /**
4089
+ * Export world
4090
+ */
4091
+ async exportWorld(worldId, format) {
4092
+ const response = await this.execute("export_world", { world_id: worldId, format });
4093
+ if (!response.success) {
4094
+ throw new Error(response.error || "Failed to export world");
4095
+ }
4096
+ return response.data;
4097
+ }
4098
+ /**
4099
+ * Get agent registry
4100
+ */
4101
+ async getAgentRegistry(filter) {
4102
+ const response = await this.execute("get_agent_registry", { filter });
4103
+ if (!response.success) {
4104
+ throw new Error(response.error || "Failed to get agent registry");
4105
+ }
4106
+ return response.data;
4107
+ }
4108
+ /**
4109
+ * Get performance metrics
4110
+ */
4111
+ async getPerformanceMetrics(options) {
4112
+ const response = await this.execute("get_performance_metrics", options || {});
4113
+ if (!response.success) {
4114
+ throw new Error(response.error || "Failed to get performance metrics");
4115
+ }
4116
+ return response.data;
4117
+ }
4118
+ /**
4119
+ * Set global configuration
4120
+ */
4121
+ async setGlobalConfig(config) {
4122
+ const response = await this.execute("set_global_config", { config });
4123
+ if (!response.success) {
4124
+ throw new Error(response.error || "Failed to set global config");
4125
+ }
4126
+ }
4127
+ /**
4128
+ * Trigger system event
4129
+ */
4130
+ async triggerEvent(eventType, eventData) {
4131
+ const response = await this.execute("trigger_event", {
4132
+ event_type: eventType,
4133
+ event_data: eventData
4134
+ });
4135
+ if (!response.success) {
4136
+ throw new Error(response.error || "Failed to trigger event");
4137
+ }
4138
+ }
4139
+ /**
4140
+ * Call MCP tool directly
4141
+ */
4142
+ async callTool(server, tool, args) {
4143
+ try {
4144
+ const response = await this.mcpToolCall(server, tool, args);
4145
+ this.emit("tool_call_success", { server, tool, args, response });
4146
+ return {
4147
+ success: true,
4148
+ data: response,
4149
+ timestamp: Date.now()
4150
+ };
4151
+ } catch (error) {
4152
+ this.emit("tool_call_error", { server, tool, args, error });
4153
+ return {
4154
+ success: false,
4155
+ error: error.message,
4156
+ timestamp: Date.now()
4157
+ };
4158
+ }
4159
+ }
4160
+ /**
4161
+ * Get available MCP tools
4162
+ */
4163
+ getAvailableTools() {
4164
+ return SPATIAL_MCP_TOOLS;
4165
+ }
4166
+ /**
4167
+ * Send MCP request
4168
+ */
4169
+ async sendMCPRequest(request) {
4170
+ const controller = new AbortController();
4171
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
4172
+ try {
4173
+ const response = await fetch(`${this.config.endpoint}/mcp/command`, {
4174
+ method: "POST",
4175
+ headers: {
4176
+ "Content-Type": "application/json",
4177
+ "x-mcp-api-key": this.config.apiKey,
4178
+ "x-agent-id": this.agentId
4179
+ },
4180
+ body: JSON.stringify(request),
4181
+ signal: controller.signal
4182
+ });
4183
+ if (!response.ok) {
4184
+ throw new Error(`MCP HTTP ${response.status}: ${response.statusText}`);
4185
+ }
4186
+ const data = await response.json();
4187
+ return data;
4188
+ } finally {
4189
+ clearTimeout(timeoutId);
4190
+ }
4191
+ }
4192
+ /**
4193
+ * Call MCP tool via orchestrator
4194
+ */
4195
+ async mcpToolCall(server, tool, args) {
4196
+ const controller = new AbortController();
4197
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
4198
+ try {
4199
+ const response = await fetch(`${this.config.endpoint}/tools/call`, {
4200
+ method: "POST",
4201
+ headers: {
4202
+ "Content-Type": "application/json",
4203
+ "x-mcp-api-key": this.config.apiKey
4204
+ },
4205
+ body: JSON.stringify({
4206
+ server,
4207
+ tool,
4208
+ args
4209
+ }),
4210
+ signal: controller.signal
4211
+ });
4212
+ if (!response.ok) {
4213
+ throw new Error(`MCP Tool Call HTTP ${response.status}: ${response.statusText}`);
4214
+ }
4215
+ const data = await response.json();
4216
+ return data;
4217
+ } finally {
4218
+ clearTimeout(timeoutId);
4219
+ }
4220
+ }
4221
+ };
4222
+ var Layer3MCPServer = class extends import_events4.EventEmitter {
4223
+ handlers = /* @__PURE__ */ new Map();
4224
+ worlds = /* @__PURE__ */ new Map();
4225
+ constructor() {
4226
+ super();
4227
+ this.registerDefaultHandlers();
4228
+ }
4229
+ /**
4230
+ * Register command handler
4231
+ */
4232
+ registerHandler(command, handler) {
4233
+ this.handlers.set(command, handler);
4234
+ }
4235
+ /**
4236
+ * Handle incoming MCP request
4237
+ */
4238
+ async handleRequest(request, context) {
4239
+ try {
4240
+ const handler = this.handlers.get(request.command);
4241
+ if (!handler) {
4242
+ return {
4243
+ success: false,
4244
+ error: `Unknown command: ${request.command}`,
4245
+ timestamp: Date.now()
4246
+ };
4247
+ }
4248
+ const data = await handler(request.params, context);
4249
+ this.emit("command_handled", { request, context, data });
4250
+ return {
4251
+ success: true,
4252
+ data,
4253
+ timestamp: Date.now()
4254
+ };
4255
+ } catch (error) {
4256
+ this.emit("command_error", { request, context, error });
4257
+ return {
4258
+ success: false,
4259
+ error: error.message,
4260
+ timestamp: Date.now()
4261
+ };
4262
+ }
4263
+ }
4264
+ /**
4265
+ * Register default handlers
4266
+ */
4267
+ registerDefaultHandlers() {
4268
+ this.registerHandler("create_world", async (params, context) => {
4269
+ const worldSpec = params.world_spec;
4270
+ const worldId = worldSpec.world_id || `world-${Date.now()}`;
4271
+ const status = {
4272
+ world_id: worldId,
4273
+ name: worldSpec.name,
4274
+ status: "initializing",
4275
+ active_agents: [],
4276
+ performance: {
4277
+ current_fps: worldSpec.target_fps,
4278
+ target_fps: worldSpec.target_fps,
4279
+ frame_time_avg_ms: 1e3 / worldSpec.target_fps,
4280
+ frame_time_max_ms: 1e3 / worldSpec.target_fps,
4281
+ quality_level: "high"
4282
+ },
4283
+ spatial_conflicts: 0,
4284
+ resource_utilization: {
4285
+ cpu_percent: 0,
4286
+ memory_mb: 0,
4287
+ gpu_percent: 0
4288
+ },
4289
+ uptime_ms: 0,
4290
+ created_at: (/* @__PURE__ */ new Date()).toISOString()
4291
+ };
4292
+ this.worlds.set(worldId, status);
4293
+ this.emit("world_created", { worldId, worldSpec, context });
4294
+ return { world_id: worldId, status };
4295
+ });
4296
+ this.registerHandler("get_world_status", async (params, context) => {
4297
+ const worldId = params.world_id;
4298
+ const status = this.worlds.get(worldId);
4299
+ if (!status) {
4300
+ throw new Error(`World not found: ${worldId}`);
4301
+ }
4302
+ return status;
4303
+ });
4304
+ this.registerHandler("export_world", async (params, context) => {
4305
+ const worldId = params.world_id;
4306
+ const format = params.format;
4307
+ const world = this.worlds.get(worldId);
4308
+ if (!world) {
4309
+ throw new Error(`World not found: ${worldId}`);
4310
+ }
4311
+ this.emit("world_exported", { worldId, format, context });
4312
+ return {
4313
+ url: `https://hololand.io/exports/${worldId}.${format}`,
4314
+ size: 1024 * 1024 * 10
4315
+ // 10MB
4316
+ };
4317
+ });
4318
+ this.registerHandler("get_agent_registry", async (params, context) => {
4319
+ const filter = params.filter;
4320
+ const agents = [];
4321
+ for (const world of this.worlds.values()) {
4322
+ for (const agent of world.active_agents) {
4323
+ if (filter) {
4324
+ if (filter.status && agent.status !== filter.status) continue;
4325
+ if (filter.role && agent.role !== filter.role) continue;
4326
+ if (filter.world_id && world.world_id !== filter.world_id) continue;
4327
+ }
4328
+ agents.push({
4329
+ ...agent,
4330
+ world_id: world.world_id,
4331
+ capabilities: []
4332
+ });
4333
+ }
4334
+ }
4335
+ return {
4336
+ agents,
4337
+ total: agents.length
4338
+ };
4339
+ });
4340
+ this.registerHandler("get_performance_metrics", async (params, context) => {
4341
+ const worldId = params.world_id;
4342
+ const agentId = params.agent_id;
4343
+ const metrics = {
4344
+ timestamp: Date.now(),
4345
+ agents: [],
4346
+ system: {
4347
+ total_fps: 90,
4348
+ target_fps: 90,
4349
+ frame_time_avg_ms: 11.1,
4350
+ frame_time_max_ms: 15,
4351
+ quality_level: "high",
4352
+ cpu_percent: 45,
4353
+ memory_mb: 2048,
4354
+ gpu_percent: 60
4355
+ }
4356
+ };
4357
+ for (const world of this.worlds.values()) {
4358
+ if (worldId && world.world_id !== worldId) continue;
4359
+ for (const agent of world.active_agents) {
4360
+ if (agentId && agent.agent_id !== agentId) continue;
4361
+ metrics.agents.push({
4362
+ agent_id: agent.agent_id,
4363
+ role: agent.role,
4364
+ frame_time_avg_ms: 10,
4365
+ frame_time_max_ms: 12,
4366
+ messages_sent: 0,
4367
+ messages_received: 0,
4368
+ spatial_conflicts: 0
4369
+ });
4370
+ }
4371
+ }
4372
+ return metrics;
4373
+ });
4374
+ this.registerHandler("set_global_config", async (params, context) => {
4375
+ const config = params.config;
4376
+ this.emit("config_updated", { config, context });
4377
+ return { success: true };
4378
+ });
4379
+ this.registerHandler("trigger_event", async (params, context) => {
4380
+ const eventType = params.event_type;
4381
+ const eventData = params.event_data;
4382
+ this.emit("system_event", { eventType, eventData, context });
4383
+ return { success: true };
4384
+ });
4385
+ }
4386
+ /**
4387
+ * Get all worlds
4388
+ */
4389
+ getWorlds() {
4390
+ return Array.from(this.worlds.values());
4391
+ }
4392
+ /**
4393
+ * Update world status
4394
+ */
4395
+ updateWorld(worldId, updates) {
4396
+ const world = this.worlds.get(worldId);
4397
+ if (world) {
4398
+ Object.assign(world, updates);
4399
+ this.emit("world_updated", { worldId, updates });
4400
+ }
4401
+ }
4402
+ };
4403
+
4404
+ // src/agents/spatial-comms/SpatialCommClient.ts
4405
+ var import_events5 = require("events");
4406
+ var FrameBudgetTracker = class {
4407
+ targetFps;
4408
+ targetFrameTimeMs;
4409
+ frameTimeSamples = [];
4410
+ maxSamples = 60;
4411
+ // Track last 60 frames
4412
+ qualityLevel = "high";
4413
+ constructor(targetFps = 90) {
4414
+ this.targetFps = targetFps;
4415
+ this.targetFrameTimeMs = 1e3 / targetFps;
4416
+ }
4417
+ /**
4418
+ * Record frame time
4419
+ */
4420
+ recordFrameTime(frameTimeMs) {
4421
+ this.frameTimeSamples.push(frameTimeMs);
4422
+ if (this.frameTimeSamples.length > this.maxSamples) {
4423
+ this.frameTimeSamples.shift();
4424
+ }
4425
+ this.autoAdjustQuality();
4426
+ }
4427
+ /**
4428
+ * Get average frame time
4429
+ */
4430
+ getAverageFrameTime() {
4431
+ if (this.frameTimeSamples.length === 0) return this.targetFrameTimeMs;
4432
+ const sum = this.frameTimeSamples.reduce((a, b) => a + b, 0);
4433
+ return sum / this.frameTimeSamples.length;
4434
+ }
4435
+ /**
4436
+ * Get maximum frame time
4437
+ */
4438
+ getMaxFrameTime() {
4439
+ if (this.frameTimeSamples.length === 0) return this.targetFrameTimeMs;
4440
+ return Math.max(...this.frameTimeSamples);
4441
+ }
4442
+ /**
4443
+ * Get current FPS
4444
+ */
4445
+ getCurrentFps() {
4446
+ const avgFrameTime = this.getAverageFrameTime();
4447
+ return 1e3 / avgFrameTime;
4448
+ }
4449
+ /**
4450
+ * Get budget remaining for current frame
4451
+ */
4452
+ getBudgetRemaining() {
4453
+ const avgFrameTime = this.getAverageFrameTime();
4454
+ return Math.max(0, this.targetFrameTimeMs - avgFrameTime);
4455
+ }
4456
+ /**
4457
+ * Check if within budget
4458
+ */
4459
+ isWithinBudget() {
4460
+ return this.getAverageFrameTime() <= this.targetFrameTimeMs * 1.1;
4461
+ }
4462
+ /**
4463
+ * Get current quality level
4464
+ */
4465
+ getQualityLevel() {
4466
+ return this.qualityLevel;
4467
+ }
4468
+ /**
4469
+ * Set quality level
4470
+ */
4471
+ setQualityLevel(level) {
4472
+ this.qualityLevel = level;
4473
+ }
4474
+ /**
4475
+ * Auto-adjust quality based on performance
4476
+ */
4477
+ autoAdjustQuality() {
4478
+ const avgFrameTime = this.getAverageFrameTime();
4479
+ const targetFrameTime = this.targetFrameTimeMs;
4480
+ if (avgFrameTime > targetFrameTime * 1.3) {
4481
+ this.qualityLevel = "minimal";
4482
+ } else if (avgFrameTime > targetFrameTime * 1.2) {
4483
+ this.qualityLevel = "low";
4484
+ } else if (avgFrameTime > targetFrameTime * 1.1) {
4485
+ this.qualityLevel = "medium";
4486
+ } else {
4487
+ this.qualityLevel = "high";
4488
+ }
4489
+ }
4490
+ /**
4491
+ * Get frame budget stats
4492
+ */
4493
+ getStats() {
4494
+ return {
4495
+ targetFps: this.targetFps,
4496
+ currentFps: this.getCurrentFps(),
4497
+ avgFrameTimeMs: this.getAverageFrameTime(),
4498
+ maxFrameTimeMs: this.getMaxFrameTime(),
4499
+ budgetRemainingMs: this.getBudgetRemaining(),
4500
+ qualityLevel: this.qualityLevel,
4501
+ withinBudget: this.isWithinBudget()
4502
+ };
4503
+ }
4504
+ /**
4505
+ * Reset tracker
4506
+ */
4507
+ reset() {
4508
+ this.frameTimeSamples = [];
4509
+ this.qualityLevel = "high";
4510
+ }
4511
+ };
4512
+ var SpatialCommClient = class extends import_events5.EventEmitter {
4513
+ agentId;
4514
+ config;
4515
+ // Layer clients
4516
+ layer1;
4517
+ layer2;
4518
+ layer3;
4519
+ // Frame budget tracker
4520
+ frameBudget;
4521
+ // State
4522
+ initialized = false;
4523
+ currentWorldId;
4524
+ constructor(agentId, config) {
4525
+ super();
4526
+ this.agentId = agentId;
4527
+ this.config = {
4528
+ layer1: { ...DEFAULT_SPATIAL_COMM_CONFIG.layer1, ...config?.layer1 || {} },
4529
+ layer2: { ...DEFAULT_SPATIAL_COMM_CONFIG.layer2, ...config?.layer2 || {} },
4530
+ layer3: { ...DEFAULT_SPATIAL_COMM_CONFIG.layer3, ...config?.layer3 || {} }
4531
+ };
4532
+ this.frameBudget = new FrameBudgetTracker(this.config.layer1.targetLatency);
4533
+ }
4534
+ /**
4535
+ * Initialize all layers
4536
+ */
4537
+ async init(options) {
4538
+ if (this.initialized) {
4539
+ throw new Error("Client already initialized");
4540
+ }
4541
+ this.layer1 = new Layer1RealTimeClient(this.agentId, this.config.layer1);
4542
+ await this.layer1.init(options?.useWebRTC);
4543
+ this.layer1.on("message", (msg) => this.emit("layer1:message", msg));
4544
+ this.layer1.on("latency_warning", (data) => this.emit("layer1:latency_warning", data));
4545
+ this.layer2 = new Layer2A2AClient(this.agentId, this.config.layer2);
4546
+ this.layer2.on("message", (msg) => this.emit("layer2:message", msg));
4547
+ this.layer2.on("spatial_conflict", (data) => this.emit("layer2:spatial_conflict", data));
4548
+ this.layer2.on("retry", (data) => this.emit("layer2:retry", data));
4549
+ this.layer3 = new Layer3MCPClient(this.agentId, this.config.layer3);
4550
+ this.layer3.on("command_success", (data) => this.emit("layer3:command_success", data));
4551
+ this.layer3.on("command_error", (data) => this.emit("layer3:command_error", data));
4552
+ this.initialized = true;
4553
+ this.emit("initialized", { agentId: this.agentId });
4554
+ }
4555
+ // ==========================================================================
4556
+ // LAYER 1: REAL-TIME OPERATIONS
4557
+ // ==========================================================================
4558
+ /**
4559
+ * Send position sync (Layer 1)
4560
+ */
4561
+ async syncPosition(position, rotation, scale, velocity) {
4562
+ if (!this.layer1) throw new Error("Layer 1 not initialized");
4563
+ await this.layer1.sendPositionSync(position, rotation, scale, velocity);
4564
+ }
4565
+ /**
4566
+ * Send frame budget update (Layer 1)
4567
+ */
4568
+ async sendFrameBudget() {
4569
+ if (!this.layer1) throw new Error("Layer 1 not initialized");
4570
+ const stats = this.frameBudget.getStats();
4571
+ await this.layer1.sendFrameBudget(
4572
+ stats.avgFrameTimeMs,
4573
+ stats.budgetRemainingMs,
4574
+ stats.targetFps,
4575
+ stats.currentFps,
4576
+ stats.qualityLevel
4577
+ );
4578
+ }
4579
+ /**
4580
+ * Record frame time (updates budget tracker)
4581
+ */
4582
+ recordFrameTime(frameTimeMs) {
4583
+ this.frameBudget.recordFrameTime(frameTimeMs);
4584
+ if (!this.frameBudget.isWithinBudget()) {
4585
+ this.emit("budget_warning", this.frameBudget.getStats());
4586
+ }
4587
+ }
4588
+ /**
4589
+ * Get frame budget stats
4590
+ */
4591
+ getFrameBudgetStats() {
4592
+ return this.frameBudget.getStats();
4593
+ }
4594
+ // ==========================================================================
4595
+ // LAYER 2: COORDINATION OPERATIONS
4596
+ // ==========================================================================
4597
+ /**
4598
+ * Assign task to agent (Layer 2)
4599
+ */
4600
+ async assignTask(toAgent, task) {
4601
+ if (!this.layer2) throw new Error("Layer 2 not initialized");
4602
+ return this.layer2.assignTask(toAgent, task);
4603
+ }
4604
+ /**
4605
+ * Complete task (Layer 2)
4606
+ */
4607
+ async completeTask(taskId, success, result, error) {
4608
+ if (!this.layer2) throw new Error("Layer 2 not initialized");
4609
+ const stats = this.frameBudget.getStats();
4610
+ return this.layer2.completeTask(taskId, success, result, error, {
4611
+ duration_ms: 0,
4612
+ // Would be tracked separately
4613
+ frame_time_avg_ms: stats.avgFrameTimeMs,
4614
+ frame_time_max_ms: stats.maxFrameTimeMs,
4615
+ quality_level: stats.qualityLevel
4616
+ });
4617
+ }
4618
+ /**
4619
+ * Claim spatial region (Layer 2)
4620
+ */
4621
+ async claimSpatialRegion(claimId, boundingBox, priority, durationMs, exclusive = true) {
4622
+ if (!this.layer2) throw new Error("Layer 2 not initialized");
4623
+ return this.layer2.claimSpatialRegion(claimId, boundingBox, priority, durationMs, exclusive);
4624
+ }
4625
+ /**
4626
+ * Request resource (Layer 2)
4627
+ */
4628
+ async requestResource(resourceId, resourceType, amount, priority = "medium") {
4629
+ if (!this.layer2) throw new Error("Layer 2 not initialized");
4630
+ return this.layer2.requestResource(resourceId, resourceType, amount, priority);
4631
+ }
4632
+ /**
4633
+ * Release resource (Layer 2)
4634
+ */
4635
+ async releaseResource(resourceId) {
4636
+ if (!this.layer2) throw new Error("Layer 2 not initialized");
4637
+ return this.layer2.releaseResource(resourceId);
4638
+ }
4639
+ /**
4640
+ * Get spatial claims (Layer 2)
4641
+ */
4642
+ getMyClaims() {
4643
+ if (!this.layer2) throw new Error("Layer 2 not initialized");
4644
+ return this.layer2.getMyClaims();
4645
+ }
4646
+ // ==========================================================================
4647
+ // LAYER 3: METADATA OPERATIONS
4648
+ // ==========================================================================
4649
+ /**
4650
+ * Create world (Layer 3)
4651
+ */
4652
+ async createWorld(worldSpec) {
4653
+ if (!this.layer3) throw new Error("Layer 3 not initialized");
4654
+ const result = await this.layer3.createWorld(worldSpec);
4655
+ this.currentWorldId = result.world_id;
4656
+ return result;
4657
+ }
4658
+ /**
4659
+ * Get world status (Layer 3)
4660
+ */
4661
+ async getWorldStatus(worldId) {
4662
+ if (!this.layer3) throw new Error("Layer 3 not initialized");
4663
+ const id = worldId || this.currentWorldId;
4664
+ if (!id) throw new Error("No world ID specified");
4665
+ return this.layer3.getWorldStatus(id);
4666
+ }
4667
+ /**
4668
+ * Export world (Layer 3)
4669
+ */
4670
+ async exportWorld(format, worldId) {
4671
+ if (!this.layer3) throw new Error("Layer 3 not initialized");
4672
+ const id = worldId || this.currentWorldId;
4673
+ if (!id) throw new Error("No world ID specified");
4674
+ return this.layer3.exportWorld(id, format);
4675
+ }
4676
+ /**
4677
+ * Get agent registry (Layer 3)
4678
+ */
4679
+ async getAgentRegistry(filter) {
4680
+ if (!this.layer3) throw new Error("Layer 3 not initialized");
4681
+ return this.layer3.getAgentRegistry(filter);
4682
+ }
4683
+ /**
4684
+ * Get performance metrics (Layer 3)
4685
+ */
4686
+ async getPerformanceMetrics(options) {
4687
+ if (!this.layer3) throw new Error("Layer 3 not initialized");
4688
+ return this.layer3.getPerformanceMetrics(options);
4689
+ }
4690
+ /**
4691
+ * Set global configuration (Layer 3)
4692
+ */
4693
+ async setGlobalConfig(config) {
4694
+ if (!this.layer3) throw new Error("Layer 3 not initialized");
4695
+ return this.layer3.setGlobalConfig(config);
4696
+ }
4697
+ // ==========================================================================
4698
+ // LIFECYCLE
4699
+ // ==========================================================================
4700
+ /**
4701
+ * Shutdown client
4702
+ */
4703
+ async shutdown() {
4704
+ if (!this.initialized) return;
4705
+ if (this.layer3) {
4706
+ }
4707
+ if (this.layer2) {
4708
+ await this.layer2.shutdown();
4709
+ }
4710
+ if (this.layer1) {
4711
+ await this.layer1.close();
4712
+ }
4713
+ this.initialized = false;
4714
+ this.emit("shutdown");
4715
+ }
4716
+ /**
4717
+ * Get client status
4718
+ */
4719
+ getStatus() {
4720
+ return {
4721
+ agentId: this.agentId,
4722
+ initialized: this.initialized,
4723
+ currentWorldId: this.currentWorldId,
4724
+ frameBudget: this.frameBudget.getStats(),
4725
+ queueStats: this.layer2?.getQueueStats() || { queueSize: 0, claimCount: 0 }
4726
+ };
4727
+ }
4728
+ };
4729
+ // Annotate the CommonJS export names for ESM import in node:
4730
+ 0 && (module.exports = {
4731
+ AgentManifestBuilder,
4732
+ AgentRegistry,
4733
+ AgentWalletRegistry,
4734
+ BUILTIN_NORMS,
4735
+ CapabilityMatcher,
4736
+ CulturalMemory,
4737
+ DEFAULT_A2A_CONFIG,
4738
+ DEFAULT_MCP_CONFIG,
4739
+ DEFAULT_PHASE_TIMINGS,
4740
+ DEFAULT_REALTIME_CONFIG,
4741
+ DEFAULT_REGISTRY_CONFIG,
4742
+ DEFAULT_SPATIAL_COMM_CONFIG,
4743
+ EffectRow,
4744
+ FederatedRegistryAdapter,
4745
+ FrameBudgetTracker,
4746
+ GCounter,
4747
+ LATENCY_THRESHOLDS,
4748
+ LWWRegister,
4749
+ Layer1RealTimeClient,
4750
+ Layer2A2AClient,
4751
+ Layer3MCPClient,
4752
+ Layer3MCPServer,
4753
+ NormEngine,
4754
+ ORSet,
4755
+ OrchestratorAgent,
4756
+ PHASE_ORDER,
4757
+ PLATFORM_CAPABILITIES,
4758
+ PROTOCOL_COMPATIBILITY,
4759
+ PROTOCOL_VERSION,
4760
+ SPATIAL_MCP_TOOLS,
4761
+ SkillWorkflowEngine,
4762
+ SpatialCommClient,
4763
+ TaskDelegationService,
4764
+ UDPRealTimeTransport,
4765
+ WebRTCRealTimeTransport,
4766
+ createAgentManifest,
4767
+ createAgentState,
4768
+ createMVCPayload,
4769
+ criticalMassForChange,
4770
+ decodeRealTimeMessage,
4771
+ defaultMatcher,
4772
+ embodimentFor,
4773
+ encodeRealTimeMessage,
4774
+ estimatePayloadSize,
4775
+ findAgents,
4776
+ findBestAgent,
4777
+ getCounter,
4778
+ getDefaultRegistry,
4779
+ getRegister,
4780
+ incrementCounter,
4781
+ mergeStates,
4782
+ negotiateHandoff,
4783
+ platformCategory,
4784
+ resetDefaultRegistry,
4785
+ setRegister,
4786
+ signOperation,
4787
+ validateManifest,
4788
+ validatePayloadBudget,
4789
+ verifyOperation
4790
+ });