@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,1015 @@
1
+ /**
2
+ * @file StructuredOutputManager.ts
3
+ * @description Implementation of the Structured Output Manager for AgentOS.
4
+ *
5
+ * Provides robust JSON Schema validation, structured generation strategies,
6
+ * and parallel function calling capabilities. Handles the complexity of
7
+ * different LLM provider APIs and output formats.
8
+ *
9
+ * @module AgentOS/Structured
10
+ * @version 1.0.0
11
+ */
12
+ import { StructuredOutputError, } from './IStructuredOutputManager.js';
13
+ /** Convert ModelUsage to TokenUsage */
14
+ function convertUsage(usage) {
15
+ if (!usage)
16
+ return undefined;
17
+ return {
18
+ promptTokens: usage.promptTokens ?? 0,
19
+ completionTokens: usage.completionTokens ?? 0,
20
+ totalTokens: usage.totalTokens ?? 0,
21
+ };
22
+ }
23
+ /**
24
+ * Known provider capabilities.
25
+ */
26
+ const PROVIDER_CAPABILITIES = {
27
+ openai: {
28
+ supportsJsonMode: true,
29
+ supportsFunctionCalling: true,
30
+ supportsParallelCalls: true,
31
+ supportsStrictMode: true,
32
+ maxFunctionsPerCall: 128,
33
+ },
34
+ anthropic: {
35
+ supportsJsonMode: false,
36
+ supportsFunctionCalling: true,
37
+ supportsParallelCalls: true,
38
+ supportsStrictMode: false,
39
+ maxFunctionsPerCall: 64,
40
+ },
41
+ openrouter: {
42
+ supportsJsonMode: true,
43
+ supportsFunctionCalling: true,
44
+ supportsParallelCalls: true,
45
+ supportsStrictMode: false,
46
+ maxFunctionsPerCall: 64,
47
+ },
48
+ ollama: {
49
+ supportsJsonMode: true,
50
+ supportsFunctionCalling: false,
51
+ supportsParallelCalls: false,
52
+ supportsStrictMode: false,
53
+ maxFunctionsPerCall: 0,
54
+ },
55
+ default: {
56
+ supportsJsonMode: false,
57
+ supportsFunctionCalling: false,
58
+ supportsParallelCalls: false,
59
+ supportsStrictMode: false,
60
+ maxFunctionsPerCall: 0,
61
+ },
62
+ };
63
+ // ============================================================================
64
+ // Implementation
65
+ // ============================================================================
66
+ /**
67
+ * Structured Output Manager implementation.
68
+ *
69
+ * Provides comprehensive structured output capabilities including:
70
+ * - JSON Schema validation with detailed error reporting
71
+ * - Multiple generation strategies (JSON mode, function calling, prompt engineering)
72
+ * - Automatic retry with feedback on validation failures
73
+ * - Parallel function calling with argument validation
74
+ * - Entity extraction from unstructured text
75
+ * - Robust JSON parsing with error recovery
76
+ *
77
+ * @implements {IStructuredOutputManager}
78
+ */
79
+ export class StructuredOutputManager {
80
+ /**
81
+ * Creates a new StructuredOutputManager instance.
82
+ *
83
+ * @param config - Configuration options
84
+ */
85
+ constructor(config) {
86
+ /** Registered schemas for reuse */
87
+ this.schemas = new Map();
88
+ /** Statistics tracking */
89
+ this.stats = {
90
+ totalGenerations: 0,
91
+ successfulGenerations: 0,
92
+ successRate: 0,
93
+ avgRetries: 0,
94
+ avgLatencyMs: 0,
95
+ byStrategy: {
96
+ json_mode: 0,
97
+ function_calling: 0,
98
+ grammar: 0,
99
+ prompt_engineering: 0,
100
+ auto: 0,
101
+ },
102
+ topValidationErrors: [],
103
+ totalTokensUsed: 0,
104
+ };
105
+ this.totalRetries = 0;
106
+ this.totalLatencyMs = 0;
107
+ this.validationErrorCounts = new Map();
108
+ this.llmProviderManager = config.llmProviderManager;
109
+ this.defaultProviderId = config.defaultProviderId || 'openai';
110
+ this.defaultModelId = config.defaultModelId || 'gpt-4o';
111
+ this.defaultMaxRetries = config.defaultMaxRetries ?? 3;
112
+ this.defaultTimeoutMs = config.defaultTimeoutMs ?? 30000;
113
+ this.logger = config.logger;
114
+ }
115
+ /**
116
+ * Initializes the manager.
117
+ */
118
+ async initialize(logger) {
119
+ this.logger = logger || this.logger;
120
+ this.logger?.info?.('StructuredOutputManager initialized');
121
+ }
122
+ /**
123
+ * Generates structured output conforming to the given schema.
124
+ */
125
+ async generate(options) {
126
+ const startTime = Date.now();
127
+ this.stats.totalGenerations++;
128
+ const providerId = options.providerId || this.defaultProviderId;
129
+ const modelId = options.modelId || this.defaultModelId;
130
+ const maxRetries = options.maxRetries ?? this.defaultMaxRetries;
131
+ const strategy = options.strategy === 'auto' || !options.strategy
132
+ ? this.recommendStrategy(providerId, modelId, options.schema)
133
+ : options.strategy;
134
+ this.stats.byStrategy[strategy]++;
135
+ this.logger?.debug?.('Starting structured generation', {
136
+ schemaName: options.schemaName,
137
+ strategy,
138
+ providerId,
139
+ modelId,
140
+ });
141
+ let lastResult;
142
+ let retryCount = 0;
143
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
144
+ try {
145
+ const result = await this.executeGeneration(options, strategy, providerId, modelId, attempt);
146
+ if (result.success) {
147
+ this.stats.successfulGenerations++;
148
+ this.totalRetries += retryCount;
149
+ this.totalLatencyMs += Date.now() - startTime;
150
+ this.updateStats();
151
+ return {
152
+ ...result,
153
+ retryCount,
154
+ latencyMs: Date.now() - startTime,
155
+ };
156
+ }
157
+ lastResult = result;
158
+ retryCount++;
159
+ // Track validation errors
160
+ result.validationErrors?.forEach(err => {
161
+ const count = this.validationErrorCounts.get(err.keyword) || 0;
162
+ this.validationErrorCounts.set(err.keyword, count + 1);
163
+ });
164
+ this.logger?.warn?.('Structured generation validation failed, retrying', {
165
+ attempt,
166
+ errors: result.validationErrors?.map(e => e.message),
167
+ });
168
+ }
169
+ catch (error) {
170
+ this.logger?.error?.('Structured generation error', {
171
+ attempt,
172
+ error: error instanceof Error ? error.message : String(error),
173
+ });
174
+ if (attempt === maxRetries) {
175
+ throw error;
176
+ }
177
+ }
178
+ }
179
+ // All retries exhausted
180
+ this.totalRetries += retryCount;
181
+ this.totalLatencyMs += Date.now() - startTime;
182
+ this.updateStats();
183
+ const finalResult = lastResult || {
184
+ success: false,
185
+ rawOutput: '',
186
+ strategyUsed: strategy,
187
+ retryCount,
188
+ latencyMs: Date.now() - startTime,
189
+ modelId,
190
+ providerId,
191
+ };
192
+ throw new StructuredOutputError(`Failed to generate valid structured output after ${maxRetries} retries`, finalResult.validationErrors || [], finalResult.rawOutput, retryCount, strategy);
193
+ }
194
+ /**
195
+ * Executes a single generation attempt.
196
+ */
197
+ async executeGeneration(options, strategy, providerId, modelId, attempt) {
198
+ const messages = this.buildMessages(options, strategy, attempt);
199
+ // Build LLM request options based on strategy
200
+ const llmOptions = {
201
+ temperature: options.temperature ?? 0.1,
202
+ maxTokens: options.maxTokens,
203
+ };
204
+ if (strategy === 'json_mode') {
205
+ llmOptions.responseFormat = { type: 'json_object' };
206
+ }
207
+ else if (strategy === 'function_calling') {
208
+ llmOptions.tools = [
209
+ {
210
+ type: 'function',
211
+ function: {
212
+ name: options.schemaName,
213
+ description: options.schemaDescription || `Generate ${options.schemaName}`,
214
+ parameters: options.schema,
215
+ strict: options.strict,
216
+ },
217
+ },
218
+ ];
219
+ llmOptions.toolChoice = { type: 'function', function: { name: options.schemaName } };
220
+ }
221
+ // Make LLM call
222
+ const provider = this.llmProviderManager.getProvider(providerId);
223
+ if (!provider) {
224
+ throw new StructuredOutputError(`Provider "${providerId}" not found`, [], '', 0, strategy);
225
+ }
226
+ const completion = await provider.generateCompletion(modelId, messages, llmOptions);
227
+ const firstChoice = completion.choices?.[0];
228
+ // Extract output based on strategy
229
+ let rawOutput;
230
+ let reasoning;
231
+ if (strategy === 'function_calling' && firstChoice?.message?.tool_calls?.length) {
232
+ rawOutput = firstChoice.message.tool_calls[0].function.arguments;
233
+ }
234
+ else {
235
+ const content = firstChoice?.message?.content;
236
+ rawOutput = typeof content === 'string' ? content : '';
237
+ // Extract reasoning if present
238
+ if (options.includeReasoning) {
239
+ const reasoningMatch = rawOutput.match(/<reasoning>([\s\S]*?)<\/reasoning>/);
240
+ if (reasoningMatch) {
241
+ reasoning = reasoningMatch[1].trim();
242
+ rawOutput = rawOutput.replace(/<reasoning>[\s\S]*?<\/reasoning>/, '').trim();
243
+ }
244
+ }
245
+ }
246
+ // Parse JSON
247
+ const parsed = this.parseJSON(rawOutput);
248
+ if (parsed === null) {
249
+ return {
250
+ success: false,
251
+ rawOutput,
252
+ validationErrors: [
253
+ {
254
+ path: '',
255
+ message: 'Failed to parse JSON from output',
256
+ keyword: 'parse',
257
+ severity: 'error',
258
+ },
259
+ ],
260
+ strategyUsed: strategy,
261
+ retryCount: attempt,
262
+ latencyMs: 0,
263
+ reasoning,
264
+ modelId,
265
+ providerId,
266
+ tokenUsage: convertUsage(completion.usage),
267
+ };
268
+ }
269
+ // Validate against schema
270
+ const validationErrors = this.validate(parsed, options.schema, options.strict);
271
+ // Run custom validator if provided
272
+ if (options.customValidator && validationErrors.length === 0) {
273
+ const customErrors = options.customValidator(parsed);
274
+ validationErrors.push(...customErrors);
275
+ }
276
+ if (validationErrors.length > 0) {
277
+ return {
278
+ success: false,
279
+ rawOutput,
280
+ validationErrors,
281
+ strategyUsed: strategy,
282
+ retryCount: attempt,
283
+ latencyMs: 0,
284
+ reasoning,
285
+ modelId,
286
+ providerId,
287
+ tokenUsage: convertUsage(completion.usage),
288
+ };
289
+ }
290
+ // Track tokens
291
+ if (completion.usage) {
292
+ this.stats.totalTokensUsed += completion.usage.totalTokens || 0;
293
+ }
294
+ return {
295
+ success: true,
296
+ data: parsed,
297
+ rawOutput,
298
+ strategyUsed: strategy,
299
+ retryCount: attempt,
300
+ latencyMs: 0,
301
+ reasoning,
302
+ modelId,
303
+ providerId,
304
+ tokenUsage: convertUsage(completion.usage),
305
+ };
306
+ }
307
+ /**
308
+ * Builds messages for the LLM request.
309
+ */
310
+ buildMessages(options, strategy, attempt) {
311
+ const messages = [];
312
+ // System prompt
313
+ let systemPrompt = options.systemPrompt || '';
314
+ if (strategy === 'json_mode' || strategy === 'prompt_engineering') {
315
+ systemPrompt += `\n\nYou must respond with valid JSON that conforms to this schema:\n${JSON.stringify(options.schema, null, 2)}`;
316
+ if (options.includeReasoning) {
317
+ systemPrompt += '\n\nBefore the JSON, you may include your reasoning wrapped in <reasoning></reasoning> tags.';
318
+ }
319
+ systemPrompt += '\n\nRespond ONLY with the JSON (and optional reasoning). No other text.';
320
+ }
321
+ if (systemPrompt) {
322
+ messages.push({ role: 'system', content: systemPrompt.trim() });
323
+ }
324
+ // User prompt
325
+ if (typeof options.prompt === 'string') {
326
+ messages.push({ role: 'user', content: options.prompt });
327
+ }
328
+ else {
329
+ messages.push(...options.prompt.map(m => ({
330
+ role: m.role,
331
+ content: m.content,
332
+ })));
333
+ }
334
+ // Add retry feedback if this is a retry
335
+ if (attempt > 0) {
336
+ messages.push({
337
+ role: 'user',
338
+ content: `Your previous response did not conform to the required schema. Please try again, ensuring the output is valid JSON matching the schema exactly.`,
339
+ });
340
+ }
341
+ return messages;
342
+ }
343
+ /**
344
+ * Generates parallel function/tool calls.
345
+ */
346
+ async generateFunctionCalls(options) {
347
+ const startTime = Date.now();
348
+ const providerId = options.providerId || this.defaultProviderId;
349
+ const modelId = options.modelId || this.defaultModelId;
350
+ const capabilities = PROVIDER_CAPABILITIES[providerId] || PROVIDER_CAPABILITIES.default;
351
+ if (!capabilities.supportsFunctionCalling) {
352
+ throw new Error(`Provider ${providerId} does not support function calling`);
353
+ }
354
+ // Build messages
355
+ const messages = typeof options.prompt === 'string'
356
+ ? [{ role: 'user', content: options.prompt }]
357
+ : options.prompt.map(m => ({ role: m.role, content: m.content }));
358
+ // Build tools
359
+ const tools = options.functions.map(fn => ({
360
+ type: 'function',
361
+ function: {
362
+ name: fn.name,
363
+ description: fn.description,
364
+ parameters: fn.parameters,
365
+ },
366
+ }));
367
+ // Make LLM call
368
+ const provider = this.llmProviderManager.getProvider(providerId);
369
+ if (!provider) {
370
+ throw new StructuredOutputError(`Provider "${providerId}" not found`, [], '', 0, 'function_calling');
371
+ }
372
+ const completion = await provider.generateCompletion(modelId, messages, {
373
+ tools,
374
+ toolChoice: options.toolChoice || 'auto',
375
+ temperature: 0.1,
376
+ });
377
+ const toolCalls = completion.choices?.[0]?.message?.tool_calls;
378
+ // Process tool calls
379
+ const calls = [];
380
+ if (toolCalls) {
381
+ for (const toolCall of toolCalls) {
382
+ const fn = options.functions.find(f => f.name === toolCall.function.name);
383
+ const args = this.parseJSON(toolCall.function.arguments) || {};
384
+ // Validate arguments
385
+ let validationErrors = [];
386
+ if (fn) {
387
+ // Use non-strict validation for function arguments by default
388
+ // to allow providers to add extra metadata
389
+ validationErrors = this.validate(args, fn.parameters, false);
390
+ }
391
+ const callResult = {
392
+ functionName: toolCall.function.name,
393
+ arguments: args,
394
+ argumentsValid: validationErrors.length === 0,
395
+ validationErrors: validationErrors.length > 0 ? validationErrors : undefined,
396
+ callId: toolCall.id || `call-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
397
+ };
398
+ // Execute handler if provided and arguments are valid
399
+ if (fn?.handler && callResult.argumentsValid) {
400
+ try {
401
+ callResult.executionResult = await fn.handler(args);
402
+ }
403
+ catch (error) {
404
+ callResult.executionError = error instanceof Error ? error.message : String(error);
405
+ }
406
+ }
407
+ calls.push(callResult);
408
+ }
409
+ }
410
+ const textContent = completion.choices?.[0]?.message?.content;
411
+ return {
412
+ success: calls.every(c => c.argumentsValid && !c.executionError),
413
+ calls,
414
+ textContent: typeof textContent === 'string' ? textContent : undefined,
415
+ tokenUsage: convertUsage(completion.usage),
416
+ latencyMs: Date.now() - startTime,
417
+ modelId,
418
+ providerId,
419
+ };
420
+ }
421
+ /**
422
+ * Extracts structured entities from unstructured text.
423
+ */
424
+ async extractEntities(options) {
425
+ const providerId = options.providerId || this.defaultProviderId;
426
+ const modelId = options.modelId || this.defaultModelId;
427
+ // Build extraction schema
428
+ const extractionSchema = options.extractAll
429
+ ? {
430
+ type: 'object',
431
+ properties: {
432
+ entities: {
433
+ type: 'array',
434
+ items: options.entitySchema,
435
+ description: 'List of extracted entities',
436
+ },
437
+ },
438
+ required: ['entities'],
439
+ }
440
+ : {
441
+ type: 'object',
442
+ properties: {
443
+ entity: options.entitySchema,
444
+ found: { type: 'boolean', description: 'Whether an entity was found' },
445
+ },
446
+ required: ['found'],
447
+ };
448
+ // Build prompt
449
+ let prompt = `Extract ${options.taskName} from the following text:\n\n"${options.text}"`;
450
+ if (options.instructions) {
451
+ prompt += `\n\nInstructions: ${options.instructions}`;
452
+ }
453
+ if (options.examples && options.examples.length > 0) {
454
+ prompt += '\n\nExamples:\n';
455
+ options.examples.forEach((ex, i) => {
456
+ prompt += `\nExample ${i + 1}:\nInput: "${ex.input}"\nOutput: ${JSON.stringify(ex.output)}\n`;
457
+ });
458
+ }
459
+ try {
460
+ const result = await this.generate({
461
+ prompt,
462
+ schema: extractionSchema,
463
+ schemaName: `${options.taskName}Extraction`,
464
+ providerId,
465
+ modelId,
466
+ temperature: 0.1,
467
+ });
468
+ if (!result.success) {
469
+ return {
470
+ success: false,
471
+ entities: [],
472
+ issues: result.validationErrors?.map(e => e.message),
473
+ tokenUsage: result.tokenUsage,
474
+ };
475
+ }
476
+ const entities = options.extractAll
477
+ ? result.data?.entities || []
478
+ : result.data?.found
479
+ ? [result.data.entity]
480
+ : [];
481
+ return {
482
+ success: true,
483
+ entities,
484
+ tokenUsage: result.tokenUsage,
485
+ };
486
+ }
487
+ catch (error) {
488
+ return {
489
+ success: false,
490
+ entities: [],
491
+ issues: [error instanceof Error ? error.message : String(error)],
492
+ };
493
+ }
494
+ }
495
+ /**
496
+ * Validates data against a JSON Schema.
497
+ */
498
+ validate(data, schema, strict) {
499
+ const issues = [];
500
+ this.validateValue(data, schema, '', issues, strict || false);
501
+ return issues;
502
+ }
503
+ /**
504
+ * Recursively validates a value against a schema.
505
+ */
506
+ validateValue(value, schema, path, issues, strict) {
507
+ // Handle $ref
508
+ if (schema.$ref) {
509
+ const refName = schema.$ref.replace('#/$defs/', '');
510
+ const refSchema = schema.$defs?.[refName] || this.schemas.get(refName);
511
+ if (refSchema) {
512
+ this.validateValue(value, refSchema, path, issues, strict);
513
+ return;
514
+ }
515
+ }
516
+ // Handle composition keywords
517
+ if (schema.allOf) {
518
+ schema.allOf.forEach((subSchema, i) => {
519
+ this.validateValue(value, subSchema, `${path}/allOf[${i}]`, issues, strict);
520
+ });
521
+ }
522
+ if (schema.anyOf) {
523
+ const anyValid = schema.anyOf.some(subSchema => {
524
+ const subIssues = [];
525
+ this.validateValue(value, subSchema, path, subIssues, strict);
526
+ return subIssues.length === 0;
527
+ });
528
+ if (!anyValid) {
529
+ issues.push({
530
+ path,
531
+ message: 'Value does not match any of the allowed schemas',
532
+ keyword: 'anyOf',
533
+ severity: 'error',
534
+ });
535
+ }
536
+ }
537
+ if (schema.oneOf) {
538
+ const validCount = schema.oneOf.filter(subSchema => {
539
+ const subIssues = [];
540
+ this.validateValue(value, subSchema, path, subIssues, strict);
541
+ return subIssues.length === 0;
542
+ }).length;
543
+ if (validCount !== 1) {
544
+ issues.push({
545
+ path,
546
+ message: `Value must match exactly one schema, but matched ${validCount}`,
547
+ keyword: 'oneOf',
548
+ severity: 'error',
549
+ });
550
+ }
551
+ }
552
+ // Type validation
553
+ if (schema.type) {
554
+ const types = Array.isArray(schema.type) ? schema.type : [schema.type];
555
+ if (!this.matchesType(value, types)) {
556
+ const actualType = this.getJSONType(value);
557
+ issues.push({
558
+ path,
559
+ message: `Expected type ${types.join(' or ')}, got ${actualType}`,
560
+ keyword: 'type',
561
+ expected: types,
562
+ actual: actualType,
563
+ severity: 'error',
564
+ });
565
+ return; // Don't continue validation if type is wrong
566
+ }
567
+ }
568
+ // Enum validation
569
+ if (schema.enum !== undefined) {
570
+ if (!schema.enum.includes(value)) {
571
+ issues.push({
572
+ path,
573
+ message: `Value must be one of: ${schema.enum.map(v => JSON.stringify(v)).join(', ')}`,
574
+ keyword: 'enum',
575
+ expected: schema.enum,
576
+ actual: value,
577
+ severity: 'error',
578
+ });
579
+ }
580
+ }
581
+ // Const validation
582
+ if (schema.const !== undefined) {
583
+ if (value !== schema.const) {
584
+ issues.push({
585
+ path,
586
+ message: `Value must be exactly ${JSON.stringify(schema.const)}`,
587
+ keyword: 'const',
588
+ expected: schema.const,
589
+ actual: value,
590
+ severity: 'error',
591
+ });
592
+ }
593
+ }
594
+ // String validations
595
+ if (typeof value === 'string') {
596
+ if (schema.minLength !== undefined && value.length < schema.minLength) {
597
+ issues.push({
598
+ path,
599
+ message: `String must be at least ${schema.minLength} characters`,
600
+ keyword: 'minLength',
601
+ expected: schema.minLength,
602
+ actual: value.length,
603
+ severity: 'error',
604
+ });
605
+ }
606
+ if (schema.maxLength !== undefined && value.length > schema.maxLength) {
607
+ issues.push({
608
+ path,
609
+ message: `String must be at most ${schema.maxLength} characters`,
610
+ keyword: 'maxLength',
611
+ expected: schema.maxLength,
612
+ actual: value.length,
613
+ severity: 'error',
614
+ });
615
+ }
616
+ if (schema.pattern) {
617
+ const regex = new RegExp(schema.pattern);
618
+ if (!regex.test(value)) {
619
+ issues.push({
620
+ path,
621
+ message: `String must match pattern: ${schema.pattern}`,
622
+ keyword: 'pattern',
623
+ expected: schema.pattern,
624
+ actual: value,
625
+ severity: 'error',
626
+ });
627
+ }
628
+ }
629
+ if (schema.format) {
630
+ const formatValid = this.validateFormat(value, schema.format);
631
+ if (!formatValid) {
632
+ issues.push({
633
+ path,
634
+ message: `String must be a valid ${schema.format}`,
635
+ keyword: 'format',
636
+ expected: schema.format,
637
+ actual: value,
638
+ severity: 'error',
639
+ });
640
+ }
641
+ }
642
+ }
643
+ // Number validations
644
+ if (typeof value === 'number') {
645
+ if (schema.minimum !== undefined && value < schema.minimum) {
646
+ issues.push({
647
+ path,
648
+ message: `Value must be >= ${schema.minimum}`,
649
+ keyword: 'minimum',
650
+ expected: schema.minimum,
651
+ actual: value,
652
+ severity: 'error',
653
+ });
654
+ }
655
+ if (schema.maximum !== undefined && value > schema.maximum) {
656
+ issues.push({
657
+ path,
658
+ message: `Value must be <= ${schema.maximum}`,
659
+ keyword: 'maximum',
660
+ expected: schema.maximum,
661
+ actual: value,
662
+ severity: 'error',
663
+ });
664
+ }
665
+ if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) {
666
+ issues.push({
667
+ path,
668
+ message: `Value must be > ${schema.exclusiveMinimum}`,
669
+ keyword: 'exclusiveMinimum',
670
+ expected: schema.exclusiveMinimum,
671
+ actual: value,
672
+ severity: 'error',
673
+ });
674
+ }
675
+ if (schema.exclusiveMaximum !== undefined && value >= schema.exclusiveMaximum) {
676
+ issues.push({
677
+ path,
678
+ message: `Value must be < ${schema.exclusiveMaximum}`,
679
+ keyword: 'exclusiveMaximum',
680
+ expected: schema.exclusiveMaximum,
681
+ actual: value,
682
+ severity: 'error',
683
+ });
684
+ }
685
+ if (schema.multipleOf !== undefined && value % schema.multipleOf !== 0) {
686
+ issues.push({
687
+ path,
688
+ message: `Value must be a multiple of ${schema.multipleOf}`,
689
+ keyword: 'multipleOf',
690
+ expected: schema.multipleOf,
691
+ actual: value,
692
+ severity: 'error',
693
+ });
694
+ }
695
+ }
696
+ // Array validations
697
+ if (Array.isArray(value)) {
698
+ if (schema.minItems !== undefined && value.length < schema.minItems) {
699
+ issues.push({
700
+ path,
701
+ message: `Array must have at least ${schema.minItems} items`,
702
+ keyword: 'minItems',
703
+ expected: schema.minItems,
704
+ actual: value.length,
705
+ severity: 'error',
706
+ });
707
+ }
708
+ if (schema.maxItems !== undefined && value.length > schema.maxItems) {
709
+ issues.push({
710
+ path,
711
+ message: `Array must have at most ${schema.maxItems} items`,
712
+ keyword: 'maxItems',
713
+ expected: schema.maxItems,
714
+ actual: value.length,
715
+ severity: 'error',
716
+ });
717
+ }
718
+ if (schema.uniqueItems && new Set(value.map(v => JSON.stringify(v))).size !== value.length) {
719
+ issues.push({
720
+ path,
721
+ message: 'Array items must be unique',
722
+ keyword: 'uniqueItems',
723
+ severity: 'error',
724
+ });
725
+ }
726
+ // Validate items
727
+ if (schema.items && !Array.isArray(schema.items)) {
728
+ value.forEach((item, index) => {
729
+ this.validateValue(item, schema.items, `${path}[${index}]`, issues, strict);
730
+ });
731
+ }
732
+ }
733
+ // Object validations
734
+ if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
735
+ const obj = value;
736
+ const keys = Object.keys(obj);
737
+ // Required properties
738
+ if (schema.required) {
739
+ schema.required.forEach(prop => {
740
+ if (!(prop in obj)) {
741
+ issues.push({
742
+ path: path ? `${path}.${prop}` : prop,
743
+ message: `Missing required property: ${prop}`,
744
+ keyword: 'required',
745
+ expected: prop,
746
+ severity: 'error',
747
+ });
748
+ }
749
+ });
750
+ }
751
+ // Property count
752
+ if (schema.minProperties !== undefined && keys.length < schema.minProperties) {
753
+ issues.push({
754
+ path,
755
+ message: `Object must have at least ${schema.minProperties} properties`,
756
+ keyword: 'minProperties',
757
+ expected: schema.minProperties,
758
+ actual: keys.length,
759
+ severity: 'error',
760
+ });
761
+ }
762
+ if (schema.maxProperties !== undefined && keys.length > schema.maxProperties) {
763
+ issues.push({
764
+ path,
765
+ message: `Object must have at most ${schema.maxProperties} properties`,
766
+ keyword: 'maxProperties',
767
+ expected: schema.maxProperties,
768
+ actual: keys.length,
769
+ severity: 'error',
770
+ });
771
+ }
772
+ // Validate each property
773
+ keys.forEach(key => {
774
+ const propPath = path ? `${path}.${key}` : key;
775
+ if (schema.properties?.[key]) {
776
+ this.validateValue(obj[key], schema.properties[key], propPath, issues, strict);
777
+ }
778
+ else if (schema.patternProperties) {
779
+ const matchingPattern = Object.keys(schema.patternProperties).find(pattern => new RegExp(pattern).test(key));
780
+ if (matchingPattern) {
781
+ this.validateValue(obj[key], schema.patternProperties[matchingPattern], propPath, issues, strict);
782
+ }
783
+ else if (strict && schema.additionalProperties === false) {
784
+ issues.push({
785
+ path: propPath,
786
+ message: `Additional property not allowed: ${key}`,
787
+ keyword: 'additionalProperties',
788
+ actual: key,
789
+ severity: 'error',
790
+ });
791
+ }
792
+ }
793
+ else if (strict && schema.additionalProperties === false) {
794
+ issues.push({
795
+ path: propPath,
796
+ message: `Additional property not allowed: ${key}`,
797
+ keyword: 'additionalProperties',
798
+ actual: key,
799
+ severity: 'error',
800
+ });
801
+ }
802
+ else if (schema.additionalProperties && typeof schema.additionalProperties === 'object') {
803
+ this.validateValue(obj[key], schema.additionalProperties, propPath, issues, strict);
804
+ }
805
+ });
806
+ }
807
+ }
808
+ /**
809
+ * Gets the JSON type of a value.
810
+ * Note: In JSON Schema, 'integer' is a subset of 'number', so integers
811
+ * should match both 'integer' and 'number' types.
812
+ */
813
+ getJSONType(value) {
814
+ if (value === null)
815
+ return 'null';
816
+ if (Array.isArray(value))
817
+ return 'array';
818
+ if (typeof value === 'number') {
819
+ // Return 'integer' only if checking against integer type specifically
820
+ // For general type checking, numbers (including integers) are 'number'
821
+ return 'number';
822
+ }
823
+ return typeof value;
824
+ }
825
+ /**
826
+ * Checks if a value matches the expected type(s).
827
+ */
828
+ matchesType(value, expectedTypes) {
829
+ const types = Array.isArray(expectedTypes) ? expectedTypes : [expectedTypes];
830
+ const actualType = typeof value;
831
+ for (const type of types) {
832
+ if (type === 'null' && value === null)
833
+ return true;
834
+ if (type === 'array' && Array.isArray(value))
835
+ return true;
836
+ if (type === 'object' && typeof value === 'object' && value !== null && !Array.isArray(value))
837
+ return true;
838
+ if (type === 'string' && actualType === 'string')
839
+ return true;
840
+ if (type === 'boolean' && actualType === 'boolean')
841
+ return true;
842
+ if (type === 'number' && actualType === 'number')
843
+ return true;
844
+ if (type === 'integer' && actualType === 'number' && Number.isInteger(value))
845
+ return true;
846
+ }
847
+ return false;
848
+ }
849
+ /**
850
+ * Validates a string format.
851
+ */
852
+ validateFormat(value, format) {
853
+ const formatValidators = {
854
+ email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
855
+ uri: /^https?:\/\/.+/,
856
+ 'uri-reference': /^(https?:\/\/|\/|\.\/|\.\.\/).*/,
857
+ uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
858
+ 'date-time': (v) => !isNaN(Date.parse(v)),
859
+ date: /^\d{4}-\d{2}-\d{2}$/,
860
+ time: /^\d{2}:\d{2}(:\d{2})?(\.\d+)?(Z|[+-]\d{2}:\d{2})?$/,
861
+ hostname: /^[a-zA-Z0-9][a-zA-Z0-9-]*(\.[a-zA-Z0-9][a-zA-Z0-9-]*)*$/,
862
+ ipv4: /^(\d{1,3}\.){3}\d{1,3}$/,
863
+ ipv6: /^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/,
864
+ regex: (v) => {
865
+ try {
866
+ new RegExp(v);
867
+ return true;
868
+ }
869
+ catch {
870
+ return false;
871
+ }
872
+ },
873
+ };
874
+ const validator = formatValidators[format];
875
+ if (!validator)
876
+ return true; // Unknown format, pass
877
+ if (typeof validator === 'function') {
878
+ return validator(value);
879
+ }
880
+ return validator.test(value);
881
+ }
882
+ /**
883
+ * Parses JSON string with error recovery.
884
+ */
885
+ parseJSON(jsonString) {
886
+ if (!jsonString)
887
+ return null;
888
+ // Try direct parse first
889
+ try {
890
+ return JSON.parse(jsonString);
891
+ }
892
+ catch {
893
+ // Continue to recovery methods
894
+ }
895
+ // Remove markdown code blocks
896
+ let cleaned = jsonString
897
+ .replace(/```json\s*/gi, '')
898
+ .replace(/```\s*/g, '')
899
+ .trim();
900
+ // Try parsing cleaned version
901
+ try {
902
+ return JSON.parse(cleaned);
903
+ }
904
+ catch {
905
+ // Continue
906
+ }
907
+ // Extract JSON from surrounding text
908
+ const jsonMatch = cleaned.match(/\{[\s\S]*\}|\[[\s\S]*\]/);
909
+ if (jsonMatch) {
910
+ cleaned = jsonMatch[0];
911
+ }
912
+ // Fix common issues
913
+ cleaned = cleaned
914
+ // Remove trailing commas
915
+ .replace(/,\s*([}\]])/g, '$1')
916
+ // Fix single quotes to double quotes (careful with nested quotes)
917
+ .replace(/'/g, '"')
918
+ // Fix unquoted keys
919
+ .replace(/(\{|,)\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*:/g, '$1"$2":');
920
+ try {
921
+ return JSON.parse(cleaned);
922
+ }
923
+ catch {
924
+ this.logger?.warn?.('Failed to parse JSON after recovery attempts', {
925
+ original: jsonString.substring(0, 200),
926
+ });
927
+ return null;
928
+ }
929
+ }
930
+ /**
931
+ * Recommends a strategy for the given provider/model.
932
+ */
933
+ recommendStrategy(providerId, modelId, schema) {
934
+ const capabilities = PROVIDER_CAPABILITIES[providerId] || PROVIDER_CAPABILITIES.default;
935
+ // Complex schemas with nested objects work better with function calling
936
+ const isComplex = schema.properties &&
937
+ Object.values(schema.properties).some((prop) => prop.type === 'object' || prop.type === 'array');
938
+ // Prefer function calling for complex schemas if supported
939
+ if (isComplex && capabilities.supportsFunctionCalling) {
940
+ return 'function_calling';
941
+ }
942
+ // Use JSON mode if available
943
+ if (capabilities.supportsJsonMode) {
944
+ return 'json_mode';
945
+ }
946
+ // Fall back to prompt engineering
947
+ return 'prompt_engineering';
948
+ }
949
+ /**
950
+ * Registers a schema for reuse.
951
+ */
952
+ registerSchema(name, schema) {
953
+ this.schemas.set(name, schema);
954
+ this.logger?.debug?.(`Registered schema: ${name}`);
955
+ }
956
+ /**
957
+ * Gets a registered schema.
958
+ */
959
+ getSchema(name) {
960
+ return this.schemas.get(name);
961
+ }
962
+ /**
963
+ * Gets statistics about structured output operations.
964
+ */
965
+ getStatistics() {
966
+ return { ...this.stats };
967
+ }
968
+ /**
969
+ * Resets statistics.
970
+ */
971
+ resetStatistics() {
972
+ this.stats = {
973
+ totalGenerations: 0,
974
+ successfulGenerations: 0,
975
+ successRate: 0,
976
+ avgRetries: 0,
977
+ avgLatencyMs: 0,
978
+ byStrategy: {
979
+ json_mode: 0,
980
+ function_calling: 0,
981
+ grammar: 0,
982
+ prompt_engineering: 0,
983
+ auto: 0,
984
+ },
985
+ topValidationErrors: [],
986
+ totalTokensUsed: 0,
987
+ };
988
+ this.totalRetries = 0;
989
+ this.totalLatencyMs = 0;
990
+ this.validationErrorCounts.clear();
991
+ }
992
+ /**
993
+ * Updates derived statistics.
994
+ */
995
+ updateStats() {
996
+ this.stats.successRate =
997
+ this.stats.totalGenerations > 0
998
+ ? this.stats.successfulGenerations / this.stats.totalGenerations
999
+ : 0;
1000
+ this.stats.avgRetries =
1001
+ this.stats.totalGenerations > 0
1002
+ ? this.totalRetries / this.stats.totalGenerations
1003
+ : 0;
1004
+ this.stats.avgLatencyMs =
1005
+ this.stats.totalGenerations > 0
1006
+ ? this.totalLatencyMs / this.stats.totalGenerations
1007
+ : 0;
1008
+ // Update top validation errors
1009
+ this.stats.topValidationErrors = Array.from(this.validationErrorCounts.entries())
1010
+ .map(([keyword, count]) => ({ keyword, count }))
1011
+ .sort((a, b) => b.count - a.count)
1012
+ .slice(0, 10);
1013
+ }
1014
+ }
1015
+ //# sourceMappingURL=StructuredOutputManager.js.map