@framers/agentos 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (601) hide show
  1. package/LICENSE +98 -0
  2. package/README.md +576 -0
  3. package/dist/api/AgentOS.d.ts +451 -0
  4. package/dist/api/AgentOS.d.ts.map +1 -0
  5. package/dist/api/AgentOS.js +1157 -0
  6. package/dist/api/AgentOS.js.map +1 -0
  7. package/dist/api/AgentOSOrchestrator.d.ts +157 -0
  8. package/dist/api/AgentOSOrchestrator.d.ts.map +1 -0
  9. package/dist/api/AgentOSOrchestrator.js +679 -0
  10. package/dist/api/AgentOSOrchestrator.js.map +1 -0
  11. package/dist/api/interfaces/IAgentOS.d.ts +138 -0
  12. package/dist/api/interfaces/IAgentOS.d.ts.map +1 -0
  13. package/dist/api/interfaces/IAgentOS.js +11 -0
  14. package/dist/api/interfaces/IAgentOS.js.map +1 -0
  15. package/dist/api/interfaces/IUnifiedAgent.d.ts +126 -0
  16. package/dist/api/interfaces/IUnifiedAgent.d.ts.map +1 -0
  17. package/dist/api/interfaces/IUnifiedAgent.js +3 -0
  18. package/dist/api/interfaces/IUnifiedAgent.js.map +1 -0
  19. package/dist/api/types/AgentOSInput.d.ts +114 -0
  20. package/dist/api/types/AgentOSInput.d.ts.map +1 -0
  21. package/dist/api/types/AgentOSInput.js +13 -0
  22. package/dist/api/types/AgentOSInput.js.map +1 -0
  23. package/dist/api/types/AgentOSResponse.d.ts +170 -0
  24. package/dist/api/types/AgentOSResponse.d.ts.map +1 -0
  25. package/dist/api/types/AgentOSResponse.js +25 -0
  26. package/dist/api/types/AgentOSResponse.js.map +1 -0
  27. package/dist/cognitive_substrate/GMI.d.ts +148 -0
  28. package/dist/cognitive_substrate/GMI.d.ts.map +1 -0
  29. package/dist/cognitive_substrate/GMI.js +1003 -0
  30. package/dist/cognitive_substrate/GMI.js.map +1 -0
  31. package/dist/cognitive_substrate/GMIManager.d.ts +98 -0
  32. package/dist/cognitive_substrate/GMIManager.d.ts.map +1 -0
  33. package/dist/cognitive_substrate/GMIManager.js +517 -0
  34. package/dist/cognitive_substrate/GMIManager.js.map +1 -0
  35. package/dist/cognitive_substrate/IGMI.d.ts +469 -0
  36. package/dist/cognitive_substrate/IGMI.d.ts.map +1 -0
  37. package/dist/cognitive_substrate/IGMI.js +111 -0
  38. package/dist/cognitive_substrate/IGMI.js.map +1 -0
  39. package/dist/cognitive_substrate/memory/IWorkingMemory.d.ts +139 -0
  40. package/dist/cognitive_substrate/memory/IWorkingMemory.d.ts.map +1 -0
  41. package/dist/cognitive_substrate/memory/IWorkingMemory.js +14 -0
  42. package/dist/cognitive_substrate/memory/IWorkingMemory.js.map +1 -0
  43. package/dist/cognitive_substrate/memory/InMemoryWorkingMemory.d.ts +143 -0
  44. package/dist/cognitive_substrate/memory/InMemoryWorkingMemory.d.ts.map +1 -0
  45. package/dist/cognitive_substrate/memory/InMemoryWorkingMemory.js +186 -0
  46. package/dist/cognitive_substrate/memory/InMemoryWorkingMemory.js.map +1 -0
  47. package/dist/cognitive_substrate/persona_overlays/PersonaOverlayManager.d.ts +33 -0
  48. package/dist/cognitive_substrate/persona_overlays/PersonaOverlayManager.d.ts.map +1 -0
  49. package/dist/cognitive_substrate/persona_overlays/PersonaOverlayManager.js +138 -0
  50. package/dist/cognitive_substrate/persona_overlays/PersonaOverlayManager.js.map +1 -0
  51. package/dist/cognitive_substrate/persona_overlays/PersonaOverlayTypes.d.ts +32 -0
  52. package/dist/cognitive_substrate/persona_overlays/PersonaOverlayTypes.d.ts.map +1 -0
  53. package/dist/cognitive_substrate/persona_overlays/PersonaOverlayTypes.js +2 -0
  54. package/dist/cognitive_substrate/persona_overlays/PersonaOverlayTypes.js.map +1 -0
  55. package/dist/cognitive_substrate/personas/IPersonaDefinition.d.ts +336 -0
  56. package/dist/cognitive_substrate/personas/IPersonaDefinition.d.ts.map +1 -0
  57. package/dist/cognitive_substrate/personas/IPersonaDefinition.js +8 -0
  58. package/dist/cognitive_substrate/personas/IPersonaDefinition.js.map +1 -0
  59. package/dist/cognitive_substrate/personas/IPersonaLoader.d.ts +78 -0
  60. package/dist/cognitive_substrate/personas/IPersonaLoader.d.ts.map +1 -0
  61. package/dist/cognitive_substrate/personas/IPersonaLoader.js +9 -0
  62. package/dist/cognitive_substrate/personas/IPersonaLoader.js.map +1 -0
  63. package/dist/cognitive_substrate/personas/PersonaLoader.d.ts +60 -0
  64. package/dist/cognitive_substrate/personas/PersonaLoader.d.ts.map +1 -0
  65. package/dist/cognitive_substrate/personas/PersonaLoader.js +138 -0
  66. package/dist/cognitive_substrate/personas/PersonaLoader.js.map +1 -0
  67. package/dist/cognitive_substrate/personas/PersonaValidation.d.ts +139 -0
  68. package/dist/cognitive_substrate/personas/PersonaValidation.d.ts.map +1 -0
  69. package/dist/cognitive_substrate/personas/PersonaValidation.js +277 -0
  70. package/dist/cognitive_substrate/personas/PersonaValidation.js.map +1 -0
  71. package/dist/cognitive_substrate/personas/definitions/atlas_systems_architect.json +29 -0
  72. package/dist/cognitive_substrate/personas/definitions/default_assistant_persona.json +346 -0
  73. package/dist/cognitive_substrate/personas/definitions/default_free_assistant.json +13 -0
  74. package/dist/cognitive_substrate/personas/definitions/index.d.ts +14 -0
  75. package/dist/cognitive_substrate/personas/definitions/index.d.ts.map +1 -0
  76. package/dist/cognitive_substrate/personas/definitions/index.js +35 -0
  77. package/dist/cognitive_substrate/personas/definitions/index.js.map +1 -0
  78. package/dist/cognitive_substrate/personas/definitions/nerf_generalist.json +11 -0
  79. package/dist/cognitive_substrate/personas/definitions/v_researcher.json +11 -0
  80. package/dist/config/AgentOSConfig.d.ts +74 -0
  81. package/dist/config/AgentOSConfig.d.ts.map +1 -0
  82. package/dist/config/AgentOSConfig.js +399 -0
  83. package/dist/config/AgentOSConfig.js.map +1 -0
  84. package/dist/config/EmbeddingManagerConfiguration.d.ts +190 -0
  85. package/dist/config/EmbeddingManagerConfiguration.d.ts.map +1 -0
  86. package/dist/config/EmbeddingManagerConfiguration.js +16 -0
  87. package/dist/config/EmbeddingManagerConfiguration.js.map +1 -0
  88. package/dist/config/MemoryLifecycleManagerConfiguration.d.ts +165 -0
  89. package/dist/config/MemoryLifecycleManagerConfiguration.d.ts.map +1 -0
  90. package/dist/config/MemoryLifecycleManagerConfiguration.js +69 -0
  91. package/dist/config/MemoryLifecycleManagerConfiguration.js.map +1 -0
  92. package/dist/config/RetrievalAugmentorConfiguration.d.ts +98 -0
  93. package/dist/config/RetrievalAugmentorConfiguration.d.ts.map +1 -0
  94. package/dist/config/RetrievalAugmentorConfiguration.js +47 -0
  95. package/dist/config/RetrievalAugmentorConfiguration.js.map +1 -0
  96. package/dist/config/ToolOrchestratorConfig.d.ts +69 -0
  97. package/dist/config/ToolOrchestratorConfig.d.ts.map +1 -0
  98. package/dist/config/ToolOrchestratorConfig.js +11 -0
  99. package/dist/config/ToolOrchestratorConfig.js.map +1 -0
  100. package/dist/config/VectorStoreConfiguration.d.ts +223 -0
  101. package/dist/config/VectorStoreConfiguration.d.ts.map +1 -0
  102. package/dist/config/VectorStoreConfiguration.js +59 -0
  103. package/dist/config/VectorStoreConfiguration.js.map +1 -0
  104. package/dist/config/extension-secrets.json +38 -0
  105. package/dist/config/extensionSecrets.d.ts +13 -0
  106. package/dist/config/extensionSecrets.d.ts.map +1 -0
  107. package/dist/config/extensionSecrets.js +24 -0
  108. package/dist/config/extensionSecrets.js.map +1 -0
  109. package/dist/core/agency/AgencyMemoryManager.d.ts +300 -0
  110. package/dist/core/agency/AgencyMemoryManager.d.ts.map +1 -0
  111. package/dist/core/agency/AgencyMemoryManager.js +657 -0
  112. package/dist/core/agency/AgencyMemoryManager.js.map +1 -0
  113. package/dist/core/agency/AgencyRegistry.d.ts +100 -0
  114. package/dist/core/agency/AgencyRegistry.d.ts.map +1 -0
  115. package/dist/core/agency/AgencyRegistry.js +209 -0
  116. package/dist/core/agency/AgencyRegistry.js.map +1 -0
  117. package/dist/core/agency/AgencyTypes.d.ts +200 -0
  118. package/dist/core/agency/AgencyTypes.d.ts.map +1 -0
  119. package/dist/core/agency/AgencyTypes.js +7 -0
  120. package/dist/core/agency/AgencyTypes.js.map +1 -0
  121. package/dist/core/agency/AgentCommunicationBus.d.ts +150 -0
  122. package/dist/core/agency/AgentCommunicationBus.d.ts.map +1 -0
  123. package/dist/core/agency/AgentCommunicationBus.js +568 -0
  124. package/dist/core/agency/AgentCommunicationBus.js.map +1 -0
  125. package/dist/core/agency/IAgentCommunicationBus.d.ts +469 -0
  126. package/dist/core/agency/IAgentCommunicationBus.d.ts.map +1 -0
  127. package/dist/core/agency/IAgentCommunicationBus.js +40 -0
  128. package/dist/core/agency/IAgentCommunicationBus.js.map +1 -0
  129. package/dist/core/agency/index.d.ts +18 -0
  130. package/dist/core/agency/index.d.ts.map +1 -0
  131. package/dist/core/agency/index.js +18 -0
  132. package/dist/core/agency/index.js.map +1 -0
  133. package/dist/core/agents/AgentCore.d.ts +385 -0
  134. package/dist/core/agents/AgentCore.d.ts.map +1 -0
  135. package/dist/core/agents/AgentCore.js +527 -0
  136. package/dist/core/agents/AgentCore.js.map +1 -0
  137. package/dist/core/agents/AgentFactory.d.ts +123 -0
  138. package/dist/core/agents/AgentFactory.d.ts.map +1 -0
  139. package/dist/core/agents/AgentFactory.js +232 -0
  140. package/dist/core/agents/AgentFactory.js.map +1 -0
  141. package/dist/core/agents/AgentPoolAgent.d.ts +244 -0
  142. package/dist/core/agents/AgentPoolAgent.d.ts.map +1 -0
  143. package/dist/core/agents/AgentPoolAgent.js +697 -0
  144. package/dist/core/agents/AgentPoolAgent.js.map +1 -0
  145. package/dist/core/agents/AgentPoolConfig.d.ts +191 -0
  146. package/dist/core/agents/AgentPoolConfig.d.ts.map +1 -0
  147. package/dist/core/agents/AgentPoolConfig.js +58 -0
  148. package/dist/core/agents/AgentPoolConfig.js.map +1 -0
  149. package/dist/core/agents/IAgent.d.ts +226 -0
  150. package/dist/core/agents/IAgent.d.ts.map +1 -0
  151. package/dist/core/agents/IAgent.js +14 -0
  152. package/dist/core/agents/IAgent.js.map +1 -0
  153. package/dist/core/agents/IAgentFactory.d.ts +137 -0
  154. package/dist/core/agents/IAgentFactory.d.ts.map +1 -0
  155. package/dist/core/agents/IAgentFactory.js +13 -0
  156. package/dist/core/agents/IAgentFactory.js.map +1 -0
  157. package/dist/core/agents/tools/Tool.d.ts +17 -0
  158. package/dist/core/agents/tools/Tool.d.ts.map +1 -0
  159. package/dist/core/agents/tools/Tool.js +8 -0
  160. package/dist/core/agents/tools/Tool.js.map +1 -0
  161. package/dist/core/ai_utilities/HybridUtilityAI.d.ts +1 -0
  162. package/dist/core/ai_utilities/HybridUtilityAI.d.ts.map +1 -0
  163. package/dist/core/ai_utilities/HybridUtilityAI.js +2 -0
  164. package/dist/core/ai_utilities/HybridUtilityAI.js.map +1 -0
  165. package/dist/core/ai_utilities/IUtilityAI.d.ts +212 -0
  166. package/dist/core/ai_utilities/IUtilityAI.d.ts.map +1 -0
  167. package/dist/core/ai_utilities/IUtilityAI.js +11 -0
  168. package/dist/core/ai_utilities/IUtilityAI.js.map +1 -0
  169. package/dist/core/ai_utilities/LLMUtilityAI.d.ts +94 -0
  170. package/dist/core/ai_utilities/LLMUtilityAI.d.ts.map +1 -0
  171. package/dist/core/ai_utilities/LLMUtilityAI.js +434 -0
  172. package/dist/core/ai_utilities/LLMUtilityAI.js.map +1 -0
  173. package/dist/core/ai_utilities/StatisticalUtilityAI.d.ts +102 -0
  174. package/dist/core/ai_utilities/StatisticalUtilityAI.d.ts.map +1 -0
  175. package/dist/core/ai_utilities/StatisticalUtilityAI.js +617 -0
  176. package/dist/core/ai_utilities/StatisticalUtilityAI.js.map +1 -0
  177. package/dist/core/conversation/ConversationContext.d.ts +259 -0
  178. package/dist/core/conversation/ConversationContext.d.ts.map +1 -0
  179. package/dist/core/conversation/ConversationContext.js +450 -0
  180. package/dist/core/conversation/ConversationContext.js.map +1 -0
  181. package/dist/core/conversation/ConversationManager.d.ts +223 -0
  182. package/dist/core/conversation/ConversationManager.d.ts.map +1 -0
  183. package/dist/core/conversation/ConversationManager.js +558 -0
  184. package/dist/core/conversation/ConversationManager.js.map +1 -0
  185. package/dist/core/conversation/ConversationMessage.d.ts +184 -0
  186. package/dist/core/conversation/ConversationMessage.d.ts.map +1 -0
  187. package/dist/core/conversation/ConversationMessage.js +66 -0
  188. package/dist/core/conversation/ConversationMessage.js.map +1 -0
  189. package/dist/core/evaluation/Evaluator.d.ts +28 -0
  190. package/dist/core/evaluation/Evaluator.d.ts.map +1 -0
  191. package/dist/core/evaluation/Evaluator.js +490 -0
  192. package/dist/core/evaluation/Evaluator.js.map +1 -0
  193. package/dist/core/evaluation/IEvaluator.d.ts +309 -0
  194. package/dist/core/evaluation/IEvaluator.d.ts.map +1 -0
  195. package/dist/core/evaluation/IEvaluator.js +12 -0
  196. package/dist/core/evaluation/IEvaluator.js.map +1 -0
  197. package/dist/core/evaluation/LLMJudge.d.ts +105 -0
  198. package/dist/core/evaluation/LLMJudge.d.ts.map +1 -0
  199. package/dist/core/evaluation/LLMJudge.js +229 -0
  200. package/dist/core/evaluation/LLMJudge.js.map +1 -0
  201. package/dist/core/evaluation/index.d.ts +9 -0
  202. package/dist/core/evaluation/index.d.ts.map +1 -0
  203. package/dist/core/evaluation/index.js +9 -0
  204. package/dist/core/evaluation/index.js.map +1 -0
  205. package/dist/core/guardrails/IGuardrailService.d.ts +142 -0
  206. package/dist/core/guardrails/IGuardrailService.d.ts.map +1 -0
  207. package/dist/core/guardrails/IGuardrailService.js +24 -0
  208. package/dist/core/guardrails/IGuardrailService.js.map +1 -0
  209. package/dist/core/guardrails/guardrailDispatcher.d.ts +36 -0
  210. package/dist/core/guardrails/guardrailDispatcher.d.ts.map +1 -0
  211. package/dist/core/guardrails/guardrailDispatcher.js +240 -0
  212. package/dist/core/guardrails/guardrailDispatcher.js.map +1 -0
  213. package/dist/core/hitl/HumanInteractionManager.d.ts +146 -0
  214. package/dist/core/hitl/HumanInteractionManager.d.ts.map +1 -0
  215. package/dist/core/hitl/HumanInteractionManager.js +491 -0
  216. package/dist/core/hitl/HumanInteractionManager.js.map +1 -0
  217. package/dist/core/hitl/IHumanInteractionManager.d.ts +521 -0
  218. package/dist/core/hitl/IHumanInteractionManager.d.ts.map +1 -0
  219. package/dist/core/hitl/IHumanInteractionManager.js +33 -0
  220. package/dist/core/hitl/IHumanInteractionManager.js.map +1 -0
  221. package/dist/core/hitl/index.d.ts +17 -0
  222. package/dist/core/hitl/index.d.ts.map +1 -0
  223. package/dist/core/hitl/index.js +17 -0
  224. package/dist/core/hitl/index.js.map +1 -0
  225. package/dist/core/knowledge/IKnowledgeGraph.d.ts +351 -0
  226. package/dist/core/knowledge/IKnowledgeGraph.d.ts.map +1 -0
  227. package/dist/core/knowledge/IKnowledgeGraph.js +10 -0
  228. package/dist/core/knowledge/IKnowledgeGraph.js.map +1 -0
  229. package/dist/core/knowledge/KnowledgeGraph.d.ts +93 -0
  230. package/dist/core/knowledge/KnowledgeGraph.d.ts.map +1 -0
  231. package/dist/core/knowledge/KnowledgeGraph.js +601 -0
  232. package/dist/core/knowledge/KnowledgeGraph.js.map +1 -0
  233. package/dist/core/knowledge/index.d.ts +8 -0
  234. package/dist/core/knowledge/index.d.ts.map +1 -0
  235. package/dist/core/knowledge/index.js +8 -0
  236. package/dist/core/knowledge/index.js.map +1 -0
  237. package/dist/core/language/LanguageService.d.ts +77 -0
  238. package/dist/core/language/LanguageService.d.ts.map +1 -0
  239. package/dist/core/language/LanguageService.js +305 -0
  240. package/dist/core/language/LanguageService.js.map +1 -0
  241. package/dist/core/language/index.d.ts +6 -0
  242. package/dist/core/language/index.d.ts.map +1 -0
  243. package/dist/core/language/index.js +6 -0
  244. package/dist/core/language/index.js.map +1 -0
  245. package/dist/core/language/interfaces.d.ts +168 -0
  246. package/dist/core/language/interfaces.d.ts.map +1 -0
  247. package/dist/core/language/interfaces.js +37 -0
  248. package/dist/core/language/interfaces.js.map +1 -0
  249. package/dist/core/language/providers/DeepLTranslationProvider.d.ts +16 -0
  250. package/dist/core/language/providers/DeepLTranslationProvider.d.ts.map +1 -0
  251. package/dist/core/language/providers/DeepLTranslationProvider.js +28 -0
  252. package/dist/core/language/providers/DeepLTranslationProvider.js.map +1 -0
  253. package/dist/core/language/providers/OpenAITranslationProvider.d.ts +17 -0
  254. package/dist/core/language/providers/OpenAITranslationProvider.d.ts.map +1 -0
  255. package/dist/core/language/providers/OpenAITranslationProvider.js +34 -0
  256. package/dist/core/language/providers/OpenAITranslationProvider.js.map +1 -0
  257. package/dist/core/language/providers/WhisperDetectionProvider.d.ts +16 -0
  258. package/dist/core/language/providers/WhisperDetectionProvider.d.ts.map +1 -0
  259. package/dist/core/language/providers/WhisperDetectionProvider.js +15 -0
  260. package/dist/core/language/providers/WhisperDetectionProvider.js.map +1 -0
  261. package/dist/core/llm/IPromptEngine.d.ts +627 -0
  262. package/dist/core/llm/IPromptEngine.d.ts.map +1 -0
  263. package/dist/core/llm/IPromptEngine.js +81 -0
  264. package/dist/core/llm/IPromptEngine.js.map +1 -0
  265. package/dist/core/llm/PromptEngine.d.ts +108 -0
  266. package/dist/core/llm/PromptEngine.d.ts.map +1 -0
  267. package/dist/core/llm/PromptEngine.js +872 -0
  268. package/dist/core/llm/PromptEngine.js.map +1 -0
  269. package/dist/core/llm/providers/AIModelProviderManager.d.ts +74 -0
  270. package/dist/core/llm/providers/AIModelProviderManager.d.ts.map +1 -0
  271. package/dist/core/llm/providers/AIModelProviderManager.js +263 -0
  272. package/dist/core/llm/providers/AIModelProviderManager.js.map +1 -0
  273. package/dist/core/llm/providers/IProvider.d.ts +327 -0
  274. package/dist/core/llm/providers/IProvider.d.ts.map +1 -0
  275. package/dist/core/llm/providers/IProvider.js +39 -0
  276. package/dist/core/llm/providers/IProvider.js.map +1 -0
  277. package/dist/core/llm/providers/errors/OllamaProviderError.d.ts +36 -0
  278. package/dist/core/llm/providers/errors/OllamaProviderError.d.ts.map +1 -0
  279. package/dist/core/llm/providers/errors/OllamaProviderError.js +40 -0
  280. package/dist/core/llm/providers/errors/OllamaProviderError.js.map +1 -0
  281. package/dist/core/llm/providers/errors/OpenAIProviderError.d.ts +42 -0
  282. package/dist/core/llm/providers/errors/OpenAIProviderError.d.ts.map +1 -0
  283. package/dist/core/llm/providers/errors/OpenAIProviderError.js +44 -0
  284. package/dist/core/llm/providers/errors/OpenAIProviderError.js.map +1 -0
  285. package/dist/core/llm/providers/errors/OpenRouterProviderError.d.ts +39 -0
  286. package/dist/core/llm/providers/errors/OpenRouterProviderError.d.ts.map +1 -0
  287. package/dist/core/llm/providers/errors/OpenRouterProviderError.js +42 -0
  288. package/dist/core/llm/providers/errors/OpenRouterProviderError.js.map +1 -0
  289. package/dist/core/llm/providers/errors/ProviderError.d.ts +37 -0
  290. package/dist/core/llm/providers/errors/ProviderError.d.ts.map +1 -0
  291. package/dist/core/llm/providers/errors/ProviderError.js +36 -0
  292. package/dist/core/llm/providers/errors/ProviderError.js.map +1 -0
  293. package/dist/core/llm/providers/implementations/OllamaProvider.d.ts +80 -0
  294. package/dist/core/llm/providers/implementations/OllamaProvider.d.ts.map +1 -0
  295. package/dist/core/llm/providers/implementations/OllamaProvider.js +473 -0
  296. package/dist/core/llm/providers/implementations/OllamaProvider.js.map +1 -0
  297. package/dist/core/llm/providers/implementations/OpenAIProvider.d.ts +160 -0
  298. package/dist/core/llm/providers/implementations/OpenAIProvider.d.ts.map +1 -0
  299. package/dist/core/llm/providers/implementations/OpenAIProvider.js +672 -0
  300. package/dist/core/llm/providers/implementations/OpenAIProvider.js.map +1 -0
  301. package/dist/core/llm/providers/implementations/OpenRouterProvider.d.ts +51 -0
  302. package/dist/core/llm/providers/implementations/OpenRouterProvider.d.ts.map +1 -0
  303. package/dist/core/llm/providers/implementations/OpenRouterProvider.js +499 -0
  304. package/dist/core/llm/providers/implementations/OpenRouterProvider.js.map +1 -0
  305. package/dist/core/llm/routing/IModelRouter.d.ts +129 -0
  306. package/dist/core/llm/routing/IModelRouter.d.ts.map +1 -0
  307. package/dist/core/llm/routing/IModelRouter.js +14 -0
  308. package/dist/core/llm/routing/IModelRouter.js.map +1 -0
  309. package/dist/core/llm/routing/ModelRouter.d.ts +157 -0
  310. package/dist/core/llm/routing/ModelRouter.d.ts.map +1 -0
  311. package/dist/core/llm/routing/ModelRouter.js +190 -0
  312. package/dist/core/llm/routing/ModelRouter.js.map +1 -0
  313. package/dist/core/llm/streaming/StreamingBatcher.d.ts +54 -0
  314. package/dist/core/llm/streaming/StreamingBatcher.d.ts.map +1 -0
  315. package/dist/core/llm/streaming/StreamingBatcher.js +173 -0
  316. package/dist/core/llm/streaming/StreamingBatcher.js.map +1 -0
  317. package/dist/core/llm/streaming/StreamingReconstructor.d.ts +69 -0
  318. package/dist/core/llm/streaming/StreamingReconstructor.d.ts.map +1 -0
  319. package/dist/core/llm/streaming/StreamingReconstructor.js +102 -0
  320. package/dist/core/llm/streaming/StreamingReconstructor.js.map +1 -0
  321. package/dist/core/marketplace/IMarketplace.d.ts +500 -0
  322. package/dist/core/marketplace/IMarketplace.d.ts.map +1 -0
  323. package/dist/core/marketplace/IMarketplace.js +10 -0
  324. package/dist/core/marketplace/IMarketplace.js.map +1 -0
  325. package/dist/core/marketplace/Marketplace.d.ts +122 -0
  326. package/dist/core/marketplace/Marketplace.d.ts.map +1 -0
  327. package/dist/core/marketplace/Marketplace.js +591 -0
  328. package/dist/core/marketplace/Marketplace.js.map +1 -0
  329. package/dist/core/marketplace/index.d.ts +8 -0
  330. package/dist/core/marketplace/index.d.ts.map +1 -0
  331. package/dist/core/marketplace/index.js +8 -0
  332. package/dist/core/marketplace/index.js.map +1 -0
  333. package/dist/core/observability/ITracer.d.ts +317 -0
  334. package/dist/core/observability/ITracer.d.ts.map +1 -0
  335. package/dist/core/observability/ITracer.js +55 -0
  336. package/dist/core/observability/ITracer.js.map +1 -0
  337. package/dist/core/observability/Tracer.d.ts +76 -0
  338. package/dist/core/observability/Tracer.d.ts.map +1 -0
  339. package/dist/core/observability/Tracer.js +360 -0
  340. package/dist/core/observability/Tracer.js.map +1 -0
  341. package/dist/core/observability/index.d.ts +9 -0
  342. package/dist/core/observability/index.d.ts.map +1 -0
  343. package/dist/core/observability/index.js +8 -0
  344. package/dist/core/observability/index.js.map +1 -0
  345. package/dist/core/orchestration/AgentOrchestrator.d.ts +243 -0
  346. package/dist/core/orchestration/AgentOrchestrator.d.ts.map +1 -0
  347. package/dist/core/orchestration/AgentOrchestrator.js +648 -0
  348. package/dist/core/orchestration/AgentOrchestrator.js.map +1 -0
  349. package/dist/core/orchestration/IAgentOrchestrator.d.ts +44 -0
  350. package/dist/core/orchestration/IAgentOrchestrator.d.ts.map +1 -0
  351. package/dist/core/orchestration/IAgentOrchestrator.js +4 -0
  352. package/dist/core/orchestration/IAgentOrchestrator.js.map +1 -0
  353. package/dist/core/orchestration/helpers.d.ts +12 -0
  354. package/dist/core/orchestration/helpers.d.ts.map +1 -0
  355. package/dist/core/orchestration/helpers.js +36 -0
  356. package/dist/core/orchestration/helpers.js.map +1 -0
  357. package/dist/core/planning/IPlanningEngine.d.ts +524 -0
  358. package/dist/core/planning/IPlanningEngine.d.ts.map +1 -0
  359. package/dist/core/planning/IPlanningEngine.js +32 -0
  360. package/dist/core/planning/IPlanningEngine.js.map +1 -0
  361. package/dist/core/planning/PlanningEngine.d.ts +161 -0
  362. package/dist/core/planning/PlanningEngine.d.ts.map +1 -0
  363. package/dist/core/planning/PlanningEngine.js +783 -0
  364. package/dist/core/planning/PlanningEngine.js.map +1 -0
  365. package/dist/core/planning/index.d.ts +25 -0
  366. package/dist/core/planning/index.d.ts.map +1 -0
  367. package/dist/core/planning/index.js +25 -0
  368. package/dist/core/planning/index.js.map +1 -0
  369. package/dist/core/sandbox/CodeSandbox.d.ts +86 -0
  370. package/dist/core/sandbox/CodeSandbox.d.ts.map +1 -0
  371. package/dist/core/sandbox/CodeSandbox.js +475 -0
  372. package/dist/core/sandbox/CodeSandbox.js.map +1 -0
  373. package/dist/core/sandbox/ICodeSandbox.d.ts +249 -0
  374. package/dist/core/sandbox/ICodeSandbox.d.ts.map +1 -0
  375. package/dist/core/sandbox/ICodeSandbox.js +24 -0
  376. package/dist/core/sandbox/ICodeSandbox.js.map +1 -0
  377. package/dist/core/sandbox/index.d.ts +9 -0
  378. package/dist/core/sandbox/index.d.ts.map +1 -0
  379. package/dist/core/sandbox/index.js +8 -0
  380. package/dist/core/sandbox/index.js.map +1 -0
  381. package/dist/core/storage/IStorageAdapter.d.ts +483 -0
  382. package/dist/core/storage/IStorageAdapter.d.ts.map +1 -0
  383. package/dist/core/storage/IStorageAdapter.js +19 -0
  384. package/dist/core/storage/IStorageAdapter.js.map +1 -0
  385. package/dist/core/storage/InMemoryStorageAdapter.d.ts +192 -0
  386. package/dist/core/storage/InMemoryStorageAdapter.d.ts.map +1 -0
  387. package/dist/core/storage/InMemoryStorageAdapter.js +343 -0
  388. package/dist/core/storage/InMemoryStorageAdapter.js.map +1 -0
  389. package/dist/core/storage/SqlStorageAdapter.d.ts +262 -0
  390. package/dist/core/storage/SqlStorageAdapter.d.ts.map +1 -0
  391. package/dist/core/storage/SqlStorageAdapter.js +485 -0
  392. package/dist/core/storage/SqlStorageAdapter.js.map +1 -0
  393. package/dist/core/storage/index.d.ts +14 -0
  394. package/dist/core/storage/index.d.ts.map +1 -0
  395. package/dist/core/storage/index.js +14 -0
  396. package/dist/core/storage/index.js.map +1 -0
  397. package/dist/core/streaming/IStreamClient.d.ts +72 -0
  398. package/dist/core/streaming/IStreamClient.d.ts.map +1 -0
  399. package/dist/core/streaming/IStreamClient.js +12 -0
  400. package/dist/core/streaming/IStreamClient.js.map +1 -0
  401. package/dist/core/streaming/StreamingManager.d.ts +242 -0
  402. package/dist/core/streaming/StreamingManager.d.ts.map +1 -0
  403. package/dist/core/streaming/StreamingManager.js +282 -0
  404. package/dist/core/streaming/StreamingManager.js.map +1 -0
  405. package/dist/core/structured/IStructuredOutputManager.d.ts +701 -0
  406. package/dist/core/structured/IStructuredOutputManager.d.ts.map +1 -0
  407. package/dist/core/structured/IStructuredOutputManager.js +74 -0
  408. package/dist/core/structured/IStructuredOutputManager.js.map +1 -0
  409. package/dist/core/structured/StructuredOutputManager.d.ts +140 -0
  410. package/dist/core/structured/StructuredOutputManager.d.ts.map +1 -0
  411. package/dist/core/structured/StructuredOutputManager.js +1015 -0
  412. package/dist/core/structured/StructuredOutputManager.js.map +1 -0
  413. package/dist/core/structured/index.d.ts +34 -0
  414. package/dist/core/structured/index.d.ts.map +1 -0
  415. package/dist/core/structured/index.js +34 -0
  416. package/dist/core/structured/index.js.map +1 -0
  417. package/dist/core/tools/ITool.d.ts +228 -0
  418. package/dist/core/tools/ITool.d.ts.map +1 -0
  419. package/dist/core/tools/ITool.js +11 -0
  420. package/dist/core/tools/ITool.js.map +1 -0
  421. package/dist/core/tools/IToolOrchestrator.d.ts +131 -0
  422. package/dist/core/tools/IToolOrchestrator.d.ts.map +1 -0
  423. package/dist/core/tools/IToolOrchestrator.js +14 -0
  424. package/dist/core/tools/IToolOrchestrator.js.map +1 -0
  425. package/dist/core/tools/ToolExecutor.d.ts +143 -0
  426. package/dist/core/tools/ToolExecutor.d.ts.map +1 -0
  427. package/dist/core/tools/ToolExecutor.js +364 -0
  428. package/dist/core/tools/ToolExecutor.js.map +1 -0
  429. package/dist/core/tools/ToolOrchestrator.d.ts +142 -0
  430. package/dist/core/tools/ToolOrchestrator.d.ts.map +1 -0
  431. package/dist/core/tools/ToolOrchestrator.js +373 -0
  432. package/dist/core/tools/ToolOrchestrator.js.map +1 -0
  433. package/dist/core/tools/permissions/IToolPermissionManager.d.ts +195 -0
  434. package/dist/core/tools/permissions/IToolPermissionManager.d.ts.map +1 -0
  435. package/dist/core/tools/permissions/IToolPermissionManager.js +14 -0
  436. package/dist/core/tools/permissions/IToolPermissionManager.js.map +1 -0
  437. package/dist/core/tools/permissions/ToolPermissionManager.d.ts +203 -0
  438. package/dist/core/tools/permissions/ToolPermissionManager.d.ts.map +1 -0
  439. package/dist/core/tools/permissions/ToolPermissionManager.js +298 -0
  440. package/dist/core/tools/permissions/ToolPermissionManager.js.map +1 -0
  441. package/dist/core/ui/IUIComponent.d.ts +11 -0
  442. package/dist/core/ui/IUIComponent.d.ts.map +1 -0
  443. package/dist/core/ui/IUIComponent.js +2 -0
  444. package/dist/core/ui/IUIComponent.js.map +1 -0
  445. package/dist/core/usage/UsageLedger.d.ts +81 -0
  446. package/dist/core/usage/UsageLedger.d.ts.map +1 -0
  447. package/dist/core/usage/UsageLedger.js +135 -0
  448. package/dist/core/usage/UsageLedger.js.map +1 -0
  449. package/dist/core/workflows/IWorkflowEngine.d.ts +42 -0
  450. package/dist/core/workflows/IWorkflowEngine.d.ts.map +1 -0
  451. package/dist/core/workflows/IWorkflowEngine.js +2 -0
  452. package/dist/core/workflows/IWorkflowEngine.js.map +1 -0
  453. package/dist/core/workflows/WorkflowEngine.d.ts +28 -0
  454. package/dist/core/workflows/WorkflowEngine.d.ts.map +1 -0
  455. package/dist/core/workflows/WorkflowEngine.js +309 -0
  456. package/dist/core/workflows/WorkflowEngine.js.map +1 -0
  457. package/dist/core/workflows/WorkflowTypes.d.ts +180 -0
  458. package/dist/core/workflows/WorkflowTypes.d.ts.map +1 -0
  459. package/dist/core/workflows/WorkflowTypes.js +26 -0
  460. package/dist/core/workflows/WorkflowTypes.js.map +1 -0
  461. package/dist/core/workflows/runtime/WorkflowRuntime.d.ts +70 -0
  462. package/dist/core/workflows/runtime/WorkflowRuntime.d.ts.map +1 -0
  463. package/dist/core/workflows/runtime/WorkflowRuntime.js +566 -0
  464. package/dist/core/workflows/runtime/WorkflowRuntime.js.map +1 -0
  465. package/dist/core/workflows/storage/IWorkflowStore.d.ts +75 -0
  466. package/dist/core/workflows/storage/IWorkflowStore.d.ts.map +1 -0
  467. package/dist/core/workflows/storage/IWorkflowStore.js +2 -0
  468. package/dist/core/workflows/storage/IWorkflowStore.js.map +1 -0
  469. package/dist/core/workflows/storage/InMemoryWorkflowStore.d.ts +14 -0
  470. package/dist/core/workflows/storage/InMemoryWorkflowStore.d.ts.map +1 -0
  471. package/dist/core/workflows/storage/InMemoryWorkflowStore.js +130 -0
  472. package/dist/core/workflows/storage/InMemoryWorkflowStore.js.map +1 -0
  473. package/dist/extensions/ExtensionLoader.d.ts +119 -0
  474. package/dist/extensions/ExtensionLoader.d.ts.map +1 -0
  475. package/dist/extensions/ExtensionLoader.js +297 -0
  476. package/dist/extensions/ExtensionLoader.js.map +1 -0
  477. package/dist/extensions/ExtensionManager.d.ts +49 -0
  478. package/dist/extensions/ExtensionManager.d.ts.map +1 -0
  479. package/dist/extensions/ExtensionManager.js +197 -0
  480. package/dist/extensions/ExtensionManager.js.map +1 -0
  481. package/dist/extensions/ExtensionRegistry.d.ts +39 -0
  482. package/dist/extensions/ExtensionRegistry.d.ts.map +1 -0
  483. package/dist/extensions/ExtensionRegistry.js +103 -0
  484. package/dist/extensions/ExtensionRegistry.js.map +1 -0
  485. package/dist/extensions/MultiRegistryLoader.d.ts +61 -0
  486. package/dist/extensions/MultiRegistryLoader.d.ts.map +1 -0
  487. package/dist/extensions/MultiRegistryLoader.js +169 -0
  488. package/dist/extensions/MultiRegistryLoader.js.map +1 -0
  489. package/dist/extensions/RegistryConfig.d.ts +86 -0
  490. package/dist/extensions/RegistryConfig.d.ts.map +1 -0
  491. package/dist/extensions/RegistryConfig.js +99 -0
  492. package/dist/extensions/RegistryConfig.js.map +1 -0
  493. package/dist/extensions/events.d.ts +19 -0
  494. package/dist/extensions/events.d.ts.map +1 -0
  495. package/dist/extensions/events.js +2 -0
  496. package/dist/extensions/events.js.map +1 -0
  497. package/dist/extensions/index.d.ts +9 -0
  498. package/dist/extensions/index.d.ts.map +1 -0
  499. package/dist/extensions/index.js +9 -0
  500. package/dist/extensions/index.js.map +1 -0
  501. package/dist/extensions/manifest.d.ts +52 -0
  502. package/dist/extensions/manifest.d.ts.map +1 -0
  503. package/dist/extensions/manifest.js +2 -0
  504. package/dist/extensions/manifest.js.map +1 -0
  505. package/dist/extensions/types.d.ts +294 -0
  506. package/dist/extensions/types.d.ts.map +1 -0
  507. package/dist/extensions/types.js +12 -0
  508. package/dist/extensions/types.js.map +1 -0
  509. package/dist/index.d.ts +49 -0
  510. package/dist/index.d.ts.map +1 -0
  511. package/dist/index.js +59 -0
  512. package/dist/index.js.map +1 -0
  513. package/dist/logging/ILogger.d.ts +8 -0
  514. package/dist/logging/ILogger.d.ts.map +1 -0
  515. package/dist/logging/ILogger.js +2 -0
  516. package/dist/logging/ILogger.js.map +1 -0
  517. package/dist/logging/PinoLogger.d.ts +12 -0
  518. package/dist/logging/PinoLogger.d.ts.map +1 -0
  519. package/dist/logging/PinoLogger.js +22 -0
  520. package/dist/logging/PinoLogger.js.map +1 -0
  521. package/dist/logging/loggerFactory.d.ts +6 -0
  522. package/dist/logging/loggerFactory.d.ts.map +1 -0
  523. package/dist/logging/loggerFactory.js +14 -0
  524. package/dist/logging/loggerFactory.js.map +1 -0
  525. package/dist/rag/EmbeddingManager.d.ts +81 -0
  526. package/dist/rag/EmbeddingManager.d.ts.map +1 -0
  527. package/dist/rag/EmbeddingManager.js +412 -0
  528. package/dist/rag/EmbeddingManager.js.map +1 -0
  529. package/dist/rag/IEmbeddingManager.d.ts +277 -0
  530. package/dist/rag/IEmbeddingManager.d.ts.map +1 -0
  531. package/dist/rag/IEmbeddingManager.js +19 -0
  532. package/dist/rag/IEmbeddingManager.js.map +1 -0
  533. package/dist/rag/IRetrievalAugmentor.d.ts +208 -0
  534. package/dist/rag/IRetrievalAugmentor.d.ts.map +1 -0
  535. package/dist/rag/IRetrievalAugmentor.js +21 -0
  536. package/dist/rag/IRetrievalAugmentor.js.map +1 -0
  537. package/dist/rag/IVectorStore.d.ts +351 -0
  538. package/dist/rag/IVectorStore.d.ts.map +1 -0
  539. package/dist/rag/IVectorStore.js +15 -0
  540. package/dist/rag/IVectorStore.js.map +1 -0
  541. package/dist/rag/IVectorStoreManager.d.ts +121 -0
  542. package/dist/rag/IVectorStoreManager.d.ts.map +1 -0
  543. package/dist/rag/IVectorStoreManager.js +13 -0
  544. package/dist/rag/IVectorStoreManager.js.map +1 -0
  545. package/dist/rag/RetrievalAugmentor.d.ts +99 -0
  546. package/dist/rag/RetrievalAugmentor.d.ts.map +1 -0
  547. package/dist/rag/RetrievalAugmentor.js +674 -0
  548. package/dist/rag/RetrievalAugmentor.js.map +1 -0
  549. package/dist/rag/VectorStoreManager.d.ts +90 -0
  550. package/dist/rag/VectorStoreManager.d.ts.map +1 -0
  551. package/dist/rag/VectorStoreManager.js +283 -0
  552. package/dist/rag/VectorStoreManager.js.map +1 -0
  553. package/dist/rag/implementations/index.d.ts +9 -0
  554. package/dist/rag/implementations/index.d.ts.map +1 -0
  555. package/dist/rag/implementations/index.js +9 -0
  556. package/dist/rag/implementations/index.js.map +1 -0
  557. package/dist/rag/implementations/vector_stores/InMemoryVectorStore.d.ts +132 -0
  558. package/dist/rag/implementations/vector_stores/InMemoryVectorStore.d.ts.map +1 -0
  559. package/dist/rag/implementations/vector_stores/InMemoryVectorStore.js +539 -0
  560. package/dist/rag/implementations/vector_stores/InMemoryVectorStore.js.map +1 -0
  561. package/dist/rag/implementations/vector_stores/SqlVectorStore.d.ts +265 -0
  562. package/dist/rag/implementations/vector_stores/SqlVectorStore.d.ts.map +1 -0
  563. package/dist/rag/implementations/vector_stores/SqlVectorStore.js +755 -0
  564. package/dist/rag/implementations/vector_stores/SqlVectorStore.js.map +1 -0
  565. package/dist/rag/implementations/vector_stores/index.d.ts +10 -0
  566. package/dist/rag/implementations/vector_stores/index.d.ts.map +1 -0
  567. package/dist/rag/implementations/vector_stores/index.js +12 -0
  568. package/dist/rag/implementations/vector_stores/index.js.map +1 -0
  569. package/dist/rag/index.d.ts +95 -0
  570. package/dist/rag/index.d.ts.map +1 -0
  571. package/dist/rag/index.js +97 -0
  572. package/dist/rag/index.js.map +1 -0
  573. package/dist/services/user_auth/AuthService.d.ts +13 -0
  574. package/dist/services/user_auth/AuthService.d.ts.map +1 -0
  575. package/dist/services/user_auth/AuthService.js +24 -0
  576. package/dist/services/user_auth/AuthService.js.map +1 -0
  577. package/dist/services/user_auth/SubscriptionService.d.ts +14 -0
  578. package/dist/services/user_auth/SubscriptionService.d.ts.map +1 -0
  579. package/dist/services/user_auth/SubscriptionService.js +34 -0
  580. package/dist/services/user_auth/SubscriptionService.js.map +1 -0
  581. package/dist/services/user_auth/types.d.ts +30 -0
  582. package/dist/services/user_auth/types.d.ts.map +1 -0
  583. package/dist/services/user_auth/types.js +2 -0
  584. package/dist/services/user_auth/types.js.map +1 -0
  585. package/dist/stubs/prismaClient.d.ts +35 -0
  586. package/dist/stubs/prismaClient.d.ts.map +1 -0
  587. package/dist/stubs/prismaClient.js +47 -0
  588. package/dist/stubs/prismaClient.js.map +1 -0
  589. package/dist/types/rateLimitTypes.d.ts +70 -0
  590. package/dist/types/rateLimitTypes.d.ts.map +1 -0
  591. package/dist/types/rateLimitTypes.js +55 -0
  592. package/dist/types/rateLimitTypes.js.map +1 -0
  593. package/dist/utils/errors.d.ts +80 -0
  594. package/dist/utils/errors.d.ts.map +1 -0
  595. package/dist/utils/errors.js +201 -0
  596. package/dist/utils/errors.js.map +1 -0
  597. package/dist/utils/uuid.d.ts +11 -0
  598. package/dist/utils/uuid.d.ts.map +1 -0
  599. package/dist/utils/uuid.js +64 -0
  600. package/dist/utils/uuid.js.map +1 -0
  601. package/package.json +84 -0
