/** * LLM Manager Module - Pure Orchestration Layer (LLM Provider Refactoring Phase 5) * * Features: * - Browser-safe LLM integration using direct provider SDKs (OpenAI, Anthropic, Google) * - Streaming responses with SSE events via World.eventEmitter specifically * - Support for all major LLM providers (OpenAI, Anthropic, Google, Azure, XAI, OpenAI-Compatible, Ollama) * - Agent activity tracking and token usage monitoring with automatic state persistence * - Error handling with SSE error events via world's eventEmitter and timeout management * - World-aware event publishing using world.eventEmitter for proper event isolation * - Conversation history support with message preparation and context management * - Global LLM call queue to ensure serialized execution (one LLM call at a time) * - Configuration injection from external sources (CLI/server) for browser compatibility * - Automatic MCP tool integration for worlds with mcpConfig * - All providers return LLMResponse with unified structure * - Granular function-based logging for detailed debugging control * * Core Functions: * - streamAgentResponse: Streaming LLM calls with SSE events via world.eventEmitter (queued) * - generateAgentResponse: Non-streaming LLM calls with automatic state management (queued) * - loadLLMProvider: Provider loading logic using injected configuration * - getLLMQueueStatus: Monitor queue status for debugging and administration * - clearLLMQueue: Emergency queue clearing for administrative purposes * * Provider Support: * - OpenAI: Direct OpenAI package integration (bypasses AI SDK bug) * - Azure: Direct OpenAI package integration with Azure endpoints (bypasses AI SDK bug) * - OpenAI-Compatible: Direct OpenAI package integration (bypasses AI SDK bug) * - XAI: Direct OpenAI package integration with XAI endpoints (bypasses AI SDK bug) * - Ollama: Direct OpenAI package integration with OpenAI-compatible endpoint (better function calling) * - Anthropic: Direct Anthropic SDK integration (improved tool calling support) * - Google: Direct Google Generative AI SDK integration (improved tool calling support) * * Granular Logging Categories: * - llm.queue: Queue operations (add, process, complete, errors) * - llm.streaming: Streaming response operations (start, chunks, finish, errors) * - llm.generation: Non-streaming response operations (start, finish, errors) * - llm.provider: Provider loading, configuration, and validation * - llm.mcp: Comprehensive MCP tool integration and execution tracking * - llm.util: Utility functions and helper operations * * Environment Variable Control: * - LOG_LLM_QUEUE=debug: Enable queue operation debugging * - LOG_LLM_STREAMING=debug: Enable streaming operation debugging * - LOG_LLM_GENERATION=debug: Enable generation operation debugging * - LOG_LLM_PROVIDER=debug: Enable provider operation debugging * - LOG_LLM_MCP=debug: Enable comprehensive MCP tool debugging (consolidates all MCP logging) * - LOG_LLM_UTIL=debug: Enable utility function debugging * * MCP Tool Logging Features (LOG_LLM_MCP=debug): * - Tool call sequence tracking with unique sequence IDs * - Tool execution performance metrics (duration in milliseconds) * - Tool result content analysis (size, type, preview) * - Tool call success/failure status with detailed error information * - Tool call dependencies and parent-child relationships * - Tool argument validation and presence checking * - Streaming vs non-streaming execution path differentiation * - Complete tool call lifecycle from start to completion * - Server-side tool execution via direct MCP server registry calls * - AI SDK tool conversion execution tracking * - Tool result processing and content type identification * * LLM Queue Implementation: * - Global singleton queue prevents concurrent LLM calls across all agents and worlds * - FIFO (First In, First Out) processing ensures fair agent response ordering * - Maximum queue size of 100 items prevents memory overflow issues * - 15-minute timeout per LLM call supports long-running tool executions (configurable) * - Warning logs at 50% timeout threshold for debugging long-running operations * - Queue status monitoring available for debugging and performance analysis * - Emergency clear function allows administrative queue reset when needed * - Proper error handling with promise rejection for failed calls * - Automatic queue processing with safety measures for edge cases * - Timeout cleanup on promise resolution prevents resource leaks and Jest hanging * - Configurable timeout via setProcessingTimeout() for different use cases * * Browser Safety Implementation: * - Zero process.env dependencies for browser compatibility * - Configuration injection via llm-config module * - All provider settings supplied externally by CLI/server components * - Type-safe configuration interfaces prevent runtime errors * - Clear error messages when configuration is missing * * Implementation Details: * - Uses direct OpenAI package for OpenAI providers to avoid AI SDK schema corruption bug * - Uses direct Anthropic SDK for Anthropic provider to fix tool calling issues * - Uses direct Google Generative AI SDK for Google provider to fix tool calling issues * - Publishes SSE events via world.eventEmitter.emit('sse', event) for proper isolation * - Updates agent activity metrics and LLM call counts automatically * - Zero dependencies on Node.js environment variables or legacy event systems * - Complete provider support with externally injected configuration * - All events scoped to specific world instance preventing cross-world interference * - Full LLM provider support with configuration validation and error handling * - Timeout handling with configurable limits and proper error recovery * - Queue-based serialization prevents API rate limits and resource conflicts * * Recent Changes: * - 2026-03-13: Added streamed `reasoningContent` forwarding and world-variable reasoning-effort propagation for OpenAI-compatible and Google direct providers. * - 2026-03-06: Moved `shell_cmd` working-directory prompt guidance into tool-aware system-message injection. * - 2026-03-06: Widened queue timeout field typing to `number` so runtime timeout overrides compile cleanly. * - 2026-03-05: Added chat-scoped LLM timeout status system events (`taking too long` warning + hard-timeout event), enforced timeout-triggered abort signaling in queue processing, and classified queue timeouts separately from user cancellations. * - 2026-03-05: Switched LLM queue timeout defaults to shared reliability config. * - 2026-03-04: Azure client creation now maps `agent.model` to Azure deployment name (with config deployment fallback) so world/agent model selection controls deployment URL routing. * - 2026-02-28: Added canonical feature-path diagnostics (`llm.prep`, `llm.request.*`, `llm.response.*`) with opt-in raw payload logging and correlation metadata. * - 2026-02-24: Required explicit chatId for streaming SSE emission and propagated chatId through start/chunk/end/error events for strict chat-scoped frontend filtering. * - 2026-02-20: Switched injected tool-usage guidance to shared `buildToolUsagePromptSection()` so HITL and other tool rules are centralized in one utility. * - 2026-02-20: Updated injected tool-usage guidance to direct LLMs to use `human_intervention_request` for human clarifications and confirmations. * - 2026-02-13: Reclassified stop-triggered aborts as cancellation/info logs (not errors) in queue and non-streaming paths. * - 2026-02-13: Added merged external+queue abort-signal support so chat stop requests can cancel follow-up continuation calls. * - 2026-02-13: Added chat-scoped LLM cancellation controls so Electron stop requests can abort active and queued calls by `worldId` + `chatId`. * - 2026-02-08: Removed stale manual tool-intervention terminology from internal comments * - 2025-11-09: Phase 5 - Updated to expect LLMResponse from all providers * - Removed old manual tool decision return type handling * - All providers now return unified LLMResponse interface with type discriminator * - Updated logging to handle LLMResponse structure (type, content, tool_calls) * - Providers are now pure clients - no tool execution, only API calls * - NO type checking for string vs object - always LLMResponse * - Tool orchestration will be handled by events.ts (Phase 6) * - Simplified tool usage guidance: minimal system prompt patch for tool availability * - Increased LLM queue timeout from 2 minutes to 15 minutes for long-running tool executions * - Replaced AI SDK with direct OpenAI, Anthropic, and Google integrations * - Implemented granular function-based logging for detailed debugging control * - Tool-specific guidance moved to individual tool descriptions (proper separation) */ import { World, Agent, AgentMessage, LLMProvider, WorldSSEEvent, LLMResponse } from './types.js'; /** * Append tool usage guidance to system message when tools are available * Returns a new array with updated system message (doesn't mutate original) */ export declare function appendToolRulesToSystemMessage(messages: AgentMessage[], toolNames: string[], options?: { workingDirectory?: string; }): AgentMessage[]; /** * LLM configuration interface */ export interface LLMConfig { provider: LLMProvider; model: string; apiKey?: string; baseUrl?: string; temperature?: number; maxTokens?: number; ollamaBaseUrl?: string; } /** * Streaming agent response with SSE events via world's eventEmitter (queued) */ export declare function streamAgentResponse(world: World, agent: Agent, messages: AgentMessage[], publishSSE: (world: World, data: Partial) => void, chatId?: string | null, abortSignal?: AbortSignal): Promise<{ response: LLMResponse; messageId: string; }>; /** * Non-streaming LLM call (queued) */ export declare function generateAgentResponse(world: World, agent: Agent, messages: AgentMessage[], _publishSSE?: (world: World, data: Partial) => void, skipTools?: boolean, chatId?: string | null, abortSignal?: AbortSignal): Promise<{ response: LLMResponse; messageId: string; }>; /** * Get current LLM queue status for monitoring and debugging */ export declare function getLLMQueueStatus(): { queueLength: number; processing: boolean; nextAgent?: string; nextWorld?: string; maxQueueSize: number; }; /** * Emergency function to clear the LLM queue (for debugging/admin use) * Returns the number of items that were cleared */ export declare function clearLLMQueue(): number; /** * Cancel active and pending LLM calls for a specific world/chat session. */ export declare function cancelLLMCallsForChat(worldId: string, chatId: string | null): { canceledPending: number; abortedActive: number; };