@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,1157 @@
1
+ // File: backend/agentos/api/AgentOS.ts
2
+ /**
3
+ * @file AgentOS.ts
4
+ * @module backend/agentos/api/AgentOS
5
+ * @version 1.1.0
6
+ *
7
+ * @description
8
+ * This file implements the primary public-facing service facade for the AgentOS platform,
9
+ * the `AgentOS` class. It acts as the unified entry point for all high-level interactions
10
+ * with the AI agent ecosystem. The `AgentOS` class orchestrates operations by delegating
11
+ * to specialized managers and services such as `AgentOSOrchestrator`, `GMIManager`,
12
+ * `StreamingManager`, and others.
13
+ *
14
+ * The architecture emphasizes:
15
+ * - **Interface-Driven Design:** `AgentOS` implements the `IAgentOS` interface, ensuring
16
+ * a clear contract for its consumers.
17
+ * - **Robust Initialization:** A comprehensive initialization sequence configures all core
18
+ * components and dependencies.
19
+ * - **Streaming-First Operations:** Core interaction methods (`processRequest`, `handleToolResult`)
20
+ * are designed as asynchronous generators, enabling real-time, chunked data flow.
21
+ * - **Structured Error Handling:** Custom error types (`AgentOSServiceError`) derived from
22
+ * a base `GMIError` provide detailed and context-aware error reporting.
23
+ * - **Comprehensive Configuration:** The system's behavior is managed through a detailed
24
+ * `AgentOSConfig` object.
25
+ *
26
+ * Key responsibilities of this module include:
27
+ * - Managing the lifecycle of the AgentOS service.
28
+ * - Providing methods for initiating chat turns, handling tool results, listing personas,
29
+ * retrieving conversation history, and processing user feedback.
30
+ * - Bridging the gap between high-level API calls and the underlying orchestration and
31
+ * cognitive processing layers.
32
+ * - Ensuring adherence to TypeScript best practices, including strict type safety,
33
+ * comprehensive JSDoc documentation, and robust error management.
34
+ *
35
+ * @see {@link ./interfaces/IAgentOS.ts} for the `IAgentOS` interface contract.
36
+ * @see {@link ./AgentOSOrchestrator.ts} for the orchestration logic.
37
+ * @see {@link ../cognitive_substrate/GMIManager.ts} for GMI lifecycle management.
38
+ * @see {@link ../core/streaming/StreamingManager.ts} for real-time data streaming.
39
+ * @see {@link @framers/agentos/utils/errors.ts} for custom error definitions.
40
+ */
41
+ import { AgentOSResponseChunkType } from './types/AgentOSResponse.js';
42
+ import { AgentOSOrchestrator } from './AgentOSOrchestrator.js';
43
+ import { GMIManager } from '../cognitive_substrate/GMIManager.js';
44
+ import { AIModelProviderManager } from '../core/llm/providers/AIModelProviderManager.js';
45
+ import { PromptEngine } from '../core/llm/PromptEngine.js';
46
+ import { ToolOrchestrator } from '../core/tools/ToolOrchestrator.js';
47
+ import { ToolExecutor } from '../core/tools/ToolExecutor.js';
48
+ import { ToolPermissionManager } from '../core/tools/permissions/ToolPermissionManager.js';
49
+ import { LLMUtilityAI } from '../core/ai_utilities/LLMUtilityAI.js';
50
+ import { ConversationManager } from '../core/conversation/ConversationManager.js';
51
+ import { StreamingManager } from '../core/streaming/StreamingManager.js';
52
+ import { GMIError, GMIErrorCode } from '../utils/errors.js';
53
+ import { uuidv4 } from '../utils/uuid.js';
54
+ import { createLogger } from '../logging/loggerFactory.js';
55
+ import { GuardrailAction } from '../core/guardrails/IGuardrailService.js';
56
+ import { evaluateInputGuardrails, createGuardrailBlockedStream, wrapOutputGuardrails, } from '../core/guardrails/guardrailDispatcher.js';
57
+ import { ExtensionManager, EXTENSION_KIND_GUARDRAIL, EXTENSION_KIND_TOOL, EXTENSION_KIND_WORKFLOW, } from '../extensions/index.js';
58
+ import { WorkflowRuntime } from '../core/workflows/runtime/WorkflowRuntime.js';
59
+ import { AgencyRegistry } from '../core/agency/AgencyRegistry.js';
60
+ import { WorkflowEngine } from '../core/workflows/WorkflowEngine.js';
61
+ import { InMemoryWorkflowStore } from '../core/workflows/storage/InMemoryWorkflowStore.js';
62
+ /**
63
+ * @class AgentOSServiceError
64
+ * @extends GMIError
65
+ * @description Custom error class for errors specifically originating from the AgentOS service facade.
66
+ * This class provides a standardized way to represent errors encountered within the `AgentOS` class,
67
+ * inheriting common error properties from `GMIError` and setting a distinct error name.
68
+ */
69
+ export class AgentOSServiceError extends GMIError {
70
+ /**
71
+ * Creates an instance of `AgentOSServiceError`.
72
+ *
73
+ * @param {string} message - A human-readable description of the error.
74
+ * @param {GMIErrorCode | string} code - A specific error code, typically from `GMIErrorCode`,
75
+ * identifying the nature of the error.
76
+ * @param {any} [details] - Optional. Additional structured details or the underlying error
77
+ * object that caused this service error.
78
+ * @param {string} [componentOrigin] - Optional. The name of the component or sub-module within
79
+ * AgentOS where the error originated or was detected. This helps in pinpointing the error's source.
80
+ */
81
+ constructor(message, code, details, componentOrigin) {
82
+ super(message, code, details, componentOrigin);
83
+ /**
84
+ * Specifies the name of the error class, used for identification.
85
+ * @public
86
+ * @override
87
+ * @readonly
88
+ * @type {string}
89
+ */
90
+ this.name = 'AgentOSServiceError';
91
+ // Ensure `name` is set correctly after super call, overriding GMIError's default if any.
92
+ // The `readonly name` field declaration handles this, but this assignment is idiomatic.
93
+ // Object.setPrototypeOf is crucial for ensuring `instanceof` works correctly with custom errors.
94
+ Object.setPrototypeOf(this, AgentOSServiceError.prototype);
95
+ }
96
+ /**
97
+ * Wraps an existing error object (which could be of any type) within a new `AgentOSServiceError` instance.
98
+ * This is useful for standardizing errors caught from lower layers or external libraries.
99
+ *
100
+ * @public
101
+ * @static
102
+ * @override
103
+ * @param {any} error - The original error object to wrap.
104
+ * @param {GMIErrorCode | string} code - The `GMIErrorCode` to assign to the new `AgentOSServiceError`.
105
+ * @param {string} message - A new, overarching message for the `AgentOSServiceError`. The original
106
+ * error's message will typically be included in the `details`.
107
+ * @param {string} [componentOrigin] - Optional. The component where this wrapping is occurring or
108
+ * where the original error was caught and is being standardized.
109
+ * @returns {AgentOSServiceError} A new instance of `AgentOSServiceError` encapsulating the original error.
110
+ *
111
+ * @example
112
+ * try {
113
+ * // some operation that might throw
114
+ * } catch (e: unknown) {
115
+ * throw AgentOSServiceError.wrap(e, GMIErrorCode.INTERNAL_SERVER_ERROR, "Failed to process user request", "RequestHandler");
116
+ * }
117
+ */
118
+ static wrap(error, code, message, componentOrigin) {
119
+ const baseMessage = error instanceof Error ? error.message : String(error);
120
+ const originalComponent = error instanceof GMIError ? error.component : undefined;
121
+ const originalDetails = error instanceof GMIError ? error.details : { underlyingError: error };
122
+ return new AgentOSServiceError(`${message}: ${baseMessage}`, code, originalDetails, componentOrigin || originalComponent);
123
+ }
124
+ }
125
+ /**
126
+ * @class AgentOS
127
+ * @implements {IAgentOS}
128
+ * @description
129
+ * The `AgentOS` class is the SOTA public-facing service facade for the entire AI agent platform.
130
+ * It provides a unified API for interacting with the system, managing the lifecycle of core
131
+ * components, and orchestrating complex AI interactions. This class ensures that all
132
+ * operations adhere to the defined architectural tenets, including robust error handling,
133
+ * comprehensive documentation, and strict type safety.
134
+ */
135
+ export class AgentOS {
136
+ /**
137
+ * Constructs an `AgentOS` instance. The instance is not operational until
138
+ * `initialize()` is called and successfully completes.
139
+ */
140
+ constructor(logger = createLogger('AgentOS')) {
141
+ this.logger = logger;
142
+ this.initialized = false;
143
+ }
144
+ /**
145
+ * Initializes the `AgentOS` service and all its core dependencies.
146
+ * This method must be called and successfully awaited before any other operations
147
+ * can be performed on the `AgentOS` instance. It sets up configurations,
148
+ * instantiates managers, and prepares the system for operation.
149
+ *
150
+ * @public
151
+ * @async
152
+ * @param {AgentOSConfig} config - The comprehensive configuration object for AgentOS.
153
+ * @returns {Promise<void>} A promise that resolves when initialization is complete.
154
+ * @throws {AgentOSServiceError} If configuration validation fails or if any critical
155
+ * dependency fails to initialize.
156
+ */
157
+ async initialize(config) {
158
+ if (this.initialized) {
159
+ this.logger.warn('AgentOS initialize() called more than once; skipping.');
160
+ return;
161
+ }
162
+ this.validateConfiguration(config);
163
+ // Make the configuration immutable after validation to prevent runtime changes.
164
+ this.config = Object.freeze({ ...config });
165
+ // Initialize LanguageService early if configured so downstream orchestration can use it.
166
+ if (config.languageConfig) {
167
+ try {
168
+ // Dynamic import may fail under certain bundler path resolutions; using explicit relative path.
169
+ const { LanguageService } = await import('../core/language/index.js');
170
+ this.languageService = new LanguageService(config.languageConfig);
171
+ await this.languageService.initialize();
172
+ this.logger.info('AgentOS LanguageService initialized');
173
+ }
174
+ catch (langErr) {
175
+ this.logger.error('Failed initializing LanguageService; continuing without multilingual features', { error: langErr?.message || langErr });
176
+ }
177
+ }
178
+ // Assign core services from configuration
179
+ this.authService = this.config.authService;
180
+ this.subscriptionService = this.config.subscriptionService;
181
+ this.prisma = this.config.prisma; // Optional - only needed for auth/subscriptions
182
+ this.guardrailService = this.config.guardrailService;
183
+ // Validate that either storageAdapter or prisma is provided
184
+ if (!this.config.storageAdapter && !this.config.prisma) {
185
+ throw new AgentOSServiceError('Either storageAdapter or prisma must be provided. Use storageAdapter for client-side (IndexedDB/SQLite) or prisma for server-side (PostgreSQL).', GMIErrorCode.CONFIGURATION_ERROR, 'AgentOS.initialize');
186
+ }
187
+ this.logger.info('AgentOS initialization sequence started');
188
+ this.extensionManager = new ExtensionManager({
189
+ manifest: this.config.extensionManifest,
190
+ secrets: this.config.extensionSecrets,
191
+ });
192
+ const extensionLifecycleContext = { logger: this.logger };
193
+ await this.extensionManager.loadManifest(extensionLifecycleContext);
194
+ await this.registerConfigGuardrailService(extensionLifecycleContext);
195
+ try {
196
+ await this.initializeWorkflowRuntime(extensionLifecycleContext);
197
+ // Initialize AI Model Provider Manager
198
+ this.modelProviderManager = new AIModelProviderManager();
199
+ await this.modelProviderManager.initialize(this.config.modelProviderManagerConfig);
200
+ console.log('AgentOS: AIModelProviderManager initialized.');
201
+ await this.ensureUtilityAIService();
202
+ // Initialize Prompt Engine
203
+ this.promptEngine = new PromptEngine();
204
+ const peUtility = this.utilityAIService;
205
+ if (typeof peUtility.summarizeConversationHistory !== 'function' ||
206
+ typeof peUtility.summarizeRAGContext !== 'function') {
207
+ const warningMsg = 'AgentOS WARNING: The provided utilityAIService does not fully implement the IPromptEngineUtilityAI interface (missing summarizeConversationHistory or summarizeRAGContext). PromptEngine functionality may be impaired.';
208
+ console.warn(warningMsg);
209
+ }
210
+ await this.promptEngine.initialize(this.config.promptEngineConfig, this.utilityAIService);
211
+ console.log('AgentOS: PromptEngine initialized.');
212
+ // Initialize Tool Permission Manager
213
+ this.toolPermissionManager = new ToolPermissionManager();
214
+ await this.toolPermissionManager.initialize(this.config.toolPermissionManagerConfig, this.authService, this.subscriptionService);
215
+ console.log('AgentOS: ToolPermissionManager initialized.');
216
+ // Initialize Tool Orchestrator
217
+ const toolRegistry = this.extensionManager.getRegistry(EXTENSION_KIND_TOOL);
218
+ this.toolExecutor = new ToolExecutor(this.authService, this.subscriptionService, toolRegistry);
219
+ this.toolOrchestrator = new ToolOrchestrator();
220
+ await this.toolOrchestrator.initialize(this.config.toolOrchestratorConfig, this.toolPermissionManager, this.toolExecutor);
221
+ console.log('AgentOS: ToolOrchestrator initialized.');
222
+ // Initialize Conversation Manager
223
+ this.conversationManager = new ConversationManager();
224
+ await this.conversationManager.initialize(this.config.conversationManagerConfig, this.utilityAIService, // General IUtilityAI for conversation tasks
225
+ this.config.storageAdapter // Use storageAdapter instead of Prisma
226
+ );
227
+ console.log('AgentOS: ConversationManager initialized.');
228
+ // Initialize Streaming Manager
229
+ this.streamingManager = new StreamingManager();
230
+ await this.streamingManager.initialize(this.config.streamingManagerConfig);
231
+ console.log('AgentOS: StreamingManager initialized.');
232
+ // Initialize GMI Manager
233
+ this.gmiManager = new GMIManager(this.config.gmiManagerConfig, this.subscriptionService, this.authService, this.conversationManager, // Removed Prisma parameter
234
+ this.promptEngine, this.modelProviderManager, this.utilityAIService, // Pass the potentially dual-role utility service
235
+ this.toolOrchestrator, undefined, this.config.personaLoader);
236
+ await this.gmiManager.initialize();
237
+ console.log('AgentOS: GMIManager initialized.');
238
+ await this.startWorkflowRuntime();
239
+ // Initialize AgentOS Orchestrator
240
+ const orchestratorDependencies = {
241
+ gmiManager: this.gmiManager,
242
+ toolOrchestrator: this.toolOrchestrator,
243
+ conversationManager: this.conversationManager,
244
+ streamingManager: this.streamingManager,
245
+ };
246
+ this.agentOSOrchestrator = new AgentOSOrchestrator();
247
+ await this.agentOSOrchestrator.initialize(this.config.orchestratorConfig, orchestratorDependencies);
248
+ this.logger.info('AgentOS orchestrator initialized');
249
+ }
250
+ catch (error) {
251
+ this.logger.error('AgentOS initialization failed', { error });
252
+ const err = error instanceof GMIError ? error : new GMIError(error instanceof Error ? error.message : 'Unknown error during AgentOS initialization', GMIErrorCode.GMI_INITIALIZATION_ERROR, // Corrected error code
253
+ error // details
254
+ );
255
+ console.error('AgentOS: Critical failure during core component initialization:', err.toJSON());
256
+ throw AgentOSServiceError.wrap(err, err.code, 'AgentOS initialization failed', 'AgentOS.initialize');
257
+ }
258
+ this.initialized = true;
259
+ this.logger.info('AgentOS initialization complete');
260
+ }
261
+ /**
262
+ * Validates the provided `AgentOSConfig` to ensure all mandatory sub-configurations
263
+ * and dependencies are present.
264
+ *
265
+ * @private
266
+ * @param {AgentOSConfig} config - The configuration object to validate.
267
+ * @throws {AgentOSServiceError} If any required configuration parameter is missing,
268
+ * with `code` set to `GMIErrorCode.CONFIGURATION_ERROR`.
269
+ */
270
+ validateConfiguration(config) {
271
+ const missingParams = [];
272
+ if (!config) {
273
+ // This case should ideally not be hit if TypeScript is used correctly at the call site,
274
+ // but as a runtime check:
275
+ missingParams.push('AgentOSConfig (entire object)');
276
+ }
277
+ else {
278
+ // Check for each required sub-configuration
279
+ const requiredConfigs = [
280
+ 'gmiManagerConfig', 'orchestratorConfig', 'promptEngineConfig',
281
+ 'toolOrchestratorConfig', 'toolPermissionManagerConfig', 'conversationManagerConfig',
282
+ 'streamingManagerConfig', 'modelProviderManagerConfig', 'defaultPersonaId',
283
+ 'authService', 'subscriptionService'
284
+ ];
285
+ for (const key of requiredConfigs) {
286
+ if (!config[key]) {
287
+ missingParams.push(String(key));
288
+ }
289
+ }
290
+ // Either storageAdapter or prisma must be provided
291
+ if (!config.storageAdapter && !config.prisma) {
292
+ missingParams.push('storageAdapter or prisma (at least one required)');
293
+ }
294
+ }
295
+ if (missingParams.length > 0) {
296
+ const message = `AgentOS Configuration Error: Missing essential parameters: ${missingParams.join(', ')}.`;
297
+ console.error(message);
298
+ throw new AgentOSServiceError(message, GMIErrorCode.CONFIGURATION_ERROR, { missingParameters: missingParams });
299
+ }
300
+ }
301
+ async registerConfigGuardrailService(context) {
302
+ if (!this.config.guardrailService) {
303
+ return;
304
+ }
305
+ const registry = this.extensionManager.getRegistry(EXTENSION_KIND_GUARDRAIL);
306
+ await registry.register({
307
+ id: 'config-guardrail-service',
308
+ kind: EXTENSION_KIND_GUARDRAIL,
309
+ payload: this.config.guardrailService,
310
+ priority: Number.MAX_SAFE_INTEGER,
311
+ metadata: { origin: 'config' },
312
+ }, context);
313
+ }
314
+ async initializeWorkflowRuntime(_context) {
315
+ this.workflowStore = this.config.workflowStore ?? new InMemoryWorkflowStore();
316
+ this.workflowEngine = new WorkflowEngine();
317
+ const workflowLogger = this.logger.child?.({ component: 'WorkflowEngine' }) ?? this.logger;
318
+ await this.workflowEngine.initialize(this.config.workflowEngineConfig ?? {}, {
319
+ store: this.workflowStore,
320
+ logger: workflowLogger,
321
+ });
322
+ const agencyLogger = this.logger.child?.({ component: 'AgencyRegistry' }) ?? this.logger;
323
+ this.agencyRegistry = new AgencyRegistry(agencyLogger);
324
+ await this.registerWorkflowDescriptorsFromRegistry();
325
+ this.workflowExtensionListener = async (event) => {
326
+ if (!this.workflowEngine) {
327
+ return;
328
+ }
329
+ if (event.type === 'descriptor:activated' && event.kind === EXTENSION_KIND_WORKFLOW) {
330
+ const descriptor = event.descriptor;
331
+ await this.handleWorkflowDescriptorActivated({
332
+ id: descriptor.id,
333
+ payload: descriptor.payload,
334
+ });
335
+ }
336
+ else if (event.type === 'descriptor:deactivated' && event.kind === EXTENSION_KIND_WORKFLOW) {
337
+ const descriptor = event.descriptor;
338
+ await this.handleWorkflowDescriptorDeactivated({
339
+ id: descriptor.id,
340
+ payload: descriptor.payload,
341
+ });
342
+ }
343
+ };
344
+ this.extensionManager.on(this.workflowExtensionListener);
345
+ this.workflowEngineListener = async (event) => {
346
+ await this.handleWorkflowEngineEvent(event);
347
+ };
348
+ this.workflowEngine.onEvent(this.workflowEngineListener);
349
+ }
350
+ async startWorkflowRuntime() {
351
+ if (!this.workflowEngine) {
352
+ return;
353
+ }
354
+ if (this.workflowRuntime) {
355
+ return;
356
+ }
357
+ if (!this.gmiManager || !this.streamingManager || !this.toolOrchestrator) {
358
+ this.logger.warn('Workflow runtime start skipped because core dependencies are not ready.');
359
+ return;
360
+ }
361
+ if (!this.agencyRegistry) {
362
+ const agencyLogger = this.logger.child?.({ component: 'AgencyRegistry' }) ?? this.logger;
363
+ this.agencyRegistry = new AgencyRegistry(agencyLogger);
364
+ }
365
+ const runtimeLogger = this.logger.child?.({ component: 'WorkflowRuntime' }) ?? this.logger;
366
+ this.workflowRuntime = new WorkflowRuntime({
367
+ workflowEngine: this.workflowEngine,
368
+ gmiManager: this.gmiManager,
369
+ streamingManager: this.streamingManager,
370
+ toolOrchestrator: this.toolOrchestrator,
371
+ extensionManager: this.extensionManager,
372
+ agencyRegistry: this.agencyRegistry,
373
+ logger: runtimeLogger,
374
+ });
375
+ await this.workflowRuntime.start();
376
+ }
377
+ async registerWorkflowDescriptorsFromRegistry() {
378
+ const registry = this.extensionManager.getRegistry(EXTENSION_KIND_WORKFLOW);
379
+ const activeDescriptors = registry.listActive();
380
+ for (const descriptor of activeDescriptors) {
381
+ await this.handleWorkflowDescriptorActivated({
382
+ id: descriptor.id,
383
+ payload: descriptor.payload,
384
+ });
385
+ }
386
+ }
387
+ async handleWorkflowDescriptorActivated(descriptor) {
388
+ try {
389
+ await this.workflowEngine.registerWorkflowDescriptor(descriptor.payload);
390
+ this.logger.debug?.('Workflow descriptor registered', {
391
+ descriptorId: descriptor.id,
392
+ workflowDefinitionId: descriptor.payload.definition.id,
393
+ });
394
+ }
395
+ catch (error) {
396
+ this.logger.error('Failed to register workflow descriptor', {
397
+ descriptorId: descriptor.id,
398
+ workflowDefinitionId: descriptor.payload.definition.id,
399
+ error,
400
+ });
401
+ }
402
+ }
403
+ async handleWorkflowDescriptorDeactivated(descriptor) {
404
+ try {
405
+ await this.workflowEngine.unregisterWorkflowDescriptor(descriptor.payload.definition.id);
406
+ this.logger.debug?.('Workflow descriptor unregistered', {
407
+ descriptorId: descriptor.id,
408
+ workflowDefinitionId: descriptor.payload.definition.id,
409
+ });
410
+ }
411
+ catch (error) {
412
+ this.logger.error('Failed to unregister workflow descriptor', {
413
+ descriptorId: descriptor.id,
414
+ workflowDefinitionId: descriptor.payload.definition.id,
415
+ error,
416
+ });
417
+ }
418
+ }
419
+ async handleWorkflowEngineEvent(event) {
420
+ try {
421
+ await this.emitWorkflowUpdate(event.workflowId);
422
+ }
423
+ catch (error) {
424
+ this.logger.error('Failed to handle workflow engine event', {
425
+ workflowId: event.workflowId,
426
+ eventType: event.type,
427
+ error,
428
+ });
429
+ }
430
+ }
431
+ async emitWorkflowUpdate(workflowId) {
432
+ if (!this.workflowEngine) {
433
+ return;
434
+ }
435
+ try {
436
+ const update = await this.workflowEngine.getWorkflowProgress(workflowId);
437
+ if (!update) {
438
+ return;
439
+ }
440
+ this.logger.debug?.('Workflow progress update ready', {
441
+ workflowId,
442
+ status: update.workflow.status,
443
+ });
444
+ if (typeof this.agentOSOrchestrator?.broadcastWorkflowUpdate === 'function') {
445
+ await this.agentOSOrchestrator.broadcastWorkflowUpdate(update);
446
+ }
447
+ else {
448
+ this.logger.warn('Workflow update could not be broadcast - orchestrator unavailable', {
449
+ workflowId,
450
+ });
451
+ }
452
+ }
453
+ catch (error) {
454
+ this.logger.error('Failed to generate workflow progress update', { workflowId, error });
455
+ }
456
+ }
457
+ getActiveGuardrailServices() {
458
+ const services = [];
459
+ if (this.extensionManager) {
460
+ const registry = this.extensionManager.getRegistry(EXTENSION_KIND_GUARDRAIL);
461
+ services.push(...registry.listActive().map((descriptor) => descriptor.payload));
462
+ }
463
+ if (this.guardrailService && !services.includes(this.guardrailService)) {
464
+ services.push(this.guardrailService);
465
+ }
466
+ return services;
467
+ }
468
+ async ensureUtilityAIService() {
469
+ if (this.utilityAIService) {
470
+ return;
471
+ }
472
+ if (this.config.utilityAIService) {
473
+ this.utilityAIService = this.config.utilityAIService;
474
+ return;
475
+ }
476
+ this.utilityAIService = await this.buildDefaultUtilityAI();
477
+ }
478
+ async buildDefaultUtilityAI() {
479
+ const fallbackUtility = new LLMUtilityAI();
480
+ const defaultProviderId = this.config.gmiManagerConfig.defaultGMIBaseConfigDefaults?.defaultLlmProviderId ||
481
+ this.config.modelProviderManagerConfig.providers[0]?.providerId ||
482
+ 'openai';
483
+ const defaultModelId = this.config.gmiManagerConfig.defaultGMIBaseConfigDefaults?.defaultLlmModelId ||
484
+ 'gpt-4o';
485
+ await fallbackUtility.initialize({
486
+ llmProviderManager: this.modelProviderManager,
487
+ defaultProviderId,
488
+ defaultModelId,
489
+ });
490
+ return fallbackUtility;
491
+ }
492
+ /**
493
+ * Ensures that the `AgentOS` service has been successfully initialized before
494
+ * attempting to perform any operations.
495
+ *
496
+ * @private
497
+ * @throws {AgentOSServiceError} If the service is not initialized, with `code`
498
+ * set to `GMIErrorCode.NOT_INITIALIZED`.
499
+ */
500
+ ensureInitialized() {
501
+ if (!this.initialized) {
502
+ throw new AgentOSServiceError('AgentOS Service is not initialized. Please call and await the initialize() method before attempting operations.', GMIErrorCode.NOT_INITIALIZED, { serviceName: 'AgentOS', operationAttemptedWhileUninitialized: true });
503
+ }
504
+ }
505
+ /**
506
+ * Processes a single interaction turn with an AI agent. This is an asynchronous generator
507
+ * that yields {@link AgentOSResponse} chunks as they become available.
508
+ *
509
+ * This method orchestrates:
510
+ * 1. Retrieval or creation of a {@link StreamId} via the {@link AgentOSOrchestrator}.
511
+ * 2. Registration of a temporary, request-scoped stream client to the {@link StreamingManager}.
512
+ * 3. Yielding of {@link AgentOSResponse} chunks received by this client.
513
+ * 4. Ensuring the temporary client is deregistered upon completion or error.
514
+ *
515
+ * The underlying {@link AgentOSOrchestrator} handles the GMI interaction and pushes
516
+ * chunks to the {@link StreamingManager}. This method acts as the bridge to make these
517
+ * chunks available as an `AsyncGenerator` to the caller (e.g., an API route handler).
518
+ *
519
+ * @public
520
+ * @async
521
+ * @generator
522
+ * @param {AgentOSInput} input - The comprehensive input for the current interaction turn.
523
+ * @yields {AgentOSResponse} Chunks of the agent's response as they are processed.
524
+ * @returns {AsyncGenerator<AgentOSResponse, void, undefined>} An asynchronous generator
525
+ * that yields response chunks. The generator completes when the interaction is finalized
526
+ * or a terminal error occurs.
527
+ * @throws {AgentOSServiceError} If a critical error occurs during setup or if the
528
+ * service is not initialized. Errors during GMI processing are typically yielded as
529
+ * `AgentOSErrorChunk`s.
530
+ */
531
+ async *processRequest(input) {
532
+ this.ensureInitialized();
533
+ // Authentication and detailed authorization would typically happen here or be delegated.
534
+ // For example:
535
+ // if (!await this.authService.isUserAuthenticated(input.sessionId, input.userId)) {
536
+ // throw new AgentOSServiceError("User not authenticated.", GMIErrorCode.AUTHENTICATION_REQUIRED);
537
+ // }
538
+ const effectivePersonaId = input.selectedPersonaId || this.config.defaultPersonaId;
539
+ const guardrailContext = {
540
+ userId: input.userId,
541
+ sessionId: input.sessionId,
542
+ personaId: effectivePersonaId,
543
+ conversationId: input.conversationId,
544
+ metadata: input.options?.customFlags,
545
+ };
546
+ const guardrailServices = this.getActiveGuardrailServices();
547
+ const guardrailReadyInput = {
548
+ ...input,
549
+ selectedPersonaId: effectivePersonaId,
550
+ };
551
+ const guardrailInputOutcome = await evaluateInputGuardrails(guardrailServices, guardrailReadyInput, guardrailContext);
552
+ const blockingEvaluation = guardrailInputOutcome.evaluation ?? guardrailInputOutcome.evaluations?.at(-1) ?? null;
553
+ if (blockingEvaluation?.action === GuardrailAction.BLOCK) {
554
+ const streamId = guardrailReadyInput.sessionId || `agentos-guardrail-${Date.now()}`;
555
+ const blockedStream = createGuardrailBlockedStream(guardrailContext, blockingEvaluation, {
556
+ streamId,
557
+ personaId: effectivePersonaId,
558
+ });
559
+ for await (const chunk of blockedStream) {
560
+ yield chunk;
561
+ }
562
+ return;
563
+ }
564
+ const orchestratorInput = {
565
+ ...guardrailInputOutcome.sanitizedInput,
566
+ selectedPersonaId: effectivePersonaId,
567
+ };
568
+ // Language negotiation (non-blocking)
569
+ let languageNegotiation = null;
570
+ if (this.languageService && this.config.languageConfig) {
571
+ try {
572
+ languageNegotiation = this.languageService.negotiate({
573
+ explicitUserLanguage: orchestratorInput.languageHint,
574
+ detectedLanguages: orchestratorInput.detectedLanguages,
575
+ conversationPreferred: undefined,
576
+ personaDefault: undefined,
577
+ configDefault: this.config.languageConfig.defaultLanguage,
578
+ supported: this.config.languageConfig.supportedLanguages,
579
+ fallbackChain: this.config.languageConfig.fallbackLanguages || [this.config.languageConfig.defaultLanguage],
580
+ preferSourceLanguageResponses: this.config.languageConfig.preferSourceLanguageResponses,
581
+ targetLanguage: orchestratorInput.targetLanguage,
582
+ });
583
+ }
584
+ catch (negErr) {
585
+ this.logger.warn('Language negotiation failed', { error: negErr?.message || negErr });
586
+ }
587
+ }
588
+ const baseStreamDebugId = orchestratorInput.sessionId || `agentos-req-${Date.now()}`;
589
+ this.logger.debug?.('processRequest invoked', {
590
+ userId: orchestratorInput.userId,
591
+ sessionId: orchestratorInput.sessionId,
592
+ personaId: orchestratorInput.selectedPersonaId,
593
+ });
594
+ let streamIdToListen;
595
+ // Temporary client bridge to adapt push-based StreamingManager to pull-based AsyncGenerator
596
+ const bridge = new AsyncStreamClientBridge(`client-processReq-${baseStreamDebugId}`);
597
+ try {
598
+ this.logger.debug?.('Registering streaming bridge for request', {
599
+ userId: orchestratorInput.userId,
600
+ sessionId: orchestratorInput.sessionId,
601
+ });
602
+ // The orchestrator creates/manages the actual stream and starts pushing chunks to StreamingManager.
603
+ // We get the streamId it uses so our bridge can listen to it.
604
+ streamIdToListen = await this.agentOSOrchestrator.orchestrateTurn({ ...orchestratorInput, languageNegotiation });
605
+ await this.streamingManager.registerClient(streamIdToListen, bridge);
606
+ this.logger.debug?.('Bridge registered', { bridgeId: bridge.id, streamId: streamIdToListen });
607
+ const guardrailWrappedStream = wrapOutputGuardrails(guardrailServices, guardrailContext, bridge.consume(), {
608
+ streamId: streamIdToListen,
609
+ personaId: effectivePersonaId,
610
+ inputEvaluations: guardrailInputOutcome.evaluations ?? [],
611
+ });
612
+ if (orchestratorInput.workflowRequest) {
613
+ const wfRequest = orchestratorInput.workflowRequest;
614
+ try {
615
+ await this.startWorkflow(wfRequest.definitionId, orchestratorInput, {
616
+ workflowId: wfRequest.workflowId,
617
+ conversationId: wfRequest.conversationId ?? orchestratorInput.conversationId ?? orchestratorInput.sessionId,
618
+ createdByUserId: orchestratorInput.userId,
619
+ context: wfRequest.context,
620
+ roleAssignments: wfRequest.roleAssignments,
621
+ metadata: wfRequest.metadata,
622
+ });
623
+ }
624
+ catch (error) {
625
+ this.logger.error('Failed to start workflow from request payload', {
626
+ workflowDefinitionId: wfRequest.definitionId,
627
+ conversationId: wfRequest.conversationId ?? orchestratorInput.conversationId,
628
+ error,
629
+ });
630
+ }
631
+ }
632
+ // Yield chunks from the guardrail-wrapped stream
633
+ for await (const chunk of guardrailWrappedStream) {
634
+ if (languageNegotiation) {
635
+ if (!chunk.metadata)
636
+ chunk.metadata = {};
637
+ chunk.metadata.language = languageNegotiation;
638
+ }
639
+ yield chunk;
640
+ if (chunk.isFinal && chunk.type !== AgentOSResponseChunkType.ERROR) {
641
+ // If a non-error chunk is final, the primary interaction part might be done.
642
+ // The stream itself might remain open for a short while for cleanup or late messages.
643
+ // The bridge's consume() will end when notifyStreamClosed is called.
644
+ break;
645
+ }
646
+ }
647
+ }
648
+ catch (error) {
649
+ const serviceError = AgentOSServiceError.wrap(error, GMIErrorCode.GMI_PROCESSING_ERROR, // Default code for facade-level processing errors
650
+ `Error during AgentOS.processRequest for user '${orchestratorInput.userId}'`, 'AgentOS.processRequest');
651
+ this.logger.error('processRequest failed', { error: serviceError, streamId: streamIdToListen });
652
+ const errorChunk = {
653
+ type: AgentOSResponseChunkType.ERROR,
654
+ streamId: streamIdToListen || baseStreamDebugId, // Use known streamId if available
655
+ gmiInstanceId: serviceError.details?.gmiInstanceId || 'agentos_facade_error',
656
+ personaId: effectivePersonaId,
657
+ isFinal: true,
658
+ timestamp: new Date().toISOString(),
659
+ code: serviceError.code.toString(),
660
+ message: serviceError.message, // Use the wrapped error's message
661
+ details: serviceError.details || { name: serviceError.name, stack: serviceError.stack },
662
+ };
663
+ yield errorChunk; // Yield the processed error
664
+ }
665
+ finally {
666
+ if (streamIdToListen) {
667
+ await this.streamingManager.deregisterClient(streamIdToListen, bridge.id).catch((deregError) => {
668
+ this.logger.warn('Failed to deregister bridge client', {
669
+ bridgeId: bridge.id,
670
+ streamId: streamIdToListen,
671
+ error: deregError.message,
672
+ });
673
+ });
674
+ }
675
+ bridge.forceClose(); // Ensure the bridge generator also terminates
676
+ }
677
+ }
678
+ /**
679
+ * Handles the result of an externally executed tool and continues the agent interaction.
680
+ * This method is an asynchronous generator that yields new {@link AgentOSResponse} chunks
681
+ * resulting from the GMI processing the tool's output.
682
+ *
683
+ * It functions similarly to `processRequest` by:
684
+ * 1. Delegating to {@link AgentOSOrchestrator.orchestrateToolResult}, which pushes new
685
+ * chunks to the *existing* `streamId`.
686
+ * 2. Registering a temporary, request-scoped stream client (bridge) to this `streamId`.
687
+ * 3. Yielding {@link AgentOSResponse} chunks received by this bridge.
688
+ * 4. Ensuring the bridge client is deregistered.
689
+ *
690
+ * @public
691
+ * @async
692
+ * @generator
693
+ * @param {StreamId} streamId - The ID of the existing stream to which the tool result pertains.
694
+ * @param {string} toolCallId - The ID of the specific tool call being responded to.
695
+ * @param {string} toolName - The name of the tool that was executed.
696
+ * @param {any} toolOutput - The output data from the tool execution.
697
+ * @param {boolean} isSuccess - Indicates whether the tool execution was successful.
698
+ * @param {string} [errorMessage] - An error message if `isSuccess` is `false`.
699
+ * @yields {AgentOSResponse} New response chunks from the agent after processing the tool result.
700
+ * @returns {AsyncGenerator<AgentOSResponse, void, undefined>} An asynchronous generator for new response chunks.
701
+ * @throws {AgentOSServiceError} If a critical error occurs during setup or if the service is not initialized.
702
+ * Errors during GMI processing are yielded as `AgentOSErrorChunk`s.
703
+ */
704
+ async *handleToolResult(streamId, toolCallId, toolName, toolOutput, isSuccess, errorMessage) {
705
+ this.ensureInitialized();
706
+ // Create a new bridge client for this specific tool result handling phase
707
+ const bridge = new AsyncStreamClientBridge(`client-toolRes-${streamId.substring(0, 8)}-${toolCallId.substring(0, 8)}`);
708
+ try {
709
+ console.log(`AgentOS.handleToolResult: Stream '${streamId}', ToolCall '${toolCallId}'. Orchestrator will push new chunks to this stream.`);
710
+ // Register the bridge client to listen for new chunks on the existing stream
711
+ await this.streamingManager.registerClient(streamId, bridge);
712
+ console.log(`AgentOS.handleToolResult: Bridge client ${bridge.id} registered to stream ${streamId}.`);
713
+ // This call is `async Promise<void>`; it triggers the orchestrator to process the tool result
714
+ // and push new chunks to the StreamingManager for the given streamId.
715
+ await this.agentOSOrchestrator.orchestrateToolResult(streamId, toolCallId, toolName, toolOutput, isSuccess, errorMessage);
716
+ // Yield new chunks received by our bridge client on the same stream
717
+ for await (const chunk of bridge.consume()) {
718
+ yield chunk;
719
+ if (chunk.isFinal && chunk.type !== AgentOSResponseChunkType.ERROR) {
720
+ break;
721
+ }
722
+ }
723
+ }
724
+ catch (error) {
725
+ const serviceError = AgentOSServiceError.wrap(error, GMIErrorCode.TOOL_ERROR, // Default code for facade-level tool result errors
726
+ `Error during AgentOS.handleToolResult for stream '${streamId}', tool '${toolName}'`, 'AgentOS.handleToolResult');
727
+ console.error(`${serviceError.name}: ${serviceError.message}`, serviceError.toJSON());
728
+ const errorChunk = {
729
+ type: AgentOSResponseChunkType.ERROR,
730
+ streamId: streamId,
731
+ gmiInstanceId: serviceError.details?.gmiInstanceId || 'agentos_facade_tool_error',
732
+ personaId: serviceError.details?.personaId || 'unknown_tool_persona',
733
+ isFinal: true,
734
+ timestamp: new Date().toISOString(),
735
+ code: serviceError.code.toString(),
736
+ message: serviceError.message,
737
+ details: serviceError.details || { name: serviceError.name, stack: serviceError.stack },
738
+ };
739
+ yield errorChunk;
740
+ }
741
+ finally {
742
+ console.log(`AgentOS.handleToolResult: Deregistering bridge client ${bridge.id} from stream ${streamId}.`);
743
+ await this.streamingManager.deregisterClient(streamId, bridge.id)
744
+ .catch(deregError => console.error(`AgentOS.handleToolResult: Error deregistering bridge client ${bridge.id}: ${deregError.message}`));
745
+ bridge.forceClose();
746
+ }
747
+ }
748
+ listWorkflowDefinitions() {
749
+ this.ensureInitialized();
750
+ return this.workflowEngine.listWorkflowDefinitions();
751
+ }
752
+ async startWorkflow(definitionId, input, options = {}) {
753
+ this.ensureInitialized();
754
+ const definition = this.workflowEngine
755
+ .listWorkflowDefinitions()
756
+ .find((item) => item.id === definitionId);
757
+ if (!definition) {
758
+ throw new AgentOSServiceError(`Workflow definition '${definitionId}' not found.`, GMIErrorCode.CONFIGURATION_ERROR, { definitionId });
759
+ }
760
+ return this.workflowEngine.startWorkflow({
761
+ input,
762
+ definition,
763
+ workflowId: options.workflowId,
764
+ conversationId: options.conversationId,
765
+ createdByUserId: options.createdByUserId,
766
+ context: options.context,
767
+ roleAssignments: options.roleAssignments,
768
+ metadata: options.metadata,
769
+ });
770
+ }
771
+ async getWorkflow(workflowId) {
772
+ this.ensureInitialized();
773
+ return this.workflowEngine.getWorkflow(workflowId);
774
+ }
775
+ async listWorkflows(options) {
776
+ this.ensureInitialized();
777
+ return this.workflowEngine.listWorkflows(options);
778
+ }
779
+ async getWorkflowProgress(workflowId, sinceTimestamp) {
780
+ this.ensureInitialized();
781
+ return this.workflowEngine.getWorkflowProgress(workflowId, sinceTimestamp);
782
+ }
783
+ async updateWorkflowStatus(workflowId, status) {
784
+ this.ensureInitialized();
785
+ return this.workflowEngine.updateWorkflowStatus(workflowId, status);
786
+ }
787
+ async applyWorkflowTaskUpdates(workflowId, updates) {
788
+ this.ensureInitialized();
789
+ return this.workflowEngine.applyTaskUpdates(workflowId, updates);
790
+ }
791
+ /**
792
+ * Lists all available personas that the requesting user (if specified) has access to.
793
+ *
794
+ * @public
795
+ * @async
796
+ * @param {string} [userId] - Optional. The ID of the user making the request. If provided,
797
+ * persona availability will be filtered based on the user's subscription tier and permissions.
798
+ * If omitted, all generally public personas might be listed (behavior determined by `GMIManager`).
799
+ * @returns {Promise<Partial<IPersonaDefinition>[]>} A promise that resolves to an array of
800
+ * persona definitions (or partial definitions suitable for public listing).
801
+ * @throws {AgentOSServiceError} If the service is not initialized.
802
+ */
803
+ async listAvailablePersonas(userId) {
804
+ this.ensureInitialized();
805
+ console.log(`AgentOS.listAvailablePersonas: Request for UserID: '${userId || "anonymous/system"}'.`);
806
+ try {
807
+ return await this.gmiManager.listAvailablePersonas(userId);
808
+ }
809
+ catch (error) {
810
+ throw AgentOSServiceError.wrap(error, GMIErrorCode.PERSONA_LOAD_ERROR, "Failed to list available personas", "AgentOS.listAvailablePersonas");
811
+ }
812
+ }
813
+ /**
814
+ * Retrieves the conversation history for a specific conversation ID, subject to user authorization.
815
+ *
816
+ * @public
817
+ * @async
818
+ * @param {string} conversationId - The unique identifier of the conversation to retrieve.
819
+ * @param {string} userId - The ID of the user requesting the history. Authorization checks
820
+ * are performed to ensure the user has access to this conversation.
821
+ * @returns {Promise<ConversationContext | null>} A promise that resolves to the
822
+ * `ConversationContext` object if found and accessible, or `null` otherwise.
823
+ * @throws {AgentOSServiceError} If the service is not initialized or if a critical error
824
+ * occurs during history retrieval (permission errors might result in `null` or specific error type).
825
+ */
826
+ async getConversationHistory(conversationId, userId) {
827
+ this.ensureInitialized();
828
+ console.log(`AgentOS.getConversationHistory: Request for ConversationID '${conversationId}', UserID '${userId}'.`);
829
+ // Authorization to access conversation history should be handled here or by the ConversationManager.
830
+ // For example, using this.authService:
831
+ // const canAccess = await this.authService.canUserAccessConversation(userId, conversationId);
832
+ // if (!canAccess) {
833
+ // console.warn(`AgentOS.getConversationHistory: User '${userId}' denied access to conversation '${conversationId}'.`);
834
+ // throw new AgentOSServiceError("Access denied to conversation history.", GMIErrorCode.PERMISSION_DENIED, { userId, conversationId });
835
+ // // Or return null, depending on desired API behavior for permission failures.
836
+ // }
837
+ try {
838
+ const context = await this.conversationManager.getConversation(conversationId);
839
+ if (context) {
840
+ // Verify ownership or access rights
841
+ if (context.getMetadata('userId') === userId /* || check other access rules */) {
842
+ return context;
843
+ }
844
+ else {
845
+ console.warn(`AgentOS.getConversationHistory: User '${userId}' attempted to access conversation '${conversationId}' belonging to another user ('${context.getMetadata('userId')}').`);
846
+ // Consider throwing PERMISSION_DENIED for explicit denial.
847
+ return null;
848
+ }
849
+ }
850
+ return null; // Conversation not found
851
+ }
852
+ catch (error) {
853
+ throw AgentOSServiceError.wrap(error, GMIErrorCode.GMI_CONTEXT_ERROR, `Failed to retrieve conversation history for ID '${conversationId}'`, "AgentOS.getConversationHistory");
854
+ }
855
+ }
856
+ /**
857
+ * Receives and processes user feedback related to a specific interaction or persona.
858
+ * The exact handling of feedback (e.g., storage, GMI adaptation) is determined by
859
+ * the configured `GMIManager` and underlying GMI implementations.
860
+ *
861
+ * @public
862
+ * @async
863
+ * @param {string} userId - The ID of the user providing the feedback.
864
+ * @param {string} sessionId - The session ID to which the feedback pertains.
865
+ * @param {string} personaId - The persona ID involved in the interaction being reviewed.
866
+ * @param {UserFeedbackPayload} feedbackPayload - The structured feedback data.
867
+ * @returns {Promise<void>} A promise that resolves when the feedback has been processed.
868
+ * @throws {AgentOSServiceError} If the service is not initialized or if an error occurs
869
+ * during feedback processing (e.g., `GMIErrorCode.GMI_FEEDBACK_ERROR`).
870
+ */
871
+ async receiveFeedback(userId, sessionId, personaId, feedbackPayload) {
872
+ this.ensureInitialized();
873
+ // Basic authorization checks for the user can be performed here.
874
+ // E.g., await this.authService.validateUserExists(userId);
875
+ console.log(`AgentOS.receiveFeedback: UserID '${userId}', SessionID '${sessionId}', PersonaID '${personaId}'. Payload:`, JSON.stringify(feedbackPayload).substring(0, 200) + "...");
876
+ try {
877
+ // Delegate feedback processing, typically to GMIManager or directly to the relevant GMI.
878
+ await this.gmiManager.processUserFeedback(userId, sessionId, personaId, feedbackPayload);
879
+ console.info(`AgentOS.receiveFeedback: Feedback processed successfully for UserID '${userId}', PersonaID '${personaId}'.`);
880
+ }
881
+ catch (error) {
882
+ throw AgentOSServiceError.wrap(error, GMIErrorCode.GMI_FEEDBACK_ERROR, "Failed to process user feedback", "AgentOS.receiveFeedback");
883
+ }
884
+ }
885
+ /**
886
+ * Initiates a graceful shutdown of the `AgentOS` service and all its components.
887
+ * This includes shutting down managers, clearing caches, and releasing resources.
888
+ *
889
+ * @public
890
+ * @async
891
+ * @returns {Promise<void>} A promise that resolves when the shutdown sequence is complete.
892
+ * @throws {AgentOSServiceError} If an error occurs during the shutdown of any critical component.
893
+ */
894
+ async shutdown() {
895
+ if (!this.initialized) {
896
+ console.warn('AgentOS Service is already shut down or was never initialized. Shutdown call is a no-op.');
897
+ return;
898
+ }
899
+ console.log('AgentOS Service: Initiating graceful shutdown sequence...');
900
+ // Order of shutdown can be important:
901
+ // 1. Orchestrator (stops new complex operations)
902
+ // 2. GMI Manager (stops GMI activities)
903
+ // 3. Streaming Manager (closes active client connections)
904
+ // 4. Other services (ConversationManager, ToolOrchestrator, PromptEngine, ModelProviderManager)
905
+ try {
906
+ if (this.workflowEngineListener && this.workflowEngine) {
907
+ this.workflowEngine.offEvent(this.workflowEngineListener);
908
+ this.workflowEngineListener = undefined;
909
+ }
910
+ if (this.workflowExtensionListener && this.extensionManager) {
911
+ this.extensionManager.off(this.workflowExtensionListener);
912
+ this.workflowExtensionListener = undefined;
913
+ }
914
+ if (this.workflowRuntime) {
915
+ await this.workflowRuntime.stop();
916
+ this.workflowRuntime = undefined;
917
+ }
918
+ this.agencyRegistry = undefined;
919
+ if (this.agentOSOrchestrator?.shutdown) {
920
+ await this.agentOSOrchestrator.shutdown();
921
+ console.log('AgentOS: AgentOSOrchestrator shut down.');
922
+ }
923
+ if (this.gmiManager?.shutdown) {
924
+ await this.gmiManager.shutdown();
925
+ console.log('AgentOS: GMIManager shut down.');
926
+ }
927
+ if (this.streamingManager?.shutdown) {
928
+ await this.streamingManager.shutdown();
929
+ console.log('AgentOS: StreamingManager shut down.');
930
+ }
931
+ if (this.conversationManager?.shutdown && typeof this.conversationManager.shutdown === 'function') {
932
+ await this.conversationManager.shutdown();
933
+ console.log('AgentOS: ConversationManager shut down.');
934
+ }
935
+ if (this.toolOrchestrator && typeof this.toolOrchestrator.shutdown === 'function') {
936
+ await this.toolOrchestrator.shutdown();
937
+ console.log('AgentOS: ToolOrchestrator shut down.');
938
+ }
939
+ // PromptEngine might have a cleanup method like clearCache
940
+ if (this.promptEngine && typeof this.promptEngine.clearCache === 'function') {
941
+ await this.promptEngine.clearCache();
942
+ console.log('AgentOS: PromptEngine cache cleared.');
943
+ }
944
+ if (this.modelProviderManager?.shutdown) {
945
+ await this.modelProviderManager.shutdown();
946
+ console.log('AgentOS: AIModelProviderManager shut down.');
947
+ }
948
+ // Other services like authService, subscriptionService, prisma might not have explicit async shutdown methods
949
+ // if they manage connections passively or are handled by process exit.
950
+ console.log('AgentOS Service: Graceful shutdown completed successfully.');
951
+ }
952
+ catch (error) {
953
+ // Even if one component fails to shut down, attempt to log and continue if possible,
954
+ // but report the overall failure.
955
+ const serviceError = AgentOSServiceError.wrap(error, GMIErrorCode.GMI_SHUTDOWN_ERROR, "Error during AgentOS service shutdown sequence", "AgentOS.shutdown");
956
+ console.error(`${serviceError.name}: ${serviceError.message}`, serviceError.toJSON());
957
+ throw serviceError; // Re-throw to indicate shutdown was problematic.
958
+ }
959
+ finally {
960
+ this.initialized = false; // Mark as uninitialized regardless of shutdown errors.
961
+ }
962
+ }
963
+ }
964
+ /**
965
+ * @class AsyncStreamClientBridge
966
+ * @implements {IStreamClient}
967
+ * @description
968
+ * A helper class that acts as an {@link IStreamClient} to bridge the push-based
969
+ * data flow from `StreamingManager` to a pull-based `AsyncGenerator` consumable
970
+ * by methods like `AgentOS.processRequest`.
971
+ *
972
+ * This class queues incoming chunks and uses promises to signal availability
973
+ * to a consuming async generator loop. It handles stream closure notifications
974
+ * to terminate the generator.
975
+ *
976
+ * @internal This class is intended for internal use within `AgentOS.ts` or similar facades.
977
+ */
978
+ class AsyncStreamClientBridge {
979
+ /**
980
+ * Creates an instance of `AsyncStreamClientBridge`.
981
+ * @param {string} [debugIdPrefix='bridge-client'] - A prefix for generating a unique debug ID.
982
+ */
983
+ constructor(debugIdPrefix = 'bridge-client') {
984
+ this.chunkQueue = [];
985
+ this.resolveNextChunkPromise = null;
986
+ this.rejectNextChunkPromise = null; // Added for error propagation
987
+ this.streamClosed = false;
988
+ this.processingError = null;
989
+ this.id = `${debugIdPrefix}-${uuidv4()}`;
990
+ }
991
+ /**
992
+ * Receives a chunk from the `StreamingManager` and makes it available to the consumer.
993
+ * If a consumer is awaiting a chunk, its promise is resolved. Otherwise, the chunk is queued.
994
+ *
995
+ * @public
996
+ * @async
997
+ * @param {AgentOSResponse} chunk - The data chunk received from the stream.
998
+ * @returns {Promise<void>} A promise that resolves when the chunk has been processed by the bridge.
999
+ */
1000
+ async sendChunk(chunk) {
1001
+ if (this.streamClosed) {
1002
+ console.warn(`AsyncStreamClientBridge (${this.id}): Received chunk on already closed stream. Chunk ignored.`, chunk.type);
1003
+ return;
1004
+ }
1005
+ this.chunkQueue.push(chunk);
1006
+ if (this.resolveNextChunkPromise) {
1007
+ const resolve = this.resolveNextChunkPromise;
1008
+ this.resolveNextChunkPromise = null; // Consume resolver
1009
+ this.rejectNextChunkPromise = null;
1010
+ // The queue is guaranteed to have at least one item here.
1011
+ resolve({ value: this.chunkQueue.shift(), done: false });
1012
+ }
1013
+ }
1014
+ /**
1015
+ * Called by `StreamingManager` when the stream this client is subscribed to is closed.
1016
+ * Signals the consuming async generator to terminate.
1017
+ *
1018
+ * @public
1019
+ * @async
1020
+ * @param {string} [reason] - Optional reason for stream closure.
1021
+ * @returns {Promise<void>} A promise that resolves when closure notification is handled.
1022
+ */
1023
+ async notifyStreamClosed(reason) {
1024
+ if (this.streamClosed)
1025
+ return; // Idempotent
1026
+ console.log(`AsyncStreamClientBridge (${this.id}): Stream closed. Reason: ${reason || 'N/A'}`);
1027
+ this.streamClosed = true;
1028
+ if (this.resolveNextChunkPromise) {
1029
+ const resolve = this.resolveNextChunkPromise;
1030
+ this.resolveNextChunkPromise = null; // Consume resolver
1031
+ this.rejectNextChunkPromise = null;
1032
+ resolve({ value: undefined, done: true });
1033
+ }
1034
+ }
1035
+ /**
1036
+ * Forcibly closes the bridge from the consumer side, typically in a `finally` block.
1037
+ * This ensures that if the consumer loop breaks for any reason, the pending promise
1038
+ * for the next chunk is resolved, preventing hangs.
1039
+ * @public
1040
+ */
1041
+ forceClose() {
1042
+ if (!this.streamClosed) {
1043
+ this.streamClosed = true;
1044
+ if (this.resolveNextChunkPromise) {
1045
+ const resolve = this.resolveNextChunkPromise;
1046
+ this.resolveNextChunkPromise = null;
1047
+ this.rejectNextChunkPromise = null;
1048
+ resolve({ value: undefined, done: true });
1049
+ }
1050
+ }
1051
+ }
1052
+ /**
1053
+ * Reports whether the client bridge considers the stream active.
1054
+ * The stream is inactive if `notifyStreamClosed` or `forceClose` has been called.
1055
+ *
1056
+ * @public
1057
+ * @returns {boolean} `true` if the stream is considered active by the bridge, `false` otherwise.
1058
+ */
1059
+ isActive() {
1060
+ return !this.streamClosed;
1061
+ }
1062
+ /**
1063
+ * Optional. Handles explicit closure requests, primarily for resource cleanup if any were held.
1064
+ * For this bridge, it mainly ensures the `streamClosed` flag is set.
1065
+ *
1066
+ * @public
1067
+ * @async
1068
+ * @param {string} [reason] - Optional reason for closing.
1069
+ * @returns {Promise<void>}
1070
+ */
1071
+ async close(reason) {
1072
+ console.log(`AsyncStreamClientBridge (${this.id}): Explicitly closed. Reason: ${reason || 'N/A'}`);
1073
+ this.forceClose();
1074
+ }
1075
+ /**
1076
+ * Consumes chunks from this bridge as an asynchronous generator.
1077
+ * This method is intended to be used by the `AgentOS` facade methods.
1078
+ *
1079
+ * @public
1080
+ * @async
1081
+ * @generator
1082
+ * @yields {AgentOSResponse} Chunks of data as they arrive.
1083
+ * @returns {AsyncGenerator<AgentOSResponse, void, undefined>}
1084
+ * @throws {Error} If an internal error occurs within the bridge's consumption logic or if `_reportError` was called.
1085
+ */
1086
+ async *consume() {
1087
+ try {
1088
+ while (true) {
1089
+ if (this.chunkQueue.length > 0) {
1090
+ yield this.chunkQueue.shift();
1091
+ continue; // Check queue again before potentially awaiting
1092
+ }
1093
+ if (this.streamClosed) {
1094
+ // If stream closed and queue is empty, iteration is done.
1095
+ break;
1096
+ }
1097
+ if (this.processingError) {
1098
+ const errToThrow = this.processingError;
1099
+ this.processingError = null; // Consume error
1100
+ throw errToThrow;
1101
+ }
1102
+ // Wait for the next chunk or stream closure
1103
+ const result = await new Promise((resolve, reject) => {
1104
+ this.resolveNextChunkPromise = resolve;
1105
+ this.rejectNextChunkPromise = reject; // Store reject
1106
+ // After setting up promises, re-check conditions in case state changed during setup.
1107
+ // This handles rapid, synchronous calls to sendChunk or notifyStreamClosed.
1108
+ if (this.chunkQueue.length > 0) {
1109
+ if (this.resolveNextChunkPromise)
1110
+ this.resolveNextChunkPromise({ value: this.chunkQueue.shift(), done: false });
1111
+ this.resolveNextChunkPromise = null;
1112
+ this.rejectNextChunkPromise = null;
1113
+ }
1114
+ else if (this.streamClosed) {
1115
+ if (this.resolveNextChunkPromise)
1116
+ this.resolveNextChunkPromise({ value: undefined, done: true });
1117
+ this.resolveNextChunkPromise = null;
1118
+ this.rejectNextChunkPromise = null;
1119
+ }
1120
+ else if (this.processingError) {
1121
+ if (this.rejectNextChunkPromise)
1122
+ this.rejectNextChunkPromise(this.processingError);
1123
+ this.processingError = null;
1124
+ this.resolveNextChunkPromise = null;
1125
+ this.rejectNextChunkPromise = null;
1126
+ }
1127
+ });
1128
+ if (result.done) {
1129
+ break;
1130
+ }
1131
+ const nextChunk = result.value;
1132
+ if (!nextChunk) {
1133
+ continue;
1134
+ }
1135
+ yield nextChunk;
1136
+ }
1137
+ }
1138
+ catch (error) {
1139
+ console.error(`AsyncStreamClientBridge (${this.id}): Error during consumption loop.`, error);
1140
+ // Ensure the generator terminates properly even if an error is thrown from the promise
1141
+ this.streamClosed = true;
1142
+ if (this.resolveNextChunkPromise) { // Clean up any lingering promise resolver
1143
+ this.resolveNextChunkPromise({ value: undefined, done: true });
1144
+ this.resolveNextChunkPromise = null;
1145
+ this.rejectNextChunkPromise = null;
1146
+ }
1147
+ throw error; // Re-throw the error to be caught by the consumer of the generator
1148
+ }
1149
+ finally {
1150
+ // Final cleanup of resolvers
1151
+ this.resolveNextChunkPromise = null;
1152
+ this.rejectNextChunkPromise = null;
1153
+ this.streamClosed = true; // Ensure it's marked closed
1154
+ }
1155
+ }
1156
+ }
1157
+ //# sourceMappingURL=AgentOS.js.map