@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.
- package/LICENSE +98 -0
- package/README.md +576 -0
- package/dist/api/AgentOS.d.ts +451 -0
- package/dist/api/AgentOS.d.ts.map +1 -0
- package/dist/api/AgentOS.js +1157 -0
- package/dist/api/AgentOS.js.map +1 -0
- package/dist/api/AgentOSOrchestrator.d.ts +157 -0
- package/dist/api/AgentOSOrchestrator.d.ts.map +1 -0
- package/dist/api/AgentOSOrchestrator.js +679 -0
- package/dist/api/AgentOSOrchestrator.js.map +1 -0
- package/dist/api/interfaces/IAgentOS.d.ts +138 -0
- package/dist/api/interfaces/IAgentOS.d.ts.map +1 -0
- package/dist/api/interfaces/IAgentOS.js +11 -0
- package/dist/api/interfaces/IAgentOS.js.map +1 -0
- package/dist/api/interfaces/IUnifiedAgent.d.ts +126 -0
- package/dist/api/interfaces/IUnifiedAgent.d.ts.map +1 -0
- package/dist/api/interfaces/IUnifiedAgent.js +3 -0
- package/dist/api/interfaces/IUnifiedAgent.js.map +1 -0
- package/dist/api/types/AgentOSInput.d.ts +114 -0
- package/dist/api/types/AgentOSInput.d.ts.map +1 -0
- package/dist/api/types/AgentOSInput.js +13 -0
- package/dist/api/types/AgentOSInput.js.map +1 -0
- package/dist/api/types/AgentOSResponse.d.ts +170 -0
- package/dist/api/types/AgentOSResponse.d.ts.map +1 -0
- package/dist/api/types/AgentOSResponse.js +25 -0
- package/dist/api/types/AgentOSResponse.js.map +1 -0
- package/dist/cognitive_substrate/GMI.d.ts +148 -0
- package/dist/cognitive_substrate/GMI.d.ts.map +1 -0
- package/dist/cognitive_substrate/GMI.js +1003 -0
- package/dist/cognitive_substrate/GMI.js.map +1 -0
- package/dist/cognitive_substrate/GMIManager.d.ts +98 -0
- package/dist/cognitive_substrate/GMIManager.d.ts.map +1 -0
- package/dist/cognitive_substrate/GMIManager.js +517 -0
- package/dist/cognitive_substrate/GMIManager.js.map +1 -0
- package/dist/cognitive_substrate/IGMI.d.ts +469 -0
- package/dist/cognitive_substrate/IGMI.d.ts.map +1 -0
- package/dist/cognitive_substrate/IGMI.js +111 -0
- package/dist/cognitive_substrate/IGMI.js.map +1 -0
- package/dist/cognitive_substrate/memory/IWorkingMemory.d.ts +139 -0
- package/dist/cognitive_substrate/memory/IWorkingMemory.d.ts.map +1 -0
- package/dist/cognitive_substrate/memory/IWorkingMemory.js +14 -0
- package/dist/cognitive_substrate/memory/IWorkingMemory.js.map +1 -0
- package/dist/cognitive_substrate/memory/InMemoryWorkingMemory.d.ts +143 -0
- package/dist/cognitive_substrate/memory/InMemoryWorkingMemory.d.ts.map +1 -0
- package/dist/cognitive_substrate/memory/InMemoryWorkingMemory.js +186 -0
- package/dist/cognitive_substrate/memory/InMemoryWorkingMemory.js.map +1 -0
- package/dist/cognitive_substrate/persona_overlays/PersonaOverlayManager.d.ts +33 -0
- package/dist/cognitive_substrate/persona_overlays/PersonaOverlayManager.d.ts.map +1 -0
- package/dist/cognitive_substrate/persona_overlays/PersonaOverlayManager.js +138 -0
- package/dist/cognitive_substrate/persona_overlays/PersonaOverlayManager.js.map +1 -0
- package/dist/cognitive_substrate/persona_overlays/PersonaOverlayTypes.d.ts +32 -0
- package/dist/cognitive_substrate/persona_overlays/PersonaOverlayTypes.d.ts.map +1 -0
- package/dist/cognitive_substrate/persona_overlays/PersonaOverlayTypes.js +2 -0
- package/dist/cognitive_substrate/persona_overlays/PersonaOverlayTypes.js.map +1 -0
- package/dist/cognitive_substrate/personas/IPersonaDefinition.d.ts +336 -0
- package/dist/cognitive_substrate/personas/IPersonaDefinition.d.ts.map +1 -0
- package/dist/cognitive_substrate/personas/IPersonaDefinition.js +8 -0
- package/dist/cognitive_substrate/personas/IPersonaDefinition.js.map +1 -0
- package/dist/cognitive_substrate/personas/IPersonaLoader.d.ts +78 -0
- package/dist/cognitive_substrate/personas/IPersonaLoader.d.ts.map +1 -0
- package/dist/cognitive_substrate/personas/IPersonaLoader.js +9 -0
- package/dist/cognitive_substrate/personas/IPersonaLoader.js.map +1 -0
- package/dist/cognitive_substrate/personas/PersonaLoader.d.ts +60 -0
- package/dist/cognitive_substrate/personas/PersonaLoader.d.ts.map +1 -0
- package/dist/cognitive_substrate/personas/PersonaLoader.js +138 -0
- package/dist/cognitive_substrate/personas/PersonaLoader.js.map +1 -0
- package/dist/cognitive_substrate/personas/PersonaValidation.d.ts +139 -0
- package/dist/cognitive_substrate/personas/PersonaValidation.d.ts.map +1 -0
- package/dist/cognitive_substrate/personas/PersonaValidation.js +277 -0
- package/dist/cognitive_substrate/personas/PersonaValidation.js.map +1 -0
- package/dist/cognitive_substrate/personas/definitions/atlas_systems_architect.json +29 -0
- package/dist/cognitive_substrate/personas/definitions/default_assistant_persona.json +346 -0
- package/dist/cognitive_substrate/personas/definitions/default_free_assistant.json +13 -0
- package/dist/cognitive_substrate/personas/definitions/index.d.ts +14 -0
- package/dist/cognitive_substrate/personas/definitions/index.d.ts.map +1 -0
- package/dist/cognitive_substrate/personas/definitions/index.js +35 -0
- package/dist/cognitive_substrate/personas/definitions/index.js.map +1 -0
- package/dist/cognitive_substrate/personas/definitions/nerf_generalist.json +11 -0
- package/dist/cognitive_substrate/personas/definitions/v_researcher.json +11 -0
- package/dist/config/AgentOSConfig.d.ts +74 -0
- package/dist/config/AgentOSConfig.d.ts.map +1 -0
- package/dist/config/AgentOSConfig.js +399 -0
- package/dist/config/AgentOSConfig.js.map +1 -0
- package/dist/config/EmbeddingManagerConfiguration.d.ts +190 -0
- package/dist/config/EmbeddingManagerConfiguration.d.ts.map +1 -0
- package/dist/config/EmbeddingManagerConfiguration.js +16 -0
- package/dist/config/EmbeddingManagerConfiguration.js.map +1 -0
- package/dist/config/MemoryLifecycleManagerConfiguration.d.ts +165 -0
- package/dist/config/MemoryLifecycleManagerConfiguration.d.ts.map +1 -0
- package/dist/config/MemoryLifecycleManagerConfiguration.js +69 -0
- package/dist/config/MemoryLifecycleManagerConfiguration.js.map +1 -0
- package/dist/config/RetrievalAugmentorConfiguration.d.ts +98 -0
- package/dist/config/RetrievalAugmentorConfiguration.d.ts.map +1 -0
- package/dist/config/RetrievalAugmentorConfiguration.js +47 -0
- package/dist/config/RetrievalAugmentorConfiguration.js.map +1 -0
- package/dist/config/ToolOrchestratorConfig.d.ts +69 -0
- package/dist/config/ToolOrchestratorConfig.d.ts.map +1 -0
- package/dist/config/ToolOrchestratorConfig.js +11 -0
- package/dist/config/ToolOrchestratorConfig.js.map +1 -0
- package/dist/config/VectorStoreConfiguration.d.ts +223 -0
- package/dist/config/VectorStoreConfiguration.d.ts.map +1 -0
- package/dist/config/VectorStoreConfiguration.js +59 -0
- package/dist/config/VectorStoreConfiguration.js.map +1 -0
- package/dist/config/extension-secrets.json +38 -0
- package/dist/config/extensionSecrets.d.ts +13 -0
- package/dist/config/extensionSecrets.d.ts.map +1 -0
- package/dist/config/extensionSecrets.js +24 -0
- package/dist/config/extensionSecrets.js.map +1 -0
- package/dist/core/agency/AgencyMemoryManager.d.ts +300 -0
- package/dist/core/agency/AgencyMemoryManager.d.ts.map +1 -0
- package/dist/core/agency/AgencyMemoryManager.js +657 -0
- package/dist/core/agency/AgencyMemoryManager.js.map +1 -0
- package/dist/core/agency/AgencyRegistry.d.ts +100 -0
- package/dist/core/agency/AgencyRegistry.d.ts.map +1 -0
- package/dist/core/agency/AgencyRegistry.js +209 -0
- package/dist/core/agency/AgencyRegistry.js.map +1 -0
- package/dist/core/agency/AgencyTypes.d.ts +200 -0
- package/dist/core/agency/AgencyTypes.d.ts.map +1 -0
- package/dist/core/agency/AgencyTypes.js +7 -0
- package/dist/core/agency/AgencyTypes.js.map +1 -0
- package/dist/core/agency/AgentCommunicationBus.d.ts +150 -0
- package/dist/core/agency/AgentCommunicationBus.d.ts.map +1 -0
- package/dist/core/agency/AgentCommunicationBus.js +568 -0
- package/dist/core/agency/AgentCommunicationBus.js.map +1 -0
- package/dist/core/agency/IAgentCommunicationBus.d.ts +469 -0
- package/dist/core/agency/IAgentCommunicationBus.d.ts.map +1 -0
- package/dist/core/agency/IAgentCommunicationBus.js +40 -0
- package/dist/core/agency/IAgentCommunicationBus.js.map +1 -0
- package/dist/core/agency/index.d.ts +18 -0
- package/dist/core/agency/index.d.ts.map +1 -0
- package/dist/core/agency/index.js +18 -0
- package/dist/core/agency/index.js.map +1 -0
- package/dist/core/agents/AgentCore.d.ts +385 -0
- package/dist/core/agents/AgentCore.d.ts.map +1 -0
- package/dist/core/agents/AgentCore.js +527 -0
- package/dist/core/agents/AgentCore.js.map +1 -0
- package/dist/core/agents/AgentFactory.d.ts +123 -0
- package/dist/core/agents/AgentFactory.d.ts.map +1 -0
- package/dist/core/agents/AgentFactory.js +232 -0
- package/dist/core/agents/AgentFactory.js.map +1 -0
- package/dist/core/agents/AgentPoolAgent.d.ts +244 -0
- package/dist/core/agents/AgentPoolAgent.d.ts.map +1 -0
- package/dist/core/agents/AgentPoolAgent.js +697 -0
- package/dist/core/agents/AgentPoolAgent.js.map +1 -0
- package/dist/core/agents/AgentPoolConfig.d.ts +191 -0
- package/dist/core/agents/AgentPoolConfig.d.ts.map +1 -0
- package/dist/core/agents/AgentPoolConfig.js +58 -0
- package/dist/core/agents/AgentPoolConfig.js.map +1 -0
- package/dist/core/agents/IAgent.d.ts +226 -0
- package/dist/core/agents/IAgent.d.ts.map +1 -0
- package/dist/core/agents/IAgent.js +14 -0
- package/dist/core/agents/IAgent.js.map +1 -0
- package/dist/core/agents/IAgentFactory.d.ts +137 -0
- package/dist/core/agents/IAgentFactory.d.ts.map +1 -0
- package/dist/core/agents/IAgentFactory.js +13 -0
- package/dist/core/agents/IAgentFactory.js.map +1 -0
- package/dist/core/agents/tools/Tool.d.ts +17 -0
- package/dist/core/agents/tools/Tool.d.ts.map +1 -0
- package/dist/core/agents/tools/Tool.js +8 -0
- package/dist/core/agents/tools/Tool.js.map +1 -0
- package/dist/core/ai_utilities/HybridUtilityAI.d.ts +1 -0
- package/dist/core/ai_utilities/HybridUtilityAI.d.ts.map +1 -0
- package/dist/core/ai_utilities/HybridUtilityAI.js +2 -0
- package/dist/core/ai_utilities/HybridUtilityAI.js.map +1 -0
- package/dist/core/ai_utilities/IUtilityAI.d.ts +212 -0
- package/dist/core/ai_utilities/IUtilityAI.d.ts.map +1 -0
- package/dist/core/ai_utilities/IUtilityAI.js +11 -0
- package/dist/core/ai_utilities/IUtilityAI.js.map +1 -0
- package/dist/core/ai_utilities/LLMUtilityAI.d.ts +94 -0
- package/dist/core/ai_utilities/LLMUtilityAI.d.ts.map +1 -0
- package/dist/core/ai_utilities/LLMUtilityAI.js +434 -0
- package/dist/core/ai_utilities/LLMUtilityAI.js.map +1 -0
- package/dist/core/ai_utilities/StatisticalUtilityAI.d.ts +102 -0
- package/dist/core/ai_utilities/StatisticalUtilityAI.d.ts.map +1 -0
- package/dist/core/ai_utilities/StatisticalUtilityAI.js +617 -0
- package/dist/core/ai_utilities/StatisticalUtilityAI.js.map +1 -0
- package/dist/core/conversation/ConversationContext.d.ts +259 -0
- package/dist/core/conversation/ConversationContext.d.ts.map +1 -0
- package/dist/core/conversation/ConversationContext.js +450 -0
- package/dist/core/conversation/ConversationContext.js.map +1 -0
- package/dist/core/conversation/ConversationManager.d.ts +223 -0
- package/dist/core/conversation/ConversationManager.d.ts.map +1 -0
- package/dist/core/conversation/ConversationManager.js +558 -0
- package/dist/core/conversation/ConversationManager.js.map +1 -0
- package/dist/core/conversation/ConversationMessage.d.ts +184 -0
- package/dist/core/conversation/ConversationMessage.d.ts.map +1 -0
- package/dist/core/conversation/ConversationMessage.js +66 -0
- package/dist/core/conversation/ConversationMessage.js.map +1 -0
- package/dist/core/evaluation/Evaluator.d.ts +28 -0
- package/dist/core/evaluation/Evaluator.d.ts.map +1 -0
- package/dist/core/evaluation/Evaluator.js +490 -0
- package/dist/core/evaluation/Evaluator.js.map +1 -0
- package/dist/core/evaluation/IEvaluator.d.ts +309 -0
- package/dist/core/evaluation/IEvaluator.d.ts.map +1 -0
- package/dist/core/evaluation/IEvaluator.js +12 -0
- package/dist/core/evaluation/IEvaluator.js.map +1 -0
- package/dist/core/evaluation/LLMJudge.d.ts +105 -0
- package/dist/core/evaluation/LLMJudge.d.ts.map +1 -0
- package/dist/core/evaluation/LLMJudge.js +229 -0
- package/dist/core/evaluation/LLMJudge.js.map +1 -0
- package/dist/core/evaluation/index.d.ts +9 -0
- package/dist/core/evaluation/index.d.ts.map +1 -0
- package/dist/core/evaluation/index.js +9 -0
- package/dist/core/evaluation/index.js.map +1 -0
- package/dist/core/guardrails/IGuardrailService.d.ts +142 -0
- package/dist/core/guardrails/IGuardrailService.d.ts.map +1 -0
- package/dist/core/guardrails/IGuardrailService.js +24 -0
- package/dist/core/guardrails/IGuardrailService.js.map +1 -0
- package/dist/core/guardrails/guardrailDispatcher.d.ts +36 -0
- package/dist/core/guardrails/guardrailDispatcher.d.ts.map +1 -0
- package/dist/core/guardrails/guardrailDispatcher.js +240 -0
- package/dist/core/guardrails/guardrailDispatcher.js.map +1 -0
- package/dist/core/hitl/HumanInteractionManager.d.ts +146 -0
- package/dist/core/hitl/HumanInteractionManager.d.ts.map +1 -0
- package/dist/core/hitl/HumanInteractionManager.js +491 -0
- package/dist/core/hitl/HumanInteractionManager.js.map +1 -0
- package/dist/core/hitl/IHumanInteractionManager.d.ts +521 -0
- package/dist/core/hitl/IHumanInteractionManager.d.ts.map +1 -0
- package/dist/core/hitl/IHumanInteractionManager.js +33 -0
- package/dist/core/hitl/IHumanInteractionManager.js.map +1 -0
- package/dist/core/hitl/index.d.ts +17 -0
- package/dist/core/hitl/index.d.ts.map +1 -0
- package/dist/core/hitl/index.js +17 -0
- package/dist/core/hitl/index.js.map +1 -0
- package/dist/core/knowledge/IKnowledgeGraph.d.ts +351 -0
- package/dist/core/knowledge/IKnowledgeGraph.d.ts.map +1 -0
- package/dist/core/knowledge/IKnowledgeGraph.js +10 -0
- package/dist/core/knowledge/IKnowledgeGraph.js.map +1 -0
- package/dist/core/knowledge/KnowledgeGraph.d.ts +93 -0
- package/dist/core/knowledge/KnowledgeGraph.d.ts.map +1 -0
- package/dist/core/knowledge/KnowledgeGraph.js +601 -0
- package/dist/core/knowledge/KnowledgeGraph.js.map +1 -0
- package/dist/core/knowledge/index.d.ts +8 -0
- package/dist/core/knowledge/index.d.ts.map +1 -0
- package/dist/core/knowledge/index.js +8 -0
- package/dist/core/knowledge/index.js.map +1 -0
- package/dist/core/language/LanguageService.d.ts +77 -0
- package/dist/core/language/LanguageService.d.ts.map +1 -0
- package/dist/core/language/LanguageService.js +305 -0
- package/dist/core/language/LanguageService.js.map +1 -0
- package/dist/core/language/index.d.ts +6 -0
- package/dist/core/language/index.d.ts.map +1 -0
- package/dist/core/language/index.js +6 -0
- package/dist/core/language/index.js.map +1 -0
- package/dist/core/language/interfaces.d.ts +168 -0
- package/dist/core/language/interfaces.d.ts.map +1 -0
- package/dist/core/language/interfaces.js +37 -0
- package/dist/core/language/interfaces.js.map +1 -0
- package/dist/core/language/providers/DeepLTranslationProvider.d.ts +16 -0
- package/dist/core/language/providers/DeepLTranslationProvider.d.ts.map +1 -0
- package/dist/core/language/providers/DeepLTranslationProvider.js +28 -0
- package/dist/core/language/providers/DeepLTranslationProvider.js.map +1 -0
- package/dist/core/language/providers/OpenAITranslationProvider.d.ts +17 -0
- package/dist/core/language/providers/OpenAITranslationProvider.d.ts.map +1 -0
- package/dist/core/language/providers/OpenAITranslationProvider.js +34 -0
- package/dist/core/language/providers/OpenAITranslationProvider.js.map +1 -0
- package/dist/core/language/providers/WhisperDetectionProvider.d.ts +16 -0
- package/dist/core/language/providers/WhisperDetectionProvider.d.ts.map +1 -0
- package/dist/core/language/providers/WhisperDetectionProvider.js +15 -0
- package/dist/core/language/providers/WhisperDetectionProvider.js.map +1 -0
- package/dist/core/llm/IPromptEngine.d.ts +627 -0
- package/dist/core/llm/IPromptEngine.d.ts.map +1 -0
- package/dist/core/llm/IPromptEngine.js +81 -0
- package/dist/core/llm/IPromptEngine.js.map +1 -0
- package/dist/core/llm/PromptEngine.d.ts +108 -0
- package/dist/core/llm/PromptEngine.d.ts.map +1 -0
- package/dist/core/llm/PromptEngine.js +872 -0
- package/dist/core/llm/PromptEngine.js.map +1 -0
- package/dist/core/llm/providers/AIModelProviderManager.d.ts +74 -0
- package/dist/core/llm/providers/AIModelProviderManager.d.ts.map +1 -0
- package/dist/core/llm/providers/AIModelProviderManager.js +263 -0
- package/dist/core/llm/providers/AIModelProviderManager.js.map +1 -0
- package/dist/core/llm/providers/IProvider.d.ts +327 -0
- package/dist/core/llm/providers/IProvider.d.ts.map +1 -0
- package/dist/core/llm/providers/IProvider.js +39 -0
- package/dist/core/llm/providers/IProvider.js.map +1 -0
- package/dist/core/llm/providers/errors/OllamaProviderError.d.ts +36 -0
- package/dist/core/llm/providers/errors/OllamaProviderError.d.ts.map +1 -0
- package/dist/core/llm/providers/errors/OllamaProviderError.js +40 -0
- package/dist/core/llm/providers/errors/OllamaProviderError.js.map +1 -0
- package/dist/core/llm/providers/errors/OpenAIProviderError.d.ts +42 -0
- package/dist/core/llm/providers/errors/OpenAIProviderError.d.ts.map +1 -0
- package/dist/core/llm/providers/errors/OpenAIProviderError.js +44 -0
- package/dist/core/llm/providers/errors/OpenAIProviderError.js.map +1 -0
- package/dist/core/llm/providers/errors/OpenRouterProviderError.d.ts +39 -0
- package/dist/core/llm/providers/errors/OpenRouterProviderError.d.ts.map +1 -0
- package/dist/core/llm/providers/errors/OpenRouterProviderError.js +42 -0
- package/dist/core/llm/providers/errors/OpenRouterProviderError.js.map +1 -0
- package/dist/core/llm/providers/errors/ProviderError.d.ts +37 -0
- package/dist/core/llm/providers/errors/ProviderError.d.ts.map +1 -0
- package/dist/core/llm/providers/errors/ProviderError.js +36 -0
- package/dist/core/llm/providers/errors/ProviderError.js.map +1 -0
- package/dist/core/llm/providers/implementations/OllamaProvider.d.ts +80 -0
- package/dist/core/llm/providers/implementations/OllamaProvider.d.ts.map +1 -0
- package/dist/core/llm/providers/implementations/OllamaProvider.js +473 -0
- package/dist/core/llm/providers/implementations/OllamaProvider.js.map +1 -0
- package/dist/core/llm/providers/implementations/OpenAIProvider.d.ts +160 -0
- package/dist/core/llm/providers/implementations/OpenAIProvider.d.ts.map +1 -0
- package/dist/core/llm/providers/implementations/OpenAIProvider.js +672 -0
- package/dist/core/llm/providers/implementations/OpenAIProvider.js.map +1 -0
- package/dist/core/llm/providers/implementations/OpenRouterProvider.d.ts +51 -0
- package/dist/core/llm/providers/implementations/OpenRouterProvider.d.ts.map +1 -0
- package/dist/core/llm/providers/implementations/OpenRouterProvider.js +499 -0
- package/dist/core/llm/providers/implementations/OpenRouterProvider.js.map +1 -0
- package/dist/core/llm/routing/IModelRouter.d.ts +129 -0
- package/dist/core/llm/routing/IModelRouter.d.ts.map +1 -0
- package/dist/core/llm/routing/IModelRouter.js +14 -0
- package/dist/core/llm/routing/IModelRouter.js.map +1 -0
- package/dist/core/llm/routing/ModelRouter.d.ts +157 -0
- package/dist/core/llm/routing/ModelRouter.d.ts.map +1 -0
- package/dist/core/llm/routing/ModelRouter.js +190 -0
- package/dist/core/llm/routing/ModelRouter.js.map +1 -0
- package/dist/core/llm/streaming/StreamingBatcher.d.ts +54 -0
- package/dist/core/llm/streaming/StreamingBatcher.d.ts.map +1 -0
- package/dist/core/llm/streaming/StreamingBatcher.js +173 -0
- package/dist/core/llm/streaming/StreamingBatcher.js.map +1 -0
- package/dist/core/llm/streaming/StreamingReconstructor.d.ts +69 -0
- package/dist/core/llm/streaming/StreamingReconstructor.d.ts.map +1 -0
- package/dist/core/llm/streaming/StreamingReconstructor.js +102 -0
- package/dist/core/llm/streaming/StreamingReconstructor.js.map +1 -0
- package/dist/core/marketplace/IMarketplace.d.ts +500 -0
- package/dist/core/marketplace/IMarketplace.d.ts.map +1 -0
- package/dist/core/marketplace/IMarketplace.js +10 -0
- package/dist/core/marketplace/IMarketplace.js.map +1 -0
- package/dist/core/marketplace/Marketplace.d.ts +122 -0
- package/dist/core/marketplace/Marketplace.d.ts.map +1 -0
- package/dist/core/marketplace/Marketplace.js +591 -0
- package/dist/core/marketplace/Marketplace.js.map +1 -0
- package/dist/core/marketplace/index.d.ts +8 -0
- package/dist/core/marketplace/index.d.ts.map +1 -0
- package/dist/core/marketplace/index.js +8 -0
- package/dist/core/marketplace/index.js.map +1 -0
- package/dist/core/observability/ITracer.d.ts +317 -0
- package/dist/core/observability/ITracer.d.ts.map +1 -0
- package/dist/core/observability/ITracer.js +55 -0
- package/dist/core/observability/ITracer.js.map +1 -0
- package/dist/core/observability/Tracer.d.ts +76 -0
- package/dist/core/observability/Tracer.d.ts.map +1 -0
- package/dist/core/observability/Tracer.js +360 -0
- package/dist/core/observability/Tracer.js.map +1 -0
- package/dist/core/observability/index.d.ts +9 -0
- package/dist/core/observability/index.d.ts.map +1 -0
- package/dist/core/observability/index.js +8 -0
- package/dist/core/observability/index.js.map +1 -0
- package/dist/core/orchestration/AgentOrchestrator.d.ts +243 -0
- package/dist/core/orchestration/AgentOrchestrator.d.ts.map +1 -0
- package/dist/core/orchestration/AgentOrchestrator.js +648 -0
- package/dist/core/orchestration/AgentOrchestrator.js.map +1 -0
- package/dist/core/orchestration/IAgentOrchestrator.d.ts +44 -0
- package/dist/core/orchestration/IAgentOrchestrator.d.ts.map +1 -0
- package/dist/core/orchestration/IAgentOrchestrator.js +4 -0
- package/dist/core/orchestration/IAgentOrchestrator.js.map +1 -0
- package/dist/core/orchestration/helpers.d.ts +12 -0
- package/dist/core/orchestration/helpers.d.ts.map +1 -0
- package/dist/core/orchestration/helpers.js +36 -0
- package/dist/core/orchestration/helpers.js.map +1 -0
- package/dist/core/planning/IPlanningEngine.d.ts +524 -0
- package/dist/core/planning/IPlanningEngine.d.ts.map +1 -0
- package/dist/core/planning/IPlanningEngine.js +32 -0
- package/dist/core/planning/IPlanningEngine.js.map +1 -0
- package/dist/core/planning/PlanningEngine.d.ts +161 -0
- package/dist/core/planning/PlanningEngine.d.ts.map +1 -0
- package/dist/core/planning/PlanningEngine.js +783 -0
- package/dist/core/planning/PlanningEngine.js.map +1 -0
- package/dist/core/planning/index.d.ts +25 -0
- package/dist/core/planning/index.d.ts.map +1 -0
- package/dist/core/planning/index.js +25 -0
- package/dist/core/planning/index.js.map +1 -0
- package/dist/core/sandbox/CodeSandbox.d.ts +86 -0
- package/dist/core/sandbox/CodeSandbox.d.ts.map +1 -0
- package/dist/core/sandbox/CodeSandbox.js +475 -0
- package/dist/core/sandbox/CodeSandbox.js.map +1 -0
- package/dist/core/sandbox/ICodeSandbox.d.ts +249 -0
- package/dist/core/sandbox/ICodeSandbox.d.ts.map +1 -0
- package/dist/core/sandbox/ICodeSandbox.js +24 -0
- package/dist/core/sandbox/ICodeSandbox.js.map +1 -0
- package/dist/core/sandbox/index.d.ts +9 -0
- package/dist/core/sandbox/index.d.ts.map +1 -0
- package/dist/core/sandbox/index.js +8 -0
- package/dist/core/sandbox/index.js.map +1 -0
- package/dist/core/storage/IStorageAdapter.d.ts +483 -0
- package/dist/core/storage/IStorageAdapter.d.ts.map +1 -0
- package/dist/core/storage/IStorageAdapter.js +19 -0
- package/dist/core/storage/IStorageAdapter.js.map +1 -0
- package/dist/core/storage/InMemoryStorageAdapter.d.ts +192 -0
- package/dist/core/storage/InMemoryStorageAdapter.d.ts.map +1 -0
- package/dist/core/storage/InMemoryStorageAdapter.js +343 -0
- package/dist/core/storage/InMemoryStorageAdapter.js.map +1 -0
- package/dist/core/storage/SqlStorageAdapter.d.ts +262 -0
- package/dist/core/storage/SqlStorageAdapter.d.ts.map +1 -0
- package/dist/core/storage/SqlStorageAdapter.js +485 -0
- package/dist/core/storage/SqlStorageAdapter.js.map +1 -0
- package/dist/core/storage/index.d.ts +14 -0
- package/dist/core/storage/index.d.ts.map +1 -0
- package/dist/core/storage/index.js +14 -0
- package/dist/core/storage/index.js.map +1 -0
- package/dist/core/streaming/IStreamClient.d.ts +72 -0
- package/dist/core/streaming/IStreamClient.d.ts.map +1 -0
- package/dist/core/streaming/IStreamClient.js +12 -0
- package/dist/core/streaming/IStreamClient.js.map +1 -0
- package/dist/core/streaming/StreamingManager.d.ts +242 -0
- package/dist/core/streaming/StreamingManager.d.ts.map +1 -0
- package/dist/core/streaming/StreamingManager.js +282 -0
- package/dist/core/streaming/StreamingManager.js.map +1 -0
- package/dist/core/structured/IStructuredOutputManager.d.ts +701 -0
- package/dist/core/structured/IStructuredOutputManager.d.ts.map +1 -0
- package/dist/core/structured/IStructuredOutputManager.js +74 -0
- package/dist/core/structured/IStructuredOutputManager.js.map +1 -0
- package/dist/core/structured/StructuredOutputManager.d.ts +140 -0
- package/dist/core/structured/StructuredOutputManager.d.ts.map +1 -0
- package/dist/core/structured/StructuredOutputManager.js +1015 -0
- package/dist/core/structured/StructuredOutputManager.js.map +1 -0
- package/dist/core/structured/index.d.ts +34 -0
- package/dist/core/structured/index.d.ts.map +1 -0
- package/dist/core/structured/index.js +34 -0
- package/dist/core/structured/index.js.map +1 -0
- package/dist/core/tools/ITool.d.ts +228 -0
- package/dist/core/tools/ITool.d.ts.map +1 -0
- package/dist/core/tools/ITool.js +11 -0
- package/dist/core/tools/ITool.js.map +1 -0
- package/dist/core/tools/IToolOrchestrator.d.ts +131 -0
- package/dist/core/tools/IToolOrchestrator.d.ts.map +1 -0
- package/dist/core/tools/IToolOrchestrator.js +14 -0
- package/dist/core/tools/IToolOrchestrator.js.map +1 -0
- package/dist/core/tools/ToolExecutor.d.ts +143 -0
- package/dist/core/tools/ToolExecutor.d.ts.map +1 -0
- package/dist/core/tools/ToolExecutor.js +364 -0
- package/dist/core/tools/ToolExecutor.js.map +1 -0
- package/dist/core/tools/ToolOrchestrator.d.ts +142 -0
- package/dist/core/tools/ToolOrchestrator.d.ts.map +1 -0
- package/dist/core/tools/ToolOrchestrator.js +373 -0
- package/dist/core/tools/ToolOrchestrator.js.map +1 -0
- package/dist/core/tools/permissions/IToolPermissionManager.d.ts +195 -0
- package/dist/core/tools/permissions/IToolPermissionManager.d.ts.map +1 -0
- package/dist/core/tools/permissions/IToolPermissionManager.js +14 -0
- package/dist/core/tools/permissions/IToolPermissionManager.js.map +1 -0
- package/dist/core/tools/permissions/ToolPermissionManager.d.ts +203 -0
- package/dist/core/tools/permissions/ToolPermissionManager.d.ts.map +1 -0
- package/dist/core/tools/permissions/ToolPermissionManager.js +298 -0
- package/dist/core/tools/permissions/ToolPermissionManager.js.map +1 -0
- package/dist/core/ui/IUIComponent.d.ts +11 -0
- package/dist/core/ui/IUIComponent.d.ts.map +1 -0
- package/dist/core/ui/IUIComponent.js +2 -0
- package/dist/core/ui/IUIComponent.js.map +1 -0
- package/dist/core/usage/UsageLedger.d.ts +81 -0
- package/dist/core/usage/UsageLedger.d.ts.map +1 -0
- package/dist/core/usage/UsageLedger.js +135 -0
- package/dist/core/usage/UsageLedger.js.map +1 -0
- package/dist/core/workflows/IWorkflowEngine.d.ts +42 -0
- package/dist/core/workflows/IWorkflowEngine.d.ts.map +1 -0
- package/dist/core/workflows/IWorkflowEngine.js +2 -0
- package/dist/core/workflows/IWorkflowEngine.js.map +1 -0
- package/dist/core/workflows/WorkflowEngine.d.ts +28 -0
- package/dist/core/workflows/WorkflowEngine.d.ts.map +1 -0
- package/dist/core/workflows/WorkflowEngine.js +309 -0
- package/dist/core/workflows/WorkflowEngine.js.map +1 -0
- package/dist/core/workflows/WorkflowTypes.d.ts +180 -0
- package/dist/core/workflows/WorkflowTypes.d.ts.map +1 -0
- package/dist/core/workflows/WorkflowTypes.js +26 -0
- package/dist/core/workflows/WorkflowTypes.js.map +1 -0
- package/dist/core/workflows/runtime/WorkflowRuntime.d.ts +70 -0
- package/dist/core/workflows/runtime/WorkflowRuntime.d.ts.map +1 -0
- package/dist/core/workflows/runtime/WorkflowRuntime.js +566 -0
- package/dist/core/workflows/runtime/WorkflowRuntime.js.map +1 -0
- package/dist/core/workflows/storage/IWorkflowStore.d.ts +75 -0
- package/dist/core/workflows/storage/IWorkflowStore.d.ts.map +1 -0
- package/dist/core/workflows/storage/IWorkflowStore.js +2 -0
- package/dist/core/workflows/storage/IWorkflowStore.js.map +1 -0
- package/dist/core/workflows/storage/InMemoryWorkflowStore.d.ts +14 -0
- package/dist/core/workflows/storage/InMemoryWorkflowStore.d.ts.map +1 -0
- package/dist/core/workflows/storage/InMemoryWorkflowStore.js +130 -0
- package/dist/core/workflows/storage/InMemoryWorkflowStore.js.map +1 -0
- package/dist/extensions/ExtensionLoader.d.ts +119 -0
- package/dist/extensions/ExtensionLoader.d.ts.map +1 -0
- package/dist/extensions/ExtensionLoader.js +297 -0
- package/dist/extensions/ExtensionLoader.js.map +1 -0
- package/dist/extensions/ExtensionManager.d.ts +49 -0
- package/dist/extensions/ExtensionManager.d.ts.map +1 -0
- package/dist/extensions/ExtensionManager.js +197 -0
- package/dist/extensions/ExtensionManager.js.map +1 -0
- package/dist/extensions/ExtensionRegistry.d.ts +39 -0
- package/dist/extensions/ExtensionRegistry.d.ts.map +1 -0
- package/dist/extensions/ExtensionRegistry.js +103 -0
- package/dist/extensions/ExtensionRegistry.js.map +1 -0
- package/dist/extensions/MultiRegistryLoader.d.ts +61 -0
- package/dist/extensions/MultiRegistryLoader.d.ts.map +1 -0
- package/dist/extensions/MultiRegistryLoader.js +169 -0
- package/dist/extensions/MultiRegistryLoader.js.map +1 -0
- package/dist/extensions/RegistryConfig.d.ts +86 -0
- package/dist/extensions/RegistryConfig.d.ts.map +1 -0
- package/dist/extensions/RegistryConfig.js +99 -0
- package/dist/extensions/RegistryConfig.js.map +1 -0
- package/dist/extensions/events.d.ts +19 -0
- package/dist/extensions/events.d.ts.map +1 -0
- package/dist/extensions/events.js +2 -0
- package/dist/extensions/events.js.map +1 -0
- package/dist/extensions/index.d.ts +9 -0
- package/dist/extensions/index.d.ts.map +1 -0
- package/dist/extensions/index.js +9 -0
- package/dist/extensions/index.js.map +1 -0
- package/dist/extensions/manifest.d.ts +52 -0
- package/dist/extensions/manifest.d.ts.map +1 -0
- package/dist/extensions/manifest.js +2 -0
- package/dist/extensions/manifest.js.map +1 -0
- package/dist/extensions/types.d.ts +294 -0
- package/dist/extensions/types.d.ts.map +1 -0
- package/dist/extensions/types.js +12 -0
- package/dist/extensions/types.js.map +1 -0
- package/dist/index.d.ts +49 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +59 -0
- package/dist/index.js.map +1 -0
- package/dist/logging/ILogger.d.ts +8 -0
- package/dist/logging/ILogger.d.ts.map +1 -0
- package/dist/logging/ILogger.js +2 -0
- package/dist/logging/ILogger.js.map +1 -0
- package/dist/logging/PinoLogger.d.ts +12 -0
- package/dist/logging/PinoLogger.d.ts.map +1 -0
- package/dist/logging/PinoLogger.js +22 -0
- package/dist/logging/PinoLogger.js.map +1 -0
- package/dist/logging/loggerFactory.d.ts +6 -0
- package/dist/logging/loggerFactory.d.ts.map +1 -0
- package/dist/logging/loggerFactory.js +14 -0
- package/dist/logging/loggerFactory.js.map +1 -0
- package/dist/rag/EmbeddingManager.d.ts +81 -0
- package/dist/rag/EmbeddingManager.d.ts.map +1 -0
- package/dist/rag/EmbeddingManager.js +412 -0
- package/dist/rag/EmbeddingManager.js.map +1 -0
- package/dist/rag/IEmbeddingManager.d.ts +277 -0
- package/dist/rag/IEmbeddingManager.d.ts.map +1 -0
- package/dist/rag/IEmbeddingManager.js +19 -0
- package/dist/rag/IEmbeddingManager.js.map +1 -0
- package/dist/rag/IRetrievalAugmentor.d.ts +208 -0
- package/dist/rag/IRetrievalAugmentor.d.ts.map +1 -0
- package/dist/rag/IRetrievalAugmentor.js +21 -0
- package/dist/rag/IRetrievalAugmentor.js.map +1 -0
- package/dist/rag/IVectorStore.d.ts +351 -0
- package/dist/rag/IVectorStore.d.ts.map +1 -0
- package/dist/rag/IVectorStore.js +15 -0
- package/dist/rag/IVectorStore.js.map +1 -0
- package/dist/rag/IVectorStoreManager.d.ts +121 -0
- package/dist/rag/IVectorStoreManager.d.ts.map +1 -0
- package/dist/rag/IVectorStoreManager.js +13 -0
- package/dist/rag/IVectorStoreManager.js.map +1 -0
- package/dist/rag/RetrievalAugmentor.d.ts +99 -0
- package/dist/rag/RetrievalAugmentor.d.ts.map +1 -0
- package/dist/rag/RetrievalAugmentor.js +674 -0
- package/dist/rag/RetrievalAugmentor.js.map +1 -0
- package/dist/rag/VectorStoreManager.d.ts +90 -0
- package/dist/rag/VectorStoreManager.d.ts.map +1 -0
- package/dist/rag/VectorStoreManager.js +283 -0
- package/dist/rag/VectorStoreManager.js.map +1 -0
- package/dist/rag/implementations/index.d.ts +9 -0
- package/dist/rag/implementations/index.d.ts.map +1 -0
- package/dist/rag/implementations/index.js +9 -0
- package/dist/rag/implementations/index.js.map +1 -0
- package/dist/rag/implementations/vector_stores/InMemoryVectorStore.d.ts +132 -0
- package/dist/rag/implementations/vector_stores/InMemoryVectorStore.d.ts.map +1 -0
- package/dist/rag/implementations/vector_stores/InMemoryVectorStore.js +539 -0
- package/dist/rag/implementations/vector_stores/InMemoryVectorStore.js.map +1 -0
- package/dist/rag/implementations/vector_stores/SqlVectorStore.d.ts +265 -0
- package/dist/rag/implementations/vector_stores/SqlVectorStore.d.ts.map +1 -0
- package/dist/rag/implementations/vector_stores/SqlVectorStore.js +755 -0
- package/dist/rag/implementations/vector_stores/SqlVectorStore.js.map +1 -0
- package/dist/rag/implementations/vector_stores/index.d.ts +10 -0
- package/dist/rag/implementations/vector_stores/index.d.ts.map +1 -0
- package/dist/rag/implementations/vector_stores/index.js +12 -0
- package/dist/rag/implementations/vector_stores/index.js.map +1 -0
- package/dist/rag/index.d.ts +95 -0
- package/dist/rag/index.d.ts.map +1 -0
- package/dist/rag/index.js +97 -0
- package/dist/rag/index.js.map +1 -0
- package/dist/services/user_auth/AuthService.d.ts +13 -0
- package/dist/services/user_auth/AuthService.d.ts.map +1 -0
- package/dist/services/user_auth/AuthService.js +24 -0
- package/dist/services/user_auth/AuthService.js.map +1 -0
- package/dist/services/user_auth/SubscriptionService.d.ts +14 -0
- package/dist/services/user_auth/SubscriptionService.d.ts.map +1 -0
- package/dist/services/user_auth/SubscriptionService.js +34 -0
- package/dist/services/user_auth/SubscriptionService.js.map +1 -0
- package/dist/services/user_auth/types.d.ts +30 -0
- package/dist/services/user_auth/types.d.ts.map +1 -0
- package/dist/services/user_auth/types.js +2 -0
- package/dist/services/user_auth/types.js.map +1 -0
- package/dist/stubs/prismaClient.d.ts +35 -0
- package/dist/stubs/prismaClient.d.ts.map +1 -0
- package/dist/stubs/prismaClient.js +47 -0
- package/dist/stubs/prismaClient.js.map +1 -0
- package/dist/types/rateLimitTypes.d.ts +70 -0
- package/dist/types/rateLimitTypes.d.ts.map +1 -0
- package/dist/types/rateLimitTypes.js +55 -0
- package/dist/types/rateLimitTypes.js.map +1 -0
- package/dist/utils/errors.d.ts +80 -0
- package/dist/utils/errors.d.ts.map +1 -0
- package/dist/utils/errors.js +201 -0
- package/dist/utils/errors.js.map +1 -0
- package/dist/utils/uuid.d.ts +11 -0
- package/dist/utils/uuid.d.ts.map +1 -0
- package/dist/utils/uuid.js +64 -0
- package/dist/utils/uuid.js.map +1 -0
- package/package.json +84 -0
|
@@ -0,0 +1,1003 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Implements the Generalized Mind Instance (GMI), the core cognitive
|
|
3
|
+
* engine of the AgentOS platform. This version integrates concrete IUtilityAI methods
|
|
4
|
+
* for tasks like JSON parsing in self-reflection and summarization for RAG ingestion,
|
|
5
|
+
* alongside its full suite of capabilities including tool orchestration, RAG interaction,
|
|
6
|
+
* and adaptive state management.
|
|
7
|
+
*
|
|
8
|
+
* @module backend/agentos/cognitive_substrate/GMI
|
|
9
|
+
* @see ./IGMI.ts for the interface definition.
|
|
10
|
+
* @see ./personas/IPersonaDefinition.ts for persona structure.
|
|
11
|
+
* @see ../core/tools/IToolOrchestrator.ts for tool orchestration.
|
|
12
|
+
* @see ../core/ai_utilities/IUtilityAI.ts for utility functions.
|
|
13
|
+
*/
|
|
14
|
+
import { uuidv4 } from '../utils/uuid.js';
|
|
15
|
+
import { GMIOutputChunkType, GMIPrimeState, GMIMood, ReasoningEntryType, GMIInteractionType,
|
|
16
|
+
// AudioOutputConfig, ImageOutputConfig are part of GMIOutput
|
|
17
|
+
} from './IGMI.js';
|
|
18
|
+
import { RagMemoryCategory } from '../rag/IRetrievalAugmentor.js';
|
|
19
|
+
import { createConversationMessage, MessageRole } from '../core/conversation/ConversationMessage.js';
|
|
20
|
+
import { GMIError, GMIErrorCode, createGMIErrorFromError } from '../utils/errors.js';
|
|
21
|
+
const DEFAULT_MAX_CONVERSATION_HISTORY_TURNS = 20;
|
|
22
|
+
const DEFAULT_SELF_REFLECTION_INTERVAL_TURNS = 5;
|
|
23
|
+
const MAX_REASONING_TRACE_ENTRIES = 500; // Limit trace size in memory
|
|
24
|
+
/**
|
|
25
|
+
* @class GMI
|
|
26
|
+
* @implements {IGMI}
|
|
27
|
+
* The core implementation of the Generalized Mind Instance, orchestrating
|
|
28
|
+
* perception, cognition, action, and adaptation.
|
|
29
|
+
*/
|
|
30
|
+
export class GMI {
|
|
31
|
+
/**
|
|
32
|
+
* Constructs a GMI instance.
|
|
33
|
+
* The GMI is not fully operational until `initialize` is called.
|
|
34
|
+
* @param {string} [gmiId] - Optional ID for the GMI. If not provided, a UUID will be generated.
|
|
35
|
+
*/
|
|
36
|
+
constructor(gmiId) {
|
|
37
|
+
this.isInitialized = false; // Maintained as per user-provided GMI.ts
|
|
38
|
+
this.gmiId = gmiId || `gmi-${uuidv4()}`;
|
|
39
|
+
this.creationTimestamp = new Date();
|
|
40
|
+
this.state = GMIPrimeState.IDLE;
|
|
41
|
+
this.currentGmiMood = GMIMood.NEUTRAL;
|
|
42
|
+
this.currentUserContext = { userId: 'uninitialized-user', skillLevel: 'novice', preferences: {} };
|
|
43
|
+
this.currentTaskContext = { taskId: `task-${uuidv4()}`, domain: 'general', complexity: 'low', status: 'not_started' };
|
|
44
|
+
this.reasoningTrace = { gmiId: this.gmiId, personaId: '', entries: [] };
|
|
45
|
+
this.conversationHistory = [];
|
|
46
|
+
this.selfReflectionIntervalTurns = DEFAULT_SELF_REFLECTION_INTERVAL_TURNS;
|
|
47
|
+
this.turnsSinceLastReflection = 0;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* @inheritdoc
|
|
51
|
+
*/
|
|
52
|
+
async initialize(persona, config) {
|
|
53
|
+
if (this.isInitialized && this.state !== GMIPrimeState.ERRORED) {
|
|
54
|
+
console.warn(`GMI (ID: ${this.gmiId}) already initialized (state: ${this.state}). Re-initializing parts.`);
|
|
55
|
+
// Selective re-initialization logic can be more granular if needed
|
|
56
|
+
this.reasoningTrace = { gmiId: this.gmiId, personaId: '', entries: [] };
|
|
57
|
+
this.conversationHistory = [];
|
|
58
|
+
}
|
|
59
|
+
this.validateInitializationInputs(persona, config);
|
|
60
|
+
this.activePersona = persona;
|
|
61
|
+
this.config = config;
|
|
62
|
+
this.workingMemory = config.workingMemory;
|
|
63
|
+
this.promptEngine = config.promptEngine;
|
|
64
|
+
this.retrievalAugmentor = config.retrievalAugmentor;
|
|
65
|
+
this.toolOrchestrator = config.toolOrchestrator;
|
|
66
|
+
this.llmProviderManager = config.llmProviderManager;
|
|
67
|
+
this.utilityAI = config.utilityAI;
|
|
68
|
+
this.reasoningTrace.personaId = this.activePersona.id;
|
|
69
|
+
await this.workingMemory.initialize(this.gmiId, this.activePersona.customFields?.defaultWorkingMemoryConfig || {});
|
|
70
|
+
this.addTraceEntry(ReasoningEntryType.LIFECYCLE, 'GMI Initializing with Persona and Config.', { personaId: persona.id });
|
|
71
|
+
await this.loadStateFromMemoryAndPersona();
|
|
72
|
+
const reflectionMetaPrompt = this.activePersona.metaPrompts?.find(mp => mp.id === 'gmi_self_trait_adjustment');
|
|
73
|
+
this.selfReflectionIntervalTurns = reflectionMetaPrompt?.trigger?.type === 'turn_interval' && typeof reflectionMetaPrompt.trigger.intervalTurns === 'number'
|
|
74
|
+
? reflectionMetaPrompt.trigger.intervalTurns
|
|
75
|
+
: DEFAULT_SELF_REFLECTION_INTERVAL_TURNS;
|
|
76
|
+
this.turnsSinceLastReflection = 0;
|
|
77
|
+
this.isInitialized = true; // Set after all essential initializations
|
|
78
|
+
this.state = GMIPrimeState.READY;
|
|
79
|
+
this.addTraceEntry(ReasoningEntryType.LIFECYCLE, 'GMI Initialization complete. State: READY.');
|
|
80
|
+
console.log(`GMI (ID: ${this.gmiId}, Persona: ${this.activePersona.id}) initialized successfully.`);
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Validates the essential inputs for GMI initialization.
|
|
84
|
+
* @param {IPersonaDefinition} persona - The persona definition.
|
|
85
|
+
* @param {GMIBaseConfig} config - The base configuration for the GMI.
|
|
86
|
+
* @private
|
|
87
|
+
* @throws {GMIError} if validation fails.
|
|
88
|
+
*/
|
|
89
|
+
validateInitializationInputs(persona, config) {
|
|
90
|
+
const errors = [];
|
|
91
|
+
if (!persona)
|
|
92
|
+
errors.push('PersonaDefinition');
|
|
93
|
+
if (!config)
|
|
94
|
+
errors.push('GMIBaseConfig');
|
|
95
|
+
else {
|
|
96
|
+
if (!config.workingMemory)
|
|
97
|
+
errors.push('config.workingMemory');
|
|
98
|
+
if (!config.promptEngine)
|
|
99
|
+
errors.push('config.promptEngine');
|
|
100
|
+
if (!config.llmProviderManager)
|
|
101
|
+
errors.push('config.llmProviderManager');
|
|
102
|
+
if (!config.utilityAI)
|
|
103
|
+
errors.push('config.utilityAI');
|
|
104
|
+
if (!config.toolOrchestrator)
|
|
105
|
+
errors.push('config.toolOrchestrator');
|
|
106
|
+
}
|
|
107
|
+
if (errors.length > 0) {
|
|
108
|
+
throw new GMIError(`GMI initialization failed, missing dependencies: ${errors.join(', ')}`, GMIErrorCode.GMI_INITIALIZATION_ERROR, { missing: errors });
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Loads initial operational state from working memory or persona defaults.
|
|
113
|
+
* @private
|
|
114
|
+
*/
|
|
115
|
+
async loadStateFromMemoryAndPersona() {
|
|
116
|
+
this.currentGmiMood = (await this.workingMemory.get('currentGmiMood')) ||
|
|
117
|
+
this.activePersona.moodAdaptation?.defaultMood || // Assuming GMIMood string is compatible
|
|
118
|
+
GMIMood.NEUTRAL;
|
|
119
|
+
const personaInitialUserCtx = this.activePersona.customFields?.initialUserContext || {};
|
|
120
|
+
const memUserCtx = await this.workingMemory.get('currentUserContext');
|
|
121
|
+
this.currentUserContext = {
|
|
122
|
+
userId: 'default_user', // Will be overridden by actual session/turn user ID
|
|
123
|
+
skillLevel: 'novice',
|
|
124
|
+
preferences: {},
|
|
125
|
+
...personaInitialUserCtx,
|
|
126
|
+
...(memUserCtx || {}), // Spread memUserCtx if it exists
|
|
127
|
+
};
|
|
128
|
+
const personaInitialTaskCtx = this.activePersona.customFields?.initialTaskContext || {};
|
|
129
|
+
const memTaskCtx = await this.workingMemory.get('currentTaskContext');
|
|
130
|
+
this.currentTaskContext = {
|
|
131
|
+
taskId: `task-${uuidv4()}`,
|
|
132
|
+
domain: this.activePersona.strengths?.[0] || 'general',
|
|
133
|
+
complexity: 'medium',
|
|
134
|
+
status: 'not_started',
|
|
135
|
+
...personaInitialTaskCtx,
|
|
136
|
+
...(memTaskCtx || {}),
|
|
137
|
+
};
|
|
138
|
+
await Promise.all([
|
|
139
|
+
this.workingMemory.set('currentGmiMood', this.currentGmiMood),
|
|
140
|
+
this.workingMemory.set('currentUserContext', this.currentUserContext),
|
|
141
|
+
this.workingMemory.set('currentTaskContext', this.currentTaskContext)
|
|
142
|
+
]);
|
|
143
|
+
this.addTraceEntry(ReasoningEntryType.STATE_CHANGE, 'GMI operational state (mood, user, task contexts) loaded/initialized.');
|
|
144
|
+
if (this.activePersona.initialMemoryImprints && this.activePersona.initialMemoryImprints.length > 0) {
|
|
145
|
+
this.addTraceEntry(ReasoningEntryType.STATE_CHANGE, `Applying ${this.activePersona.initialMemoryImprints.length} initial memory imprints from persona.`);
|
|
146
|
+
for (const imprint of this.activePersona.initialMemoryImprints) {
|
|
147
|
+
if (imprint.key && imprint.value !== undefined) {
|
|
148
|
+
await this.workingMemory.set(imprint.key, imprint.value);
|
|
149
|
+
this.addTraceEntry(ReasoningEntryType.DEBUG, `Applied memory imprint: '${imprint.key}'`, { value: imprint.value, description: imprint.description });
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
/** @inheritdoc */
|
|
155
|
+
getPersona() {
|
|
156
|
+
if (!this.isInitialized || !this.activePersona) {
|
|
157
|
+
throw new GMIError("GMI is not properly initialized or has no active persona.", GMIErrorCode.NOT_INITIALIZED);
|
|
158
|
+
}
|
|
159
|
+
return this.activePersona;
|
|
160
|
+
}
|
|
161
|
+
/** @inheritdoc */
|
|
162
|
+
getCurrentPrimaryPersonaId() {
|
|
163
|
+
if (!this.activePersona) {
|
|
164
|
+
throw new GMIError("GMI has no active persona assigned.", GMIErrorCode.NOT_INITIALIZED);
|
|
165
|
+
}
|
|
166
|
+
return this.activePersona.id;
|
|
167
|
+
}
|
|
168
|
+
/** @inheritdoc */
|
|
169
|
+
getGMIId() { return this.gmiId; }
|
|
170
|
+
/** @inheritdoc */
|
|
171
|
+
getCurrentState() { return this.state; }
|
|
172
|
+
/** @inheritdoc */
|
|
173
|
+
getReasoningTrace() {
|
|
174
|
+
return JSON.parse(JSON.stringify(this.reasoningTrace));
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Adds an entry to the GMI's reasoning trace.
|
|
178
|
+
* @private
|
|
179
|
+
*/
|
|
180
|
+
addTraceEntry(type, message, details, timestamp) {
|
|
181
|
+
if (this.reasoningTrace.entries.length >= MAX_REASONING_TRACE_ENTRIES) {
|
|
182
|
+
this.reasoningTrace.entries.shift();
|
|
183
|
+
}
|
|
184
|
+
const entry = {
|
|
185
|
+
timestamp: timestamp || new Date(),
|
|
186
|
+
type,
|
|
187
|
+
message: message.substring(0, 1000), // Cap message length
|
|
188
|
+
details: details ? JSON.parse(JSON.stringify(details)) : {},
|
|
189
|
+
};
|
|
190
|
+
this.reasoningTrace.entries.push(entry);
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Ensures the GMI is initialized and in a READY state.
|
|
194
|
+
* @private
|
|
195
|
+
*/
|
|
196
|
+
ensureReady() {
|
|
197
|
+
if (!this.isInitialized) {
|
|
198
|
+
throw new GMIError(`GMI (ID: ${this.gmiId}) is not initialized.`, GMIErrorCode.NOT_INITIALIZED);
|
|
199
|
+
}
|
|
200
|
+
if (this.state !== GMIPrimeState.READY) {
|
|
201
|
+
throw new GMIError(`GMI (ID: ${this.gmiId}) is not in READY state. Current state: ${this.state}.`, GMIErrorCode.INVALID_STATE, { currentGMIState: this.state });
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Creates a standardized GMIOutputChunk.
|
|
206
|
+
* @private
|
|
207
|
+
*/
|
|
208
|
+
createOutputChunk(interactionId, type, content, extras = {}) {
|
|
209
|
+
return {
|
|
210
|
+
interactionId, type, content,
|
|
211
|
+
timestamp: new Date(),
|
|
212
|
+
chunkId: `gmi-chunk-${uuidv4()}`,
|
|
213
|
+
...extras,
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Updates the internal conversation history with new input.
|
|
218
|
+
* @private
|
|
219
|
+
*/
|
|
220
|
+
updateConversationHistory(turnInput) {
|
|
221
|
+
let messageToAdd = null;
|
|
222
|
+
switch (turnInput.type) {
|
|
223
|
+
case GMIInteractionType.TEXT:
|
|
224
|
+
messageToAdd = { role: 'user', content: turnInput.content, name: turnInput.metadata?.userName || turnInput.userId };
|
|
225
|
+
break;
|
|
226
|
+
case GMIInteractionType.MULTIMODAL_CONTENT:
|
|
227
|
+
messageToAdd = { role: 'user', content: turnInput.content, name: turnInput.metadata?.userName || turnInput.userId };
|
|
228
|
+
break;
|
|
229
|
+
case GMIInteractionType.TOOL_RESPONSE: {
|
|
230
|
+
const results = Array.isArray(turnInput.content) ? turnInput.content : [turnInput.content];
|
|
231
|
+
results.forEach(result => {
|
|
232
|
+
this.conversationHistory.push({
|
|
233
|
+
role: 'tool',
|
|
234
|
+
tool_call_id: result.toolCallId,
|
|
235
|
+
name: result.toolName,
|
|
236
|
+
content: typeof result.output === 'string' ? result.output : JSON.stringify(result.output),
|
|
237
|
+
});
|
|
238
|
+
});
|
|
239
|
+
break;
|
|
240
|
+
}
|
|
241
|
+
case GMIInteractionType.SYSTEM_MESSAGE:
|
|
242
|
+
messageToAdd = { role: 'system', content: turnInput.content };
|
|
243
|
+
break;
|
|
244
|
+
}
|
|
245
|
+
if (messageToAdd)
|
|
246
|
+
this.conversationHistory.push(messageToAdd);
|
|
247
|
+
const maxHistoryMessages = this.activePersona.conversationContextConfig?.maxMessages ||
|
|
248
|
+
this.activePersona.memoryConfig?.conversationContext?.maxMessages ||
|
|
249
|
+
DEFAULT_MAX_CONVERSATION_HISTORY_TURNS;
|
|
250
|
+
if (this.conversationHistory.length > maxHistoryMessages) {
|
|
251
|
+
const removeCount = this.conversationHistory.length - maxHistoryMessages;
|
|
252
|
+
this.conversationHistory.splice(0, removeCount);
|
|
253
|
+
this.addTraceEntry(ReasoningEntryType.DEBUG, `Conversation history trimmed to ${maxHistoryMessages} messages.`);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Adds a tool call result to the GMI's internal conversation history.
|
|
258
|
+
* @private
|
|
259
|
+
* @param {ToolCallResult} toolCallResult - The result from the tool execution.
|
|
260
|
+
*/
|
|
261
|
+
updateConversationHistoryWithToolResult(toolCallResult) {
|
|
262
|
+
this.conversationHistory.push({
|
|
263
|
+
role: 'tool',
|
|
264
|
+
tool_call_id: toolCallResult.toolCallId,
|
|
265
|
+
name: toolCallResult.toolName, // Name of the tool
|
|
266
|
+
content: toolCallResult.isError
|
|
267
|
+
? `Error from tool '${toolCallResult.toolName}': ${JSON.stringify(toolCallResult.errorDetails || toolCallResult.output)}`
|
|
268
|
+
: (typeof toolCallResult.output === 'string' ? toolCallResult.output : JSON.stringify(toolCallResult.output)),
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* Creates a conversation-history snapshot compatible with `PromptComponents`.
|
|
273
|
+
* @private
|
|
274
|
+
*/
|
|
275
|
+
buildConversationHistoryForPrompt() {
|
|
276
|
+
return this.conversationHistory.map(msg => this.convertChatMessageToConversationMessage(msg));
|
|
277
|
+
}
|
|
278
|
+
convertChatMessageToConversationMessage(chatMsg) {
|
|
279
|
+
const conversationMessage = createConversationMessage(this.mapChatRoleToMessageRole(chatMsg.role), this.normalizeChatMessageContent(chatMsg.content), {
|
|
280
|
+
name: chatMsg.name,
|
|
281
|
+
tool_call_id: chatMsg.tool_call_id,
|
|
282
|
+
});
|
|
283
|
+
if (chatMsg.tool_calls && chatMsg.tool_calls.length > 0) {
|
|
284
|
+
conversationMessage.tool_calls = chatMsg.tool_calls
|
|
285
|
+
.filter(tc => !!tc?.function?.name)
|
|
286
|
+
.map(tc => ({
|
|
287
|
+
id: tc.id,
|
|
288
|
+
name: tc.function.name,
|
|
289
|
+
arguments: this.parseToolCallArguments(tc.function.arguments),
|
|
290
|
+
}));
|
|
291
|
+
}
|
|
292
|
+
return conversationMessage;
|
|
293
|
+
}
|
|
294
|
+
mapChatRoleToMessageRole(role) {
|
|
295
|
+
switch (role) {
|
|
296
|
+
case 'system':
|
|
297
|
+
return MessageRole.SYSTEM;
|
|
298
|
+
case 'assistant':
|
|
299
|
+
return MessageRole.ASSISTANT;
|
|
300
|
+
case 'tool':
|
|
301
|
+
return MessageRole.TOOL;
|
|
302
|
+
default:
|
|
303
|
+
return MessageRole.USER;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
normalizeChatMessageContent(content) {
|
|
307
|
+
if (typeof content === 'undefined') {
|
|
308
|
+
return null;
|
|
309
|
+
}
|
|
310
|
+
if (content === null || typeof content === 'string') {
|
|
311
|
+
return content;
|
|
312
|
+
}
|
|
313
|
+
if (Array.isArray(content)) {
|
|
314
|
+
return content.map(part => ({ ...part }));
|
|
315
|
+
}
|
|
316
|
+
return content;
|
|
317
|
+
}
|
|
318
|
+
parseToolCallArguments(args) {
|
|
319
|
+
if (!args) {
|
|
320
|
+
return {};
|
|
321
|
+
}
|
|
322
|
+
if (typeof args === 'string') {
|
|
323
|
+
try {
|
|
324
|
+
return JSON.parse(args);
|
|
325
|
+
}
|
|
326
|
+
catch {
|
|
327
|
+
return {};
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
if (typeof args === 'object') {
|
|
331
|
+
return args;
|
|
332
|
+
}
|
|
333
|
+
return {};
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* Builds the PromptExecutionContext for the PromptEngine.
|
|
337
|
+
* @private
|
|
338
|
+
* @returns {PromptExecutionContext} The context for prompt construction.
|
|
339
|
+
*/
|
|
340
|
+
buildPromptExecutionContext() {
|
|
341
|
+
if (!this.isInitialized || !this.activePersona || !this.currentUserContext || !this.currentTaskContext || !this.workingMemory) {
|
|
342
|
+
throw new GMIError("GMI context not properly initialized for prompt construction.", GMIErrorCode.INVALID_STATE);
|
|
343
|
+
}
|
|
344
|
+
const context = {
|
|
345
|
+
activePersona: this.activePersona,
|
|
346
|
+
workingMemory: this.workingMemory,
|
|
347
|
+
currentMood: this.currentGmiMood,
|
|
348
|
+
userSkillLevel: this.currentUserContext.skillLevel,
|
|
349
|
+
userPreferences: this.currentUserContext.preferences,
|
|
350
|
+
taskHint: this.currentTaskContext.domain,
|
|
351
|
+
taskComplexity: this.currentTaskContext.complexity,
|
|
352
|
+
// language: this.currentUserContext.language, // If available
|
|
353
|
+
// conversationSignals: this.detectConversationSignals(), // If such method exists
|
|
354
|
+
};
|
|
355
|
+
return context;
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Determines if RAG retrieval should be triggered based on the current query and persona configuration.
|
|
359
|
+
* @private
|
|
360
|
+
* @param {string} query - The current user query.
|
|
361
|
+
* @returns {boolean} True if RAG should be triggered, false otherwise.
|
|
362
|
+
*/
|
|
363
|
+
shouldTriggerRAGRetrieval(query) {
|
|
364
|
+
if (!query || query.trim() === '')
|
|
365
|
+
return false;
|
|
366
|
+
const ragConfig = this.activePersona.memoryConfig?.ragConfig;
|
|
367
|
+
const retrievalTriggers = ragConfig?.retrievalTriggers;
|
|
368
|
+
if (retrievalTriggers?.onUserQuery) {
|
|
369
|
+
return true;
|
|
370
|
+
}
|
|
371
|
+
// TODO: Implement more sophisticated logic based on other retrievalTriggers
|
|
372
|
+
// (e.g., onIntentDetected, onToolFailure, customLogicFunctionName)
|
|
373
|
+
return false; // Default
|
|
374
|
+
}
|
|
375
|
+
/** @inheritdoc */
|
|
376
|
+
async *processTurnStream(turnInput) {
|
|
377
|
+
this.ensureReady();
|
|
378
|
+
this.state = GMIPrimeState.PROCESSING;
|
|
379
|
+
const turnId = turnInput.interactionId || `turn-${uuidv4()}`;
|
|
380
|
+
// Store turnId on reasoningTrace for current turn
|
|
381
|
+
if (this.reasoningTrace)
|
|
382
|
+
this.reasoningTrace.turnId = turnId;
|
|
383
|
+
this.addTraceEntry(ReasoningEntryType.INTERACTION_START, `Processing turn '${turnId}' for user '${turnInput.userId}'`, { inputType: turnInput.type, inputPreview: String(turnInput.content).substring(0, 100) });
|
|
384
|
+
// Initialize aggregates for the final GMIOutput
|
|
385
|
+
let aggregatedResponseText = "";
|
|
386
|
+
const aggregatedToolCalls = [];
|
|
387
|
+
const aggregatedUiCommands = [];
|
|
388
|
+
const aggregatedUsage = { totalTokens: 0, promptTokens: 0, completionTokens: 0, breakdown: [] };
|
|
389
|
+
let lastErrorForOutput = undefined;
|
|
390
|
+
try {
|
|
391
|
+
if (turnInput.userContextOverride) {
|
|
392
|
+
this.currentUserContext = { ...this.currentUserContext, ...turnInput.userContextOverride };
|
|
393
|
+
await this.workingMemory.set('currentUserContext', this.currentUserContext);
|
|
394
|
+
}
|
|
395
|
+
if (turnInput.taskContextOverride) {
|
|
396
|
+
this.currentTaskContext = { ...this.currentTaskContext, ...turnInput.taskContextOverride };
|
|
397
|
+
await this.workingMemory.set('currentTaskContext', this.currentTaskContext);
|
|
398
|
+
}
|
|
399
|
+
if (turnInput.userId && this.currentUserContext.userId !== turnInput.userId) {
|
|
400
|
+
this.currentUserContext.userId = turnInput.userId;
|
|
401
|
+
await this.workingMemory.set('currentUserContext', this.currentUserContext);
|
|
402
|
+
}
|
|
403
|
+
this.updateConversationHistory(turnInput);
|
|
404
|
+
let safetyBreak = 0;
|
|
405
|
+
main_processing_loop: while (safetyBreak < 5) {
|
|
406
|
+
safetyBreak++;
|
|
407
|
+
let augmentedContextFromRAG = "";
|
|
408
|
+
const lastMessage = this.conversationHistory.length > 0 ? this.conversationHistory[this.conversationHistory.length - 1] : null;
|
|
409
|
+
const isUserInitiatedTurn = lastMessage?.role === 'user';
|
|
410
|
+
if (this.retrievalAugmentor && this.activePersona.memoryConfig?.ragConfig?.enabled && isUserInitiatedTurn && lastMessage?.content) {
|
|
411
|
+
const currentQueryForRag = typeof lastMessage.content === 'string' ? lastMessage.content : JSON.stringify(lastMessage.content);
|
|
412
|
+
if (this.shouldTriggerRAGRetrieval(currentQueryForRag)) {
|
|
413
|
+
this.addTraceEntry(ReasoningEntryType.RAG_QUERY_START, "RAG retrieval triggered.", { queryPreview: currentQueryForRag.substring(0, 100) });
|
|
414
|
+
const retrievalOptions = {
|
|
415
|
+
topK: this.activePersona.memoryConfig?.ragConfig?.defaultRetrievalTopK || 5,
|
|
416
|
+
targetDataSourceIds: this.activePersona.memoryConfig?.ragConfig?.dataSources?.filter(ds => ds.isEnabled).map(ds => ds.dataSourceNameOrId),
|
|
417
|
+
// TODO: Populate other options like metadataFilter, strategy from persona config
|
|
418
|
+
};
|
|
419
|
+
const ragResult = await this.retrievalAugmentor.retrieveContext(currentQueryForRag, retrievalOptions);
|
|
420
|
+
augmentedContextFromRAG = ragResult.augmentedContext;
|
|
421
|
+
this.addTraceEntry(ReasoningEntryType.RAG_QUERY_RESULT, 'RAG context retrieved.', { length: augmentedContextFromRAG.length });
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
const promptExecContext = this.buildPromptExecutionContext();
|
|
425
|
+
const baseSystemPrompts = Array.isArray(this.activePersona.baseSystemPrompt)
|
|
426
|
+
? this.activePersona.baseSystemPrompt
|
|
427
|
+
: typeof this.activePersona.baseSystemPrompt === 'object' && 'template' in this.activePersona.baseSystemPrompt
|
|
428
|
+
? [{ content: this.activePersona.baseSystemPrompt.template, priority: 1 }]
|
|
429
|
+
: typeof this.activePersona.baseSystemPrompt === 'string'
|
|
430
|
+
? [{ content: this.activePersona.baseSystemPrompt, priority: 1 }]
|
|
431
|
+
: [];
|
|
432
|
+
const promptComponents = {
|
|
433
|
+
systemPrompts: baseSystemPrompts,
|
|
434
|
+
conversationHistory: this.buildConversationHistoryForPrompt(),
|
|
435
|
+
userInput: isUserInitiatedTurn && typeof lastMessage?.content === 'string' ? lastMessage.content : null,
|
|
436
|
+
retrievedContext: augmentedContextFromRAG,
|
|
437
|
+
// tools: this.activePersona.embeddedTools, // If ITool[] and PromptComponents.tools takes ITool[]
|
|
438
|
+
};
|
|
439
|
+
const preferredModelIdFromInput = turnInput.metadata?.options?.preferredModelId;
|
|
440
|
+
const modelIdToUse = preferredModelIdFromInput || this.activePersona.defaultModelId || this.config.defaultLlmModelId;
|
|
441
|
+
const providerIdForModel = this.activePersona.defaultProviderId || this.config.defaultLlmProviderId;
|
|
442
|
+
if (!modelIdToUse) {
|
|
443
|
+
throw new GMIError("Could not determine modelId for LLM call.", GMIErrorCode.CONFIGURATION_ERROR, { turnId });
|
|
444
|
+
}
|
|
445
|
+
const modelDetails = await this.llmProviderManager.getModelInfo(modelIdToUse, providerIdForModel);
|
|
446
|
+
const modelTargetInfo = {
|
|
447
|
+
modelId: modelIdToUse,
|
|
448
|
+
providerId: modelDetails?.providerId || providerIdForModel || this.llmProviderManager.getProviderForModel(modelIdToUse)?.providerId || 'unknown',
|
|
449
|
+
maxContextTokens: modelDetails?.contextWindowSize || 8192, // Default fallback
|
|
450
|
+
capabilities: modelDetails?.capabilities || [],
|
|
451
|
+
promptFormatType: 'openai_chat', // TODO: Determine from modelDetails or provider features
|
|
452
|
+
toolSupport: { supported: modelDetails?.capabilities.includes('tool_use') || false, format: 'openai_functions' }, // TODO: Determine format
|
|
453
|
+
};
|
|
454
|
+
const promptEngineResult = await this.promptEngine.constructPrompt(promptComponents, modelTargetInfo, promptExecContext);
|
|
455
|
+
promptEngineResult.issues?.forEach(issue => this.addTraceEntry(ReasoningEntryType.WARNING, `Prompt Engine Issue: ${issue.message}`, issue));
|
|
456
|
+
this.addTraceEntry(ReasoningEntryType.PROMPT_CONSTRUCTION_COMPLETE, `Prompt constructed for model ${modelTargetInfo.modelId}.`);
|
|
457
|
+
const provider = this.llmProviderManager.getProvider(modelTargetInfo.providerId);
|
|
458
|
+
if (!provider) {
|
|
459
|
+
throw new GMIError(`LLM Provider '${modelTargetInfo.providerId}' not found or not initialized.`, GMIErrorCode.LLM_PROVIDER_UNAVAILABLE);
|
|
460
|
+
}
|
|
461
|
+
const toolsForLLM = await this.toolOrchestrator.listAvailableTools({
|
|
462
|
+
personaId: this.activePersona.id,
|
|
463
|
+
personaCapabilities: this.activePersona.allowedCapabilities || [],
|
|
464
|
+
userContext: this.currentUserContext,
|
|
465
|
+
});
|
|
466
|
+
const llmOptions = {
|
|
467
|
+
temperature: turnInput.metadata?.options?.temperature ?? this.activePersona.defaultModelCompletionOptions?.temperature ?? 0.7,
|
|
468
|
+
maxTokens: turnInput.metadata?.options?.maxTokens ?? this.activePersona.defaultModelCompletionOptions?.maxTokens ?? 2048,
|
|
469
|
+
tools: toolsForLLM.length > 0 ? toolsForLLM.map(t => ({ type: "function", function: { name: t.name, description: t.description, parameters: t.inputSchema } })) : undefined,
|
|
470
|
+
toolChoice: turnInput.metadata?.options?.toolChoice || (toolsForLLM.length > 0 ? "auto" : undefined),
|
|
471
|
+
userId: this.currentUserContext.userId,
|
|
472
|
+
stream: true, // For generateCompletionStream
|
|
473
|
+
responseFormat: turnInput.metadata?.options?.responseFormat,
|
|
474
|
+
};
|
|
475
|
+
this.addTraceEntry(ReasoningEntryType.LLM_CALL_START, `Streaming from ${modelTargetInfo.modelId}. Tools: ${toolsForLLM.length}.`);
|
|
476
|
+
let currentIterationTextResponse = "";
|
|
477
|
+
let currentIterationToolCallRequests = [];
|
|
478
|
+
let textDeltaEmitted = false;
|
|
479
|
+
for await (const chunk of provider.generateCompletionStream(modelTargetInfo.modelId, promptEngineResult.prompt, llmOptions)) {
|
|
480
|
+
if (chunk.error) {
|
|
481
|
+
throw new GMIError(`LLM stream error: ${chunk.error.message}`, GMIErrorCode.LLM_PROVIDER_ERROR, chunk.error.details);
|
|
482
|
+
}
|
|
483
|
+
if (chunk.responseTextDelta) {
|
|
484
|
+
currentIterationTextResponse += chunk.responseTextDelta;
|
|
485
|
+
aggregatedResponseText += chunk.responseTextDelta; // Aggregate for final output
|
|
486
|
+
yield this.createOutputChunk(turnInput.interactionId, GMIOutputChunkType.TEXT_DELTA, chunk.responseTextDelta, { usage: chunk.usage });
|
|
487
|
+
textDeltaEmitted = true;
|
|
488
|
+
}
|
|
489
|
+
// Handle fully formed tool_calls if present in the chunk's message
|
|
490
|
+
const choice = chunk.choices?.[0];
|
|
491
|
+
if (choice?.message?.tool_calls && choice.message.tool_calls.length > 0) {
|
|
492
|
+
currentIterationToolCallRequests = choice.message.tool_calls.map((tc) => ({
|
|
493
|
+
id: tc.id || `toolcall-${uuidv4()}`, // Ensure ID
|
|
494
|
+
name: tc.function.name,
|
|
495
|
+
arguments: typeof tc.function.arguments === 'string'
|
|
496
|
+
? JSON.parse(tc.function.arguments)
|
|
497
|
+
: tc.function.arguments,
|
|
498
|
+
}));
|
|
499
|
+
aggregatedToolCalls.push(...currentIterationToolCallRequests); // Aggregate for final output
|
|
500
|
+
yield this.createOutputChunk(turnInput.interactionId, GMIOutputChunkType.TOOL_CALL_REQUEST, [...currentIterationToolCallRequests]);
|
|
501
|
+
this.addTraceEntry(ReasoningEntryType.TOOL_CALL_REQUESTED, `LLM requested tool(s).`, { requests: currentIterationToolCallRequests });
|
|
502
|
+
}
|
|
503
|
+
if (chunk.isFinal && choice?.finishReason) {
|
|
504
|
+
this.addTraceEntry(ReasoningEntryType.LLM_CALL_COMPLETE, `LLM stream part finished. Reason: ${choice.finishReason}`, { usage: chunk.usage });
|
|
505
|
+
if (chunk.usage) {
|
|
506
|
+
yield this.createOutputChunk(turnInput.interactionId, GMIOutputChunkType.USAGE_UPDATE, chunk.usage);
|
|
507
|
+
// Aggregate usage
|
|
508
|
+
aggregatedUsage.promptTokens += chunk.usage.promptTokens || 0;
|
|
509
|
+
aggregatedUsage.completionTokens += chunk.usage.completionTokens || 0;
|
|
510
|
+
aggregatedUsage.totalTokens = aggregatedUsage.promptTokens + aggregatedUsage.completionTokens;
|
|
511
|
+
if (chunk.usage.costUSD)
|
|
512
|
+
aggregatedUsage.totalCostUSD = (aggregatedUsage.totalCostUSD || 0) + chunk.usage.costUSD;
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
} // End LLM stream
|
|
516
|
+
// Ensure at least one TEXT_DELTA is emitted for this turn if text was produced
|
|
517
|
+
if (!textDeltaEmitted && aggregatedResponseText) {
|
|
518
|
+
yield this.createOutputChunk(turnInput.interactionId, GMIOutputChunkType.TEXT_DELTA, aggregatedResponseText);
|
|
519
|
+
}
|
|
520
|
+
this.conversationHistory.push({
|
|
521
|
+
role: 'assistant',
|
|
522
|
+
content: currentIterationTextResponse || null,
|
|
523
|
+
tool_calls: currentIterationToolCallRequests.length > 0
|
|
524
|
+
? currentIterationToolCallRequests.map(tc => ({
|
|
525
|
+
id: tc.id,
|
|
526
|
+
type: 'function',
|
|
527
|
+
function: { name: tc.name, arguments: JSON.stringify(tc.arguments) }
|
|
528
|
+
}))
|
|
529
|
+
: undefined,
|
|
530
|
+
});
|
|
531
|
+
if (currentIterationToolCallRequests.length > 0) {
|
|
532
|
+
this.state = GMIPrimeState.AWAITING_TOOL_RESULT;
|
|
533
|
+
const toolExecutionResults = [];
|
|
534
|
+
for (const toolCallReq of currentIterationToolCallRequests) {
|
|
535
|
+
const requestDetails = {
|
|
536
|
+
toolCallRequest: toolCallReq,
|
|
537
|
+
gmiId: this.gmiId, personaId: this.activePersona.id,
|
|
538
|
+
personaCapabilities: this.activePersona.allowedCapabilities || [],
|
|
539
|
+
userContext: this.currentUserContext, correlationId: turnId,
|
|
540
|
+
};
|
|
541
|
+
this.addTraceEntry(ReasoningEntryType.TOOL_EXECUTION_START, `Orchestrating tool: ${toolCallReq.name}`, { reqId: toolCallReq.id });
|
|
542
|
+
const result = await this.toolOrchestrator.processToolCall(requestDetails);
|
|
543
|
+
toolExecutionResults.push(result);
|
|
544
|
+
this.addTraceEntry(ReasoningEntryType.TOOL_EXECUTION_RESULT, `Tool '${toolCallReq.name}' result. Success: ${!result.isError}`, { result });
|
|
545
|
+
}
|
|
546
|
+
toolExecutionResults.forEach(tcResult => this.updateConversationHistoryWithToolResult(tcResult));
|
|
547
|
+
currentIterationTextResponse = ""; // Reset for next iteration if any
|
|
548
|
+
currentIterationToolCallRequests = []; // Reset
|
|
549
|
+
this.state = GMIPrimeState.PROCESSING;
|
|
550
|
+
continue main_processing_loop;
|
|
551
|
+
}
|
|
552
|
+
break main_processing_loop; // Break if no tool calls
|
|
553
|
+
}
|
|
554
|
+
await this.performPostTurnIngestion(typeof turnInput.content === 'string' ? turnInput.content : JSON.stringify(turnInput.content), aggregatedResponseText);
|
|
555
|
+
this.turnsSinceLastReflection++;
|
|
556
|
+
const reflectionMetaPrompt = this.activePersona.metaPrompts?.find(mp => mp.id === 'gmi_self_trait_adjustment');
|
|
557
|
+
if (reflectionMetaPrompt?.trigger?.type === 'turn_interval' &&
|
|
558
|
+
this.turnsSinceLastReflection >= (reflectionMetaPrompt.trigger.intervalTurns || this.selfReflectionIntervalTurns)) {
|
|
559
|
+
this.addTraceEntry(ReasoningEntryType.SELF_REFLECTION_TRIGGERED, `Interval reached.`);
|
|
560
|
+
this._triggerAndProcessSelfReflection().catch(err => {
|
|
561
|
+
console.error(`GMI (ID: ${this.gmiId}): Background self-reflection error:`, err);
|
|
562
|
+
this.addTraceEntry(ReasoningEntryType.ERROR, "Self-reflection background process failed.", { error: err.message });
|
|
563
|
+
});
|
|
564
|
+
this.turnsSinceLastReflection = 0;
|
|
565
|
+
}
|
|
566
|
+
// Prepare the final GMIOutput for the generator's return value
|
|
567
|
+
const finalTurnOutput = {
|
|
568
|
+
isFinal: true,
|
|
569
|
+
responseText: aggregatedResponseText || null,
|
|
570
|
+
toolCalls: aggregatedToolCalls.length > 0 ? aggregatedToolCalls : undefined,
|
|
571
|
+
uiCommands: aggregatedUiCommands.length > 0 ? aggregatedUiCommands : undefined, // Assuming GMI can populate these
|
|
572
|
+
usage: aggregatedUsage,
|
|
573
|
+
error: lastErrorForOutput,
|
|
574
|
+
};
|
|
575
|
+
return finalTurnOutput; // Return the aggregated output
|
|
576
|
+
}
|
|
577
|
+
catch (error) {
|
|
578
|
+
const gmiError = createGMIErrorFromError(error, GMIErrorCode.GMI_PROCESSING_ERROR, { turnId }, `Error in GMI turn '${turnId}'.`);
|
|
579
|
+
this.state = GMIPrimeState.ERRORED;
|
|
580
|
+
lastErrorForOutput = { code: gmiError.code, message: gmiError.message, details: gmiError.details };
|
|
581
|
+
this.addTraceEntry(ReasoningEntryType.ERROR, `GMI processing error: ${gmiError.message}`, gmiError.toPlainObject());
|
|
582
|
+
console.error(`GMI (ID: ${this.gmiId}) error in turn '${turnId}':`, gmiError);
|
|
583
|
+
yield this.createOutputChunk(turnInput.interactionId, GMIOutputChunkType.ERROR, gmiError.message, { errorDetails: gmiError.toPlainObject() });
|
|
584
|
+
// Still need to return a GMIOutput for the generator contract
|
|
585
|
+
return {
|
|
586
|
+
isFinal: true,
|
|
587
|
+
responseText: null,
|
|
588
|
+
error: lastErrorForOutput,
|
|
589
|
+
usage: aggregatedUsage, // Could be partial
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
finally {
|
|
593
|
+
if (this.state !== GMIPrimeState.ERRORED && this.state !== GMIPrimeState.AWAITING_TOOL_RESULT) {
|
|
594
|
+
this.state = GMIPrimeState.READY;
|
|
595
|
+
}
|
|
596
|
+
// This final chunk is part of the stream, not the return value of the generator
|
|
597
|
+
yield this.createOutputChunk(turnInput.interactionId, GMIOutputChunkType.FINAL_RESPONSE_MARKER, 'Turn processing sequence complete.', { isFinal: true });
|
|
598
|
+
this.addTraceEntry(ReasoningEntryType.INTERACTION_END, `Turn '${turnId}' finished. GMI State: ${this.state}.`);
|
|
599
|
+
if (this.reasoningTrace)
|
|
600
|
+
this.reasoningTrace.turnId = undefined;
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
/** @inheritdoc */
|
|
604
|
+
async handleToolResult(toolCallId, toolName, resultPayload, _userId) {
|
|
605
|
+
if (!this.isInitialized) {
|
|
606
|
+
throw new GMIError("GMI is not initialized. Cannot handle tool result.", GMIErrorCode.NOT_INITIALIZED);
|
|
607
|
+
}
|
|
608
|
+
// Allow handling tool results if processing or specifically awaiting
|
|
609
|
+
if (this.state !== GMIPrimeState.AWAITING_TOOL_RESULT && this.state !== GMIPrimeState.PROCESSING) {
|
|
610
|
+
this.addTraceEntry(ReasoningEntryType.WARNING, `handleToolResult called when GMI state is ${this.state}. Expected AWAITING_TOOL_RESULT or PROCESSING.`, { toolCallId, toolName });
|
|
611
|
+
// Depending on desired robustness, could throw an error or try to proceed.
|
|
612
|
+
}
|
|
613
|
+
this.state = GMIPrimeState.PROCESSING; // Set state to processing
|
|
614
|
+
// Use current turnId if available, or generate a new interactionId for this specific handling
|
|
615
|
+
const interactionId = this.reasoningTrace?.turnId || `tool_handler_turn_${uuidv4()}`;
|
|
616
|
+
this.addTraceEntry(ReasoningEntryType.TOOL_EXECUTION_RESULT, `Received external tool result for '${toolName}' (ID: ${toolCallId}) to be processed.`, { toolCallId, toolName, success: resultPayload.type === 'success', interactionId });
|
|
617
|
+
const toolCallResult = {
|
|
618
|
+
toolCallId,
|
|
619
|
+
toolName,
|
|
620
|
+
output: resultPayload.type === 'success' ? resultPayload.result : resultPayload.error,
|
|
621
|
+
isError: resultPayload.type === 'error',
|
|
622
|
+
errorDetails: resultPayload.type === 'error' ? resultPayload.error : undefined,
|
|
623
|
+
};
|
|
624
|
+
this.updateConversationHistoryWithToolResult(toolCallResult);
|
|
625
|
+
// Construct a system turn input to represent the continuation after tool result
|
|
626
|
+
const systemTurnInput = {
|
|
627
|
+
interactionId,
|
|
628
|
+
userId: this.currentUserContext.userId, // Use the GMI's current user context
|
|
629
|
+
sessionId: this.reasoningTrace?.sessionId,
|
|
630
|
+
type: GMIInteractionType.SYSTEM_MESSAGE, // Or a specific type for internal continuation
|
|
631
|
+
content: `Internally processing result for tool '${toolName}'.`, // System message content
|
|
632
|
+
metadata: {
|
|
633
|
+
isToolContinuation: true,
|
|
634
|
+
originalToolCallId: toolCallId,
|
|
635
|
+
}
|
|
636
|
+
};
|
|
637
|
+
// Collect all chunks from processTurnStream to form a single GMIOutput
|
|
638
|
+
let _aggregatedResponseText = "";
|
|
639
|
+
const aggregatedToolCalls = [];
|
|
640
|
+
const aggregatedUsage = { totalTokens: 0, promptTokens: 0, completionTokens: 0, breakdown: [] };
|
|
641
|
+
let _lastErrorForOutput = undefined;
|
|
642
|
+
const stream = this.processTurnStream(systemTurnInput); // This now returns GMIOutput
|
|
643
|
+
const finalGmiOutputFromStream = await (async () => {
|
|
644
|
+
for await (const chunk of stream) {
|
|
645
|
+
// Process chunks as they arrive if needed for intermediate steps,
|
|
646
|
+
// but the final GMIOutput will be the generator's return value.
|
|
647
|
+
// Here, we mainly care about the final returned GMIOutput.
|
|
648
|
+
// However, if processTurnStream itself aggregates, this loop might just be to exhaust it.
|
|
649
|
+
if (chunk.type === GMIOutputChunkType.TEXT_DELTA && typeof chunk.content === 'string') {
|
|
650
|
+
_aggregatedResponseText += chunk.content;
|
|
651
|
+
}
|
|
652
|
+
if (chunk.type === GMIOutputChunkType.TOOL_CALL_REQUEST && Array.isArray(chunk.content)) {
|
|
653
|
+
aggregatedToolCalls.push(...chunk.content);
|
|
654
|
+
}
|
|
655
|
+
if (chunk.usage) {
|
|
656
|
+
aggregatedUsage.promptTokens += chunk.usage.promptTokens || 0;
|
|
657
|
+
aggregatedUsage.completionTokens += chunk.usage.completionTokens || 0;
|
|
658
|
+
aggregatedUsage.totalTokens = aggregatedUsage.promptTokens + aggregatedUsage.completionTokens;
|
|
659
|
+
if (chunk.usage.costUSD)
|
|
660
|
+
aggregatedUsage.totalCostUSD = (aggregatedUsage.totalCostUSD || 0) + chunk.usage.costUSD;
|
|
661
|
+
}
|
|
662
|
+
if (chunk.type === GMIOutputChunkType.ERROR) {
|
|
663
|
+
_lastErrorForOutput = chunk.errorDetails || { code: GMIErrorCode.GMI_PROCESSING_ERROR, message: String(chunk.content) };
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
// The actual final GMIOutput comes from the generator's return value
|
|
667
|
+
// This requires `processTurnStream` to be `async function* (...) : AsyncGenerator<..., GMIOutput, ...>`
|
|
668
|
+
// and to have a `return finalOutput;` statement.
|
|
669
|
+
// The loop above will collect intermediate chunks, and the 'return' from the generator is the key.
|
|
670
|
+
// This structure is a bit complex with nested generators. Let's assume processTurnStream does return a GMIOutput.
|
|
671
|
+
// The way AsyncGenerator TReturn works, the last value is 'done: true, value: TReturn'.
|
|
672
|
+
// My processTurnStream is modified to return GMIOutput.
|
|
673
|
+
let result = await stream.next();
|
|
674
|
+
while (!result.done) {
|
|
675
|
+
// This loop is mainly to exhaust the stream if previous loop didn't fully.
|
|
676
|
+
// The crucial part is what processTurnStream *returns*.
|
|
677
|
+
result = await stream.next();
|
|
678
|
+
}
|
|
679
|
+
return result.value; // This is the GMIOutput
|
|
680
|
+
})();
|
|
681
|
+
this.addTraceEntry(ReasoningEntryType.INTERACTION_END, `Continuation after tool '${toolName}' (ID: ${toolCallId}) processed.`);
|
|
682
|
+
return finalGmiOutputFromStream;
|
|
683
|
+
}
|
|
684
|
+
/**
|
|
685
|
+
* Performs post-turn RAG ingestion if configured.
|
|
686
|
+
* @private
|
|
687
|
+
*/
|
|
688
|
+
async performPostTurnIngestion(userInput, gmiResponse) {
|
|
689
|
+
const ragConfig = this.activePersona.memoryConfig?.ragConfig;
|
|
690
|
+
const ingestionTriggers = ragConfig?.ingestionTriggers;
|
|
691
|
+
const ingestionProcessingConfig = ragConfig?.ingestionProcessing;
|
|
692
|
+
if (!this.retrievalAugmentor || !ragConfig?.enabled || !ingestionTriggers?.onTurnSummary) {
|
|
693
|
+
return;
|
|
694
|
+
}
|
|
695
|
+
try {
|
|
696
|
+
const textToSummarize = `User: ${userInput}\n\nAssistant: ${gmiResponse}`;
|
|
697
|
+
let documentContent = textToSummarize;
|
|
698
|
+
const summarizationEnabled = ingestionProcessingConfig?.summarization?.enabled !== false;
|
|
699
|
+
if (this.utilityAI && summarizationEnabled) {
|
|
700
|
+
const summarizationOptions = {
|
|
701
|
+
desiredLength: ingestionProcessingConfig?.summarization?.targetLength || 'short',
|
|
702
|
+
method: ingestionProcessingConfig?.summarization?.method || 'abstractive_llm',
|
|
703
|
+
modelId: ingestionProcessingConfig?.summarization?.modelId || this.activePersona.defaultModelId || this.config.defaultLlmModelId,
|
|
704
|
+
providerId: ingestionProcessingConfig?.summarization?.providerId || this.activePersona.defaultProviderId || this.config.defaultLlmProviderId,
|
|
705
|
+
};
|
|
706
|
+
this.addTraceEntry(ReasoningEntryType.RAG_INGESTION_DETAIL, "Summarizing turn for RAG ingestion.", { textLength: textToSummarize.length, options: summarizationOptions });
|
|
707
|
+
documentContent = await this.utilityAI.summarize(textToSummarize, summarizationOptions);
|
|
708
|
+
}
|
|
709
|
+
const turnIdForMetadata = this.reasoningTrace.turnId || "unknown_turn"; // Handle undefined turnId
|
|
710
|
+
const docToIngest = {
|
|
711
|
+
id: `turnsummary-${this.gmiId}-${turnIdForMetadata}-${uuidv4()}`, // Ensure unique ID
|
|
712
|
+
content: documentContent,
|
|
713
|
+
metadata: {
|
|
714
|
+
gmiId: this.gmiId, personaId: this.activePersona.id, userId: this.currentUserContext.userId,
|
|
715
|
+
timestamp: new Date().toISOString(), type: "conversation_turn_summary",
|
|
716
|
+
turnId: turnIdForMetadata, // Now guaranteed to be a string
|
|
717
|
+
},
|
|
718
|
+
dataSourceId: ragConfig.defaultIngestionDataSourceId,
|
|
719
|
+
};
|
|
720
|
+
const ingestionOptions = {
|
|
721
|
+
userId: this.currentUserContext.userId, personaId: this.activePersona.id,
|
|
722
|
+
};
|
|
723
|
+
this.addTraceEntry(ReasoningEntryType.RAG_INGESTION_START, "Ingesting turn summary to RAG.", { documentId: docToIngest.id });
|
|
724
|
+
const ingestionResult = await this.retrievalAugmentor.ingestDocuments(docToIngest, ingestionOptions);
|
|
725
|
+
if (ingestionResult.failedCount > 0) {
|
|
726
|
+
this.addTraceEntry(ReasoningEntryType.WARNING, "Post-turn RAG ingestion encountered errors.", { errors: ingestionResult.errors });
|
|
727
|
+
}
|
|
728
|
+
else {
|
|
729
|
+
this.addTraceEntry(ReasoningEntryType.RAG_INGESTION_COMPLETE, "Post-turn RAG ingestion successful.", { ingestedIds: ingestionResult.ingestedIds });
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
catch (error) {
|
|
733
|
+
const gmiError = createGMIErrorFromError(error, GMIErrorCode.RAG_INGESTION_FAILED, undefined, "Error during post-turn RAG ingestion.");
|
|
734
|
+
this.addTraceEntry(ReasoningEntryType.ERROR, gmiError.message, gmiError.toPlainObject());
|
|
735
|
+
console.error(`GMI (ID: ${this.gmiId}): RAG Ingestion Error - ${gmiError.message}`, gmiError.details);
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
/** @inheritdoc */
|
|
739
|
+
async _triggerAndProcessSelfReflection() {
|
|
740
|
+
// ... (GMI.ts code for _triggerAndProcessSelfReflection provided by user, with my error fixes)
|
|
741
|
+
// Key fixes to apply within this method based on error list:
|
|
742
|
+
// - Error 32: Use GMIErrorCode.PARSING_ERROR (ensure it's added to errors.ts)
|
|
743
|
+
// - Error 33, 34: GMIError.wrap -> createGMIErrorFromError or new GMIError; PROCESSING_ERROR -> GMI_PROCESSING_ERROR
|
|
744
|
+
// - Error 35: Review logic for `this.state = previousState === ...`
|
|
745
|
+
// - Error 27 (ModelCompletionOptions.modelId): Fix in getModelAndProviderForLLMCall or here if directly accessed.
|
|
746
|
+
// - Error 31 (PROVIDER_ERROR): Change to LLM_PROVIDER_ERROR.
|
|
747
|
+
const reflectionMetaPromptDef = this.activePersona.metaPrompts?.find(mp => mp.id === 'gmi_self_trait_adjustment');
|
|
748
|
+
if (!reflectionMetaPromptDef?.promptTemplate) {
|
|
749
|
+
this.addTraceEntry(ReasoningEntryType.SELF_REFLECTION_SKIPPED, "Self-reflection disabled or no 'gmi_self_trait_adjustment' meta-prompt.");
|
|
750
|
+
return;
|
|
751
|
+
}
|
|
752
|
+
if (this.state === GMIPrimeState.REFLECTING) {
|
|
753
|
+
this.addTraceEntry(ReasoningEntryType.SELF_REFLECTION_SKIPPED, "Self-reflection already in progress.");
|
|
754
|
+
return;
|
|
755
|
+
}
|
|
756
|
+
const previousState = this.state;
|
|
757
|
+
this.state = GMIPrimeState.REFLECTING;
|
|
758
|
+
this.addTraceEntry(ReasoningEntryType.SELF_REFLECTION_START, "Starting self-reflection cycle.");
|
|
759
|
+
try {
|
|
760
|
+
const evidence = {
|
|
761
|
+
recentConversation: this.conversationHistory.slice(-10),
|
|
762
|
+
recentTraceEntries: this.reasoningTrace.entries.slice(-20),
|
|
763
|
+
currentMood: this.currentGmiMood,
|
|
764
|
+
currentUserContext: this.currentUserContext,
|
|
765
|
+
currentTaskContext: this.currentTaskContext,
|
|
766
|
+
};
|
|
767
|
+
this.addTraceEntry(ReasoningEntryType.SELF_REFLECTION_DETAIL, "Gathered evidence for reflection.", {
|
|
768
|
+
conversationSampleCount: evidence.recentConversation.length,
|
|
769
|
+
traceSampleCount: evidence.recentTraceEntries.length
|
|
770
|
+
});
|
|
771
|
+
let metaPromptText = (typeof reflectionMetaPromptDef.promptTemplate === 'string')
|
|
772
|
+
? reflectionMetaPromptDef.promptTemplate
|
|
773
|
+
: reflectionMetaPromptDef.promptTemplate.template;
|
|
774
|
+
metaPromptText = metaPromptText
|
|
775
|
+
.replace(/\{\{\s*evidence\s*\}\}/gi, JSON.stringify(evidence).substring(0, 4000) + "...")
|
|
776
|
+
.replace(/\{\{\s*current_mood\s*\}\}/gi, this.currentGmiMood)
|
|
777
|
+
.replace(/\{\{\s*user_skill\s*\}\}/gi, this.currentUserContext.skillLevel || "unknown")
|
|
778
|
+
.replace(/\{\{\s*task_complexity\s*\}\}/gi, this.currentTaskContext.complexity || "unknown");
|
|
779
|
+
this.addTraceEntry(ReasoningEntryType.SELF_REFLECTION_DETAIL, "Constructed meta-prompt.", { preview: metaPromptText.substring(0, 100) });
|
|
780
|
+
const { modelId, providerId } = this.getModelAndProviderForLLMCall(reflectionMetaPromptDef.modelId, reflectionMetaPromptDef.providerId, this.activePersona.defaultModelId || this.config.defaultLlmModelId, this.activePersona.defaultProviderId || this.config.defaultLlmProviderId);
|
|
781
|
+
const provider = this.llmProviderManager.getProvider(providerId);
|
|
782
|
+
if (!provider) {
|
|
783
|
+
throw new GMIError(`Provider '${providerId}' not found for self-reflection.`, GMIErrorCode.LLM_PROVIDER_UNAVAILABLE);
|
|
784
|
+
}
|
|
785
|
+
// Using generateCompletion as generate is often for older text completion models
|
|
786
|
+
const llmResponse = await provider.generateCompletion(modelId, [{ role: 'user', content: metaPromptText }], {
|
|
787
|
+
maxTokens: reflectionMetaPromptDef.maxOutputTokens || 512,
|
|
788
|
+
temperature: reflectionMetaPromptDef.temperature || 0.3,
|
|
789
|
+
responseFormat: { type: "json_object" } // Request JSON output
|
|
790
|
+
});
|
|
791
|
+
const responseContent = llmResponse.choices?.[0]?.message?.content;
|
|
792
|
+
if (!responseContent || typeof responseContent !== 'string') {
|
|
793
|
+
throw new GMIError("Self-reflection LLM call returned no valid content.", GMIErrorCode.LLM_PROVIDER_ERROR, { response: llmResponse });
|
|
794
|
+
}
|
|
795
|
+
this.addTraceEntry(ReasoningEntryType.SELF_REFLECTION_DETAIL, "LLM response for reflection received.", { preview: responseContent.substring(0, 100) });
|
|
796
|
+
const parseOptions = {
|
|
797
|
+
attemptFixWithLLM: true,
|
|
798
|
+
llmModelIdForFix: reflectionMetaPromptDef.modelId || modelId,
|
|
799
|
+
llmProviderIdForFix: reflectionMetaPromptDef.providerId || providerId,
|
|
800
|
+
};
|
|
801
|
+
const parsedUpdates = await this.utilityAI.parseJsonSafe(responseContent, parseOptions);
|
|
802
|
+
if (!parsedUpdates) {
|
|
803
|
+
throw new GMIError("Failed to parse/fix JSON from self-reflection LLM.", GMIErrorCode.PARSING_ERROR, { responseText: responseContent });
|
|
804
|
+
}
|
|
805
|
+
this.addTraceEntry(ReasoningEntryType.SELF_REFLECTION_DETAIL, "Parsed trait update suggestions.", { suggestions: parsedUpdates });
|
|
806
|
+
let stateChanged = false;
|
|
807
|
+
// ... (Apply updates as in the original GMI.ts code, ensuring null checks if needed)
|
|
808
|
+
if (parsedUpdates.updatedGmiMood && Object.values(GMIMood).includes(parsedUpdates.updatedGmiMood) && this.currentGmiMood !== parsedUpdates.updatedGmiMood) {
|
|
809
|
+
this.currentGmiMood = parsedUpdates.updatedGmiMood;
|
|
810
|
+
await this.workingMemory.set('currentGmiMood', this.currentGmiMood);
|
|
811
|
+
stateChanged = true;
|
|
812
|
+
}
|
|
813
|
+
if (parsedUpdates.updatedUserSkillLevel && this.currentUserContext.skillLevel !== parsedUpdates.updatedUserSkillLevel) {
|
|
814
|
+
this.currentUserContext.skillLevel = parsedUpdates.updatedUserSkillLevel;
|
|
815
|
+
await this.workingMemory.set('currentUserContext', this.currentUserContext);
|
|
816
|
+
stateChanged = true;
|
|
817
|
+
}
|
|
818
|
+
if (parsedUpdates.updatedTaskComplexity && this.currentTaskContext.complexity !== parsedUpdates.updatedTaskComplexity) {
|
|
819
|
+
this.currentTaskContext.complexity = parsedUpdates.updatedTaskComplexity;
|
|
820
|
+
await this.workingMemory.set('currentTaskContext', this.currentTaskContext);
|
|
821
|
+
stateChanged = true;
|
|
822
|
+
}
|
|
823
|
+
if (parsedUpdates.newMemoryImprints && parsedUpdates.newMemoryImprints.length > 0) {
|
|
824
|
+
for (const imprint of parsedUpdates.newMemoryImprints) {
|
|
825
|
+
if (imprint.key)
|
|
826
|
+
await this.workingMemory.set(imprint.key, imprint.value);
|
|
827
|
+
}
|
|
828
|
+
stateChanged = true;
|
|
829
|
+
this.addTraceEntry(ReasoningEntryType.STATE_CHANGE, "New memory imprints added from self-reflection.", { imprints: parsedUpdates.newMemoryImprints.map(i => i.key) });
|
|
830
|
+
}
|
|
831
|
+
if (stateChanged) {
|
|
832
|
+
this.addTraceEntry(ReasoningEntryType.STATE_CHANGE, "GMI state updated via self-reflection.", {
|
|
833
|
+
newMood: this.currentGmiMood, newUserSkill: this.currentUserContext.skillLevel, newTaskComplexity: this.currentTaskContext.complexity,
|
|
834
|
+
rationale: parsedUpdates.adjustmentRationale
|
|
835
|
+
});
|
|
836
|
+
}
|
|
837
|
+
else {
|
|
838
|
+
this.addTraceEntry(ReasoningEntryType.SELF_REFLECTION_DETAIL, "No state changes applied from self-reflection.", { rationale: parsedUpdates.adjustmentRationale });
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
catch (error) {
|
|
842
|
+
const gmiError = createGMIErrorFromError(error, GMIErrorCode.GMI_PROCESSING_ERROR, undefined, `Error during self-reflection.`);
|
|
843
|
+
this.addTraceEntry(ReasoningEntryType.ERROR, `Self-reflection failed: ${gmiError.message}`, gmiError.toPlainObject());
|
|
844
|
+
console.error(`GMI (ID: ${this.gmiId}) self-reflection error:`, gmiError);
|
|
845
|
+
}
|
|
846
|
+
finally {
|
|
847
|
+
// Or, if specific state is needed, previousState should be one of the valid non-reflecting states.
|
|
848
|
+
const disallowedStates = new Set([GMIPrimeState.IDLE, GMIPrimeState.INITIALIZING]);
|
|
849
|
+
this.state = disallowedStates.has(previousState) ? GMIPrimeState.READY : previousState;
|
|
850
|
+
this.addTraceEntry(ReasoningEntryType.SELF_REFLECTION_COMPLETE, "Self-reflection cycle finished.");
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
/**
|
|
854
|
+
* Helper to determine model and provider for internal LLM calls.
|
|
855
|
+
* @private
|
|
856
|
+
*/
|
|
857
|
+
getModelAndProviderForLLMCall(preferredModelId, preferredProviderId, systemDefaultModelId, systemDefaultProviderId) {
|
|
858
|
+
let modelId = preferredModelId || this.activePersona.defaultModelId || systemDefaultModelId;
|
|
859
|
+
let providerId = preferredProviderId || this.activePersona.defaultProviderId || systemDefaultProviderId;
|
|
860
|
+
if (!modelId) {
|
|
861
|
+
const defaultProvider = this.llmProviderManager.getDefaultProvider();
|
|
862
|
+
modelId = defaultProvider?.defaultModelId;
|
|
863
|
+
if (!providerId && modelId) { // If modelId found from default provider, use that providerId
|
|
864
|
+
providerId = defaultProvider?.providerId;
|
|
865
|
+
}
|
|
866
|
+
if (!modelId) { // Still no modelId after all fallbacks
|
|
867
|
+
throw new GMIError("Cannot determine modelId for LLM call: No preferred, persona default, system default, or provider default found.", GMIErrorCode.CONFIGURATION_ERROR);
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
if (!providerId && modelId.includes('/')) {
|
|
871
|
+
const parts = modelId.split('/');
|
|
872
|
+
if (parts.length >= 2) { // Can be "openai/gpt-3.5-turbo" or "ollama/modelname/variant"
|
|
873
|
+
providerId = parts[0];
|
|
874
|
+
// modelId = parts.slice(1).join('/'); // Keep full model name if provider prefix was there
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
if (!providerId) {
|
|
878
|
+
const foundProvider = this.llmProviderManager.getProviderForModel(modelId);
|
|
879
|
+
if (foundProvider) {
|
|
880
|
+
providerId = foundProvider.providerId;
|
|
881
|
+
}
|
|
882
|
+
else {
|
|
883
|
+
throw new GMIError(`Cannot determine providerId for model '${modelId}'. No explicit providerId, unable to infer from modelId, and no default provider found for it.`, GMIErrorCode.CONFIGURATION_ERROR, { modelId });
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
// Ensure modelId doesn't contain the provider prefix if providerId is now set
|
|
887
|
+
if (modelId.startsWith(providerId + '/')) {
|
|
888
|
+
modelId = modelId.substring(providerId.length + 1);
|
|
889
|
+
}
|
|
890
|
+
return { modelId, providerId };
|
|
891
|
+
}
|
|
892
|
+
/** @inheritdoc */
|
|
893
|
+
async onMemoryLifecycleEvent(event) {
|
|
894
|
+
this.ensureReady();
|
|
895
|
+
this.addTraceEntry(ReasoningEntryType.MEMORY_LIFECYCLE_EVENT_RECEIVED, `Received memory lifecycle event: ${event.type}`, { eventId: event.eventId, itemId: event.itemId });
|
|
896
|
+
const personaLifecycleConf = this.activePersona.memoryConfig?.lifecycleConfig;
|
|
897
|
+
let gmiDecision = event.proposedAction;
|
|
898
|
+
let rationale = 'GMI default action: align with MemoryLifecycleManager proposal.';
|
|
899
|
+
if (personaLifecycleConf?.negotiationEnabled && event.negotiable) {
|
|
900
|
+
this.addTraceEntry(ReasoningEntryType.MEMORY_LIFECYCLE_NEGOTIATION_START, "GMI negotiation for memory item.", { event });
|
|
901
|
+
if (event.category === RagMemoryCategory.USER_EXPLICIT_MEMORY.toString() &&
|
|
902
|
+
(event.type === 'DELETION_PROPOSED' || event.type === 'EVICTION_PROPOSED') &&
|
|
903
|
+
event.proposedAction === 'DELETE') {
|
|
904
|
+
gmiDecision = 'PREVENT_ACTION';
|
|
905
|
+
rationale = 'GMI policy: User explicit memory requires careful review; preventing immediate deletion/eviction.';
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
const response = {
|
|
909
|
+
gmiId: this.gmiId, eventId: event.eventId, actionTaken: gmiDecision, rationale,
|
|
910
|
+
};
|
|
911
|
+
this.addTraceEntry(ReasoningEntryType.MEMORY_LIFECYCLE_RESPONSE_SENT, `Responding to memory event: ${response.actionTaken}`, { response });
|
|
912
|
+
return response;
|
|
913
|
+
}
|
|
914
|
+
/** @inheritdoc */
|
|
915
|
+
async analyzeAndReportMemoryHealth() {
|
|
916
|
+
this.ensureReady();
|
|
917
|
+
this.addTraceEntry(ReasoningEntryType.HEALTH_CHECK_REQUESTED, "Analyzing GMI memory health.");
|
|
918
|
+
const workingMemorySize = await this.workingMemory.size();
|
|
919
|
+
const ragHealth = this.retrievalAugmentor ? await this.retrievalAugmentor.checkHealth() : { isHealthy: true, details: "RAG not configured." };
|
|
920
|
+
const memoryHealthReport = {
|
|
921
|
+
overallStatus: ragHealth.isHealthy ? 'OPERATIONAL' : 'DEGRADED',
|
|
922
|
+
workingMemoryStats: { itemCount: workingMemorySize },
|
|
923
|
+
ragSystemStats: ragHealth,
|
|
924
|
+
issues: [],
|
|
925
|
+
};
|
|
926
|
+
if (!ragHealth.isHealthy)
|
|
927
|
+
memoryHealthReport.issues?.push({ severity: 'warning', component: 'RetrievalAugmentor', description: "RAG system health check failed.", details: ragHealth.details });
|
|
928
|
+
this.addTraceEntry(ReasoningEntryType.HEALTH_CHECK_RESULT, "Memory health analysis complete.", { status: memoryHealthReport.overallStatus });
|
|
929
|
+
return memoryHealthReport;
|
|
930
|
+
}
|
|
931
|
+
/** @inheritdoc */
|
|
932
|
+
async getOverallHealth() {
|
|
933
|
+
this.addTraceEntry(ReasoningEntryType.HEALTH_CHECK_REQUESTED, "Overall GMI health check.");
|
|
934
|
+
const memoryHealth = await this.analyzeAndReportMemoryHealth();
|
|
935
|
+
const dependenciesStatus = [];
|
|
936
|
+
// Example extended dependency check
|
|
937
|
+
const checkDep = async (name, service) => {
|
|
938
|
+
if (!service || typeof service.checkHealth !== 'function') {
|
|
939
|
+
dependenciesStatus.push({ componentName: name, status: 'UNKNOWN', details: `${name} service not configured or has no health check.` });
|
|
940
|
+
return;
|
|
941
|
+
}
|
|
942
|
+
try {
|
|
943
|
+
const health = await service.checkHealth();
|
|
944
|
+
dependenciesStatus.push({ componentName: name, status: health.isHealthy ? 'HEALTHY' : 'UNHEALTHY', details: health.details });
|
|
945
|
+
}
|
|
946
|
+
catch (e) {
|
|
947
|
+
dependenciesStatus.push({ componentName: name, status: 'ERROR', details: e.message });
|
|
948
|
+
}
|
|
949
|
+
};
|
|
950
|
+
await Promise.all([
|
|
951
|
+
checkDep('AIModelProviderManager', this.llmProviderManager), // Cast if AIModelProviderManager doesn't directly implement checkHealth
|
|
952
|
+
checkDep('ToolOrchestrator', this.toolOrchestrator),
|
|
953
|
+
checkDep('UtilityAI', this.utilityAI), // Cast if IUtilityAI doesn't have checkHealth
|
|
954
|
+
checkDep('PromptEngine', this.promptEngine), // Cast if IPromptEngine doesn't have checkHealth
|
|
955
|
+
// retrievalAugmentor already included in memoryHealth
|
|
956
|
+
]);
|
|
957
|
+
let overallSystemHealthy = memoryHealth?.overallStatus === 'OPERATIONAL';
|
|
958
|
+
dependenciesStatus.forEach(dep => { if (dep.status !== 'HEALTHY')
|
|
959
|
+
overallSystemHealthy = false; });
|
|
960
|
+
const report = {
|
|
961
|
+
gmiId: this.gmiId,
|
|
962
|
+
personaId: this.activePersona?.id || 'uninitialized',
|
|
963
|
+
timestamp: new Date(),
|
|
964
|
+
overallStatus: overallSystemHealthy ? 'HEALTHY' : 'DEGRADED',
|
|
965
|
+
currentState: this.state,
|
|
966
|
+
memoryHealth,
|
|
967
|
+
dependenciesStatus,
|
|
968
|
+
recentErrors: this.reasoningTrace.entries.filter(e => e.type === ReasoningEntryType.ERROR).slice(-5),
|
|
969
|
+
// uptimeSeconds, activeTurnsProcessed would need dedicated tracking if required
|
|
970
|
+
};
|
|
971
|
+
this.addTraceEntry(ReasoningEntryType.HEALTH_CHECK_RESULT, "Overall GMI health check complete.", { status: report.overallStatus });
|
|
972
|
+
return report;
|
|
973
|
+
}
|
|
974
|
+
/** @inheritdoc */
|
|
975
|
+
async shutdown() {
|
|
976
|
+
if (this.state === GMIPrimeState.SHUTDOWN || (this.state === GMIPrimeState.IDLE && !this.isInitialized)) {
|
|
977
|
+
console.log(`GMI (ID: ${this.gmiId}) already shut down or was never fully initialized.`);
|
|
978
|
+
this.state = GMIPrimeState.SHUTDOWN;
|
|
979
|
+
return;
|
|
980
|
+
}
|
|
981
|
+
this.state = GMIPrimeState.SHUTTING_DOWN;
|
|
982
|
+
this.addTraceEntry(ReasoningEntryType.LIFECYCLE, "GMI shutting down.");
|
|
983
|
+
try {
|
|
984
|
+
await this.workingMemory?.close?.();
|
|
985
|
+
await this.retrievalAugmentor?.shutdown?.();
|
|
986
|
+
await this.toolOrchestrator?.shutdown?.();
|
|
987
|
+
// await this.promptEngine?.shutdown?.();
|
|
988
|
+
await this.utilityAI?.shutdown?.(); // Assuming IUtilityAI might have an optional shutdown
|
|
989
|
+
}
|
|
990
|
+
catch (error) {
|
|
991
|
+
const shutdownError = createGMIErrorFromError(error, GMIErrorCode.INTERNAL_SERVER_ERROR, undefined, "Error during GMI component shutdown.");
|
|
992
|
+
this.addTraceEntry(ReasoningEntryType.ERROR, shutdownError.message, shutdownError.toPlainObject());
|
|
993
|
+
console.error(`GMI (ID: ${this.gmiId}): Error during component shutdown:`, shutdownError);
|
|
994
|
+
}
|
|
995
|
+
finally {
|
|
996
|
+
this.state = GMIPrimeState.SHUTDOWN;
|
|
997
|
+
this.isInitialized = false; // Mark as not initialized
|
|
998
|
+
this.addTraceEntry(ReasoningEntryType.LIFECYCLE, "GMI shutdown complete.");
|
|
999
|
+
console.log(`GMI (ID: ${this.gmiId}) shut down.`);
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
//# sourceMappingURL=GMI.js.map
|