@@ -0,0 +1,648 @@
1
+ // File: backend/agentos/core/orchestration/AgentOrchestrator.ts
2
+ /**
3
+ * @fileoverview Implements the `AgentOSOrchestrator` class, the central nervous system for AgentOS interactions.
4
+ * This module is responsible for the intricate coordination between the public-facing `AgentOS` API
5
+ * and the cognitive core, the `GMI` (Generalized Mind Instance). It meticulously manages the
6
+ * entire lifecycle of an interaction turn.
7
+ *
8
+ * Key Responsibilities:
9
+ * - **GMI Instance Management**: Selection/creation of GMI instances via `GMIManager`.
10
+ * - **Contextualization**: Preparation and loading of `ConversationContext`.
11
+ * - **Input Processing**: Transformation of `AgentOSInput` into `GMITurnInput`.
12
+ * - **Streaming Output Handling**: Iteration over `GMIOutputChunk` streams from the GMI.
13
+ * - **Tool Use Coordination**:
14
+ * - Relaying `ToolCallRequest`s to the client (via `StreamingManager`).
15
+ * - Receiving tool execution results.
16
+ * - Forwarding tool results back to the GMI via `handleToolResult`.
17
+ * - Processing the GMI's response (`GMIOutput`) post-tool execution.
18
+ * - **Response Streaming**: Conversion of GMI outputs into `AgentOSResponse` chunks and their
19
+ * distribution through the `StreamingManager`.
20
+ * - **State Management**: Tracking active interaction streams and their associated contexts.
21
+ * - **Error Handling**: Robust error management for orchestration failures.
22
+ *
23
+ * The orchestrator embodies asynchronous processing and streaming, ensuring a responsive user experience.
24
+ * It relies on dependency injection for its core components, promoting modularity and testability.
25
+ *
26
+ * @module backend/agentos/core/orchestration/AgentOSOrchestrator
27
+ */
28
+ import { AgentOSResponseChunkType, } from '../../api/types/AgentOSResponse.js';
29
+ import { GMIInteractionType, GMIOutputChunkType, } from '../../cognitive_substrate/IGMI.js';
30
+ // import { ITool } from '../tools/ITool.js'; // ITool not directly used here, but good to keep if planned
31
+ import { MessageRole } from '../conversation/ConversationMessage.js';
32
+ import { uuidv4 } from '../../utils/uuid.js';
33
+ import { GMIError, GMIErrorCode, createGMIErrorFromError } from '../../utils/errors.js';
34
+ import { normalizeUsage, snapshotPersonaDetails } from './helpers.js';
35
+ /**
36
+ * @class AgentOSOrchestrator
37
+ * @classdesc
38
+ * The `AgentOSOrchestrator` serves as the master conductor of interactions within the AgentOS platform.
39
+ * It is the critical intermediary layer that bridges high-level API requests (`AgentOSInput`)
40
+ * with the sophisticated cognitive processing of Generalized Mind Instances (`IGMI`).
41
+ * Its primary function is to manage the entire lifecycle of a user's interaction turn, a potentially
42
+ * complex, multi-step process.
43
+ */
44
+ export class AgentOSOrchestrator {
45
+ /**
46
+ * Constructs an AgentOSOrchestrator instance.
47
+ * The orchestrator is not operational until `initialize()` is successfully called.
48
+ */
49
+ constructor() {
50
+ this.initialized = false;
51
+ this.activeStreamContexts = new Map();
52
+ }
53
+ /**
54
+ * Initializes the AgentOSOrchestrator with its configuration and essential service dependencies.
55
+ * This method must be called and resolve successfully before the orchestrator can process any requests.
56
+ * It sets up the orchestrator's internal state and validates its dependencies.
57
+ *
58
+ * @public
59
+ * @async
60
+ * @param {AgentOSOrchestratorConfig} config - Configuration settings for the orchestrator.
61
+ * @param {AgentOSOrchestratorDependencies} dependencies - An object containing instances of required services.
62
+ * @returns {Promise<void>} A Promise that resolves when initialization is complete.
63
+ * @throws {GMIError} If critical dependencies are missing (GMIErrorCode.CONFIGURATION_ERROR).
64
+ */
65
+ async initialize(config, dependencies) {
66
+ if (this.initialized) {
67
+ console.warn('AgentOSOrchestrator: Instance is already initialized. Skipping re-initialization.');
68
+ return;
69
+ }
70
+ if (!dependencies.gmiManager || !dependencies.toolOrchestrator || !dependencies.conversationManager || !dependencies.streamingManager) {
71
+ const missingDeps = [
72
+ !dependencies.gmiManager && "gmiManager",
73
+ !dependencies.toolOrchestrator && "toolOrchestrator",
74
+ !dependencies.conversationManager && "conversationManager",
75
+ !dependencies.streamingManager && "streamingManager",
76
+ ].filter(Boolean).join(', ');
77
+ throw new GMIError(`AgentOSOrchestrator: Initialization failed due to missing essential dependencies: ${missingDeps}.`, GMIErrorCode.CONFIGURATION_ERROR, { missingDependencies: missingDeps });
78
+ }
79
+ this.config = Object.freeze({
80
+ maxToolCallIterations: config.maxToolCallIterations ?? 5,
81
+ defaultAgentTurnTimeoutMs: config.defaultAgentTurnTimeoutMs ?? 120000,
82
+ enableConversationalPersistence: config.enableConversationalPersistence ?? true,
83
+ logToolCalls: config.logToolCalls ?? false,
84
+ });
85
+ this.dependencies = Object.freeze(dependencies);
86
+ this.initialized = true;
87
+ console.log(`AgentOSOrchestrator initialized successfully. Configuration: ${JSON.stringify(this.config)}`);
88
+ }
89
+ /**
90
+ * Ensures that the orchestrator has been initialized before performing operations.
91
+ * @private
92
+ * @throws {GMIError} If the orchestrator is not initialized (GMIErrorCode.NOT_INITIALIZED).
93
+ */
94
+ ensureInitialized() {
95
+ if (!this.initialized) {
96
+ throw new GMIError('AgentOSOrchestrator is not initialized. Please call the initialize() method first.', GMIErrorCode.NOT_INITIALIZED, { component: 'AgentOSOrchestrator' });
97
+ }
98
+ }
99
+ /**
100
+ * Pushes a response chunk to the client via the StreamingManager.
101
+ * This is a centralized helper for all chunk types.
102
+ * @private
103
+ * @param {StreamId} agentOSStreamId - The unique ID of the AgentOS stream.
104
+ * @param {AgentOSResponseChunkType} type - The type of chunk being pushed.
105
+ * @param {string} gmiInstanceId - The ID of the GMI instance generating this chunk.
106
+ * @param {string} personaId - The ID of the persona active during this chunk's generation.
107
+ * @param {boolean} isFinal - Whether this chunk marks the end of the response for this stream.
108
+ * @param {any} data - The specific payload data for the chunk, varying by `type`.
109
+ * @returns {Promise<void>}
110
+ */
111
+ async pushChunkToStream(agentOSStreamId, type, gmiInstanceId, personaId, // This is now consistently a string
112
+ isFinal, data) {
113
+ const baseChunk = { type, streamId: agentOSStreamId, gmiInstanceId, personaId, isFinal, timestamp: new Date().toISOString() };
114
+ let chunk;
115
+ switch (type) {
116
+ case AgentOSResponseChunkType.TEXT_DELTA:
117
+ chunk = { ...baseChunk, textDelta: data.textDelta };
118
+ break;
119
+ case AgentOSResponseChunkType.SYSTEM_PROGRESS:
120
+ chunk = { ...baseChunk, message: data.message, progressPercentage: data.progressPercentage, statusCode: data.statusCode };
121
+ break;
122
+ case AgentOSResponseChunkType.TOOL_CALL_REQUEST:
123
+ chunk = { ...baseChunk, toolCalls: data.toolCalls, rationale: data.rationale };
124
+ break;
125
+ case AgentOSResponseChunkType.TOOL_RESULT_EMISSION:
126
+ chunk = { ...baseChunk, toolCallId: data.toolCallId, toolName: data.toolName, toolResult: data.toolResult, isSuccess: data.isSuccess, errorMessage: data.errorMessage };
127
+ break;
128
+ case AgentOSResponseChunkType.UI_COMMAND:
129
+ chunk = { ...baseChunk, uiCommands: data.uiCommands };
130
+ break;
131
+ case AgentOSResponseChunkType.ERROR:
132
+ chunk = { ...baseChunk, code: data.code, message: data.message, details: data.details };
133
+ break;
134
+ case AgentOSResponseChunkType.FINAL_RESPONSE:
135
+ chunk = {
136
+ ...baseChunk,
137
+ finalResponseText: data.finalResponseText,
138
+ finalToolCalls: data.finalToolCalls,
139
+ finalUiCommands: data.finalUiCommands,
140
+ audioOutput: data.audioOutput,
141
+ imageOutput: data.imageOutput,
142
+ usage: normalizeUsage(data.usage),
143
+ reasoningTrace: data.reasoningTrace,
144
+ error: data.error,
145
+ updatedConversationContext: data.updatedConversationContext,
146
+ activePersonaDetails: data.activePersonaDetails
147
+ };
148
+ break;
149
+ case AgentOSResponseChunkType.METADATA_UPDATE:
150
+ chunk = { ...baseChunk, updates: data.updates };
151
+ break;
152
+ case AgentOSResponseChunkType.WORKFLOW_UPDATE:
153
+ chunk = { ...baseChunk, workflow: data.workflow };
154
+ break;
155
+ case AgentOSResponseChunkType.AGENCY_UPDATE:
156
+ chunk = { ...baseChunk, agency: data.agency };
157
+ break;
158
+ default: {
159
+ const exhaustiveCheck = type;
160
+ const errorMsg = `Internal Error: Unknown stream chunk type '${exhaustiveCheck}' encountered by orchestrator.`;
161
+ console.error(`AgentOSOrchestrator: ${errorMsg}`);
162
+ chunk = {
163
+ ...baseChunk,
164
+ type: AgentOSResponseChunkType.ERROR,
165
+ code: GMIErrorCode.INTERNAL_SERVER_ERROR.toString(),
166
+ message: errorMsg,
167
+ details: { originalData: data, originalType: type }
168
+ };
169
+ break;
170
+ }
171
+ }
172
+ try {
173
+ await this.dependencies.streamingManager.pushChunk(agentOSStreamId, chunk);
174
+ }
175
+ catch (pushError) {
176
+ console.error(`AgentOSOrchestrator: Failed to push chunk to stream ${agentOSStreamId}. Type: ${type}. Error: ${pushError.message}`, pushError);
177
+ }
178
+ }
179
+ /**
180
+ * Pushes a standardized error chunk to the client.
181
+ * @private
182
+ * @param {StreamId} agentOSStreamId - The ID of the AgentOS stream.
183
+ * @param {string} personaId - The ID of the persona associated with this error.
184
+ * @param {string} [gmiInstanceId='unknown_gmi_instance'] - The ID of the GMI instance.
185
+ * @param {GMIErrorCode | string} code - The error code.
186
+ * @param {string} message - The error message.
187
+ * @param {any} [details] - Additional error details.
188
+ * @returns {Promise<void>}
189
+ */
190
+ async pushErrorChunk(agentOSStreamId, personaId, // Ensured to be string by callers
191
+ gmiInstanceId = 'unknown_gmi_instance', code, message, details) {
192
+ await this.pushChunkToStream(agentOSStreamId, AgentOSResponseChunkType.ERROR, gmiInstanceId, personaId, true, { code: code.toString(), message, details });
193
+ }
194
+ /**
195
+ * Orchestrates a complete user interaction turn, starting from an `AgentOSInput`.
196
+ * This method initiates a new stream for the interaction via `StreamingManager`,
197
+ * then delegates the complex, potentially long-running processing to `_processTurnInternal`
198
+ * without awaiting its completion. This allows `orchestrateTurn` to return the `StreamId`
199
+ * to the caller (e.g., `AgentOS` facade) immediately, enabling clients to subscribe to the
200
+ * stream for real-time updates.
201
+ *
202
+ * @public
203
+ * @async
204
+ * @param {AgentOSInput} input - The comprehensive input for the current turn from the API layer.
205
+ * @returns {Promise<StreamId>} The unique ID of the stream established for this interaction.
206
+ * Clients should use this ID to listen for `AgentOSResponse` chunks.
207
+ * @throws {GMIError} If the `StreamingManager` fails to create a new stream (e.g., `GMIErrorCode.STREAM_ERROR`).
208
+ */
209
+ async orchestrateTurn(input) {
210
+ this.ensureInitialized();
211
+ const baseStreamId = input.sessionId ? `agentos-session-${input.sessionId}` : `agentos-turn-${uuidv4()}`;
212
+ const agentOSStreamId = await this.dependencies.streamingManager.createStream(baseStreamId);
213
+ console.log(`AgentOSOrchestrator: Orchestrating new turn. AgentOS Stream ID: ${agentOSStreamId}, User: ${input.userId}, Input Session: ${input.sessionId}`);
214
+ this._processTurnInternal(agentOSStreamId, input).catch(async (criticalError) => {
215
+ console.error(`AgentOSOrchestrator: CRITICAL UNHANDLED error from _processTurnInternal initiation for stream ${agentOSStreamId}:`, criticalError);
216
+ const streamContext = this.activeStreamContexts.get(agentOSStreamId);
217
+ const personaIdForError = input.selectedPersonaId || streamContext?.personaId || 'unknown_critical_error_persona';
218
+ const gmiInstanceIdForError = streamContext?.gmi?.getGMIId() || 'orchestrator_pre_gmi_critical_error';
219
+ try {
220
+ await this.pushErrorChunk(agentOSStreamId, personaIdForError, gmiInstanceIdForError, GMIErrorCode.INTERNAL_SERVER_ERROR, `A critical unrecoverable orchestration error occurred: ${criticalError.message}`, { errorName: criticalError.name, rawErrorString: String(criticalError), stack: criticalError.stack });
221
+ if (this.activeStreamContexts.has(agentOSStreamId)) {
222
+ // TS2554 fix: Pass only 1 or 2 arguments
223
+ await this.dependencies.streamingManager.closeStream(agentOSStreamId, "Critical orchestrator error during turn processing initiation.");
224
+ }
225
+ }
226
+ catch (cleanupError) {
227
+ console.error(`AgentOSOrchestrator: Error during critical error cleanup messaging for stream ${agentOSStreamId}:`, cleanupError);
228
+ }
229
+ this.activeStreamContexts.delete(agentOSStreamId);
230
+ });
231
+ return agentOSStreamId;
232
+ }
233
+ /**
234
+ * Constructs a `GMITurnInput` object from the API-level `AgentOSInput`.
235
+ * This method maps and transforms data to the structure expected by the `IGMI`.
236
+ *
237
+ * @private
238
+ * @param {StreamId} agentOSStreamId - The orchestrator-level stream ID, used to generate a GMI interaction ID.
239
+ * @param {AgentOSInput} agentOSInput - The input received from the AgentOS API layer.
240
+ * @param {string} activePersonaId - The definitive ID of the persona resolved for this turn. Guaranteed to be a string by caller.
241
+ * @returns {GMITurnInput} The structured input object ready for the GMI.
242
+ */
243
+ constructGMITurnInput(agentOSStreamId, agentOSInput, activePersonaId) {
244
+ const { userId, sessionId, options, textInput, visionInputs, audioInput, userFeedback, selectedPersonaId, userApiKeys } = agentOSInput;
245
+ const gmiInputMetadata = {
246
+ options: {
247
+ ...(options || {}),
248
+ preferredModelId: options?.preferredModelId,
249
+ preferredProviderId: options?.preferredProviderId,
250
+ temperature: options?.temperature,
251
+ topP: options?.topP,
252
+ maxTokens: options?.maxTokens,
253
+ toolChoice: options?.toolChoice,
254
+ responseFormat: options?.responseFormat,
255
+ },
256
+ userApiKeys,
257
+ userFeedback,
258
+ explicitPersonaSwitchId: selectedPersonaId !== activePersonaId ? selectedPersonaId : undefined,
259
+ taskHint: '',
260
+ };
261
+ let type;
262
+ let content;
263
+ if ((visionInputs && visionInputs.length > 0) || audioInput) {
264
+ type = GMIInteractionType.MULTIMODAL_CONTENT;
265
+ const multiModalPayload = {};
266
+ if (textInput !== null && textInput !== undefined)
267
+ multiModalPayload.text = textInput;
268
+ if (visionInputs)
269
+ multiModalPayload.vision = visionInputs;
270
+ if (audioInput)
271
+ multiModalPayload.audio = audioInput;
272
+ content = multiModalPayload;
273
+ if (gmiInputMetadata)
274
+ gmiInputMetadata.taskHint = textInput ? 'user_multimodal_query_with_text' : (visionInputs && visionInputs.length > 0 && audioInput) ? 'user_visual_audio_query' : (visionInputs && visionInputs.length > 0) ? 'user_visual_query' : 'user_audio_query';
275
+ }
276
+ else if (textInput !== null && textInput !== undefined && textInput.trim() !== '') {
277
+ type = GMIInteractionType.TEXT;
278
+ content = textInput;
279
+ if (gmiInputMetadata)
280
+ gmiInputMetadata.taskHint = 'user_text_query';
281
+ }
282
+ else if (userFeedback) {
283
+ type = GMIInteractionType.SYSTEM_MESSAGE;
284
+ content = { type: 'feedback_provided', payload: userFeedback };
285
+ if (gmiInputMetadata)
286
+ gmiInputMetadata.taskHint = 'user_feedback_submission';
287
+ }
288
+ else {
289
+ type = GMIInteractionType.SYSTEM_MESSAGE;
290
+ content = "System: Orchestrator initiating turn with no direct textual, visual, or audio input from user.";
291
+ if (gmiInputMetadata)
292
+ gmiInputMetadata.taskHint = 'system_initiated_turn_or_ping';
293
+ console.warn(`AgentOSOrchestrator (Stream: ${agentOSStreamId}): No primary user input. Classifying as system message.`);
294
+ }
295
+ return {
296
+ interactionId: `${agentOSStreamId}_gmi_turn_${uuidv4()}`,
297
+ userId,
298
+ sessionId: sessionId || agentOSStreamId,
299
+ type,
300
+ content,
301
+ metadata: gmiInputMetadata,
302
+ timestamp: new Date(),
303
+ };
304
+ }
305
+ /**
306
+ * Core internal turn processing logic. This method is executed asynchronously by `orchestrateTurn`.
307
+ * It manages the GMI interaction loop, including streaming chunks, handling tool call requests,
308
+ * and ensuring finalization of the stream.
309
+ *
310
+ * @private
311
+ * @async
312
+ * @param {StreamId} agentOSStreamId - The unique ID for this AgentOS-level stream.
313
+ * @param {AgentOSInput} input - The initial input for this turn.
314
+ * @returns {Promise<void>} Resolves when processing for this turn is complete or a terminal error occurs.
315
+ */
316
+ async _processTurnInternal(agentOSStreamId, input) {
317
+ let gmi;
318
+ let conversationContext;
319
+ const requestedPersonaId = input.selectedPersonaId || 'default';
320
+ let activePersonaId = requestedPersonaId;
321
+ let gmiInstanceIdForChunks = 'gmi_pending_initialization';
322
+ let activeStreamCtx;
323
+ try {
324
+ const gmiResult = await this.dependencies.gmiManager.getOrCreateGMIForSession(input.userId, input.sessionId || agentOSStreamId, requestedPersonaId, input.conversationId);
325
+ gmi = gmiResult.gmi;
326
+ conversationContext = gmiResult.conversationContext;
327
+ activePersonaId = gmi.getCurrentPrimaryPersonaId(); // Ensure this returns a string
328
+ gmiInstanceIdForChunks = gmi.getGMIId();
329
+ activeStreamCtx = {
330
+ gmi, userId: input.userId, sessionId: input.sessionId || agentOSStreamId, personaId: activePersonaId,
331
+ conversationId: conversationContext.sessionId,
332
+ conversationContext, userApiKeys: input.userApiKeys, processingOptions: input.options
333
+ };
334
+ this.activeStreamContexts.set(agentOSStreamId, activeStreamCtx);
335
+ await this.pushChunkToStream(agentOSStreamId, AgentOSResponseChunkType.SYSTEM_PROGRESS, gmiInstanceIdForChunks, activePersonaId, false, { message: `Persona ${activePersonaId} ready. GMI Instance: ${gmiInstanceIdForChunks}`, progressPercentage: 10 });
336
+ const gmiTurnInput = this.constructGMITurnInput(agentOSStreamId, input, activePersonaId);
337
+ const gmiStreamIterator = gmi.processTurnStream(gmiTurnInput);
338
+ let finalGMIOutputFromStream;
339
+ let iteratorResult = await gmiStreamIterator.next();
340
+ while (!iteratorResult.done) {
341
+ const gmiChunk = iteratorResult.value;
342
+ await this.transformAndPushGMIChunk(agentOSStreamId, activeStreamCtx, gmiChunk);
343
+ if (gmiChunk.type === GMIOutputChunkType.TOOL_CALL_REQUEST) {
344
+ console.log(`AgentOSOrchestrator (Stream: ${agentOSStreamId}): GMI requested tool(s). Pausing internal GMI processing for this turn.`);
345
+ return;
346
+ }
347
+ iteratorResult = await gmiStreamIterator.next();
348
+ }
349
+ finalGMIOutputFromStream = iteratorResult.value;
350
+ if (this.config.enableConversationalPersistence && conversationContext) {
351
+ if (finalGMIOutputFromStream?.responseText) {
352
+ const assistantTextMessage = {
353
+ role: MessageRole.ASSISTANT,
354
+ content: finalGMIOutputFromStream.responseText,
355
+ metadata: { agentPersonaId: activePersonaId },
356
+ };
357
+ conversationContext.addMessage(assistantTextMessage);
358
+ }
359
+ if (finalGMIOutputFromStream?.toolCalls) {
360
+ const assistantToolMessage = {
361
+ role: MessageRole.ASSISTANT,
362
+ content: null,
363
+ tool_calls: finalGMIOutputFromStream.toolCalls,
364
+ metadata: { agentPersonaId: activePersonaId },
365
+ };
366
+ conversationContext.addMessage(assistantToolMessage);
367
+ }
368
+ await this.dependencies.conversationManager.saveConversation(conversationContext);
369
+ }
370
+ const personaDef = gmi.getPersona();
371
+ if (!finalGMIOutputFromStream) {
372
+ console.warn(`AgentOSOrchestrator (Stream: ${agentOSStreamId}): GMI stream completed without an explicit final GMIOutput. Constructing a default final response.`);
373
+ const lastMessage = activeStreamCtx.conversationContext.getLastMessage();
374
+ finalGMIOutputFromStream = {
375
+ isFinal: true,
376
+ responseText: lastMessage?.role === MessageRole.ASSISTANT ? (lastMessage.content || "Processing concluded.") : "Processing concluded.",
377
+ };
378
+ }
379
+ await this.pushChunkToStream(agentOSStreamId, AgentOSResponseChunkType.FINAL_RESPONSE, gmiInstanceIdForChunks, activePersonaId, true, {
380
+ finalResponseText: finalGMIOutputFromStream.responseText,
381
+ finalToolCalls: finalGMIOutputFromStream.toolCalls,
382
+ finalUiCommands: finalGMIOutputFromStream.uiCommands,
383
+ audioOutput: finalGMIOutputFromStream.audioOutput,
384
+ imageOutput: finalGMIOutputFromStream.imageOutput,
385
+ usage: normalizeUsage(finalGMIOutputFromStream.usage),
386
+ reasoningTrace: finalGMIOutputFromStream.reasoningTrace,
387
+ error: finalGMIOutputFromStream.error,
388
+ updatedConversationContext: conversationContext.toJSON(),
389
+ activePersonaDetails: snapshotPersonaDetails(personaDef),
390
+ });
391
+ // TS2554 fix: Pass only 1 or 2 arguments
392
+ await this.dependencies.streamingManager.closeStream(agentOSStreamId, "Turn processing complete.");
393
+ }
394
+ catch (error) {
395
+ const gmiErr = createGMIErrorFromError(error, GMIErrorCode.GMI_PROCESSING_ERROR, { agentOSStreamId }, `Unhandled error in _processTurnInternal`);
396
+ console.error(`AgentOSOrchestrator: Error during _processTurnInternal for stream ${agentOSStreamId}:`, gmiErr);
397
+ const personaIdForCatch = activePersonaId || input.selectedPersonaId || 'unknown_error_persona'; // activePersonaId should be set if try block started
398
+ await this.pushErrorChunk(agentOSStreamId, personaIdForCatch, gmiInstanceIdForChunks, gmiErr.code, gmiErr.message, gmiErr.details);
399
+ if (this.activeStreamContexts.has(agentOSStreamId)) {
400
+ // TS2554 fix: Pass only 1 or 2 arguments
401
+ await this.dependencies.streamingManager.closeStream(agentOSStreamId, `Error: ${gmiErr.message}`);
402
+ }
403
+ }
404
+ finally {
405
+ this.activeStreamContexts.delete(agentOSStreamId);
406
+ console.log(`AgentOSOrchestrator: Cleaned up context for AgentOS Stream ${agentOSStreamId}.`);
407
+ }
408
+ }
409
+ /**
410
+ * Handles the result of an externally executed tool, feeding it back into the active GMI instance.
411
+ * It then processes the GMI's subsequent output (`GMIOutput`), streaming further responses or
412
+ * new tool requests as needed.
413
+ *
414
+ * @public
415
+ * @async
416
+ * @param {StreamId} agentOSStreamId - The orchestrator-level stream ID for this interaction flow.
417
+ * @param {string} toolCallId - The ID of the specific tool call (from `ToolCallRequest`) whose result is being provided.
418
+ * @param {string} toolName - The name of the tool that was executed.
419
+ * @param {any} toolOutput - The output data returned by the tool execution.
420
+ * @param {boolean} isSuccess - A flag indicating whether the tool execution was successful.
421
+ * @param {string} [errorMessage] - An optional error message if `isSuccess` is false.
422
+ * @returns {Promise<void>} Resolves when the tool result has been processed and subsequent GMI output streamed.
423
+ * @throws {GMIError} If the `agentOSStreamId` is not found or if a critical error occurs during GMI's handling of the tool result.
424
+ */
425
+ async orchestrateToolResult(agentOSStreamId, toolCallId, toolName, toolOutput, isSuccess, errorMessage) {
426
+ this.ensureInitialized();
427
+ const streamContext = this.activeStreamContexts.get(agentOSStreamId);
428
+ if (!streamContext) {
429
+ const errMsg = `AgentOSOrchestrator: Cannot orchestrate tool result. No active stream context found for streamId: ${agentOSStreamId}. Tool: ${toolName}, CallID: ${toolCallId}`;
430
+ console.error(errMsg);
431
+ throw new GMIError(errMsg, GMIErrorCode.RESOURCE_NOT_FOUND, { agentOSStreamId, toolCallId, toolName });
432
+ }
433
+ const { gmi, userId, personaId, userApiKeys } = streamContext; // Removed conversationContext as it's not directly used here
434
+ const gmiInstanceIdForChunks = gmi.getGMIId();
435
+ const toolResultPayload = isSuccess
436
+ ? { type: 'success', result: toolOutput }
437
+ : { type: 'error', error: { code: 'EXTERNAL_TOOL_ERROR', message: errorMessage || `External tool '${toolName}' execution failed.` } };
438
+ console.log(`AgentOSOrchestrator (Stream: ${agentOSStreamId}): Feeding tool result for GMI ${gmiInstanceIdForChunks}, Tool Call ID ${toolCallId} (${toolName}) back to GMI.`);
439
+ try {
440
+ await this.pushChunkToStream(agentOSStreamId, AgentOSResponseChunkType.TOOL_RESULT_EMISSION, gmiInstanceIdForChunks, personaId, false, { toolCallId, toolName, toolResult: toolOutput, isSuccess, errorMessage });
441
+ const gmiOutputAfterTool = await gmi.handleToolResult(toolCallId, toolName, toolResultPayload, userId, userApiKeys || {});
442
+ await this.processGMIOutput(agentOSStreamId, streamContext, gmiOutputAfterTool, true);
443
+ if (gmiOutputAfterTool.toolCalls && gmiOutputAfterTool.toolCalls.length > 0 && !gmiOutputAfterTool.isFinal) {
444
+ await this.pushChunkToStream(agentOSStreamId, AgentOSResponseChunkType.TOOL_CALL_REQUEST, gmiInstanceIdForChunks, personaId, false, { toolCalls: gmiOutputAfterTool.toolCalls, rationale: gmiOutputAfterTool.responseText || "Agent requires further tool execution based on previous tool's result." });
445
+ }
446
+ else if (gmiOutputAfterTool.isFinal) {
447
+ console.log(`AgentOSOrchestrator (Stream: ${agentOSStreamId}): GMI interaction concluded as final after tool result processing.`);
448
+ }
449
+ }
450
+ catch (error) {
451
+ const gmiErr = createGMIErrorFromError(error, GMIErrorCode.TOOL_ERROR, { agentOSStreamId, toolCallId, toolName }, `Error processing tool result for '${toolName}'`);
452
+ console.error(`AgentOSOrchestrator (Stream: ${agentOSStreamId}): Critical error during orchestrateToolResult:`, gmiErr);
453
+ await this.pushErrorChunk(agentOSStreamId, personaId, gmiInstanceIdForChunks, gmiErr.code, gmiErr.message, gmiErr.details);
454
+ if (this.activeStreamContexts.has(agentOSStreamId)) {
455
+ // TS2554 fix: Pass only 1 or 2 arguments
456
+ await this.dependencies.streamingManager.closeStream(agentOSStreamId, `Critical error during tool result processing: ${gmiErr.message}`);
457
+ this.activeStreamContexts.delete(agentOSStreamId);
458
+ }
459
+ }
460
+ }
461
+ /**
462
+ * Processes a direct `GMIOutput` object (typically the result of `gmi.handleToolResult` or the
463
+ * final return value of `gmi.processTurnStream`). It transforms and pushes the relevant
464
+ * parts of this `GMIOutput` as `AgentOSResponse` chunks to the client stream.
465
+ *
466
+ * @private
467
+ * @async
468
+ * @param {StreamId} agentOSStreamId - The ID of the AgentOS stream.
469
+ * @param {ActiveStreamContext} streamContext - The context for the current active stream.
470
+ * @param {GMIOutput} gmiOutput - The GMI output object to process.
471
+ * @param {boolean} isContinuationAfterTool - Indicates if this output is a direct result of processing a tool.
472
+ * @returns {Promise<void>}
473
+ */
474
+ async processGMIOutput(agentOSStreamId, streamContext, gmiOutput, _isContinuationAfterTool) {
475
+ const { gmi, personaId, conversationContext } = streamContext;
476
+ const gmiInstanceIdForChunks = gmi.getGMIId();
477
+ if (gmiOutput.responseText) {
478
+ await this.pushChunkToStream(agentOSStreamId, AgentOSResponseChunkType.TEXT_DELTA, gmiInstanceIdForChunks, personaId, false, { textDelta: gmiOutput.responseText });
479
+ }
480
+ if (gmiOutput.uiCommands && gmiOutput.uiCommands.length > 0) {
481
+ await this.pushChunkToStream(agentOSStreamId, AgentOSResponseChunkType.UI_COMMAND, gmiInstanceIdForChunks, personaId, false, { uiCommands: gmiOutput.uiCommands });
482
+ }
483
+ if (gmiOutput.error) {
484
+ await this.pushErrorChunk(agentOSStreamId, personaId, gmiInstanceIdForChunks, gmiOutput.error.code, gmiOutput.error.message, gmiOutput.error.details);
485
+ if (this.activeStreamContexts.has(agentOSStreamId)) {
486
+ // TS2554 fix: Pass only 1 or 2 arguments
487
+ await this.dependencies.streamingManager.closeStream(agentOSStreamId, `GMI reported an error: ${gmiOutput.error.message}`);
488
+ this.activeStreamContexts.delete(agentOSStreamId);
489
+ }
490
+ return;
491
+ }
492
+ if (gmiOutput.isFinal && (!gmiOutput.toolCalls || gmiOutput.toolCalls.length === 0)) {
493
+ if (this.config.enableConversationalPersistence && conversationContext) {
494
+ try {
495
+ if (gmiOutput.responseText) {
496
+ const assistantFinalMessage = {
497
+ role: MessageRole.ASSISTANT,
498
+ content: gmiOutput.responseText,
499
+ metadata: { agentPersonaId: personaId },
500
+ };
501
+ conversationContext.addMessage(assistantFinalMessage);
502
+ }
503
+ await this.dependencies.conversationManager.saveConversation(conversationContext);
504
+ console.log(`AgentOSOrchestrator (Stream: ${agentOSStreamId}): Conversation context ${conversationContext.sessionId} saved.`);
505
+ }
506
+ catch (saveError) {
507
+ console.error(`AgentOSOrchestrator (Stream: ${agentOSStreamId}): Failed to save conversation context ${conversationContext.sessionId}: ${saveError.message}`, saveError);
508
+ }
509
+ }
510
+ const personaDef = gmi.getPersona();
511
+ await this.pushChunkToStream(agentOSStreamId, AgentOSResponseChunkType.FINAL_RESPONSE, gmiInstanceIdForChunks, personaId, true, {
512
+ finalResponseText: gmiOutput.responseText,
513
+ finalToolCalls: gmiOutput.toolCalls,
514
+ finalUiCommands: gmiOutput.uiCommands,
515
+ audioOutput: gmiOutput.audioOutput,
516
+ imageOutput: gmiOutput.imageOutput,
517
+ usage: normalizeUsage(gmiOutput.usage),
518
+ reasoningTrace: gmiOutput.reasoningTrace,
519
+ error: gmiOutput.error,
520
+ updatedConversationContext: conversationContext.toJSON(),
521
+ activePersonaDetails: snapshotPersonaDetails(personaDef),
522
+ });
523
+ if (this.activeStreamContexts.has(agentOSStreamId)) {
524
+ // TS2554 fix: Pass only 1 or 2 arguments
525
+ await this.dependencies.streamingManager.closeStream(agentOSStreamId, "Interaction processing complete, final response sent.");
526
+ this.activeStreamContexts.delete(agentOSStreamId);
527
+ console.log(`AgentOSOrchestrator (Stream: ${agentOSStreamId}): Finalized and cleaned up stream context.`);
528
+ }
529
+ }
530
+ }
531
+ /**
532
+ * Transforms a single `GMIOutputChunk` from the GMI's stream into one or more
533
+ * `AgentOSResponse` chunks and pushes them to the client via the `StreamingManager`.
534
+ *
535
+ * @private
536
+ * @async
537
+ * @param {StreamId} agentOSStreamId - The ID of the AgentOS stream.
538
+ * @param {ActiveStreamContext} streamContext - The context for the current active stream.
539
+ * @param {GMIOutputChunk} gmiChunk - The chunk of output received from the GMI.
540
+ * @returns {Promise<void>}
541
+ */
542
+ async transformAndPushGMIChunk(agentOSStreamId, streamContext, gmiChunk) {
543
+ const { gmi, personaId } = streamContext;
544
+ const gmiInstanceIdForChunks = gmi.getGMIId();
545
+ const isChunkFinal = gmiChunk.isFinal ?? false;
546
+ switch (gmiChunk.type) {
547
+ case GMIOutputChunkType.TEXT_DELTA:
548
+ if (gmiChunk.content && typeof gmiChunk.content === 'string') {
549
+ await this.pushChunkToStream(agentOSStreamId, AgentOSResponseChunkType.TEXT_DELTA, gmiInstanceIdForChunks, personaId, isChunkFinal, { textDelta: gmiChunk.content });
550
+ }
551
+ break;
552
+ case GMIOutputChunkType.SYSTEM_MESSAGE: {
553
+ if (gmiChunk.content && typeof gmiChunk.content === 'object' && gmiChunk.content !== null) {
554
+ const progressData = gmiChunk.content;
555
+ await this.pushChunkToStream(agentOSStreamId, AgentOSResponseChunkType.SYSTEM_PROGRESS, gmiInstanceIdForChunks, personaId, isChunkFinal, progressData);
556
+ }
557
+ break;
558
+ }
559
+ case GMIOutputChunkType.TOOL_CALL_REQUEST: {
560
+ if (gmiChunk.content && Array.isArray(gmiChunk.content) && gmiChunk.content.length > 0) {
561
+ const toolCalls = gmiChunk.content;
562
+ const rationale = gmiChunk.metadata?.rationale || "Agent is considering using tools.";
563
+ await this.pushChunkToStream(agentOSStreamId, AgentOSResponseChunkType.TOOL_CALL_REQUEST, gmiInstanceIdForChunks, personaId, false, // Tool call requests are typically not final for the turn
564
+ { toolCalls, rationale });
565
+ }
566
+ break;
567
+ }
568
+ case GMIOutputChunkType.UI_COMMAND: {
569
+ if (gmiChunk.content && Array.isArray(gmiChunk.content)) {
570
+ await this.pushChunkToStream(agentOSStreamId, AgentOSResponseChunkType.UI_COMMAND, gmiInstanceIdForChunks, personaId, isChunkFinal, { uiCommands: gmiChunk.content });
571
+ }
572
+ break;
573
+ }
574
+ case GMIOutputChunkType.ERROR: {
575
+ const errorContent = gmiChunk.content;
576
+ const errorDetailsObj = gmiChunk.errorDetails || (typeof errorContent === 'object' && errorContent !== null ? errorContent : { messageFromContent: String(errorContent) });
577
+ await this.pushErrorChunk(agentOSStreamId, personaId, gmiInstanceIdForChunks, errorDetailsObj?.code || GMIErrorCode.GMI_PROCESSING_ERROR, errorDetailsObj?.message || String(errorContent) || 'An unspecified GMI error occurred.', errorDetailsObj);
578
+ if (isChunkFinal && this.activeStreamContexts.has(agentOSStreamId)) {
579
+ // TS2554 fix: Pass only 1 or 2 arguments
580
+ await this.dependencies.streamingManager.closeStream(agentOSStreamId, `GMI stream reported a final error: ${errorDetailsObj?.message || String(errorContent)}`);
581
+ this.activeStreamContexts.delete(agentOSStreamId);
582
+ }
583
+ break;
584
+ }
585
+ case GMIOutputChunkType.FINAL_RESPONSE_MARKER:
586
+ console.log(`AgentOSOrchestrator (Stream: ${agentOSStreamId}): Received FINAL_RESPONSE_MARKER from GMI. isFinal on chunk: ${isChunkFinal}.`);
587
+ break;
588
+ case GMIOutputChunkType.USAGE_UPDATE:
589
+ if (this.config.logToolCalls) {
590
+ console.log(`AgentOSOrchestrator (Stream: ${agentOSStreamId}): Received USAGE_UPDATE from GMI:`, gmiChunk.content);
591
+ }
592
+ await this.pushChunkToStream(agentOSStreamId, AgentOSResponseChunkType.METADATA_UPDATE, gmiInstanceIdForChunks, personaId, isChunkFinal, { updates: { usage: gmiChunk.content } });
593
+ break;
594
+ case GMIOutputChunkType.REASONING_STATE_UPDATE:
595
+ if (this.config.logToolCalls) {
596
+ console.log(`AgentOSOrchestrator (Stream: ${agentOSStreamId}): GMI Reasoning State Update:`, gmiChunk.content);
597
+ }
598
+ await this.pushChunkToStream(agentOSStreamId, AgentOSResponseChunkType.METADATA_UPDATE, gmiInstanceIdForChunks, personaId, isChunkFinal, { updates: { reasoningState: gmiChunk.content } });
599
+ break;
600
+ case GMIOutputChunkType.LATENCY_REPORT:
601
+ if (this.config.logToolCalls) {
602
+ console.log(`AgentOSOrchestrator (Stream: ${agentOSStreamId}): GMI Latency Report:`, gmiChunk.content);
603
+ }
604
+ await this.pushChunkToStream(agentOSStreamId, AgentOSResponseChunkType.METADATA_UPDATE, gmiInstanceIdForChunks, personaId, isChunkFinal, { updates: { latencyReport: gmiChunk.content } });
605
+ break;
606
+ default: {
607
+ const exhaustiveCheck = gmiChunk.type;
608
+ console.warn(`AgentOSOrchestrator (Stream: ${agentOSStreamId}): Encountered an unhandled GMIOutputChunkType: '${exhaustiveCheck}'. Chunk content:`, gmiChunk.content);
609
+ break;
610
+ }
611
+ }
612
+ }
613
+ /**
614
+ * Gracefully shuts down the AgentOSOrchestrator.
615
+ * This involves notifying and closing any active streams managed by the associated `StreamingManager`
616
+ * and clearing internal state. Dependencies like `GMIManager` are assumed to be shut down
617
+ * by the main `AgentOS` service.
618
+ *
619
+ * @public
620
+ * @async
621
+ * @returns {Promise<void>} A promise that resolves when the shutdown process is complete.
622
+ */
623
+ async shutdown() {
624
+ if (!this.initialized) {
625
+ console.warn("AgentOSOrchestrator: Shutdown called but orchestrator was not initialized or already shut down.");
626
+ return;
627
+ }
628
+ console.log(`AgentOSOrchestrator: Initiating shutdown. Closing ${this.activeStreamContexts.size} active stream contexts...`);
629
+ const streamClosePromises = [];
630
+ for (const streamId of this.activeStreamContexts.keys()) {
631
+ console.log(`AgentOSOrchestrator: Requesting closure of stream ${streamId} due to orchestrator shutdown.`);
632
+ streamClosePromises.push(
633
+ // TS2554 fix: Pass only 1 or 2 arguments
634
+ this.dependencies.streamingManager.closeStream(streamId, "AgentOS Orchestrator is shutting down.")
635
+ .catch((e) => console.error(`AgentOSOrchestrator: Error closing stream ${streamId} during shutdown: ${e.message}`)));
636
+ }
637
+ try {
638
+ await Promise.allSettled(streamClosePromises);
639
+ }
640
+ catch (e) {
641
+ console.error("AgentOSOrchestrator: Errors occurred while closing active streams during shutdown:", e);
642
+ }
643
+ this.activeStreamContexts.clear();
644
+ this.initialized = false;
645
+ console.log("AgentOSOrchestrator: Shutdown complete. All active stream contexts cleared.");
646
+ }
647
+ }
648
+ //# sourceMappingURL=AgentOrchestrator.js.map