@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,679 @@
1
+ // File: backend/agentos/api/AgentOSOrchestrator.ts
2
+ /**
3
+ * @fileoverview Implements the `AgentOSOrchestrator`, which acts as the central
4
+ * coordinator between the public-facing `AgentOS` API and the internal `GMI`
5
+ * instances. It manages the full lifecycle of an interaction turn, including
6
+ * GMI selection, input preparation, handling GMI's streaming output, and
7
+ * coordinating tool execution and result feedback.
8
+ * @module backend/agentos/api/AgentOSOrchestrator
9
+ */
10
+ import { AgentOSResponseChunkType, } from './types/AgentOSResponse.js';
11
+ import { GMIInteractionType, // Added for GMITurnInput
12
+ GMIOutputChunkType, // Added for comparisons
13
+ } from '../cognitive_substrate/IGMI.js';
14
+ import { uuidv4 } from '../utils/uuid.js';
15
+ import { GMIError, GMIErrorCode } from '../utils/errors.js';
16
+ import { normalizeUsage, snapshotPersonaDetails } from '../core/orchestration/helpers.js';
17
+ /**
18
+ * @class AgentOSOrchestrator
19
+ * @description
20
+ * The `AgentOSOrchestrator` is responsible for unifying the request handling
21
+ * pipeline for AgentOS. It bridges the high-level `AgentOSInput` from the
22
+ * public API to the internal `GMI` processing logic. It ensures that user
23
+ * requests are routed to the correct GMI, manages the GMI's turn lifecycle,
24
+ * and handles the complex dance of tool calls and streaming responses.
25
+ */
26
+ export class AgentOSOrchestrator {
27
+ constructor() {
28
+ this.initialized = false;
29
+ /**
30
+ * A map to hold ongoing stream contexts.
31
+ * Key: streamId (generated by orchestrator for this interaction flow).
32
+ * Value: ActiveStreamContext.
33
+ * @private
34
+ */
35
+ this.activeStreamContexts = new Map();
36
+ }
37
+ /**
38
+ * Initializes the AgentOSOrchestrator with its configuration and dependencies.
39
+ * This method must be called successfully before orchestrating any turns.
40
+ *
41
+ * @public
42
+ * @async
43
+ * @param {AgentOSOrchestratorConfig} config - Configuration settings for the orchestrator.
44
+ * @param {AgentOSOrchestratorDependencies} dependencies - Required services.
45
+ * @returns {Promise<void>} A Promise that resolves when initialization is complete.
46
+ * @throws {GMIError} If any critical dependency is missing or config is invalid.
47
+ */
48
+ async initialize(config, dependencies) {
49
+ if (this.initialized) {
50
+ console.warn('AgentOSOrchestrator already initialized. Skipping re-initialization.');
51
+ return;
52
+ }
53
+ if (!dependencies.gmiManager || !dependencies.toolOrchestrator || !dependencies.conversationManager || !dependencies.streamingManager) {
54
+ throw new GMIError('AgentOSOrchestrator: Missing essential dependencies (gmiManager, toolOrchestrator, conversationManager, streamingManager).', GMIErrorCode.CONFIGURATION_ERROR);
55
+ }
56
+ this.config = {
57
+ maxToolCallIterations: config.maxToolCallIterations ?? 5,
58
+ defaultAgentTurnTimeoutMs: config.defaultAgentTurnTimeoutMs ?? 120000,
59
+ enableConversationalPersistence: config.enableConversationalPersistence ?? true,
60
+ };
61
+ this.dependencies = dependencies;
62
+ this.initialized = true;
63
+ console.log('AgentOSOrchestrator initialized.');
64
+ }
65
+ /**
66
+ * Ensures the orchestrator is initialized.
67
+ * @private
68
+ * @throws {GMIError} If not initialized.
69
+ */
70
+ ensureInitialized() {
71
+ if (!this.initialized) {
72
+ throw new GMIError('AgentOSOrchestrator is not initialized. Call initialize() first.', GMIErrorCode.NOT_INITIALIZED);
73
+ }
74
+ }
75
+ /**
76
+ * Helper method to create and push response chunks via StreamingManager.
77
+ * @private
78
+ */
79
+ async pushChunkToStream(streamId, type, gmiInstanceId, personaId, isFinal, data) {
80
+ const baseChunk = {
81
+ type,
82
+ streamId,
83
+ gmiInstanceId,
84
+ personaId,
85
+ isFinal,
86
+ timestamp: new Date().toISOString(),
87
+ };
88
+ if (data && typeof data === 'object' && 'metadata' in data && data.metadata) {
89
+ baseChunk.metadata = data.metadata;
90
+ }
91
+ const ctx = this.activeStreamContexts.get(streamId);
92
+ if (ctx?.languageNegotiation) {
93
+ baseChunk.metadata = baseChunk.metadata || {};
94
+ if (!baseChunk.metadata.language)
95
+ baseChunk.metadata.language = ctx.languageNegotiation;
96
+ }
97
+ let chunk;
98
+ switch (type) {
99
+ case AgentOSResponseChunkType.TEXT_DELTA:
100
+ chunk = { ...baseChunk, textDelta: data.textDelta };
101
+ break;
102
+ case AgentOSResponseChunkType.SYSTEM_PROGRESS:
103
+ chunk = {
104
+ ...baseChunk,
105
+ message: data.message,
106
+ progressPercentage: data.progressPercentage,
107
+ statusCode: data.statusCode,
108
+ };
109
+ break;
110
+ case AgentOSResponseChunkType.TOOL_CALL_REQUEST:
111
+ chunk = {
112
+ ...baseChunk,
113
+ toolCalls: data.toolCalls,
114
+ rationale: data.rationale,
115
+ };
116
+ break;
117
+ case AgentOSResponseChunkType.TOOL_RESULT_EMISSION:
118
+ chunk = {
119
+ ...baseChunk,
120
+ toolCallId: data.toolCallId,
121
+ toolName: data.toolName,
122
+ toolResult: data.toolResult,
123
+ isSuccess: data.isSuccess,
124
+ errorMessage: data.errorMessage,
125
+ };
126
+ break;
127
+ case AgentOSResponseChunkType.UI_COMMAND:
128
+ chunk = { ...baseChunk, uiCommands: data.uiCommands };
129
+ break;
130
+ case AgentOSResponseChunkType.ERROR:
131
+ chunk = {
132
+ ...baseChunk,
133
+ code: data.code,
134
+ message: data.message,
135
+ details: data.details,
136
+ };
137
+ break;
138
+ case AgentOSResponseChunkType.FINAL_RESPONSE:
139
+ chunk = {
140
+ ...baseChunk,
141
+ finalResponseText: data.finalResponseText,
142
+ finalToolCalls: data.finalToolCalls,
143
+ finalUiCommands: data.finalUiCommands,
144
+ audioOutput: data.audioOutput,
145
+ imageOutput: data.imageOutput,
146
+ usage: normalizeUsage(data.usage),
147
+ reasoningTrace: data.reasoningTrace,
148
+ error: data.error,
149
+ updatedConversationContext: data.updatedConversationContext,
150
+ activePersonaDetails: data.activePersonaDetails,
151
+ };
152
+ break;
153
+ case AgentOSResponseChunkType.WORKFLOW_UPDATE:
154
+ chunk = {
155
+ ...baseChunk,
156
+ workflow: data.workflow,
157
+ };
158
+ break;
159
+ default:
160
+ console.error(`AgentOSOrchestrator: Unknown chunk type encountered in pushChunkToStream: ${type}`);
161
+ chunk = {
162
+ ...baseChunk,
163
+ type: AgentOSResponseChunkType.ERROR,
164
+ code: GMIErrorCode.INTERNAL_SERVER_ERROR,
165
+ message: `Unknown chunk type: ${type}`,
166
+ details: data,
167
+ };
168
+ }
169
+ try {
170
+ await this.dependencies.streamingManager.pushChunk(streamId, chunk);
171
+ }
172
+ catch (pushError) {
173
+ // Gracefully handle attempts to push after a stream is closed or missing
174
+ console.error(`AgentOSOrchestrator: Failed to push chunk to stream ${streamId}. Type: ${type}. Error: ${pushError?.message}`, pushError);
175
+ }
176
+ }
177
+ async broadcastWorkflowUpdate(update) {
178
+ this.ensureInitialized();
179
+ const targets = [];
180
+ for (const [streamId, context] of this.activeStreamContexts.entries()) {
181
+ if (update.workflow.conversationId &&
182
+ context.conversationId !== update.workflow.conversationId) {
183
+ continue;
184
+ }
185
+ targets.push({ streamId, context });
186
+ }
187
+ if (targets.length === 0) {
188
+ console.debug('AgentOSOrchestrator: No active streams for workflow update', {
189
+ workflowId: update.workflow.workflowId,
190
+ conversationId: update.workflow.conversationId,
191
+ });
192
+ return;
193
+ }
194
+ await Promise.allSettled(targets.map(async ({ streamId, context }) => {
195
+ const gmiId = context.gmi.getGMIId();
196
+ const metadata = {
197
+ workflowId: update.workflow.workflowId,
198
+ definitionId: update.workflow.definitionId,
199
+ conversationId: update.workflow.conversationId,
200
+ status: update.workflow.status,
201
+ };
202
+ await this.pushChunkToStream(streamId, AgentOSResponseChunkType.WORKFLOW_UPDATE, gmiId, context.personaId, false, {
203
+ workflow: update,
204
+ metadata,
205
+ });
206
+ }));
207
+ }
208
+ /**
209
+ * Helper method to create and push error chunks.
210
+ * @private
211
+ */
212
+ async pushErrorChunk(streamId, personaId, gmiInstanceId = 'unknown_gmi_instance', code, message, details) {
213
+ await this.pushChunkToStream(streamId, AgentOSResponseChunkType.ERROR, gmiInstanceId, personaId, true, // Errors are usually final for the current operation
214
+ { code: code.toString(), message, details });
215
+ }
216
+ /**
217
+ * Orchestrates a full logical turn for a user request.
218
+ * This involves managing GMI interaction, tool calls, and streaming responses.
219
+ * Instead of directly yielding, it uses the StreamingManager to push chunks.
220
+ *
221
+ * @public
222
+ * @async
223
+ * @param {AgentOSInput} input - The comprehensive input for the current turn.
224
+ * @returns {Promise<StreamId>} The ID of the stream to which responses will be pushed.
225
+ * @throws {GMIError} If critical initialization or setup fails.
226
+ */
227
+ async orchestrateTurn(input) {
228
+ this.ensureInitialized();
229
+ const agentOSStreamId = await this.dependencies.streamingManager.createStream();
230
+ console.log(`AgentOSOrchestrator: Starting turn for AgentOS Stream ${agentOSStreamId}, User ${input.userId}, Session ${input.sessionId}`);
231
+ // Execute the turn processing asynchronously without awaiting it here,
232
+ // so this method can return the streamId quickly.
233
+ this._processTurnInternal(agentOSStreamId, input).catch(async (criticalError) => {
234
+ console.error(`AgentOSOrchestrator: Critical unhandled error in _processTurnInternal for stream ${agentOSStreamId}:`, criticalError);
235
+ try {
236
+ await this.pushErrorChunk(agentOSStreamId, input.selectedPersonaId || 'unknown_persona', 'orchestrator_critical', GMIErrorCode.INTERNAL_SERVER_ERROR, `A critical orchestration error occurred: ${criticalError.message}`, { name: criticalError.name, stack: criticalError.stack });
237
+ await this.dependencies.streamingManager.closeStream(agentOSStreamId, "Critical orchestrator error");
238
+ }
239
+ catch (cleanupError) {
240
+ console.error(`AgentOSOrchestrator: Error during critical error cleanup for stream ${agentOSStreamId}:`, cleanupError);
241
+ }
242
+ this.activeStreamContexts.delete(agentOSStreamId);
243
+ });
244
+ return agentOSStreamId;
245
+ }
246
+ /**
247
+ * Internal processing logic for a turn, designed to be called without await by `orchestrateTurn`.
248
+ * @private
249
+ */
250
+ async _processTurnInternal(agentOSStreamId, input) {
251
+ if (!input.selectedPersonaId) {
252
+ throw new GMIError('AgentOSOrchestrator requires a selectedPersonaId on AgentOSInput.', GMIErrorCode.VALIDATION_ERROR);
253
+ }
254
+ let gmi;
255
+ let conversationContext;
256
+ let currentPersonaId = input.selectedPersonaId;
257
+ let gmiInstanceIdForChunks = 'gmi_pending_init';
258
+ try {
259
+ const gmiResult = await this.dependencies.gmiManager.getOrCreateGMIForSession(input.userId, input.sessionId, // This is AgentOS's session ID, GMI might have its own.
260
+ input.selectedPersonaId, // Can be undefined, GMIManager handles default.
261
+ input.conversationId, // Can be undefined, GMIManager might default to sessionId.
262
+ input.options?.preferredModelId, input.options?.preferredProviderId, input.userApiKeys);
263
+ gmi = gmiResult.gmi;
264
+ conversationContext = gmiResult.conversationContext;
265
+ currentPersonaId = gmi.getCurrentPrimaryPersonaId(); // Get actual personaId from GMI
266
+ gmiInstanceIdForChunks = gmi.getGMIId();
267
+ const streamContext = {
268
+ gmi, userId: input.userId, sessionId: input.sessionId, personaId: currentPersonaId,
269
+ conversationId: conversationContext.sessionId, // Use actual conversation ID from context
270
+ conversationContext, userApiKeys: input.userApiKeys, processingOptions: input.options
271
+ };
272
+ this.activeStreamContexts.set(agentOSStreamId, streamContext);
273
+ await this.pushChunkToStream(agentOSStreamId, AgentOSResponseChunkType.SYSTEM_PROGRESS, gmiInstanceIdForChunks, currentPersonaId, false, { message: `Initializing persona ${currentPersonaId}... GMI: ${gmiInstanceIdForChunks}`, progressPercentage: 10 });
274
+ const gmiInput = this.constructGMITurnInput(agentOSStreamId, input, streamContext);
275
+ let currentToolCallIteration = 0;
276
+ let continueProcessing = true;
277
+ let lastGMIOutput; // To store the result from handleToolResult or final processTurnStream result
278
+ while (continueProcessing && currentToolCallIteration < this.config.maxToolCallIterations) {
279
+ currentToolCallIteration++;
280
+ let gmiStreamIterator;
281
+ if (lastGMIOutput?.toolCalls && lastGMIOutput.toolCalls.length > 0) {
282
+ // This case should be handled by external call to orchestrateToolResult.
283
+ // If GMI's handleToolResult itself requests more tools *synchronously* in its GMIOutput,
284
+ // the orchestrator needs to initiate those.
285
+ // For now, we assume gmi.processTurnStream is the entry point for a 'thought cycle'.
286
+ // This part of the loop might need to re-evaluate if GMI.handleToolResult directly returns new tool_calls.
287
+ // Based on GMI.ts, handleToolResult calls processTurnStream internally and returns a final GMIOutput for that step.
288
+ // So, we'd take the tool_calls from that GMIOutput and then break this loop to let orchestrateToolResult handle them.
289
+ await this.processGMIOutput(agentOSStreamId, streamContext, lastGMIOutput, true /*isContinuation*/);
290
+ if (lastGMIOutput.toolCalls && lastGMIOutput.toolCalls.length > 0) {
291
+ // Yield tool call requests and expect external call to orchestrateToolResult
292
+ continueProcessing = false; // Exit this loop, further action via orchestrateToolResult
293
+ break;
294
+ }
295
+ continueProcessing = !lastGMIOutput.isFinal; // isFinal comes from GMIOutput
296
+ if (!continueProcessing)
297
+ break;
298
+ // If not final and no tool calls, what's the next GMI input? This implies GMI yielded intermediate text.
299
+ // The GMI itself should manage its internal state for continuation.
300
+ // Here we assume processTurnStream will pick up from where it left.
301
+ // For simplicity in this refactor, we'll assume after handleToolResult, if not final & no tools, it's an error or unexpected state.
302
+ // A robust solution might require GMI to provide a continuation token or explicit next step.
303
+ console.warn(`AgentOSOrchestrator: GMI output after tool result was not final and had no tool calls. Ending turn for stream ${agentOSStreamId}.`);
304
+ continueProcessing = false;
305
+ break;
306
+ }
307
+ else {
308
+ gmiStreamIterator = gmi.processTurnStream(gmiInput); // For initial turn or if GMI internally continues
309
+ }
310
+ for await (const gmiChunk of gmiStreamIterator) {
311
+ await this.transformAndPushGMIChunk(agentOSStreamId, streamContext, gmiChunk);
312
+ if (gmiChunk.type === GMIOutputChunkType.TOOL_CALL_REQUEST && gmiChunk.content) {
313
+ // GMI is requesting tools. Orchestrator will yield this, then await external tool results.
314
+ continueProcessing = false; // Stop this current GMI processing loop.
315
+ break; // Break from iterating gmiStreamIterator
316
+ }
317
+ if (gmiChunk.isFinal || gmiChunk.type === GMIOutputChunkType.FINAL_RESPONSE_MARKER) {
318
+ continueProcessing = false;
319
+ // The TReturn of processTurnStream will be captured if structure allows
320
+ // break; // Not strictly needed if isFinal means generator ends
321
+ }
322
+ }
323
+ // Capture the TReturn (GMIOutput) from the processTurnStream generator
324
+ // This is tricky with for...await...of.
325
+ // We'll assume the *last* chunk processing or a FINAL_RESPONSE_MARKER helps form `lastGMIOutput`.
326
+ // Or, better, GMI.processTurnStream should be consumed differently to get TReturn.
327
+ // For now, if continueProcessing is true, it implies gmiStreamIterator finished without tool_calls or explicit final marker.
328
+ // If it *did* have a FINAL_RESPONSE_MARKER or isFinal:true, continueProcessing would be false.
329
+ if (continueProcessing) { // Stream ended without tool request or explicit final chunk.
330
+ // This means the generator completed, and its return value (GMIOutput) should be used.
331
+ // However, getting TReturn from for...await...of is not direct.
332
+ // Let's assume GMI.ts ensures its last yielded chunk conveys finality or the structure of the return value.
333
+ // Or, the loop naturally ends and `lastGMIOutput` should be based on aggregation.
334
+ // This part is complex without knowing exactly how TReturn is retrieved alongside yielded values.
335
+ // For this iteration, we'll assume if the loop finishes and continueProcessing is true, it's effectively the end of this GMI cycle.
336
+ // lastGMIOutput should have been formed by the *last state of aggregation* if the GMI is well-behaved.
337
+ // The GMI.processTurnStream itself *returns* GMIOutput. This is what we need.
338
+ // TODO: Refactor to correctly get the TReturn from gmiStreamIterator.
339
+ // A simplified approach: if the loop finishes and no tool calls are pending, we assume the interaction for this step is done.
340
+ // The generation of the AgentOSFinalResponseChunk should use the accumulated state.
341
+ // For now, if we reach here, it means the stream finished. We consider it implicitly final for this iteration.
342
+ continueProcessing = false;
343
+ }
344
+ if (!continueProcessing)
345
+ break; // Exit the while loop
346
+ } // End while
347
+ if (currentToolCallIteration >= this.config.maxToolCallIterations && continueProcessing) {
348
+ console.warn(`AgentOSOrchestrator: Max tool call iterations reached for stream ${agentOSStreamId}. Forcing termination.`);
349
+ await this.pushErrorChunk(agentOSStreamId, currentPersonaId, gmiInstanceIdForChunks, GMIErrorCode.RATE_LIMIT_EXCEEDED, // Or a more specific code
350
+ 'Agent reached maximum tool call iterations.', { maxIterations: this.config.maxToolCallIterations });
351
+ }
352
+ // Final processing at the end of the turn or if no more continuation.
353
+ // This should use the true GMIOutput returned by GMI (either initial or after tool handling)
354
+ // For now, this relies on the fact that the last interaction with GMI (processTurnStream or handleToolResult)
355
+ // updated the conversation context, and we generate a final response summary.
356
+ if (this.config.enableConversationalPersistence && conversationContext) {
357
+ await this.dependencies.conversationManager.saveConversation(conversationContext);
358
+ }
359
+ // Send a final response chunk if not already implicitly sent by an error or final GMI chunk transform.
360
+ // This part needs careful consideration of what `lastGMIOutput` represents here.
361
+ // It should represent the *actual* TReturn from the GMI's processing.
362
+ const finalGMIStateForResponse = lastGMIOutput ||
363
+ {
364
+ isFinal: true,
365
+ responseText: gmi ? 'Processing complete.' : 'Processing ended.',
366
+ };
367
+ await this.pushChunkToStream(agentOSStreamId, AgentOSResponseChunkType.FINAL_RESPONSE, gmiInstanceIdForChunks, currentPersonaId, true, {
368
+ finalResponseText: finalGMIStateForResponse.responseText ?? null,
369
+ finalToolCalls: finalGMIStateForResponse.toolCalls,
370
+ finalUiCommands: finalGMIStateForResponse.uiCommands,
371
+ audioOutput: finalGMIStateForResponse.audioOutput,
372
+ imageOutput: finalGMIStateForResponse.imageOutput,
373
+ usage: normalizeUsage(finalGMIStateForResponse.usage),
374
+ reasoningTrace: finalGMIStateForResponse.reasoningTrace,
375
+ error: finalGMIStateForResponse.error,
376
+ updatedConversationContext: conversationContext ? conversationContext.toJSON() : undefined,
377
+ activePersonaDetails: snapshotPersonaDetails(gmi?.getPersona?.()),
378
+ });
379
+ }
380
+ catch (error) {
381
+ const gmiErr = GMIError.wrap?.(error, GMIErrorCode.GMI_PROCESSING_ERROR, `Error in orchestrateTurn for stream ${agentOSStreamId}`) ||
382
+ new GMIError(`Error in orchestrateTurn for stream ${agentOSStreamId}: ${error.message}`, GMIErrorCode.GMI_PROCESSING_ERROR, error);
383
+ console.error(`AgentOSOrchestrator: Error during _processTurnInternal for stream ${agentOSStreamId}:`, gmiErr);
384
+ await this.pushErrorChunk(agentOSStreamId, currentPersonaId, gmiInstanceIdForChunks, gmiErr.code, gmiErr.message, gmiErr.details);
385
+ }
386
+ finally {
387
+ // Don't close stream here, AgentOS will close it when client disconnects or request ends.
388
+ // Or StreamingManager handles timeouts.
389
+ this.activeStreamContexts.delete(agentOSStreamId);
390
+ console.log(`AgentOSOrchestrator: Finished processing for AgentOS Stream ${agentOSStreamId}. Context removed.`);
391
+ }
392
+ }
393
+ /**
394
+ * Handles the result of an external tool execution, feeding it back into the
395
+ * relevant GMI instance for continued processing.
396
+ * Uses StreamingManager to push subsequent GMI outputs.
397
+ *
398
+ * @public
399
+ * @async
400
+ * @param {string} agentOSStreamId - The orchestrator's stream ID for this interaction flow.
401
+ * @param {string} toolCallId - The ID of the tool call being responded to.
402
+ * @param {string} toolName - The name of the tool.
403
+ * @param {any} toolOutput - The output from the tool.
404
+ * @param {boolean} isSuccess - Whether the tool execution was successful.
405
+ * @param {string} [errorMessage] - Error message if not successful.
406
+ * @returns {Promise<void>}
407
+ * @throws {GMIError} If stream context is not found or GMI fails to handle result.
408
+ */
409
+ async orchestrateToolResult(agentOSStreamId, toolCallId, toolName, toolOutput, isSuccess, errorMessage) {
410
+ this.ensureInitialized();
411
+ const streamContext = this.activeStreamContexts.get(agentOSStreamId);
412
+ if (!streamContext) {
413
+ const errMsg = `Orchestrator: Received tool result for unknown or inactive streamId: ${agentOSStreamId}. Tool: ${toolName}, CallID: ${toolCallId}`;
414
+ console.error(errMsg);
415
+ // Cannot push to a non-existent stream context. This is a critical failure.
416
+ throw new GMIError(errMsg, GMIErrorCode.RESOURCE_NOT_FOUND, { agentOSStreamId, toolCallId });
417
+ }
418
+ const { gmi, userId, personaId, conversationContext, userApiKeys } = streamContext;
419
+ const gmiInstanceIdForChunks = gmi.getGMIId();
420
+ const toolResultPayload = isSuccess
421
+ ? { type: 'success', result: toolOutput }
422
+ : { type: 'error', error: { code: 'EXTERNAL_TOOL_ERROR', message: errorMessage || `External tool '${toolName}' execution failed.` } };
423
+ console.log(`AgentOSOrchestrator: Feeding tool result for stream ${agentOSStreamId}, GMI ${gmiInstanceIdForChunks}, tool call ${toolCallId} (${toolName}) back to GMI.`);
424
+ try {
425
+ // Emit the tool result itself as a chunk
426
+ await this.pushChunkToStream(agentOSStreamId, AgentOSResponseChunkType.TOOL_RESULT_EMISSION, gmiInstanceIdForChunks, personaId, false, { toolCallId, toolName, toolResult: toolOutput, isSuccess, errorMessage });
427
+ // GMI processes the tool result and gives a *final output for that step*
428
+ const gmiOutputAfterTool = await gmi.handleToolResult(toolCallId, toolName, toolResultPayload, userId, userApiKeys || {});
429
+ // Process the GMIOutput (which is not a stream of chunks)
430
+ await this.processGMIOutput(agentOSStreamId, streamContext, gmiOutputAfterTool, false);
431
+ // If GMIOutput indicates further tool calls are needed by the GMI
432
+ if (gmiOutputAfterTool.toolCalls && gmiOutputAfterTool.toolCalls.length > 0) {
433
+ await this.pushChunkToStream(agentOSStreamId, AgentOSResponseChunkType.TOOL_CALL_REQUEST, gmiInstanceIdForChunks, personaId, false, // Not final, more interaction expected
434
+ { toolCalls: gmiOutputAfterTool.toolCalls, rationale: gmiOutputAfterTool.responseText || "Agent requires further tool execution." });
435
+ // The orchestrator now waits for another external call to `orchestrateToolResult` for these new calls.
436
+ }
437
+ else if (gmiOutputAfterTool.isFinal) {
438
+ if (this.config.enableConversationalPersistence && conversationContext) {
439
+ await this.dependencies.conversationManager.saveConversation(conversationContext);
440
+ }
441
+ // If it's final and no more tool calls, the interaction for this GMI processing cycle might be done.
442
+ // Push a final response marker or the already pushed final data from processGMIOutput takes precedence.
443
+ await this.pushChunkToStream(agentOSStreamId, AgentOSResponseChunkType.FINAL_RESPONSE, gmiInstanceIdForChunks, personaId, true, {
444
+ finalResponseText: gmiOutputAfterTool.responseText,
445
+ finalToolCalls: gmiOutputAfterTool.toolCalls,
446
+ finalUiCommands: gmiOutputAfterTool.uiCommands,
447
+ audioOutput: gmiOutputAfterTool.audioOutput,
448
+ imageOutput: gmiOutputAfterTool.imageOutput,
449
+ usage: normalizeUsage(gmiOutputAfterTool.usage),
450
+ reasoningTrace: gmiOutputAfterTool.reasoningTrace,
451
+ error: gmiOutputAfterTool.error,
452
+ updatedConversationContext: conversationContext.toJSON(),
453
+ activePersonaDetails: snapshotPersonaDetails(gmi.getPersona?.()),
454
+ });
455
+ this.activeStreamContexts.delete(agentOSStreamId); // Clean up context for this completed flow
456
+ await this.dependencies.streamingManager.closeStream(agentOSStreamId, "Tool processing complete and final response generated.");
457
+ }
458
+ // If not final and no tool calls, the GMI might have provided intermediate text.
459
+ // The stream remains open for further GMI internal processing or new user input.
460
+ }
461
+ catch (error) {
462
+ const gmiErr = GMIError.wrap?.(error, GMIErrorCode.TOOL_ERROR, `Error in orchestrateToolResult for stream ${agentOSStreamId}`) ||
463
+ new GMIError(`Error in orchestrateToolResult for stream ${agentOSStreamId}: ${error.message}`, GMIErrorCode.TOOL_ERROR, error);
464
+ console.error(`AgentOSOrchestrator: Critical error processing tool result for stream ${agentOSStreamId}:`, gmiErr);
465
+ await this.pushErrorChunk(agentOSStreamId, personaId, gmiInstanceIdForChunks, gmiErr.code, gmiErr.message, gmiErr.details);
466
+ this.activeStreamContexts.delete(agentOSStreamId);
467
+ await this.dependencies.streamingManager.closeStream(agentOSStreamId, "Critical error during tool result processing.");
468
+ throw gmiErr; // Re-throw to signal failure to caller if necessary
469
+ }
470
+ }
471
+ /**
472
+ * Processes a GMIOutput object (typically from handleToolResult or the end of a processTurnStream)
473
+ * and pushes relevant chunks to the client stream.
474
+ * @private
475
+ */
476
+ async processGMIOutput(agentOSStreamId, streamContext, gmiOutput, _isContinuation // True if this GMIOutput is from an internal GMI continuation, false if from initial turn/tool result
477
+ ) {
478
+ const { gmi, personaId, conversationContext } = streamContext;
479
+ const gmiInstanceIdForChunks = gmi.getGMIId();
480
+ if (gmiOutput.responseText) {
481
+ await this.pushChunkToStream(agentOSStreamId, AgentOSResponseChunkType.TEXT_DELTA, gmiInstanceIdForChunks, personaId, false, // text delta is not final by itself
482
+ { textDelta: gmiOutput.responseText });
483
+ }
484
+ if (gmiOutput.uiCommands && gmiOutput.uiCommands.length > 0) {
485
+ await this.pushChunkToStream(agentOSStreamId, AgentOSResponseChunkType.UI_COMMAND, gmiInstanceIdForChunks, personaId, false, { uiCommands: gmiOutput.uiCommands });
486
+ }
487
+ if (gmiOutput.error) {
488
+ await this.pushErrorChunk(agentOSStreamId, personaId, gmiInstanceIdForChunks, gmiOutput.error.code, gmiOutput.error.message, gmiOutput.error.details);
489
+ // If an error occurs in GMIOutput, it's usually final for this interaction path
490
+ if (gmiOutput.isFinal) {
491
+ this.activeStreamContexts.delete(agentOSStreamId);
492
+ await this.dependencies.streamingManager.closeStream(agentOSStreamId, `GMI reported an error: ${gmiOutput.error.message}`);
493
+ }
494
+ return; // Stop further processing of this GMIOutput if there's an error
495
+ }
496
+ // Note: Tool calls from GMIOutput are handled by the calling method (orchestrateTurn or orchestrateToolResult)
497
+ // to decide on looping or yielding ToolCallRequestChunks.
498
+ if (gmiOutput.isFinal && (!gmiOutput.toolCalls || gmiOutput.toolCalls.length === 0)) {
499
+ if (this.config.enableConversationalPersistence && conversationContext) {
500
+ await this.dependencies.conversationManager.saveConversation(conversationContext);
501
+ }
502
+ // This is a final response without further tool calls
503
+ await this.pushChunkToStream(agentOSStreamId, AgentOSResponseChunkType.FINAL_RESPONSE, gmiInstanceIdForChunks, personaId, true, {
504
+ finalResponseText: gmiOutput.responseText,
505
+ finalToolCalls: gmiOutput.toolCalls, // Should be empty or undefined here
506
+ finalUiCommands: gmiOutput.uiCommands,
507
+ audioOutput: gmiOutput.audioOutput,
508
+ imageOutput: gmiOutput.imageOutput,
509
+ usage: normalizeUsage(gmiOutput.usage),
510
+ reasoningTrace: gmiOutput.reasoningTrace,
511
+ error: gmiOutput.error, // Should be undefined here if we reached this point
512
+ updatedConversationContext: conversationContext.toJSON(),
513
+ activePersonaDetails: snapshotPersonaDetails(gmi.getPersona?.()),
514
+ });
515
+ this.activeStreamContexts.delete(agentOSStreamId);
516
+ await this.dependencies.streamingManager.closeStream(agentOSStreamId, "Processing complete.");
517
+ }
518
+ }
519
+ /**
520
+ * Transforms a GMIOutputChunk into one or more AgentOSResponse chunks and pushes them.
521
+ * @private
522
+ */
523
+ async transformAndPushGMIChunk(agentOSStreamId, streamContext, gmiChunk) {
524
+ const { gmi, personaId, conversationContext } = streamContext;
525
+ const gmiInstanceIdForChunks = gmi.getGMIId();
526
+ switch (gmiChunk.type) {
527
+ case GMIOutputChunkType.TEXT_DELTA:
528
+ if (gmiChunk.content && typeof gmiChunk.content === 'string') {
529
+ await this.pushChunkToStream(agentOSStreamId, AgentOSResponseChunkType.TEXT_DELTA, gmiInstanceIdForChunks, personaId, gmiChunk.isFinal ?? false, { textDelta: gmiChunk.content });
530
+ }
531
+ break;
532
+ case GMIOutputChunkType.SYSTEM_MESSAGE: // Was SystemProgress
533
+ if (gmiChunk.content && typeof gmiChunk.content === 'object') {
534
+ const progressContent = gmiChunk.content;
535
+ await this.pushChunkToStream(agentOSStreamId, AgentOSResponseChunkType.SYSTEM_PROGRESS, gmiInstanceIdForChunks, personaId, gmiChunk.isFinal ?? false, progressContent);
536
+ }
537
+ break;
538
+ case GMIOutputChunkType.TOOL_CALL_REQUEST:
539
+ if (gmiChunk.content && Array.isArray(gmiChunk.content)) {
540
+ const toolCalls = gmiChunk.content;
541
+ await this.pushChunkToStream(agentOSStreamId, AgentOSResponseChunkType.TOOL_CALL_REQUEST, gmiInstanceIdForChunks, personaId, false, // Tool call request is not final for the AgentOS turn
542
+ { toolCalls, rationale: gmiChunk.metadata?.rationale || "Agent requires tool execution." });
543
+ }
544
+ break;
545
+ case GMIOutputChunkType.UI_COMMAND:
546
+ if (gmiChunk.content && Array.isArray(gmiChunk.content)) {
547
+ await this.pushChunkToStream(agentOSStreamId, AgentOSResponseChunkType.UI_COMMAND, gmiInstanceIdForChunks, personaId, gmiChunk.isFinal ?? false, { uiCommands: gmiChunk.content });
548
+ }
549
+ break;
550
+ case GMIOutputChunkType.ERROR: {
551
+ const errDetails = gmiChunk.errorDetails || { message: gmiChunk.content };
552
+ await this.pushErrorChunk(agentOSStreamId, personaId, gmiInstanceIdForChunks, errDetails.code || GMIErrorCode.GMI_PROCESSING_ERROR, errDetails.message || String(gmiChunk.content) || 'Unknown GMI processing error.', errDetails.details || errDetails);
553
+ // If GMI sends an error chunk that it considers final for its operation
554
+ if (gmiChunk.isFinal) {
555
+ this.activeStreamContexts.delete(agentOSStreamId);
556
+ await this.dependencies.streamingManager.closeStream(agentOSStreamId, `GMI stream error: ${errDetails.message || String(gmiChunk.content)}`);
557
+ }
558
+ break;
559
+ }
560
+ case GMIOutputChunkType.FINAL_RESPONSE_MARKER:
561
+ // This chunk signals the end of GMI's streaming.
562
+ // The actual final content should have been accumulated or is in this chunk's content/metadata.
563
+ // The calling loop should now construct and send AgentOSFinalResponseChunk.
564
+ // This chunk itself typically doesn't map directly to an AgentOSResponse other than triggering finalization.
565
+ // However, AgentOS.ts expects a final response from the generator.
566
+ // For now, if GMI explicitly sends this, we ensure the stream is marked for closure.
567
+ // The main _processTurnInternal loop will handle the comprehensive AgentOSFinalResponseChunk.
568
+ if (gmiChunk.isFinal) { // This marker SHOULD imply isFinal=true
569
+ if (this.config.enableConversationalPersistence && conversationContext) {
570
+ await this.dependencies.conversationManager.saveConversation(conversationContext);
571
+ }
572
+ // This is a simplified final response based *only* on this marker chunk.
573
+ // A more robust solution accumulates all data through the turn.
574
+ await this.pushChunkToStream(agentOSStreamId, AgentOSResponseChunkType.FINAL_RESPONSE, gmiInstanceIdForChunks, personaId, true, {
575
+ finalResponseText: typeof gmiChunk.content === 'string' ? gmiChunk.content : "Processing complete.",
576
+ // other fields like usage, trace would need to be on the FINAL_RESPONSE_MARKER content
577
+ // or aggregated throughout the turn.
578
+ updatedConversationContext: conversationContext.toJSON(),
579
+ activePersonaDetails: snapshotPersonaDetails(gmi.getPersona?.()),
580
+ });
581
+ this.activeStreamContexts.delete(agentOSStreamId);
582
+ await this.dependencies.streamingManager.closeStream(agentOSStreamId, "GMI processing complete (final marker).");
583
+ }
584
+ break;
585
+ case GMIOutputChunkType.USAGE_UPDATE:
586
+ // TODO: Could send a specific AgentOSMetadataUpdateChunk if defined, or log.
587
+ console.log(`AgentOSOrchestrator: UsageUpdate from GMI on stream ${agentOSStreamId}:`, gmiChunk.content);
588
+ break;
589
+ default:
590
+ console.warn(`AgentOSOrchestrator: Unhandled GMIOutputChunkType '${gmiChunk.type}' on stream ${agentOSStreamId}. Content:`, gmiChunk.content);
591
+ }
592
+ }
593
+ /**
594
+ * Constructs GMITurnInput from AgentOSInput.
595
+ * @private
596
+ */
597
+ constructGMITurnInput(agentOSStreamId, input, streamContext) {
598
+ const { userId, sessionId, options } = input;
599
+ const { gmi } = streamContext;
600
+ const gmiInputMetadata = {
601
+ gmiId: gmi.getGMIId(),
602
+ // Pass relevant options to GMI if it needs them
603
+ processingOptions: options,
604
+ // User API keys are handled by GMIManager when fetching/creating GMI,
605
+ // but can be passed in metadata if GMI needs them per-turn for some reason.
606
+ userApiKeys: input.userApiKeys,
607
+ userFeedback: input.userFeedback,
608
+ explicitPersonaSwitchId: input.selectedPersonaId,
609
+ // Task hint can be more sophisticated, based on input analysis
610
+ taskHint: input.textInput ? 'user_text_query' : (input.visionInputs || input.audioInput) ? 'user_multimodal_query' : 'general_query',
611
+ // GMI.ts specific fields if any, not standard in IGMI.GMITurnInput
612
+ modelSelectionOverrides: {
613
+ preferredModelId: options?.preferredModelId,
614
+ preferredProviderId: options?.preferredProviderId,
615
+ temperature: options?.temperature,
616
+ topP: options?.topP,
617
+ maxTokens: options?.maxTokens,
618
+ },
619
+ personaStateOverrides: [], // Example
620
+ };
621
+ let type;
622
+ let content;
623
+ if (input.visionInputs && input.visionInputs.length > 0 || input.audioInput) {
624
+ type = GMIInteractionType.MULTIMODAL_CONTENT;
625
+ const multiModalContent = {};
626
+ if (input.textInput)
627
+ multiModalContent.text = input.textInput;
628
+ if (input.visionInputs)
629
+ multiModalContent.vision = input.visionInputs;
630
+ if (input.audioInput)
631
+ multiModalContent.audio = input.audioInput;
632
+ content = multiModalContent;
633
+ }
634
+ else if (input.textInput) {
635
+ type = GMIInteractionType.TEXT;
636
+ content = input.textInput;
637
+ }
638
+ else {
639
+ // Fallback or error if no meaningful input
640
+ type = GMIInteractionType.SYSTEM_MESSAGE; // E.g. an empty ping or keep-alive
641
+ content = "No primary user input provided for this turn.";
642
+ console.warn(`AgentOSOrchestrator: No primary input in AgentOSInput for stream ${agentOSStreamId}. Sending as system message to GMI.`);
643
+ }
644
+ return {
645
+ interactionId: agentOSStreamId + `_turn_${uuidv4()}`, // More specific interaction ID for GMI
646
+ userId,
647
+ sessionId, // AgentOS session ID
648
+ type,
649
+ content,
650
+ metadata: gmiInputMetadata,
651
+ timestamp: new Date(),
652
+ };
653
+ }
654
+ /**
655
+ * Shuts down the AgentOSOrchestrator.
656
+ * Currently, this mainly involves clearing active stream contexts.
657
+ * Dependencies like GMIManager are assumed to be shut down by AgentOS.
658
+ *
659
+ * @public
660
+ * @async
661
+ * @returns {Promise<void>} A promise that resolves when shutdown is complete.
662
+ */
663
+ async shutdown() {
664
+ console.log('AgentOSOrchestrator: Shutting down...');
665
+ // Notify and close streams managed by StreamingManager for contexts held here
666
+ for (const streamId of this.activeStreamContexts.keys()) {
667
+ try {
668
+ await this.dependencies.streamingManager.closeStream(streamId, "Orchestrator shutting down.");
669
+ }
670
+ catch (e) {
671
+ console.error(`AgentOSOrchestrator: Error closing stream ${streamId} during shutdown: ${e.message}`);
672
+ }
673
+ }
674
+ this.activeStreamContexts.clear();
675
+ this.initialized = false;
676
+ console.log('AgentOSOrchestrator: Shutdown complete.');
677
+ }
678
+ }
679
+ //# sourceMappingURL=AgentOSOrchestrator.js.map