art-framework 0.3.8 → 0.4.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 +21 -0
- package/README.md +4 -1
- package/dist/index.cjs +76 -135
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +139 -125
- package/dist/index.d.ts +139 -125
- package/dist/index.js +76 -135
- package/dist/index.js.map +1 -1
- package/package.json +22 -5
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/systems/reasoning/ProviderManagerImpl.ts","../src/utils/logger.ts","../src/systems/ui/typed-socket.ts","../src/systems/ui/llm-stream-socket.ts","../src/systems/ui/a2a-task-socket.ts","../src/types/schemas.ts","../src/types/index.ts","../src/utils/uuid.ts","../src/core/agents/pes-agent.ts","../src/integrations/storage/inMemory.ts","../src/integrations/storage/indexedDB.ts","../src/systems/context/repositories/ConversationRepository.ts","../src/systems/context/repositories/ObservationRepository.ts","../src/systems/context/repositories/StateRepository.ts","../src/systems/context/repositories/TaskStatusRepository.ts","../src/systems/context/managers/ConversationManager.ts","../src/systems/context/managers/StateManager.ts","../src/systems/observation/observation-manager.ts","../src/systems/tool/ToolRegistry.ts","../src/utils/validation.ts","../src/systems/tool/ToolSystem.ts","../src/systems/reasoning/PromptManager.ts","../src/systems/reasoning/SystemPromptResolver.ts","../src/systems/reasoning/ReasoningEngine.ts","../src/utils/xml-matcher.ts","../src/systems/reasoning/OutputParser.ts","../src/systems/ui/observation-socket.ts","../src/systems/ui/conversation-socket.ts","../src/systems/ui/ui-system.ts","../src/systems/auth/AuthManager.ts","../src/systems/mcp/McpProxyTool.ts","../src/systems/mcp/ConfigManager.ts","../src/systems/mcp/McpClient.ts","../src/systems/mcp/McpManager.ts","../src/systems/a2a/AgentDiscoveryService.ts","../src/systems/a2a/TaskDelegationService.ts","../src/core/agent-factory.ts","../src/integrations/storage/supabase.ts","../src/integrations/reasoning/gemini.ts","../src/integrations/reasoning/openai.ts","../src/integrations/reasoning/anthropic.ts","../src/integrations/reasoning/openrouter.ts","../src/integrations/reasoning/deepseek.ts","../src/integrations/reasoning/ollama.ts","../src/tools/CalculatorTool.ts","../src/auth/PKCEOAuthStrategy.ts","../src/auth/ApiKeyStrategy.ts","../src/auth/GenericOAuthStrategy.ts","../src/auth/ZyntopiaOAuthStrategy.ts","../src/index.ts"],"names":["ErrorCode","ARTError","_ARTError","message","code","originalError","details","str","UnknownProviderError","providerName","LocalProviderConflictError","requestedProvider","activeProvider","LocalInstanceBusyError","modelId","ApiQueueTimeoutError","AdapterInstantiationError","ProviderManagerImpl","config","p","sortedAdapterOptions","obj","key","configSignature","existingInstance","release","providerEntry","idleLocalProviderDifferentSignature","sig","instance","entry","resolve","reject","adapterInstance","adapterOptions","error","newManagedInstance","nextRequest","LogLevel","_Logger","args","Logger","TypedSocket","callback","filter","options","id","uuidv4","subscription","data","filterCheck","socketType","sub","_filter","_options","LLMStreamSocket","event","A2ATaskSocket","taskRepository","task","metadata","previousStatus","eventType","tasks","events","a","b","ArtStandardMessageSchema","z","val","ArtStandardPromptSchema","MessageRole","ObservationType","ModelCapability","A2ATaskStatus","A2ATaskPriority","generateUUID","DEFAULT_PERSONA","PESAgent","dependencies","props","startTime","traceId","status","errorMessage","llmCalls","toolCallsCount","finalAiMessage","aggregatedLlmMetadata","phase","threadContext","planningSystemPrompt","synthesisSystemPrompt","runtimeProviderConfig","finalPersona","history","availableTools","planningOutput","planningMetadata","planningContext","delegatedA2ATasks","completedA2ATasks","toolResults","r","finalResponseContent","synthesisMetadata","uiMetadata","artError","err","saveError","endTime","callPersona","threadPersona","instancePersona","threadId","historyOptions","rawHistory","systemPrompt","formattedHistory","candidateAgents","a2aPromptSection","potentialTaskType","agent","planningPrompt","delegationToolSchema","allTools","toolsJson","t","planningOptions","planningOutputText","parsedPlanningOutput","planningStreamError","planningStream","delegationCalls","call","delegatedTasks","agentId","taskType","input","instructions","targetAgent","now","a2aTask","delegatedTask","a2aTasks","maxWaitTimeMs","pollIntervalMs","updatedTasks","incompleteTasks","i","latestTask","completedTasks","failedTasks","timeoutTasks","totalWaitTime","toolCalls","localToolCalls","synthesisPrompt","wrappedSynthesisSystemPrompt","toolsDiscovered","plannedCallsSummary","c","a2aSummary","result","synthesisOptions","synthesisStreamError","synthesisStream","synthesisErrorMessage","mainContent","metadataBlockRegex","match","parseError","finalTimestamp","msg","role","InMemoryStorageAdapter","_config","collection","collectionMap","item","filterOptions","results","DEFAULT_DB_NAME","DEFAULT_DB_VERSION","IndexedDBStorageAdapter","request","existingStores","missingStores","store","errorEvent","existingStoreNames","storeName","mode","sName","dataAsAny","dataToStore","transaction","sortKey","sortDir","valA","valB","skip","limit","storeNames","clearCount","totalStores","ConversationRepository","storageAdapter","messages","setPromises","messageToStore","filteredMessages","m","_id","rest","ObservationRepository","observation","filteredObservations","typeSet","obs","StateRepository","storedContext","context","contextToStore","currentContext","newContext","state","TaskStatusRepository","taskToStore","taskId","storedTask","updates","existingTask","updatedTask","filteredTasks","statusArray","queryResults","offset","cleanTask","ConversationManager","conversationRepository","conversationSocket","deepClone","clonedObj","StateManager","stateRepository","strategy","_userId","contextFromRepo","cachedContext","originalStateSnapshot","toolName","cachedData","currentState","currentStateSnapshot","toolNames","currentEnabledTools","newEnabledTools","updatedConfig","tool","ObservationManager","observationRepository","observationSocket","observationData","ToolRegistry","stateManager","executor","allExecutors","allSchemas","enabledToolNames","enabledSchemas","predicate","removed","name","exec","ajv","Ajv","compiledValidators","validateJsonSchema","schema","schemaKey","validate","ToolSystem","toolRegistry","observationManager","callId","validationResult","errorMessages","e","executionContext","PROMPT_FRAGMENTS","PromptManager","fragment","trimmedKey","value","prompt","ZodError","blueprint","renderedTemplate","mustache","parsedPrompt","applyStrategy","base","addition","normalizeOverride","SystemPromptResolver","promptManager","registry","finalPrompt","levels","lvl","ov","rendered","spec","variables","template","_m","v","ReasoningEngine","providerManager","providerConfig","accessor","streamResult","XmlMatcher","tagName","transform","position","newMatchStatus","statusToUse","lastChunk","chunksToYield","chunk","char","parsedToolCallSchema","toolCallsSchema","OutputParser","output","processedOutput","thoughtsList","chunks","nonThinkingContent","jsonParsed","raw","s","first","last","out","validation","titleMatch","intentMatch","planMatch","toolCallsMatch","toolCallsString","jsonArrayString","parsedJson","jsonRegex","jsonMatch","cleanedJsonString","ObservationSocket","observationFilter","ConversationSocket","messageOptions","UISystem","a2aTaskRepository","AuthManager","strategyId","count","McpProxyTool","card","toolDefinition","mcpManager","client","response","duration","validatedResponse","CallToolResultSchema","ConfigManager","storedConfig","rawConfig","validatedConfig","defaultConfig","cleanConfig","serverId","serverConfig","fixedConfig","base64UrlEncode","buffer","sha256Base64Url","digest","generateRandomString","length","array","TokenManager","oauthConfig","exp","token","body","res","McpClientController","_McpClientController","baseUrl","scopes","asMetadataUrl","asMetadataRes","existing","randomId","clientId","codeVerifier","codeChallenge","authUrl","url","discoveryDoc","customFetch","headers","newOptions","sessionIdHeader","StreamableHTTPClientTransport","Client","McpManager","_stateManager","authManager","mcpConfig","localServerConfigs","discoveredServerConfigs","allServerConfigs","discoveredConfig","registeredToolCount","toolsToRegister","toolDef","proxyTool","disconnectionPromises","existingClient","conn","targetUrl","hasInstall","install","getInstallUrl","hostname","info","getAllowedInfo","requestHosts","discoveryEndpoint","mcpCards","service","mcpCard","server","normalized","updated","fallback","timeoutMs","start","prefix","AgentDiscoveryService","cacheKey","cached","controller","timeoutId","a2aServices","agents","topK","topMatches","capabilities","totalScore","matchedCapabilities","capability","capLower","taskLower","capabilityScore","semanticPairs","word1","word2","getWordRoot","word","capWords","taskWords","capWord","taskWord","matchingAgents","requiredCap","agentCap","TaskDelegationService","submissionResponse","persistError","taskSubmissionUrl","submissionPayload","lastError","attempt","responseData","delay","statusUrl","statusData","statusResponse","updatedMetadata","cancelUrl","AgentFactory","storageConfig","AgentCoreImplementation","createArtInstance","factory","agentCore","uiSystem","conversationManager","SupabaseStorageAdapter","createClient","table","row","query","tables","GeminiAdapter","GoogleGenAI","sessionId","stream","callContext","modelOverride","modelToUse","contents","generationConfig","includeThoughts","thinkingBudget","requestConfig","genAIInstance","timeToFirstTokenMs","streamUsageMetadata","streamFinishReason","parts","part","partText","isThought","textPart","totalGenerationTimeMs","finalUsage","firstCandidate","responseText","finishReason","usageMetadata","nonStreamParts","tokenType","artPrompt","geminiContents","systemPromptContent","userContent","toolCall","OPENAI_DEFAULT_MODEL_ID","OPENAI_DEFAULT_MAX_TOKENS","OPENAI_DEFAULT_TEMPERATURE","OpenAIAdapter","OpenAI","availableArtTools","openaiApiParams","maxTokens","temperature","openaiOptions","reasoningEffort","reasoningSummary","responsesInput","translationResult","openaiTools","requestBody","K","streamInstance","accumulatedText","accumulatedReasoning","finalStopReason","accumulatedToolCalls","content","reasoningText","toolUseBlocks","outputItem","summary","tu","artMsg","systemText","translatedContent","toolResultText","userText","toolCallsText","tc","artTools","artTool","ANTHROPIC_DEFAULT_MODEL_ID","ANTHROPIC_DEFAULT_MAX_TOKENS","AnthropicAdapter","Anthropic","anthropicApiParams","topP","stopSequences","thinking","anthropicMessages","anthropicTools","accumulatedToolUses","toolUseAcc","thinkingBlockIndexes","currentInputTokens","currentOutputTokens","initialMetadata","deltaMetadata","thinkingText","block","textDelta","thinkingDelta","partial","joined","parsed","idx","toolData","betas","currentRoleInternal","messageRoleToPush","lastMessage","currentLastMessageContentArray","contentToMergeArray","mergedContent","lastArtMsg","blocks","toolResultBlock","OpenRouterAdapter","openAiMessages","openAiTools","openRouterOptions","includeReasoning","payload","apiUrl","errorBody","_a","tid","trid","sid","aggregatedToolCalls","reader","decoder","done","lines","line","dataContent","choice","delta","reasoningDetails","rd","tcDelta","dst","firstChoice","responseMessage","thinkingType","responseContent","tokenPayload","usage","assistantMsg","DeepSeekAdapter","parsedError","OllamaAdapter","cleanBaseUrl","accumulatedOutputTokens","finalApiResponseUsage","modelIdForTransform","messagesToProcess","translatedMessages","currentRoleForCompare","currentOpenAIMsgPart","allowedFunctions","_CalculatorTool","expression","previousResult","executionScope","resultValue","evaluate","outputResult","CalculatorTool","PKCEOAuthStrategy","evt","params","statePayload","authorizationUrl","errorDescription","tokenResponse","errorText","tokenData","randomBytes","verifier","hashBuffer","bytes","ApiKeyStrategy","apiKey","headerName","GenericOAuthStrategy","tokenRequest","expiresIn","expiresAt","cachedToken","_ZyntopiaOAuthStrategy","environment","defaultTokenEndpoint","defaultScopes","zyntopiaConfig","genericConfig","clientSecret","customScopes","ZyntopiaOAuthStrategy","VERSION"],"mappings":"gmBAMO,IAAKA,CAAAA,CAAAA,CAAAA,CAAAA,GAGRA,EAAA,cAAA,CAAiB,gBAAA,CAEjBA,EAAA,eAAA,CAAkB,iBAAA,CAElBA,CAAAA,CAAA,mBAAA,CAAsB,qBAAA,CAItBA,CAAAA,CAAA,cAAgB,eAAA,CAEhBA,CAAAA,CAAA,iBAAmB,kBAAA,CAEnBA,CAAAA,CAAA,YAAc,aAAA,CAIdA,CAAAA,CAAA,kBAAA,CAAqB,oBAAA,CAErBA,CAAAA,CAAA,wBAAA,CAA2B,2BAE3BA,CAAAA,CAAA,qBAAA,CAAwB,wBAExBA,CAAAA,CAAA,sBAAA,CAAyB,yBAEzBA,CAAAA,CAAA,yBAAA,CAA4B,2BAAA,CAE5BA,CAAAA,CAAA,wBAAA,CAA2B,0BAAA,CAE3BA,EAAA,yBAAA,CAA4B,2BAAA,CAI5BA,CAAAA,CAAA,cAAA,CAAiB,gBAAA,CAEjBA,CAAAA,CAAA,8BAAgC,+BAAA,CAEhCA,CAAAA,CAAA,oBAAA,CAAuB,sBAAA,CAEvBA,CAAAA,CAAA,aAAA,CAAgB,gBAIhBA,CAAAA,CAAA,eAAA,CAAkB,kBAElBA,CAAAA,CAAA,qBAAA,CAAwB,wBAExBA,CAAAA,CAAA,gBAAA,CAAmB,kBAAA,CAEnBA,CAAAA,CAAA,sBAAA,CAAyB,wBAAA,CAEzBA,EAAA,iBAAA,CAAoB,mBAAA,CAIpBA,EAAA,aAAA,CA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AW,aAAa,CAAA,CAAE,QAAA,CAASA,CAAAA,CAAO,WAAW,CAAA,CAC7F,MAAM,IAAI,KAAA,CAAM,uEAAuE,EAEzF,GAAIA,CAAAA,CAAO,cAAA,GAAmBA,CAAAA,CAAO,cAAA,CAAiB,GAAA,EAAQA,CAAAA,CAAO,cAAA,CAAiB,KACpF,MAAM,IAAI,KAAA,CAAM,2DAA2D,CAAA,CAE7E,GAAIA,CAAAA,CAAO,oBAAA,GAAyBA,EAAO,oBAAA,CAAuB,GAAA,EAASA,CAAAA,CAAO,oBAAA,CAAuB,GAAA,CAAA,CACvG,MAAM,IAAI,KAAA,CAAM,oEAAoE,CAExF,CACF,CAAA,CA1Ma8pB,CAAAA,CACa,kBAAA,CAAqB,CAC3C,UAAA,CAAY,uCAAA,CACZ,QAAS,+CAAA,CACT,WAAA,CAAa,2CACf,CAAA,CALWA,CAAAA,CAOa,uBAAA,CAA0B,CAChD,UAAA,CAAY,8CACZ,OAAA,CAAS,4DAAA,CACT,WAAA,CAAa,0EACf,CAAA,CAXK,IAAMQ,EAAAA,CAANR,MCoRMS,EAAAA,CAAU","file":"index.js","sourcesContent":["// src/errors.ts\n\n/**\n * Defines standard error codes for the ART framework.\n * These codes categorize errors originating from different subsystems.\n */\nexport enum ErrorCode {\n // Configuration Errors\n /** Invalid or malformed configuration provided. */\n INVALID_CONFIG = 'INVALID_CONFIG',\n /** A required API key was not provided. */\n MISSING_API_key = 'MISSING_API_KEY',\n /** General configuration-related error. */\n CONFIGURATION_ERROR = 'CONFIGURATION_ERROR',\n\n // Storage Errors\n /** A generic error occurred in the storage layer. */\n STORAGE_ERROR = 'STORAGE_ERROR',\n /** The requested thread could not be found in storage. */\n THREAD_NOT_FOUND = 'THREAD_NOT_FOUND',\n /** Failed to save data to the storage layer. */\n SAVE_FAILED = 'SAVE_FAILED',\n\n // Reasoning Errors\n /** An error occurred while communicating with the LLM provider. */\n LLM_PROVIDER_ERROR = 'LLM_PROVIDER_ERROR',\n /** Failed to generate a prompt. */\n PROMPT_GENERATION_FAILED = 'PROMPT_GENERATION_FAILED',\n /** Failed to parse the output from the LLM. */\n OUTPUT_PARSING_FAILED = 'OUTPUT_PARSING_FAILED',\n /** Error during prompt template rendering or initial structure creation. */\n PROMPT_ASSEMBLY_FAILED = 'PROMPT_ASSEMBLY_FAILED',\n /** The requested prompt fragment does not exist. */\n PROMPT_FRAGMENT_NOT_FOUND = 'PROMPT_FRAGMENT_NOT_FOUND',\n /** The constructed prompt object failed schema validation. */\n PROMPT_VALIDATION_FAILED = 'PROMPT_VALIDATION_FAILED',\n /** Failed to translate the ART standard prompt to a provider-specific format. */\n PROMPT_TRANSLATION_FAILED = 'PROMPT_TRANSLATION_FAILED',\n\n // Tool Errors\n /** The requested tool could not be found in the registry. */\n TOOL_NOT_FOUND = 'TOOL_NOT_FOUND',\n /** The provided tool schema failed validation. */\n TOOL_SCHEMA_VALIDATION_FAILED = 'TOOL_SCHEMA_VALIDATION_FAILED',\n /** A generic error occurred during tool execution. */\n TOOL_EXECUTION_ERROR = 'TOOL_EXECUTION_ERROR',\n /** The requested tool is disabled for the current thread. */\n TOOL_DISABLED = 'TOOL_DISABLED',\n\n // Agent Core / Orchestration Errors\n /** The planning phase of the agent failed. */\n PLANNING_FAILED = 'PLANNING_FAILED',\n /** An error occurred within the ToolSystem execution loop. */\n TOOL_EXECUTION_FAILED = 'TOOL_EXECUTION_FAILED',\n /** The synthesis phase of the agent failed. */\n SYNTHESIS_FAILED = 'SYNTHESIS_FAILED',\n /** A general error occurred during the agent's process method. */\n AGENT_PROCESSING_ERROR = 'AGENT_PROCESSING_ERROR',\n /** An A2A (Agent-to-Agent) task delegation failed. */\n DELEGATION_FAILED = 'DELEGATION_FAILED',\n\n // General Errors\n /** A network error occurred. */\n NETWORK_ERROR = 'NETWORK_ERROR',\n /** An operation timed out. */\n TIMEOUT_ERROR = 'TIMEOUT_ERROR',\n /** An operation timed out (duplicate of TIMEOUT_ERROR). */\n TIMEOUT = 'TIMEOUT',\n /** An error occurred with an external service. */\n EXTERNAL_SERVICE_ERROR = 'EXTERNAL_SERVICE_ERROR',\n /** The requested task was not found. */\n TASK_NOT_FOUND = 'TASK_NOT_FOUND',\n /** Input data failed validation. */\n VALIDATION_ERROR = 'VALIDATION_ERROR',\n /** The request was invalid or malformed. */\n INVALID_REQUEST = 'INVALID_REQUEST',\n /** A task with the same ID already exists. */\n DUPLICATE_TASK_ID = 'DUPLICATE_TASK_ID',\n /** A generic error occurred in a repository. */\n REPOSITORY_ERROR = 'REPOSITORY_ERROR',\n /** A connection is already established. */\n ALREADY_CONNECTED = 'ALREADY_CONNECTED',\n /** A required configuration is missing. */\n MISSING_CONFIG = 'MISSING_CONFIG',\n /** The requested feature is not implemented. */\n NOT_IMPLEMENTED = 'NOT_IMPLEMENTED',\n /** No active connection is available. */\n NOT_CONNECTED = 'NOT_CONNECTED',\n /** The request timed out. */\n REQUEST_TIMEOUT = 'REQUEST_TIMEOUT',\n /** Standard input is not available. */\n NO_STDIN = 'NO_STDIN',\n /** The provided URL is not an HTTP/HTTPS URL. */\n NO_HTTP_URL = 'NO_HTTP_URL',\n /** An HTTP error occurred. */\n HTTP_ERROR = 'HTTP_ERROR',\n /** The requested server was not found. */\n SERVER_NOT_FOUND = 'SERVER_NOT_FOUND',\n /** A health check for a service failed. */\n HEALTH_CHECK_FAILED = 'HEALTH_CHECK_FAILED',\n /** Failed to discover tools from a remote source. */\n TOOL_DISCOVERY_FAILED = 'TOOL_DISCOVERY_FAILED',\n /** The requested transport protocol is not supported. */\n UNSUPPORTED_TRANSPORT = 'UNSUPPORTed_TRANSPORT',\n /** A CORS browser extension is required to proceed. */\n CORS_EXTENSION_REQUIRED = 'CORS_EXTENSION_REQUIRED',\n /** CORS permissions are required but have not been granted. */\n CORS_PERMISSION_REQUIRED = 'CORS_PERMISSION_REQUIRED',\n /** An unknown or unexpected error occurred. */\n UNKNOWN_ERROR = 'UNKNOWN_ERROR',\n\n // Provider Manager Errors\n /** The requested LLM provider is not known or configured. */\n UNKNOWN_PROVIDER = 'UNKNOWN_PROVIDER',\n /** Attempted to activate a local provider when another is already active. */\n LOCAL_PROVIDER_CONFLICT = 'LOCAL_PROVIDER_CONFLICT',\n /** The requested local LLM instance is currently busy. */\n LOCAL_INSTANCE_BUSY = 'LOCAL_INSTANCE_BUSY',\n /** Timeout waiting for an available instance of an API provider. */\n API_QUEUE_TIMEOUT = 'API_QUEUE_TIMEOUT',\n /** Failed to instantiate an adapter for a provider. */\n ADAPTER_INSTANTIATION_ERROR = 'ADAPTER_INSTANTIATION_ERROR',\n}\n\n/**\n * Custom error class for ART framework specific errors.\n * It includes an error code, an optional original error for chaining,\n * and a details object for additional context.\n */\nexport class ARTError extends Error {\n /** The specific error code from the ErrorCode enum. */\n public readonly code: ErrorCode;\n /** The original error that caused this error, if any. */\n public readonly originalError?: Error;\n /** A record of additional details about the error. */\n public details: Record<string, any>;\n\n /**\n * Creates an instance of ARTError.\n * @param {string} message - The error message.\n * @param {ErrorCode} code - The error code.\n * @param {Error} [originalError] - The original error, if any.\n * @param {Record<string, any>} [details={}] - Additional details about the error.\n */\n constructor(message: string, code: ErrorCode, originalError?: Error, details: Record<string, any> = {}) {\n super(message);\n this.name = 'ARTError';\n this.code = code;\n this.originalError = originalError;\n this.details = details;\n\n // Maintains proper stack trace in V8 environments (Node, Chrome)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, ARTError);\n }\n }\n\n /**\n * Returns a string representation of the error, including the original error if present.\n * @returns {string} The string representation of the error.\n */\n toString(): string {\n let str = `${this.name} [${this.code}]: ${this.message}`;\n if (this.originalError) {\n str += `\\nCaused by: ${this.originalError.stack || this.originalError.toString()}`;\n }\n return str;\n }\n}\n\n/**\n * Error thrown when a requested LLM provider is not known or configured.\n */\nexport class UnknownProviderError extends ARTError {\n constructor(providerName: string) {\n super(`Unknown provider requested: ${providerName}`, ErrorCode.UNKNOWN_PROVIDER);\n this.name = 'UnknownProviderError';\n }\n}\n\n/**\n * Error thrown when attempting to activate a local provider while another is already active.\n */\nexport class LocalProviderConflictError extends ARTError {\n constructor(requestedProvider: string, activeProvider: string) {\n super(`Cannot activate local provider '${requestedProvider}'. Local provider '${activeProvider}' is already active.`, ErrorCode.LOCAL_PROVIDER_CONFLICT);\n this.name = 'LocalProviderConflictError';\n }\n}\n\n/**\n * Error thrown when a requested local LLM instance is currently busy.\n */\nexport class LocalInstanceBusyError extends ARTError {\n constructor(providerName: string, modelId: string) {\n super(`Local provider instance '${providerName}:${modelId}' is currently busy.`, ErrorCode.LOCAL_INSTANCE_BUSY);\n this.name = 'LocalInstanceBusyError';\n }\n}\n\n/**\n * Error thrown when a timeout occurs while waiting for an available instance of an API provider.\n */\nexport class ApiQueueTimeoutError extends ARTError {\n constructor(providerName: string) {\n super(`Timeout waiting for an available instance of API provider '${providerName}'.`, ErrorCode.API_QUEUE_TIMEOUT);\n this.name = 'ApiQueueTimeoutError';\n }\n}\n\n/**\n * Error thrown when an adapter for a provider fails to instantiate.\n */\nexport class AdapterInstantiationError extends ARTError {\n constructor(providerName: string, originalError: Error) {\n super(`Failed to instantiate adapter for provider '${providerName}'.`, ErrorCode.ADAPTER_INSTANTIATION_ERROR, originalError);\n this.name = 'AdapterInstantiationError';\n }\n}","import {\n IProviderManager,\n ProviderManagerConfig,\n RuntimeProviderConfig,\n ManagedAdapterAccessor,\n AvailableProviderEntry,\n} from '@/types/providers';\nimport { ProviderAdapter } from '@/core/interfaces';\nimport {\n UnknownProviderError,\n LocalProviderConflictError,\n LocalInstanceBusyError,\n AdapterInstantiationError, // Will need this later\n} from '@/errors';\n\n/** Internal type to track managed adapter instances */\ninterface ManagedInstance {\n adapter: ProviderAdapter;\n configSignature: string;\n state: 'idle' | 'active';\n lastUsedTimestamp?: number; // For API instance idle eviction\n idleTimer?: NodeJS.Timeout; // Timer reference for idle timeout\n}\n\n/** Internal type for queued requests */\ninterface QueuedRequest {\n config: RuntimeProviderConfig;\n resolve: (value: ManagedAdapterAccessor | PromiseLike<ManagedAdapterAccessor>) => void;\n reject: (reason?: any) => void;\n}\n\n/**\n * Manages the lifecycle and access to multiple ProviderAdapter implementations.\n */\nexport class ProviderManagerImpl implements IProviderManager {\n private availableProviders: Map<string, AvailableProviderEntry>;\n private maxParallelApiInstancesPerProvider: number;\n private apiInstanceIdleTimeoutMs: number;\n private managedInstances: Map<string, ManagedInstance>;\n private requestQueue: QueuedRequest[]; // Use the refined queue item type\n\n constructor(config: ProviderManagerConfig) {\n this.availableProviders = new Map(config.availableProviders.map(p => [p.name, p]));\n this.maxParallelApiInstancesPerProvider = config.maxParallelApiInstancesPerProvider ?? 5;\n this.apiInstanceIdleTimeoutMs = (config.apiInstanceIdleTimeoutSeconds ?? 300) * 1000;\n this.managedInstances = new Map();\n this.requestQueue = [];\n }\n\n /**\n * Generates a stable configuration signature for caching.\n * @param config The runtime provider configuration.\n * @returns A string signature.\n */\n private _getConfigSignature(config: RuntimeProviderConfig): string {\n const sortedAdapterOptions = config.adapterOptions\n ? Object.keys(config.adapterOptions).sort().reduce((obj: any, key) => {\n // Never include secrets in signature logs; signature remains internal only\n obj[key] = key.toLowerCase().includes('key') ? '***' : config.adapterOptions[key];\n return obj;\n }, {})\n : {};\n return JSON.stringify({\n providerName: config.providerName,\n modelId: config.modelId,\n adapterOptions: sortedAdapterOptions,\n });\n }\n\n getAvailableProviders(): string[] {\n return Array.from(this.availableProviders.keys());\n }\n\n async getAdapter(config: RuntimeProviderConfig): Promise<ManagedAdapterAccessor> {\n const configSignature = this._getConfigSignature(config);\n\n // 1. Check cache for existing instance\n const existingInstance = this.managedInstances.get(configSignature);\n\n if (existingInstance && existingInstance.state === 'idle') {\n // Reuse idle instance\n existingInstance.state = 'active';\n // Clear idle timer when reusing\n if (existingInstance.idleTimer) {\n clearTimeout(existingInstance.idleTimer);\n existingInstance.idleTimer = undefined;\n }\n\n const release = () => this._releaseAdapter(configSignature);\n return { adapter: existingInstance.adapter, release };\n }\n\n // 2. Check local provider constraints\n const providerEntry = this.availableProviders.get(config.providerName);\n if (!providerEntry) {\n throw new UnknownProviderError(config.providerName);\n }\n\n if (providerEntry.isLocal) {\n let idleLocalProviderDifferentSignature: ManagedInstance | undefined = undefined;\n\n for (const [sig, instance] of this.managedInstances.entries()) {\n const entry = this.availableProviders.get(instance.configSignature.split('\"providerName\":\"')[1].split('\"')[0]);\n if (entry?.isLocal) {\n if (instance.state === 'active') {\n if (sig !== configSignature) {\n throw new LocalProviderConflictError(config.providerName, entry.name);\n } else {\n throw new LocalInstanceBusyError(config.providerName, config.modelId);\n }\n } else if (instance.state === 'idle' && sig !== configSignature) {\n idleLocalProviderDifferentSignature = instance;\n }\n }\n }\n\n if (idleLocalProviderDifferentSignature) {\n await this._evictInstance(idleLocalProviderDifferentSignature.configSignature);\n }\n }\n\n // 3. Check API provider concurrency limits\n if (!providerEntry.isLocal) {\n const activeApiInstancesCount = Array.from(this.managedInstances.values()).filter(\n instance => {\n const entry = this.availableProviders.get(instance.configSignature.split('\"providerName\":\"')[1].split('\"')[0]);\n return entry && !entry.isLocal && instance.state === 'active' && entry.name === config.providerName;\n }\n ).length;\n\n if (activeApiInstancesCount >= this.maxParallelApiInstancesPerProvider) {\n return new Promise<ManagedAdapterAccessor>((resolve, reject) => {\n this.requestQueue.push({ config, resolve, reject });\n });\n }\n }\n\n // 4. Create new instance\n let adapterInstance: ProviderAdapter;\n try {\n const adapterOptions = { \n ...config.adapterOptions, \n providerName: config.providerName \n };\n adapterInstance = new providerEntry.adapter(adapterOptions);\n } catch (error: any) {\n throw new AdapterInstantiationError(config.providerName, error);\n }\n\n // 5. Store new instance\n const newManagedInstance: ManagedInstance = {\n adapter: adapterInstance,\n configSignature: configSignature,\n state: 'active',\n };\n this.managedInstances.set(configSignature, newManagedInstance);\n\n // 6. Return accessor\n const release = () => this._releaseAdapter(configSignature);\n return { adapter: newManagedInstance.adapter, release };\n }\n\n /**\n * Internal method to release an adapter instance back to the manager.\n * @param configSignature The signature of the instance to release.\n */\n private _releaseAdapter(configSignature: string): void {\n const instance = this.managedInstances.get(configSignature);\n if (!instance) {\n return;\n }\n\n instance.state = 'idle';\n instance.lastUsedTimestamp = Date.now();\n\n const providerEntry = this.availableProviders.get(instance.configSignature.split('\"providerName\":\"')[1].split('\"')[0]);\n\n // Start idle timer for API instances\n if (providerEntry && !providerEntry.isLocal) {\n if (instance.idleTimer) {\n clearTimeout(instance.idleTimer);\n }\n instance.idleTimer = setTimeout(() => {\n this._evictInstance(configSignature);\n }, this.apiInstanceIdleTimeoutMs);\n }\n\n // Check request queue\n if (this.requestQueue.length > 0) {\n const nextRequest = this.requestQueue.shift();\n if (nextRequest) {\n this.getAdapter(nextRequest.config)\n .then(nextRequest.resolve)\n .catch(nextRequest.reject);\n }\n }\n }\n\n /**\n * Internal method to evict an instance from the manager.\n * @param configSignature The signature of the instance to evict.\n */\n private async _evictInstance(configSignature: string): Promise<void> {\n const instance = this.managedInstances.get(configSignature);\n\n if (instance && instance.state === 'idle') {\n if (instance.adapter.shutdown) {\n try {\n await instance.adapter.shutdown();\n } catch (_error) {\n // swallow adapter shutdown errors\n }\n }\n\n this.managedInstances.delete(configSignature);\n if (instance.idleTimer) {\n clearTimeout(instance.idleTimer);\n instance.idleTimer = undefined;\n }\n }\n }\n}","/**\n * @module utils/logger\n * Provides a simple, static, and configurable logger for the ART framework.\n * It supports different log levels and can be enabled or disabled globally.\n */\n\n/**\n * Defines the available logging levels, ordered from most verbose to least verbose.\n *\n * @enum {number}\n */\nexport enum LogLevel {\n /** Detailed debugging information, useful for development. */\n DEBUG = 0,\n /** General informational messages about application flow. */\n INFO = 1,\n /** Potential issues or unexpected situations that don't prevent execution. */\n WARN = 2,\n /** Errors that indicate a failure or problem. */\n ERROR = 3,\n}\n\n/**\n * Configuration options for the static Logger class.\n *\n * @interface LoggerConfig\n */\nexport interface LoggerConfig {\n /**\n * The minimum log level to output messages for. Messages below this level will be ignored.\n * @property {LogLevel} level\n */\n level: LogLevel;\n /**\n * An optional prefix string to prepend to all log messages (e.g., '[MyApp]'). Defaults to '[ART]'.\n * @property {string} [prefix]\n */\n prefix?: string;\n}\n\n/**\n * A simple static logger class for outputting messages to the console at different levels.\n *\n * @remarks\n * Configuration is global via the static `configure` method.\n *\n * @class Logger\n */\nexport class Logger {\n private static config: LoggerConfig = {\n level: LogLevel.INFO,\n };\n\n /**\n * Configures the static logger settings.\n *\n * @param config A partial `LoggerConfig` object. Provided settings will override defaults.\n */\n static configure(config: Partial<LoggerConfig>): void {\n Logger.config = { ...Logger.config, ...config };\n }\n\n /**\n * Logs a message at the DEBUG level.\n *\n * @remarks\n * Only outputs if the configured log level is DEBUG.\n *\n * @param message The main log message string.\n * @param args Additional arguments to include in the console output (e.g., objects, arrays).\n */\n static debug(message: string, ...args: any[]): void {\n if (Logger.config.level <= LogLevel.DEBUG) {\n // eslint-disable-next-line no-console\n console.debug(`${Logger.config.prefix || '[ART]'} ${message}`, ...args);\n }\n }\n\n /**\n * Logs a message at the INFO level.\n *\n * @remarks\n * Outputs if the configured log level is INFO or DEBUG.\n *\n * @param message The main log message string.\n * @param args Additional arguments to include in the console output.\n */\n static info(message: string, ...args: any[]): void {\n if (Logger.config.level <= LogLevel.INFO) {\n // eslint-disable-next-line no-console\n console.info(`${Logger.config.prefix || '[ART]'} ${message}`, ...args);\n }\n }\n\n /**\n * Logs a message at the WARN level.\n *\n * @remarks\n * Outputs if the configured log level is WARN, INFO, or DEBUG.\n *\n * @param message The main log message string.\n * @param args Additional arguments to include in the console output.\n */\n static warn(message: string, ...args: any[]): void {\n if (Logger.config.level <= LogLevel.WARN) {\n // eslint-disable-next-line no-console\n console.warn(`${Logger.config.prefix || '[ART]'} ${message}`, ...args);\n }\n }\n\n /**\n * Logs a message at the ERROR level.\n *\n * @remarks\n * Outputs if the configured log level is ERROR, WARN, INFO, or DEBUG.\n *\n * @param message The main log message string.\n * @param args Additional arguments to include in the console output (often an error object).\n */\n static error(message: string, ...args: any[]): void {\n if (Logger.config.level <= LogLevel.ERROR) {\n // eslint-disable-next-line no-console\n console.error(`${Logger.config.prefix || '[ART]'} ${message}`, ...args);\n }\n }\n}","// src/systems/ui/typed-socket.ts\nimport { v4 as uuidv4 } from 'uuid';\nimport { Logger } from '@/utils/logger'; // Assuming logger exists\n\nexport type UnsubscribeFunction = () => void;\n\nexport interface Subscription<DataType, FilterType> {\n id: string;\n callback: (data: DataType) => void;\n filter?: FilterType;\n options?: { threadId?: string };\n}\n\n/**\n * A generic class for implementing a publish/subscribe pattern with filtering capabilities.\n * Designed for decoupling components, particularly UI updates from backend events.\n */\nexport class TypedSocket<DataType, FilterType = any> {\n protected subscriptions: Map<string, Subscription<DataType, FilterType>> = new Map();\n // Removed logger instance property\n\n constructor() {\n // No logger instantiation needed\n }\n\n /**\n * Subscribes a callback function to receive notifications.\n * @param callback - The function to call when new data is notified.\n * @param filter - An optional filter to only receive specific types of data.\n * @param options - Optional configuration, like a threadId for filtering.\n * @returns An unsubscribe function.\n */\n subscribe(\n callback: (data: DataType) => void,\n filter?: FilterType,\n options?: { threadId?: string }\n ): UnsubscribeFunction {\n const id = uuidv4();\n const subscription: Subscription<DataType, FilterType> = { id, callback, filter, options };\n this.subscriptions.set(id, subscription);\n Logger.debug(`New subscription added: ${id}, Filter: ${JSON.stringify(filter)}, Options: ${JSON.stringify(options)}`); // Use static Logger\n\n return () => {\n this.subscriptions.delete(id);\n Logger.debug(`Subscription removed: ${id}`); // Use static Logger\n };\n }\n\n /**\n * Notifies all relevant subscribers with new data.\n * @param data - The data payload to send to subscribers.\n * @param options - Optional targeting options (e.g., targetThreadId).\n * @param filterCheck - A function to check if a subscription's filter matches the data.\n */\n notify(\n data: DataType,\n options?: { targetThreadId?: string; targetSessionId?: string }, // targetSessionId might be useful later\n filterCheck?: (data: DataType, filter?: FilterType) => boolean\n ): void {\n // ADD THIS LOG: Identify the socket instance being notified\n const socketType = this.constructor.name; // Get class name (e.g., 'LLMStreamSocket', 'ObservationSocket')\n Logger.debug(`[${socketType}] notify() called. Data type: ${typeof data}, Sub count: ${this.subscriptions.size}, Options: ${JSON.stringify(options)}`);\n\n Logger.debug(`Notifying ${this.subscriptions.size} subscribers. Data: ${JSON.stringify(data).substring(0, 100)}..., Options: ${JSON.stringify(options)}`); // Use static Logger\n this.subscriptions.forEach((sub) => {\n try {\n // 1. Check threadId if provided in both subscription options and notification options\n if (sub.options?.threadId && options?.targetThreadId && sub.options.threadId !== options.targetThreadId) {\n return; // Skip if thread IDs don't match\n }\n\n // 2. Check filter if provided and a filterCheck function exists\n if (filterCheck && sub.filter !== undefined && !filterCheck(data, sub.filter)) {\n return; // Skip if filter doesn't match\n }\n\n // If checks pass, invoke the callback\n Logger.debug(`Checks passed for sub ${sub.id}. Invoking callback.`); // Add log before callback\n sub.callback(data);\n } catch (error) {\n Logger.error(`Error executing subscription callback ${sub.id}:`, error); // Use static Logger\n // Decide if we should remove the faulty subscription? For now, just log.\n }\n });\n }\n\n /**\n * Optional: Retrieves historical data. This base implementation is empty.\n * Subclasses might implement this by interacting with repositories.\n */\n async getHistory?(_filter?: FilterType, _options?: { threadId?: string; limit?: number }): Promise<DataType[]> { // Prefix unused vars\n Logger.warn('getHistory is not implemented in the base TypedSocket.'); // Use static Logger\n return [];\n }\n\n /**\n * Clears all subscriptions. Useful for cleanup.\n */\n clearAllSubscriptions(): void {\n this.subscriptions.clear();\n Logger.debug('All subscriptions cleared.'); // Use static Logger\n }\n}","// src/systems/ui/llm-stream-socket.ts\nimport { TypedSocket } from './typed-socket';\nimport { StreamEvent } from '@/types';\nimport { Logger } from '@/utils/logger';\n\n// Define the type for the filter used in this specific socket\nexport type StreamEventTypeFilter = StreamEvent['type'] | Array<StreamEvent['type']>;\n\n/**\n * A dedicated socket for broadcasting LLM stream events (`StreamEvent`) to UI subscribers.\n * Extends the generic TypedSocket and implements filtering based on `StreamEvent.type`.\n */\nexport class LLMStreamSocket extends TypedSocket<StreamEvent, StreamEventTypeFilter> {\n\n constructor() {\n super(); // Call base constructor\n Logger.debug('LLMStreamSocket initialized.');\n }\n\n /**\n * Notifies subscribers about a new LLM stream event.\n * Filters based on event type if a filter is provided during subscription.\n * @param event - The StreamEvent data.\n */\n notifyStreamEvent(event: StreamEvent): void {\n Logger.debug(`Notifying LLMStreamEvent: ${event.type} for thread ${event.threadId}, trace ${event.traceId}`);\n super.notify(\n event,\n { targetThreadId: event.threadId, targetSessionId: event.sessionId },\n // Filter check function: Matches if no filter or if event type matches filter\n (data, filter) => {\n if (!filter) return true; // No filter, always notify\n if (Array.isArray(filter)) {\n return filter.includes(data.type); // Check if type is in the array\n }\n return data.type === filter; // Check for single type match\n }\n );\n }\n\n // getHistory is not applicable for transient stream events, so we don't implement it.\n // The base class provides an empty implementation with a warning if called.\n}","import { TypedSocket } from './typed-socket';\nimport { A2ATask, A2ATaskStatus, A2ATaskPriority } from '@/types';\nimport { Logger } from '@/utils/logger';\nimport { IA2ATaskRepository } from '@/core/interfaces';\n\n/**\n * Filter type for A2A task notifications.\n * Allows filtering by task status, task type, agent, or priority.\n */\nexport interface A2ATaskFilter {\n /** Filter by task status (single status or array of statuses) */\n status?: A2ATaskStatus | A2ATaskStatus[];\n /** Filter by task type (e.g., 'analyze', 'synthesize', 'transform') */\n taskType?: string | string[];\n /** Filter by source agent ID */\n sourceAgentId?: string;\n /** Filter by target agent ID */\n targetAgentId?: string;\n /** Filter by task priority */\n priority?: A2ATaskPriority | string;\n /** Filter by thread ID */\n threadId?: string;\n}\n\n/**\n * Event data structure for A2A task updates.\n * Contains the updated task and metadata about the change.\n */\nexport interface A2ATaskEvent {\n /** The A2A task that was updated */\n task: A2ATask;\n /** The type of event that occurred */\n eventType: 'created' | 'updated' | 'completed' | 'failed' | 'cancelled' | 'status_changed' | 'delegated';\n /** Timestamp when the event occurred */\n timestamp: number;\n /** Previous status (if applicable) for status change events */\n previousStatus?: A2ATaskStatus;\n /** Additional metadata about the event */\n metadata?: {\n /** Whether this was an automatic update or manual */\n automatic?: boolean;\n /** The component that triggered the update */\n source?: string;\n /** Any additional context */\n context?: Record<string, any>;\n };\n}\n\n/**\n * A specialized TypedSocket for handling A2A task status updates and events.\n * Allows filtering by task status, type, agent, and other criteria.\n * Can optionally fetch historical task data from a repository.\n */\nexport class A2ATaskSocket extends TypedSocket<A2ATaskEvent, A2ATaskFilter> {\n private taskRepository?: IA2ATaskRepository;\n\n constructor(taskRepository?: IA2ATaskRepository) {\n super();\n this.taskRepository = taskRepository;\n Logger.debug('A2ATaskSocket initialized.');\n }\n\n /**\n * Notifies subscribers about a new A2A task event.\n * @param event - The A2A task event data.\n */\n notifyTaskEvent(event: A2ATaskEvent): void {\n Logger.debug(`Notifying A2A Task Event: ${event.task.taskId} (${event.eventType}) status: ${event.task.status}`);\n \n super.notify(\n event,\n { \n targetThreadId: event.task.metadata.correlationId, // Use correlationId as threadId if available\n targetSessionId: event.task.sourceAgent.agentId \n },\n (data, filter) => this.matchesFilter(data, filter)\n );\n }\n\n /**\n * Convenience method to notify about a task creation.\n * @param task - The newly created A2A task.\n * @param metadata - Optional additional metadata about the creation.\n */\n notifyTaskCreated(task: A2ATask, metadata?: A2ATaskEvent['metadata']): void {\n this.notifyTaskEvent({\n task,\n eventType: 'created',\n timestamp: Date.now(),\n metadata\n });\n }\n\n /**\n * Convenience method to notify about a task update.\n * @param task - The updated A2A task.\n * @param previousStatus - The previous status of the task (if status changed).\n * @param metadata - Optional additional metadata about the update.\n */\n notifyTaskUpdated(task: A2ATask, previousStatus?: A2ATaskStatus, metadata?: A2ATaskEvent['metadata']): void {\n // Determine the specific event type based on the status\n let eventType: A2ATaskEvent['eventType'] = 'updated';\n \n if (previousStatus && previousStatus !== task.status) {\n eventType = 'status_changed';\n if (task.status === A2ATaskStatus.COMPLETED) {\n eventType = 'completed';\n } else if (task.status === A2ATaskStatus.FAILED) {\n eventType = 'failed';\n } else if (task.status === A2ATaskStatus.CANCELLED) {\n eventType = 'cancelled';\n } else if (task.targetAgent && previousStatus === A2ATaskStatus.PENDING) {\n eventType = 'delegated';\n }\n }\n\n this.notifyTaskEvent({\n task,\n eventType,\n timestamp: Date.now(),\n previousStatus,\n metadata\n });\n }\n\n /**\n * Convenience method to notify about task delegation.\n * @param task - The delegated A2A task.\n * @param metadata - Optional additional metadata about the delegation.\n */\n notifyTaskDelegated(task: A2ATask, metadata?: A2ATaskEvent['metadata']): void {\n this.notifyTaskEvent({\n task,\n eventType: 'delegated',\n timestamp: Date.now(),\n metadata\n });\n }\n\n /**\n * Convenience method to notify about task completion.\n * @param task - The completed A2A task.\n * @param metadata - Optional additional metadata about the completion.\n */\n notifyTaskCompleted(task: A2ATask, metadata?: A2ATaskEvent['metadata']): void {\n this.notifyTaskEvent({\n task,\n eventType: 'completed',\n timestamp: Date.now(),\n metadata\n });\n }\n\n /**\n * Convenience method to notify about task failure.\n * @param task - The failed A2A task.\n * @param metadata - Optional additional metadata about the failure.\n */\n notifyTaskFailed(task: A2ATask, metadata?: A2ATaskEvent['metadata']): void {\n this.notifyTaskEvent({\n task,\n eventType: 'failed',\n timestamp: Date.now(),\n metadata\n });\n }\n\n /**\n * Retrieves historical A2A task events, optionally filtered by criteria.\n * Note: This method constructs events from stored tasks, not from a dedicated event log.\n * @param filter - Optional A2ATaskFilter to filter the tasks.\n * @param options - Optional threadId and limit.\n * @returns A promise resolving to an array of A2A task events.\n */\n async getHistory(\n filter?: A2ATaskFilter,\n options?: { threadId?: string; limit?: number }\n ): Promise<A2ATaskEvent[]> {\n if (!this.taskRepository) {\n Logger.warn('Cannot getHistory for A2ATaskSocket: IA2ATaskRepository not configured.');\n return [];\n }\n\n Logger.debug(`Getting history for A2ATaskSocket: Thread ${options?.threadId}, Filter: ${JSON.stringify(filter)}, Limit: ${options?.limit}`);\n\n try {\n let tasks: A2ATask[] = [];\n\n // Fetch tasks based on available filters\n if (options?.threadId) {\n // If threadId is specified, get tasks by thread (assuming threadId maps to correlationId)\n tasks = await this.taskRepository.getTasksByThread(options.threadId);\n } else if (filter?.status) {\n // If status filter is specified, get tasks by status\n tasks = await this.taskRepository.getTasksByStatus(filter.status, {\n limit: options?.limit\n });\n } else {\n // Fallback: get tasks by status (all non-cancelled tasks)\n tasks = await this.taskRepository.getTasksByStatus([\n A2ATaskStatus.PENDING,\n A2ATaskStatus.IN_PROGRESS,\n A2ATaskStatus.COMPLETED,\n A2ATaskStatus.FAILED,\n A2ATaskStatus.WAITING,\n A2ATaskStatus.REVIEW\n ], { limit: options?.limit });\n }\n\n // Convert tasks to events and apply client-side filtering\n let events: A2ATaskEvent[] = tasks\n .map(task => this.taskToEvent(task))\n .filter(event => this.matchesFilter(event, filter));\n\n // Sort by timestamp (newest first)\n events.sort((a, b) => b.timestamp - a.timestamp);\n\n // Apply limit if specified and not already applied at repository level\n if (options?.limit && (!filter?.status || options.threadId)) {\n events = events.slice(0, options.limit);\n }\n\n return events;\n } catch (error) {\n Logger.error(`Error fetching A2A task history:`, error);\n return [];\n }\n }\n\n /**\n * Converts an A2ATask to an A2ATaskEvent for historical data.\n * @param task - The A2ATask to convert.\n * @returns An A2ATaskEvent representing the current state of the task.\n */\n private taskToEvent(task: A2ATask): A2ATaskEvent {\n // Determine event type based on current task status\n let eventType: A2ATaskEvent['eventType'] = 'updated';\n \n if (task.status === A2ATaskStatus.COMPLETED) {\n eventType = 'completed';\n } else if (task.status === A2ATaskStatus.FAILED) {\n eventType = 'failed';\n } else if (task.status === A2ATaskStatus.CANCELLED) {\n eventType = 'cancelled';\n } else if (task.targetAgent) {\n eventType = 'delegated';\n } else if (task.metadata.createdAt === task.metadata.updatedAt) {\n eventType = 'created';\n }\n\n return {\n task,\n eventType,\n timestamp: task.metadata.updatedAt || task.metadata.createdAt,\n metadata: {\n automatic: true,\n source: 'history',\n context: {\n taskType: task.payload.taskType,\n priority: task.priority,\n hasTargetAgent: !!task.targetAgent\n }\n }\n };\n }\n\n /**\n * Checks if an A2A task event matches the specified filter criteria.\n * @param event - The A2A task event to check.\n * @param filter - The filter criteria (optional).\n * @returns True if the event matches the filter, false otherwise.\n */\n private matchesFilter(event: A2ATaskEvent, filter?: A2ATaskFilter): boolean {\n if (!filter) return true;\n\n const task = event.task;\n\n // Filter by status\n if (filter.status) {\n const statusArray = Array.isArray(filter.status) ? filter.status : [filter.status];\n if (!statusArray.includes(task.status)) {\n return false;\n }\n }\n\n // Filter by task type\n if (filter.taskType) {\n const taskTypeArray = Array.isArray(filter.taskType) ? filter.taskType : [filter.taskType];\n if (!taskTypeArray.includes(task.payload.taskType)) {\n return false;\n }\n }\n\n // Filter by source agent ID\n if (filter.sourceAgentId && task.sourceAgent.agentId !== filter.sourceAgentId) {\n return false;\n }\n\n // Filter by target agent ID\n if (filter.targetAgentId) {\n if (!task.targetAgent || task.targetAgent.agentId !== filter.targetAgentId) {\n return false;\n }\n }\n\n // Filter by priority\n if (filter.priority && task.priority !== filter.priority) {\n return false;\n }\n\n // Filter by thread ID (using correlationId as threadId)\n if (filter.threadId && task.metadata.correlationId !== filter.threadId) {\n return false;\n }\n\n return true;\n }\n} ","/**\n * @module types/schemas\n * This module defines Zod schemas for validating the core data structures of the ART framework,\n * ensuring type safety and data integrity at runtime.\n */\nimport { z } from 'zod';\nimport { ArtStandardMessageRole } from '@/types'; // Import role type from main types\n\n/**\n * Zod schema for validating a single {@link ArtStandardMessage} object.\n *\n * @remarks\n * This schema enforces the structural and type requirements for each message, including:\n * - A valid `role` from the {@link ArtStandardMessageRole} enum.\n * - `content` that matches the expected type for a given role (e.g., string for 'user', string or null for 'assistant').\n * - The presence of `tool_call_id` for 'tool' or 'tool_result' roles.\n * - The structure of `tool_calls` when present in an 'assistant' message.\n *\n * It uses a `.refine()` method to implement context-aware validation based on the message's `role`.\n */\nexport const ArtStandardMessageSchema = z.object({\n role: z.custom<ArtStandardMessageRole>((val) => {\n // Basic check, refine if needed based on actual ArtStandardMessageRole definition\n // Ensure all roles from ArtStandardMessageRole are included here\n return typeof val === 'string' && ['system', 'user', 'assistant', 'tool', 'tool_request', 'tool_result'].includes(val);\n }, { message: \"Invalid message role\" }),\n // Define content explicitly matching 'string | object | null' from interface\n content: z.union([z.string(), z.record(z.any()), z.null()]),\n name: z.string().optional(),\n tool_calls: z.array(z.object({\n id: z.string(),\n type: z.literal('function'),\n function: z.object({\n name: z.string(),\n arguments: z.string(), // Arguments are expected to be a stringified JSON\n }),\n })).optional(),\n tool_call_id: z.string().optional(),\n}).strict().refine(data => {\n // Role-specific validation logic:\n if (data.role === 'tool' || data.role === 'tool_result') { // 'tool' is the standard, 'tool_result' might be used internally\n if (!data.tool_call_id) return false; // tool_call_id is required for tool role\n // Content for tool role should ideally be a string (stringified result)\n // if (typeof data.content !== 'string') return false; // Uncomment for stricter validation\n }\n if (data.role === 'assistant') {\n // Assistant content should be string or null (if only making tool calls)\n if (data.content !== null && typeof data.content !== 'string') return false;\n // If content is null/empty, tool_calls should ideally exist (though not strictly enforced here)\n }\n if (data.role === 'user' || data.role === 'system') {\n // User/System content must be a string\n if (typeof data.content !== 'string') return false;\n }\n // 'tool_request' role might not be used directly, validation TBD if needed.\n\n return true;\n}, {\n message: \"Invalid message structure based on role (e.g., tool_call_id missing for tool role, invalid content type for user/system, assistant content not string/null)\",\n // path: ['role', 'content', 'tool_call_id'], // Optional: Specify path for better error reporting\n});\n\n\n/**\n * Zod schema for validating an entire {@link ArtStandardPrompt} (an array of messages).\n *\n * @remarks\n * This is a straightforward array schema that applies the {@link ArtStandardMessageSchema} to each element,\n * ensuring that every message in the prompt conforms to the required structure.\n */\nexport const ArtStandardPromptSchema = z.array(ArtStandardMessageSchema);","// src/types/index.ts\nimport type { RuntimeProviderConfig } from './providers'; // Import for use within this file\nimport type { IToolExecutor, IAgentCore } from '@/core/interfaces'; // For ArtInstanceConfig\nimport type { LogLevel } from '@/utils/logger'; // For ArtInstanceConfig\nimport type { StorageAdapter } from '@/core/interfaces'; // For ArtInstanceConfig (storage property)\n// --- ART Error Types ---\nexport {\n ErrorCode,\n ARTError,\n UnknownProviderError,\n LocalProviderConflictError,\n LocalInstanceBusyError,\n ApiQueueTimeoutError,\n AdapterInstantiationError\n} from '@/errors';\n\n/**\n * @module types\n *\n * This module aggregates and exports the core data structures, enums, and type definitions\n * used throughout the ART framework. It serves as the single source of truth for\n * a majority of the framework's types.\n *\n * Key exports include:\n * - {@link AgentProps}: Input properties for agent execution.\n * - {@link AgentFinalResponse}: Standardized output from an agent.\n * - {@link ConversationMessage}: Structure for a single message in a conversation.\n * - {@link ToolSchema}: Definition for a tool's capabilities.\n * - {@link A2ATask}: Structure for Agent-to-Agent tasks.\n * - Various enums like {@link MessageRole}, {@link ModelCapability}, etc.\n */\n\n// --- UI Socket Related Types ---\nexport { LLMStreamSocket } from '@/systems/ui/llm-stream-socket';\nexport { TypedSocket } from '@/systems/ui/typed-socket';\nexport { A2ATaskSocket } from '@/systems/ui/a2a-task-socket';\nexport type { UnsubscribeFunction } from '@/systems/ui/typed-socket';\n\n// --- Zod Schemas for Validation ---\nexport { ArtStandardPromptSchema, ArtStandardMessageSchema } from './schemas';\n\n\n// Re-export necessary types from submodules\nexport type {\n ProviderManagerConfig,\n AvailableProviderEntry,\n RuntimeProviderConfig,\n ManagedAdapterAccessor,\n IProviderManager\n} from './providers';\n\n/**\n * Represents the role of a message sender in a conversation.\n *\n * @enum {string}\n */\nexport enum MessageRole {\n /** The end-user interacting with the agent. */\n USER = 'USER',\n /** The AI agent. */\n AI = 'AI',\n /** A system-level message providing context or instructions. */\n SYSTEM = 'SYSTEM',\n /** A message containing the result of a tool execution. */\n TOOL = 'TOOL',\n}\n\n/**\n * Represents a single message within a conversation thread.\n *\n * @interface ConversationMessage\n */\nexport interface ConversationMessage {\n /**\n * A unique identifier for this specific message.\n * @property {string} messageId\n */\n messageId: string;\n /**\n * The identifier of the conversation thread this message belongs to.\n * @property {string} threadId\n */\n threadId: string;\n /**\n * The role of the sender (User, AI, System, or Tool).\n * @property {MessageRole} role\n */\n role: MessageRole;\n /**\n * The textual content of the message.\n * @property {string} content\n */\n content: string;\n /**\n * A Unix timestamp (in milliseconds) indicating when the message was created.\n * @property {number} timestamp\n */\n timestamp: number;\n /**\n * Optional metadata associated with the message (e.g., related observation IDs, tool call info, UI state).\n * @property {Record<string, any>} [metadata]\n */\n metadata?: Record<string, any>;\n}\n\n/**\n * Represents the type of an observation record, capturing significant events during agent execution.\n *\n * @enum {string}\n */\nexport enum ObservationType {\n /** The user's inferred intent. */\n INTENT = 'INTENT',\n /** The generated concise thread title. */\n TITLE = 'TITLE',\n /** The agent's step-by-step plan to address the intent. */\n PLAN = 'PLAN',\n /** The agent's internal monologue or reasoning process. */\n THOUGHTS = 'THOUGHTS',\n /** Records the LLM's decision to call one or more tools (part of the plan). */\n TOOL_CALL = 'TOOL_CALL',\n /** Records the actual execution attempt and result of a specific tool call. */\n TOOL_EXECUTION = 'TOOL_EXECUTION',\n /** Records events specifically related to the synthesis phase (e.g., the LLM call). */\n SYNTHESIS = 'SYNTHESIS',\n /** Records an error encountered during any phase of execution. */\n ERROR = 'ERROR',\n /** Records the final AI response message generated by the agent. */\n FINAL_RESPONSE = 'FINAL_RESPONSE',\n /** Records changes made to the agent's persistent state. */\n STATE_UPDATE = 'STATE_UPDATE',\n\n // New types for streaming events\n /** Logged by Agent Core when LLM stream consumption begins. */\n LLM_STREAM_START = 'LLM_STREAM_START',\n /** Logged by Agent Core upon receiving a METADATA stream event. Content should be LLMMetadata. */\n LLM_STREAM_METADATA = 'LLM_STREAM_METADATA',\n /** Logged by Agent Core upon receiving an END stream event. */\n LLM_STREAM_END = 'LLM_STREAM_END',\n /** Logged by Agent Core upon receiving an ERROR stream event. Content should be Error object or message. */\n LLM_STREAM_ERROR = 'LLM_STREAM_ERROR',\n}\n\n// --- NEW ENUM DEFINITION ---\n/**\n * Represents the different capabilities a model might possess.\n * Used for model selection and validation.\n *\n * @enum {string}\n */\nexport enum ModelCapability {\n /** Basic text generation/understanding. */\n TEXT = 'text',\n /** Ability to process and understand images. */\n VISION = 'vision',\n /** Supports streaming responses chunk by chunk. */\n STREAMING = 'streaming',\n /** Capable of using tools/function calling. */\n TOOL_USE = 'tool_use',\n /** Built-in or optimized for Retrieval-Augmented Generation. */\n RAG = 'rag',\n /** Specialized in understanding or generating code. */\n CODE = 'code',\n /** Advanced reasoning, planning, complex instruction following. */\n REASONING = 'reasoning'\n}\n// --- END NEW ENUM DEFINITION ---\n\n\n/**\n * Represents a recorded event during the agent's execution.\n *\n * @interface Observation\n */\nexport interface Observation {\n /**\n * A unique identifier for this specific observation record.\n * @property {string} id\n */\n id: string;\n /**\n * The identifier of the conversation thread this observation relates to.\n * @property {string} threadId\n */\n threadId: string;\n /**\n * An optional identifier for tracing a request across multiple systems or components.\n * @property {string} [traceId]\n */\n traceId?: string;\n /**\n * A Unix timestamp (in milliseconds) indicating when the observation was recorded.\n * @property {number} timestamp\n */\n timestamp: number;\n /**\n * The category of the event being observed (e.g., PLAN, THOUGHTS, TOOL_EXECUTION).\n * @property {ObservationType} type\n */\n type: ObservationType;\n /**\n * A concise, human-readable title summarizing the observation (often generated based on type/metadata).\n * @property {string} title\n */\n title: string;\n /**\n * The main data payload of the observation, structure depends on the `type`.\n *\n * @remarks\n * Common content shapes by `type`:\n * - `TITLE`: `{ title: string }` — a concise thread title (<= 10 words)\n * - `INTENT`: `{ intent: string }`\n * - `PLAN`: `{ plan: string; rawOutput?: string }`\n * - `TOOL_CALL`: `{ toolCalls: ParsedToolCall[] }`\n * - `TOOL_EXECUTION`: `{ callId: string; toolName: string; status: 'success' | 'error'; output?: any; error?: string }`\n * - `FINAL_RESPONSE`: `{ message: ConversationMessage; uiMetadata?: object }`\n * @property {any} content\n */\n content: any;\n /**\n * Optional metadata providing additional context (e.g., source phase, related IDs, status).\n * @property {Record<string, any>} [metadata]\n */\n metadata?: Record<string, any>;\n}\n\n/**\n * Represents a single event emitted from an asynchronous LLM stream (`ReasoningEngine.call`).\n *\n * @remarks\n * Allows for real-time delivery of tokens, metadata, errors, and lifecycle signals.\n * Adapters are responsible for translating provider-specific stream chunks into these standard events.\n *\n * @interface StreamEvent\n */\nexport interface StreamEvent {\n /**\n * The type of the stream event.\n * - `TOKEN`: A chunk of text generated by the LLM.\n * - `METADATA`: Information about the LLM call (e.g., token counts, stop reason), typically sent once at the end.\n * - `ERROR`: An error occurred during the LLM call or stream processing. `data` will contain the Error object.\n * - `END`: Signals the successful completion of the stream. `data` is typically null.\n * @property {'TOKEN' | 'METADATA' | 'ERROR' | 'END'} type\n */\n type: 'TOKEN' | 'METADATA' | 'ERROR' | 'END';\n /**\n * The actual content of the event.\n * - For `TOKEN`: string (the text chunk).\n * - For `METADATA`: `LLMMetadata` object.\n * - For `ERROR`: `Error` object or error details.\n * - For `END`: null.\n * @property {any} data\n */\n data: any;\n /**\n * Optional: Provides a more specific classification for `TOKEN` events,\n * combining LLM-level detection (thinking/response, if available from adapter)\n * and agent-level context (`callContext` from `CallOptions`).\n * Used by consumers (like UI) to differentiate between intermediate thoughts and the final response.\n *\n * - `LLM_THINKING`: Token identified by the adapter as part of the LLM's internal reasoning/thought process.\n * - `LLM_RESPONSE`: Token identified by the adapter as part of the LLM's final response content.\n * - `AGENT_THOUGHT_LLM_THINKING`: Token from an LLM call made in the 'AGENT_THOUGHT' context, identified as thinking.\n * - `AGENT_THOUGHT_LLM_RESPONSE`: Token from an LLM call made in the 'AGENT_THOUGHT' context, identified as response (e.g., the raw planning output).\n * - `FINAL_SYNTHESIS_LLM_THINKING`: Token from an LLM call made in the 'FINAL_SYNTHESIS' context, identified as thinking.\n * - `FINAL_SYNTHESIS_LLM_RESPONSE`: Token from an LLM call made in the 'FINAL_SYNTHESIS' context, identified as response (part of the final answer to the user).\n *\n * @remarks\n * Not all adapters can reliably distinguish 'LLM_THINKING' vs 'LLM_RESPONSE'.\n * Adapters should prioritize setting the agent context part (`AGENT_THOUGHT_...` or `FINAL_SYNTHESIS_...`) based on `CallOptions.callContext`.\n * If thinking detection is unavailable, adapters should default to `AGENT_THOUGHT_LLM_RESPONSE` or `FINAL_SYNTHESIS_LLM_RESPONSE`.\n * @property {'LLM_THINKING' | 'LLM_RESPONSE' | 'AGENT_THOUGHT_LLM_THINKING' | 'AGENT_THOUGHT_LLM_RESPONSE' | 'FINAL_SYNTHESIS_LLM_THINKING' | 'FINAL_SYNTHESIS_LLM_RESPONSE'} [tokenType]\n */\n tokenType?: 'LLM_THINKING' | 'LLM_RESPONSE' | 'AGENT_THOUGHT_LLM_THINKING' | 'AGENT_THOUGHT_LLM_RESPONSE' | 'FINAL_SYNTHESIS_LLM_THINKING' | 'FINAL_SYNTHESIS_LLM_RESPONSE';\n /**\n * The identifier of the conversation thread this event belongs to.\n * @property {string} threadId\n */\n threadId: string;\n /**\n * The identifier tracing the specific agent execution cycle this event is part of.\n * @property {string} traceId\n */\n traceId: string;\n /**\n * Optional identifier linking the event to a specific UI tab/window.\n * @property {string} [sessionId]\n */\n sessionId?: string;\n}\n\n/**\n * Represents a basic JSON Schema definition, focusing on object types commonly used for tool inputs/outputs.\n * This is a simplified representation and doesn't cover all JSON Schema features.\n *\n * @interface JsonObjectSchema\n */\nexport interface JsonObjectSchema {\n /**\n * @property {'object'} type\n */\n type: 'object';\n /**\n * @property {object} properties\n */\n properties: {\n [key: string]: {\n type: string; // e.g., 'string', 'number', 'boolean', 'object', 'array'\n description?: string;\n default?: any;\n items?: JsonObjectSchema | { type: string }; // For array type\n properties?: JsonObjectSchema['properties']; // For nested object type\n required?: string[]; // For nested object type\n additionalProperties?: boolean | { type: string };\n [key: string]: any; // Allow other JSON schema properties\n };\n };\n required?: string[];\n additionalProperties?: boolean;\n}\n\n// Allow for other schema types (string, number, etc.) although object is most common for tools\nexport type JsonSchema = JsonObjectSchema | { type: 'string' | 'number' | 'boolean' | 'array', [key: string]: any };\n\n/**\n * Structure for holding metadata about an LLM call, typically received via a `METADATA` `StreamEvent`\n * or parsed from a non-streaming response. Fields are optional as availability varies by provider and stream state.\n *\n * @interface LLMMetadata\n */\nexport interface LLMMetadata {\n /**\n * The number of tokens in the input prompt, if available.\n * @property {number} [inputTokens]\n */\n inputTokens?: number;\n /**\n * The number of tokens generated in the output response, if available.\n * @property {number} [outputTokens]\n */\n outputTokens?: number;\n /**\n * The number of tokens identified as part of the LLM's internal thinking process (if available from provider).\n * @property {number} [thinkingTokens]\n */\n thinkingTokens?: number;\n /**\n * The time elapsed (in milliseconds) until the first token was generated in a streaming response, if applicable and available.\n * @property {number} [timeToFirstTokenMs]\n */\n timeToFirstTokenMs?: number;\n /**\n * The total time elapsed (in milliseconds) for the entire generation process, if available.\n * @property {number} [totalGenerationTimeMs]\n */\n totalGenerationTimeMs?: number;\n /**\n * The reason the LLM stopped generating tokens (e.g., 'stop_sequence', 'max_tokens', 'tool_calls'), if available.\n * @property {string} [stopReason]\n */\n stopReason?: string;\n /**\n * Optional raw usage data provided directly by the LLM provider for extensibility (structure depends on provider).\n * @property {any} [providerRawUsage]\n */\n providerRawUsage?: any;\n /**\n * The trace ID associated with the LLM call, useful for correlating metadata with the specific request.\n * @property {string} [traceId]\n */\n traceId?: string; // Include traceId if this object might be stored or passed independently.\n}\n\n/**\n * Defines the schema for a tool, including its input parameters.\n * Uses JSON Schema format for inputSchema.\n *\n * @interface ToolSchema\n */\nexport interface ToolSchema {\n /**\n * A unique name identifying the tool (used in LLM prompts and registry lookups). Must be unique.\n * @property {string} name\n */\n name: string;\n /**\n * A clear description of what the tool does, intended for the LLM to understand its purpose and usage.\n * @property {string} description\n */\n description: string;\n /**\n * A JSON Schema object defining the structure, types, and requirements of the input arguments the tool expects.\n * @property {JsonSchema} inputSchema\n */\n inputSchema: JsonSchema;\n /**\n * An optional JSON Schema object defining the expected structure of the data returned in the `output` field of a successful `ToolResult`.\n * @property {JsonSchema} [outputSchema]\n */\n outputSchema?: JsonSchema;\n /**\n * Optional array of examples demonstrating how to use the tool, useful for few-shot prompting of the LLM.\n * @property {Array<{ input: any; output?: any; description?: string }>} [examples]\n */\n examples?: Array<{ input: any; output?: any; description?: string }>;\n}\n/**\n * Represents the structured result of a tool execution.\n *\n * @interface ToolResult\n */\nexport interface ToolResult {\n /**\n * The unique identifier of the corresponding `ParsedToolCall` that initiated this execution attempt.\n * @property {string} callId\n */\n callId: string;\n /**\n * The name of the tool that was executed.\n * @property {string} toolName\n */\n toolName: string;\n /**\n * Indicates whether the tool execution succeeded or failed.\n * @property {'success' | 'error'} status\n */\n status: 'success' | 'error';\n /**\n * The data returned by the tool upon successful execution. Structure may be validated against `outputSchema`.\n * @property {any} [output]\n */\n output?: any;\n /**\n * A descriptive error message if the execution failed (`status` is 'error').\n * @property {string} [error]\n */\n error?: string;\n /**\n * Optional metadata about the execution (e.g., duration, cost, logs).\n * @property {object} [metadata]\n */\n metadata?: {\n sources?: Array<{\n sourceName: string;\n url?: string;\n [key: string]: any;\n }>;\n [key: string]: any;\n };\n}\n\n// --- SYSTEM PROMPT STANDARDIZATION TYPES ---\n/**\n * Strategy for combining custom system prompt content across precedence levels.\n *\n * @typedef {'append' | 'prepend'} SystemPromptMergeStrategy\n */\nexport type SystemPromptMergeStrategy = 'append' | 'prepend';\n\n/**\n * Named preset for system prompts, supporting variables and a default merge strategy.\n *\n * @interface SystemPromptSpec\n */\nexport interface SystemPromptSpec {\n /**\n * Optional explicit ID; when in a registry map, the key is typically the tag.\n * @property {string} [id]\n */\n id?: string;\n /**\n * Template string. Supports simple {{variable}} placeholders and {{fragment:name}} for PromptManager fragments.\n * @property {string} template\n */\n template: string;\n /**\n * Default variables applied if not provided at use time.\n * @property {Record<string, any>} [defaultVariables]\n */\n defaultVariables?: Record<string, any>;\n /**\n * Default strategy to combine this spec with lower levels. Defaults to 'append'.\n * @property {SystemPromptMergeStrategy} [mergeStrategy]\n */\n mergeStrategy?: SystemPromptMergeStrategy;\n}\n\n/**\n * Registry of available system prompt presets (tags) at the instance level.\n *\n * @interface SystemPromptsRegistry\n */\nexport interface SystemPromptsRegistry {\n /**\n * Tag to use when no other tag is specified.\n * @property {string} [defaultTag]\n */\n defaultTag?: string;\n /**\n * Mapping of tag -> spec.\n * @property {Record<string, SystemPromptSpec>} specs\n */\n specs: Record<string, SystemPromptSpec>;\n}\n\n/**\n * Override provided at instance/thread/call level to select a tag and/or provide variables,\n * or to provide freeform content and a merge strategy.\n *\n * @interface SystemPromptOverride\n */\nexport interface SystemPromptOverride {\n /**\n * Preset tag from the registry (e.g., 'default', 'legal_advisor').\n * @property {string} [tag]\n */\n tag?: string;\n /**\n * Variables to substitute in the selected template.\n * @property {Record<string, any>} [variables]\n */\n variables?: Record<string, any>;\n /**\n * Freeform content to apply directly (escape hatch).\n * @property {string} [content]\n */\n content?: string;\n /**\n * Merge behavior against previous level: append | prepend.\n * @property {SystemPromptMergeStrategy} [strategy]\n */\n strategy?: SystemPromptMergeStrategy;\n}\n\n/**\n * Represents a parsed request from the LLM to call a specific tool.\n *\n * @interface ParsedToolCall\n */\nexport interface ParsedToolCall {\n /**\n * A unique identifier generated by the OutputParser for this specific tool call request within a plan.\n * @property {string} callId\n */\n callId: string;\n /**\n * The name of the tool the LLM intends to call. Must match a registered tool's schema name.\n * @property {string} toolName\n */\n toolName: string;\n /**\n * The arguments object, parsed from the LLM response, intended to be passed to the tool's `execute` method after validation.\n * @property {any} arguments\n */\n arguments: any;\n}\n\n/**\n * Configuration specific to a conversation thread.\n *\n * @interface ThreadConfig\n */\n export interface ThreadConfig {\n /**\n * Default provider configuration for this thread.\n * @property {RuntimeProviderConfig} providerConfig\n */\n providerConfig: RuntimeProviderConfig;\n /**\n * An array of tool names (matching `ToolSchema.name`) that are permitted for use within this thread.\n * @property {string[]} enabledTools\n */\n enabledTools: string[];\n /**\n * The maximum number of past messages (`ConversationMessage` objects) to retrieve for context.\n * @property {number} historyLimit\n */\n historyLimit: number;\n /**\n * Optional system prompt override to be used for this thread, overriding instance or agent defaults.\n * @property {string | SystemPromptOverride} [systemPrompt]\n */\n systemPrompt?: string | SystemPromptOverride;\n /**\n * Optional: Defines the identity and high-level guidance for the agent for this specific thread.\n * This overrides the instance-level persona.\n * @property {Partial<AgentPersona>} [persona]\n */\n persona?: Partial<AgentPersona>;\n // TODO: Add other potential thread-specific settings (e.g., RAG configuration, default timeouts)\n }\n\n/**\n * Represents non-configuration state associated with an agent or thread.\n * Could include user preferences, accumulated knowledge, etc. (Less defined for v1.0)\n *\n * @interface AgentState\n */\nexport interface AgentState {\n /**\n * The primary data payload of the agent's state. Structure is application-defined.\n * @property {any} data\n */\n data: any;\n /**\n * An optional version number for the agent's state, useful for migrations or tracking changes.\n * @property {number} [version]\n */\n version?: number;\n /**\n * Allows for other arbitrary properties to be stored in the agent's state.\n * @property {any} [key: string]\n */\n [key: string]: any;\n}\n\n/**\n * Encapsulates the configuration and state for a specific thread.\n *\n * @interface ThreadContext\n */\nexport interface ThreadContext {\n /**\n * The configuration settings (`ThreadConfig`) currently active for the thread.\n * @property {ThreadConfig} config\n */\n config: ThreadConfig;\n /**\n * The persistent state (`AgentState`) associated with the thread, or `null` if no state exists.\n * @property {AgentState | null} state\n */\n state: AgentState | null;\n}\n\n/**\n * Properties required to initiate an agent processing cycle.\n *\n * @interface AgentProps\n */\nexport interface AgentProps {\n /**\n * The user's input query or request to the agent.\n * @property {string} query\n */\n query: string;\n /**\n * The mandatory identifier for the conversation thread. All context is scoped to this ID.\n * @property {string} threadId\n */\n threadId: string;\n /**\n * An optional identifier for the specific UI session, useful for targeting UI updates.\n * @property {string} [sessionId]\n */\n sessionId?: string;\n /**\n * An optional identifier for the user interacting with the agent.\n * @property {string} [userId]\n */\n userId?: string;\n /**\n * An optional identifier used for tracing a request across multiple systems or services.\n * @property {string} [traceId]\n */\n traceId?: string;\n /**\n * Optional runtime options that can override default behaviors for this specific `process` call.\n * @property {AgentOptions} [options]\n */\n options?: AgentOptions;\n // Note: Core dependencies (StateManager, ConversationManager, etc.) are typically injected\n // during `createArtInstance` and are accessed internally by the Agent Core, not passed in AgentProps.\n}\n\n/**\n * Options to override agent behavior at runtime.\n *\n * @interface AgentOptions\n */\n export interface AgentOptions {\n /**\n * Override specific LLM parameters (e.g., temperature, max_tokens) for this call only.\n * @property {Record<string, any>} [llmParams]\n */\n llmParams?: Record<string, any>;\n /**\n * Override provider configuration for this specific call.\n * @property {RuntimeProviderConfig} [providerConfig]\n */\n providerConfig?: RuntimeProviderConfig; // Add this line\n /**\n * Force the use of specific tools, potentially overriding the thread's `enabledTools` for this call (use with caution).\n * @property {string[]} [forceTools]\n */\n forceTools?: string[];\n /**\n * Specify a particular reasoning model to use for this call, overriding the thread's default.\n * @property {{ provider: string; model: string }} [overrideModel]\n */\n overrideModel?: { provider: string; model: string };\n /**\n * Request a streaming response for this specific agent process call.\n * @property {boolean} [stream]\n */\n stream?: boolean;\n /**\n * Override the prompt template used for this specific call.\n * @property {string} [promptTemplateId]\n */\n promptTemplateId?: string;\n /**\n * Optional system prompt override/tag to override thread, instance, or agent defaults for this specific call.\n * @property {string | SystemPromptOverride} [systemPrompt]\n */\n systemPrompt?: string | SystemPromptOverride;\n /**\n * Optional: Defines the identity and high-level guidance for the agent for this specific call.\n * This overrides both the instance-level and thread-level persona.\n * @property {Partial<AgentPersona>} [persona]\n */\n persona?: Partial<AgentPersona>;\n // TODO: Add other potential runtime overrides (e.g., history length).\n }\n\n/**\n * The final structured response returned by the agent core after processing.\n *\n * @interface AgentFinalResponse\n */\nexport interface AgentFinalResponse {\n /**\n * The final `ConversationMessage` generated by the AI, which has also been persisted.\n * @property {ConversationMessage} response\n */\n response: ConversationMessage;\n /**\n * Metadata summarizing the execution cycle that produced this response.\n * @property {ExecutionMetadata} metadata\n */\n metadata: ExecutionMetadata;\n}\n\n/**\n * Metadata summarizing an agent execution cycle, including performance metrics and outcomes.\n *\n * @interface ExecutionMetadata\n */\nexport interface ExecutionMetadata {\n /**\n * The thread ID associated with this execution cycle.\n * @property {string} threadId\n */\n threadId: string;\n /**\n * The trace ID used during this execution, if provided.\n * @property {string} [traceId]\n */\n traceId?: string;\n /**\n * The user ID associated with the execution, if provided.\n * @property {string} [userId]\n */\n userId?: string;\n /**\n * The overall status of the execution ('success', 'error', or 'partial' if some steps failed but a response was generated).\n * @property {'success' | 'error' | 'partial'} status\n */\n status: 'success' | 'error' | 'partial';\n /**\n * The total duration of the `agent.process()` call in milliseconds.\n * @property {number} totalDurationMs\n */\n totalDurationMs: number;\n /**\n * The number of calls made to the `ReasoningEngine`.\n * @property {number} llmCalls\n */\n llmCalls: number;\n /**\n * The number of tool execution attempts made by the `ToolSystem`.\n * @property {number} toolCalls\n */\n toolCalls: number;\n /**\n * An optional estimated cost for the LLM calls made during this execution.\n * @property {number} [llmCost]\n */\n llmCost?: number;\n /**\n * A top-level error message if the overall status is 'error' or 'partial'.\n * @property {string} [error]\n */\n error?: string;\n /**\n * Aggregated metadata from LLM calls made during the execution.\n * @property {LLMMetadata} [llmMetadata]\n */\n llmMetadata?: LLMMetadata;\n}\n\n/**\n * Context provided to a tool during its execution.\n *\n * @interface ExecutionContext\n */\nexport interface ExecutionContext {\n /**\n * The ID of the thread in which the tool is being executed.\n * @property {string} threadId\n */\n threadId: string;\n /**\n * The trace ID for this execution cycle, if available.\n * @property {string} [traceId]\n */\n traceId?: string;\n /**\n * The user ID associated with the execution, if available.\n * @property {string} [userId]\n */\n userId?: string;\n // TODO: Potentially include access tokens or credentials scoped to this execution, if needed securely.\n // TODO: Consider providing limited access to StateManager or other relevant context if required by complex tools.\n}\n\n/**\n * Options for configuring an LLM call, including streaming and context information.\n *\n * @interface CallOptions\n */\nexport interface CallOptions {\n /**\n * The mandatory thread ID, used by the ReasoningEngine to fetch thread-specific configuration (e.g., model, params) via StateManager.\n * @property {string} threadId\n */\n threadId: string;\n /**\n * Optional trace ID for correlation.\n * @property {string} [traceId]\n */\n traceId?: string;\n /**\n * Optional user ID.\n * @property {string} [userId]\n */\n userId?: string;\n /**\n * Optional session ID.\n * @property {string} [sessionId]\n */\n sessionId?: string; // Added sessionId\n /**\n * Request a streaming response from the LLM provider.\n * Adapters MUST check this flag.\n * @property {boolean} [stream]\n */\n stream?: boolean;\n /**\n * Provides context for the LLM call, allowing adapters to differentiate\n * between agent-level thoughts and final synthesis calls for token typing.\n * Agent Core MUST provide this.\n * @property {'AGENT_THOUGHT' | 'FINAL_SYNTHESIS' | string} [callContext]\n */\n callContext?: 'AGENT_THOUGHT' | 'FINAL_SYNTHESIS' | string;\n /**\n * An optional callback function invoked when the LLM streams intermediate 'thoughts' or reasoning steps.\n * @deprecated Prefer using StreamEvent with appropriate tokenType for thoughts. Kept for potential transitional compatibility.\n */\n // onThought?: (thought: string) => void; // Commented out as per implementation plan decision (Ref: 7.2, Checklist Phase 1)\n /**\n * Carries the specific target provider and configuration for this call.\n * @property {RuntimeProviderConfig} providerConfig\n */\n providerConfig: RuntimeProviderConfig;\n /**\n * Additional key-value pairs representing provider-specific parameters (e.g., `temperature`, `max_tokens`, `top_p`). These often override defaults set in `ThreadConfig`.\n * @property {any} [key: string]\n */\n [key: string]: any;\n}\n\n// --- ART STANDARD PROMPT TYPES (Refactor Phase 1) ---\n\n/**\n * Defines the standard roles for messages within the `ArtStandardPrompt` format.\n *\n * @remarks\n * These roles are chosen for broad compatibility across major LLM providers (like OpenAI, Anthropic, Gemini).\n * Provider Adapters are responsible for translating these standard roles into the specific formats\n * required by their respective APIs (e.g., 'assistant' might become 'model' for Gemini).\n *\n * - `system`: Instructions or context provided to the AI, typically at the beginning.\n * - `user`: Input or queries from the end-user. Also used to wrap `tool_result` content for some providers (e.g., Gemini).\n * - `assistant`: Responses generated by the AI model. Can contain text content and/or `tool_calls`.\n * - `tool_request`: Represents the LLM's request to use tools (often implicitly part of an `assistant` message with `tool_calls`). Included for potential future explicit use.\n * - `tool_result`: The outcome (output or error) of executing a requested tool call.\n *\n * @typedef {'system' | 'user' | 'assistant' | 'tool_request' | 'tool_result' | 'tool'} ArtStandardMessageRole\n */\n export type ArtStandardMessageRole = 'system' | 'user' | 'assistant' | 'tool_request' | 'tool_result' | 'tool'; // Added 'tool' role\n\n/**\n * Represents a single message in the standardized, provider-agnostic `ArtStandardPrompt` format.\n *\n * @remarks\n * This structure aims to capture common message elements used by various LLM APIs.\n *\n * @interface ArtStandardMessage\n */\nexport interface ArtStandardMessage {\n /**\n * The role indicating the source or type of the message.\n * @property {ArtStandardMessageRole} role\n */\n role: ArtStandardMessageRole;\n /**\n * The primary content of the message. The type and interpretation depend on the `role`:\n * - `system`: string (The system instruction).\n * - `user`: string (The user's text input).\n * - `assistant`: string | null (The AI's text response, or null/empty if only making `tool_calls`).\n * - `tool_request`: object | null (Structured representation of the tool call, often implicitly handled via `assistant` message's `tool_calls`).\n * - `tool_result`: string (Stringified JSON output or error message from the tool execution).\n * @property {string | object | null} content\n */\n content: string | object | null;\n /**\n * Optional name associated with the message. Primarily used for `tool_result` role to specify the name of the tool that was executed.\n * @property {string} [name]\n */\n name?: string;\n /**\n * Optional array of tool calls requested by the assistant.\n *\n * @remarks\n * Only relevant for 'assistant' role messages that trigger tool usage.\n * Structure mirrors common provider formats (e.g., OpenAI).\n *\n * @property {Array<{ id: string; type: 'function'; function: { name: string; arguments: string; }; }>} [tool_calls]\n */\n tool_calls?: Array<{\n /** A unique identifier for this specific tool call request. */\n id: string;\n /** The type of the tool call, typically 'function'. */\n type: 'function'; // Assuming 'function' is the standard type\n /** Details of the function to be called. */\n function: {\n /** The name of the function/tool to call. */\n name: string;\n /** A stringified JSON object representing the arguments for the function. */\n arguments: string;\n };\n }>;\n /**\n * Optional identifier linking a 'tool_result' message back to the specific 'tool_calls' entry\n * in the preceding 'assistant' message that requested it.\n * Required for 'tool_result' role.\n * @property {string} [tool_call_id]\n */\n tool_call_id?: string;\n}\n\n/**\n * Represents the entire prompt as an array of standardized messages (`ArtStandardMessage`).\n *\n * @remarks\n * Constructed by agent logic (e.g., `PESAgent`) and optionally validated via\n * `PromptManager.validatePrompt` before being sent to the `ReasoningEngine` and\n * translated by a `ProviderAdapter` for provider-specific API formats.\n *\n * @typedef {ArtStandardMessage[]} ArtStandardPrompt\n */\nexport type ArtStandardPrompt = ArtStandardMessage[];\n\n/**\n * Represents the contextual data gathered by Agent Logic (e.g., `PESAgent`) to be injected\n * into a Mustache blueprint/template by the `PromptManager.assemblePrompt` method.\n *\n * @remarks\n * Contains standard fields commonly needed for prompts, plus allows for arbitrary\n * additional properties required by specific agent blueprints. Agent logic is responsible\n * for populating this context appropriately before calling `assemblePrompt`.\n *\n * @interface PromptContext\n */\nexport interface PromptContext {\n /**\n * The user's current query or input relevant to this prompt generation step.\n * @property {string} [query]\n */\n query?: string;\n /**\n * The conversation history, typically formatted as an array suitable for the blueprint\n * (e.g., array of objects with `role` and `content`). Agent logic should pre-format this.\n *\n * @remarks\n * While `ArtStandardPrompt` could be used, simpler structures might be preferred for blueprints.\n *\n * @property {Array<{ role: string; content: string; [key: string]: any }>} [history]\n */\n history?: Array<{ role: string; content: string; [key: string]: any }>; // Flexible history format for blueprints\n /**\n * The schemas of the tools available for use, potentially pre-formatted for the blueprint\n * (e.g., with `inputSchemaJson` pre-stringified).\n * @property {Array<ToolSchema & { inputSchemaJson?: string }>} [availableTools]\n */\n availableTools?: Array<ToolSchema & { inputSchemaJson?: string }>;\n /**\n * The results from any tools executed in a previous step, potentially pre-formatted for the blueprint\n * (e.g., with `outputJson` pre-stringified).\n * @property {Array<ToolResult & { outputJson?: string }>} [toolResults]\n */\n toolResults?: Array<ToolResult & { outputJson?: string }>;\n /**\n * The system prompt string to be used (resolved by agent logic from config or defaults).\n * @property {string} [systemPrompt]\n */\n systemPrompt?: string;\n /**\n * Allows agent patterns (like PES) to pass any other custom data needed by their specific blueprints (e.g., `intent`, `plan`).\n * @property {any} [key: string]\n */\n [key: string]: any;\n}\n\n/**\n * Represents a Mustache template that can be rendered with a PromptContext to produce an ArtStandardPrompt.\n * Used by the PromptManager.assemblePrompt method.\n *\n * @interface PromptBlueprint\n */\nexport interface PromptBlueprint {\n /**\n * The Mustache template string that will be rendered with context data to produce a JSON string representing an ArtStandardPrompt\n * @property {string} template\n */\n template: string;\n}\n\n// --- END ART STANDARD PROMPT TYPES ---\n\n\n/**\n * Represents the prompt data formatted for a specific LLM provider.\n * Can be a simple string or a complex object (e.g., for OpenAI Chat Completion API).\n *\n * @deprecated Use `ArtStandardPrompt` as the standard intermediate format. ProviderAdapters handle final formatting.\n * @typedef {ArtStandardPrompt} FormattedPrompt\n */\nexport type FormattedPrompt = ArtStandardPrompt; // Point deprecated type to the new standard\n\n/**\n * Options for filtering data retrieved from storage.\n * Structure depends heavily on the underlying adapter's capabilities.\n *\n * @interface FilterOptions\n */\nexport interface FilterOptions {\n /**\n * An object defining filter criteria (e.g., `{ threadId: 'abc', type: 'TOOL_EXECUTION' }`). Structure may depend on adapter capabilities.\n * @property {Record<string, any>} [filter]\n */\n filter?: Record<string, any>;\n /**\n * An object defining sorting criteria (e.g., `{ timestamp: 'desc' }`).\n * @property {Record<string, 'asc' | 'desc'>} [sort]\n */\n sort?: Record<string, 'asc' | 'desc'>;\n /**\n * The maximum number of records to return.\n * @property {number} [limit]\n */\n limit?: number;\n /**\n * The number of records to skip (for pagination).\n * @property {number} [skip]\n */\n skip?: number;\n // TODO: Consider adding projection options to retrieve only specific fields.\n}\n\n/**\n * Options for retrieving conversation messages.\n *\n * @interface MessageOptions\n */\nexport interface MessageOptions {\n /**\n * The maximum number of messages to retrieve.\n * @property {number} [limit]\n */\n limit?: number;\n /**\n * Retrieve messages created before this Unix timestamp (milliseconds).\n * @property {number} [beforeTimestamp]\n */\n beforeTimestamp?: number;\n /**\n * Retrieve messages created after this Unix timestamp (milliseconds).\n * @property {number} [afterTimestamp]\n */\n afterTimestamp?: number;\n /**\n * Optionally filter messages by role (e.g., retrieve only 'AI' messages).\n * @property {MessageRole[]} [roles]\n */\n roles?: MessageRole[];\n}\n\n/**\n * Options for filtering observations.\n *\n * @interface ObservationFilter\n */\nexport interface ObservationFilter {\n /**\n * An array of `ObservationType` enums to filter by. If provided, only observations matching these types are returned.\n * @property {ObservationType[]} [types]\n */\n types?: ObservationType[];\n /**\n * Retrieve observations recorded before this Unix timestamp (milliseconds).\n * @property {number} [beforeTimestamp]\n */\n beforeTimestamp?: number;\n /**\n * Retrieve observations recorded after this Unix timestamp (milliseconds).\n * @property {number} [afterTimestamp]\n */\n afterTimestamp?: number;\n // TODO: Add other potential criteria like filtering by metadata content if needed.\n}\n\n// Removed duplicate TypedSocket interface definition.\n// The primary definition is in src/core/interfaces.ts\n\n/**\n * Defines the strategy for saving AgentState.\n *\n * @remarks\n * - 'explicit': AgentState is only saved when `StateManager.setAgentState()` is explicitly called by the agent.\n * `StateManager.saveStateIfModified()` will be a no-op for AgentState persistence.\n * - 'implicit': AgentState is loaded by `StateManager.loadThreadContext()`, and if modified by the agent,\n * `StateManager.saveStateIfModified()` will attempt to automatically persist these changes\n * by comparing the current state with a snapshot taken at load time.\n * `StateManager.setAgentState()` will still work for explicit saves.\n *\n * @typedef {'explicit' | 'implicit'} StateSavingStrategy\n */\nexport type StateSavingStrategy = 'explicit' | 'implicit';\n\n// Explicitly import ProviderManagerConfig here for ArtInstanceConfig\nimport type { ProviderManagerConfig as PMConfig } from './providers';\n// Import McpManagerConfig for ArtInstanceConfig\nimport type { McpManagerConfig } from '../systems/mcp/types';\n\n/**\n * Configuration for creating an ART instance.\n *\n * @interface ArtInstanceConfig\n */\nexport interface ArtInstanceConfig {\n /**\n * Configuration for the storage adapter.\n * Can be a pre-configured `StorageAdapter` instance,\n * or an object specifying the type and options for a built-in adapter.\n *\n * @example { type: 'indexedDB', dbName: 'MyArtDB' }\n *\n * @property {StorageAdapter | { type: 'memory' | 'indexedDB', dbName?: string, version?: number, objectStores?: any[] }} storage\n */\n storage: StorageAdapter | { type: 'memory' | 'indexedDB', dbName?: string, version?: number, objectStores?: any[] };\n /**\n * Configuration for the ProviderManager, defining available LLM provider adapters.\n * @property {PMConfig} providers\n */\n providers: PMConfig; // Use the aliased import\n /**\n * The agent core implementation class to use.\n * Defaults to `PESAgent` if not provided.\n *\n * @example MyCustomAgentClass\n *\n * @property {new (dependencies: any) => IAgentCore} [agentCore]\n */\n agentCore?: new (dependencies: any) => IAgentCore; // Constructor type for an IAgentCore implementation\n /**\n * An optional array of tool executor instances to register at initialization.\n * @property {IToolExecutor[]} [tools]\n */\n tools?: IToolExecutor[];\n /**\n * Defines the strategy for saving `AgentState`. Defaults to 'explicit'.\n *\n * @remarks\n * - 'explicit': `AgentState` is only saved when `StateManager.setAgentState()` is explicitly called by the agent.\n * `StateManager.saveStateIfModified()` will be a no-op for `AgentState` persistence.\n * - 'implicit': `AgentState` is loaded by `StateManager.loadThreadContext()`. If modified by the agent,\n * `StateManager.saveStateIfModified()` will attempt to automatically persist these changes.\n * `StateManager.setAgentState()` will still work for explicit saves in this mode.\n *\n * @property {StateSavingStrategy} [stateSavingStrategy]\n */\n stateSavingStrategy?: StateSavingStrategy;\n /**\n * Optional configuration for the framework's logger.\n * @property {{ level?: LogLevel }} [logger]\n */\n logger?: {\n /** Minimum log level to output. Defaults to 'info'. */\n level?: LogLevel;\n };\n /**\n * Optional: Defines the default identity and high-level guidance for the agent.\n * This can be overridden at the thread or call level.\n * @property {AgentPersona} [persona]\n */\n persona?: AgentPersona;\n /**\n * Optional configuration for MCP (Model Context Protocol) manager.\n * Enables connection to external MCP servers for dynamic tool loading.\n * @property {McpManagerConfig} [mcpConfig]\n */\n mcpConfig?: McpManagerConfig;\n /**\n * Optional configuration for authentication strategies.\n * Used for secure connections to external services and MCP servers.\n * @property {object} [authConfig]\n */\n authConfig?: {\n /**\n * Whether to enable authentication manager. Defaults to false.\n * @property {boolean} [enabled]\n */\n enabled?: boolean;\n /**\n * Pre-configured authentication strategies to register at startup.\n * @property {Array<{ id: string; strategy: any }>} [strategies]\n */\n strategies?: Array<{ id: string; strategy: any }>;\n };\n /**\n * Optional: Configuration for A2A services.\n * @property {object} [a2aConfig]\n */\n a2aConfig?: {\n /**\n * The endpoint for discovering A2A agents.\n * @property {string} [discoveryEndpoint]\n */\n discoveryEndpoint?: string;\n /**\n * The callback URL for receiving A2A task updates.\n * @property {string} [callbackUrl]\n */\n callbackUrl?: string;\n };\n // Add other top-level configuration properties as needed, e.g.:\n // defaultThreadConfig?: Partial<ThreadConfig>;\n}\n\n/**\n * Represents the possible states of an A2A (Agent-to-Agent) task.\n *\n * @enum {string}\n */\nexport enum A2ATaskStatus {\n /** Task has been created but not yet assigned to an agent. */\n PENDING = 'PENDING',\n /** Task has been assigned to an agent and is being processed. */\n IN_PROGRESS = 'IN_PROGRESS',\n /** Task has been completed successfully. */\n COMPLETED = 'COMPLETED',\n /** Task has failed during execution. */\n FAILED = 'FAILED',\n /** Task has been cancelled before completion. */\n CANCELLED = 'CANCELLED',\n /** Task is waiting for external dependencies or manual intervention. */\n WAITING = 'WAITING',\n /** Task is being reviewed for quality assurance. */\n REVIEW = 'REVIEW'\n}\n\n/**\n * Represents the priority level of an A2A task.\n *\n * @enum {string}\n */\nexport enum A2ATaskPriority {\n /** Low priority. */\n LOW = 'LOW',\n /** Medium priority. */\n MEDIUM = 'MEDIUM',\n /** High priority. */\n HIGH = 'HIGH',\n /** Urgent priority. */\n URGENT = 'URGENT'\n}\n\n/**\n * Represents agent information for A2A task assignment.\n *\n * @interface A2AAgentInfo\n */\nexport interface A2AAgentInfo {\n /**\n * Unique identifier for the agent.\n * @property {string} agentId\n */\n agentId: string;\n /**\n * Human-readable name for the agent.\n * @property {string} agentName\n */\n agentName: string;\n /**\n * The type or role of the agent (e.g., 'reasoning', 'data-processing', 'synthesis').\n * @property {string} agentType\n */\n agentType: string;\n /**\n * Base URL or endpoint for communicating with the agent.\n * @property {string} [endpoint]\n */\n endpoint?: string;\n /**\n * Agent capabilities or specializations.\n * @property {string[]} [capabilities]\n */\n capabilities?: string[];\n /**\n * Current load or availability status of the agent.\n * @property {'available' | 'busy' | 'offline'} [status]\n */\n status?: 'available' | 'busy' | 'offline';\n /**\n * Authentication configuration for communicating with the agent.\n * @property {object} [authentication]\n */\n authentication?: {\n /**\n * Type of authentication required.\n * @property {'bearer' | 'api_key' | 'none'} type\n */\n type: 'bearer' | 'api_key' | 'none';\n /**\n * Bearer token for authorization (if type is 'bearer').\n * @property {string} [token]\n */\n token?: string;\n /**\n * API key for authorization (if type is 'api_key').\n * @property {string} [apiKey]\n */\n apiKey?: string;\n };\n}\n\n/**\n * Represents metadata about A2A task execution.\n *\n * @interface A2ATaskMetadata\n */\nexport interface A2ATaskMetadata {\n /**\n * Timestamp when the task was created (Unix timestamp in milliseconds).\n * @property {number} createdAt\n */\n createdAt: number;\n /**\n * Timestamp when the task was last updated (Unix timestamp in milliseconds).\n * @property {number} updatedAt\n */\n updatedAt: number;\n /**\n * Timestamp when the task was started (if applicable).\n * @property {number} [startedAt]\n */\n startedAt?: number;\n /**\n * Timestamp when the task was completed/failed (if applicable).\n * @property {number} [completedAt]\n */\n completedAt?: number;\n /**\n * Timestamp when the task was delegated to a remote agent (if applicable).\n * @property {number} [delegatedAt]\n */\n delegatedAt?: number;\n /**\n * Timestamp when the task was last updated (for compatibility).\n * @property {number} [lastUpdated]\n */\n lastUpdated?: number;\n /**\n * The user or system that initiated this task.\n * @property {string} [initiatedBy]\n */\n initiatedBy?: string;\n /**\n * Correlation ID for tracking related tasks across the system.\n * @property {string} [correlationId]\n */\n correlationId?: string;\n /**\n * Number of retry attempts made for this task.\n * @property {number} [retryCount]\n */\n retryCount?: number;\n /**\n * Maximum number of retry attempts allowed.\n * @property {number} [maxRetries]\n */\n maxRetries?: number;\n /**\n * Timeout duration in milliseconds.\n * @property {number} [timeoutMs]\n */\n timeoutMs?: number;\n /**\n * Estimated completion time in milliseconds (if provided by remote agent).\n * @property {number} [estimatedCompletionMs]\n */\n estimatedCompletionMs?: number;\n /**\n * Tags or labels for categorizing tasks.\n * @property {string[]} [tags]\n */\n tags?: string[];\n}\n\n/**\n * Represents the result of an A2A task execution.\n *\n * @interface A2ATaskResult\n */\nexport interface A2ATaskResult {\n /**\n * Whether the task execution was successful.\n * @property {boolean} success\n */\n success: boolean;\n /**\n * The data returned by the task execution.\n * @property {any} [data]\n */\n data?: any;\n /**\n * Error message if the task failed.\n * @property {string} [error]\n */\n error?: string;\n /**\n * Additional metadata about the execution.\n * @property {object} [metadata]\n */\n metadata?: {\n sources?: Array<{\n sourceName: string;\n url?: string;\n [key: string]: any;\n }>;\n [key: string]: any;\n };\n /**\n * Execution duration in milliseconds.\n * @property {number} [durationMs]\n */\n durationMs?: number;\n}\n\n/**\n * Represents a task for Agent-to-Agent (A2A) communication and delegation.\n * Used for asynchronous task delegation between AI agents in distributed systems.\n *\n * @interface A2ATask\n */\nexport interface A2ATask {\n /**\n * Unique identifier for the task.\n * @property {string} taskId\n */\n taskId: string;\n /**\n * The thread this task belongs to (top-level for efficient filtering).\n * @property {string} threadId\n */\n threadId: string;\n \n /**\n * Current status of the task.\n * @property {A2ATaskStatus} status\n */\n status: A2ATaskStatus;\n \n /**\n * The data payload containing task parameters and context.\n * @property {object} payload\n */\n payload: {\n /**\n * The type of task to be executed (e.g., 'analyze', 'synthesize', 'transform').\n * @property {string} taskType\n */\n taskType: string;\n /**\n * Input data required for task execution.\n * @property {any} input\n */\n input: any;\n /**\n * Instructions or configuration for the task.\n * @property {string} [instructions]\n */\n instructions?: string;\n /**\n * Additional parameters specific to the task type.\n * @property {Record<string, any>} [parameters]\n */\n parameters?: Record<string, any>;\n };\n \n /**\n * Information about the agent that created/requested this task.\n * @property {A2AAgentInfo} sourceAgent\n */\n sourceAgent: A2AAgentInfo;\n \n /**\n * Information about the agent assigned to execute this task (if assigned).\n * @property {A2AAgentInfo} [targetAgent]\n */\n targetAgent?: A2AAgentInfo;\n \n /**\n * Task priority level.\n * @property {A2ATaskPriority} priority\n */\n priority: A2ATaskPriority;\n \n /**\n * Task execution metadata.\n * @property {A2ATaskMetadata} metadata\n */\n metadata: A2ATaskMetadata;\n \n /**\n * The result of task execution (if completed).\n * @property {A2ATaskResult} [result]\n */\n result?: A2ATaskResult;\n \n /**\n * Callback URL or identifier for task completion notifications.\n * @property {string} [callbackUrl]\n */\n callbackUrl?: string;\n \n /**\n * Dependencies that must be completed before this task can start.\n * @property {string[]} [dependencies]\n */\n dependencies?: string[];\n}\n\n/**\n * Represents a request to create a new A2A task.\n *\n * @interface CreateA2ATaskRequest\n */\nexport interface CreateA2ATaskRequest {\n /**\n * The type of task to be executed.\n * @property {string} taskType\n */\n taskType: string;\n /**\n * Input data for the task.\n * @property {any} input\n */\n input: any;\n /**\n * Instructions for task execution.\n * @property {string} [instructions]\n */\n instructions?: string;\n /**\n * Task parameters.\n * @property {Record<string, any>} [parameters]\n */\n parameters?: Record<string, any>;\n /**\n * Task priority.\n * @property {A2ATaskPriority} [priority]\n */\n priority?: A2ATaskPriority;\n /**\n * Source agent information.\n * @property {A2AAgentInfo} sourceAgent\n */\n sourceAgent: A2AAgentInfo;\n /**\n * Preferred target agent (if any).\n * @property {A2AAgentInfo} [preferredTargetAgent]\n */\n preferredTargetAgent?: A2AAgentInfo;\n /**\n * Task dependencies.\n * @property {string[]} [dependencies]\n */\n dependencies?: string[];\n /**\n * Callback URL for notifications.\n * @property {string} [callbackUrl]\n */\n callbackUrl?: string;\n /**\n * Task timeout in milliseconds.\n * @property {number} [timeoutMs]\n */\n timeoutMs?: number;\n /**\n * Maximum retry attempts.\n * @property {number} [maxRetries]\n */\n maxRetries?: number;\n /**\n * Task tags.\n * @property {string[]} [tags]\n */\n tags?: string[];\n}\n\n/**\n * Represents an update to an existing A2A task.\n *\n * @interface UpdateA2ATaskRequest\n */\nexport interface UpdateA2ATaskRequest {\n /**\n * Task ID to update.\n * @property {string} taskId\n */\n taskId: string;\n /**\n * New task status (if changing).\n * @property {A2ATaskStatus} [status]\n */\n status?: A2ATaskStatus;\n /**\n * Target agent assignment (if assigning/reassigning).\n * @property {A2AAgentInfo} [targetAgent]\n */\n targetAgent?: A2AAgentInfo;\n /**\n * Task result (if completing).\n * @property {A2ATaskResult} [result]\n */\n result?: A2ATaskResult;\n /**\n * Additional metadata updates.\n * @property {Partial<A2ATaskMetadata>} [metadata]\n */\n metadata?: Partial<A2ATaskMetadata>;\n}\n\n/**\n * Defines the default identity and high-level guidance for an agent.\n * This is provided at the instance level and can be overridden by thread or call-specific prompts.\n *\n * @interface AgentPersona\n */\nexport interface AgentPersona {\n /**\n * The name or identity of the agent (e.g., \"Zoi\").\n * This will be used in the synthesis prompt.\n * @property {string} name\n */\n name: string;\n\n /**\n * The default system prompt that provides high-level guidance.\n * This serves as the base layer in the system prompt resolution hierarchy.\n * @property {string} defaultSystemPrompt\n */\n prompts: StageSpecificPrompts;\n}\n\n/**\n * Defines stage-specific system prompts for planning and synthesis.\n *\n * @interface StageSpecificPrompts\n */\nexport interface StageSpecificPrompts {\n /**\n * System prompt to guide the planning phase.\n * Focuses on reasoning, expertise, and tool selection.\n * @property {string} [planning]\n */\n planning?: string;\n\n /**\n * System prompt to guide the synthesis phase.\n * Focuses on tone, formatting, and final response structure.\n * @property {string} [synthesis]\n */\n synthesis?: string;\n}","/**\n * @module utils/uuid\n * Provides a utility function for generating Version 4 UUIDs.\n */\nimport { v4 as uuidv4 } from 'uuid';\n\n/**\n * Generates a unique Version 4 UUID (Universally Unique Identifier) string.\n *\n * @remarks\n * Uses the underlying 'uuid' library's v4 implementation.\n *\n * @returns A randomly generated UUID string (e.g., \"f47ac10b-58cc-4372-a567-0e02b2c3d479\").\n *\n * @see {@link https://www.npmjs.com/package/uuid | uuid npm package}\n */\nexport const generateUUID = (): string => {\n return uuidv4();\n};","// src/core/agents/pes-agent.ts\nimport {\n IAgentCore,\n StateManager,\n ConversationManager,\n ToolRegistry,\n // PromptManager, // Removed - PESAgent will construct prompt object directly\n ReasoningEngine,\n OutputParser,\n ObservationManager,\n ToolSystem,\n UISystem, // Added UISystem import\n IA2ATaskRepository // Added A2A task repository interface\n // Assuming repository interfaces might be needed indirectly or for type safety, though not directly used\n} from '@/core/interfaces';\nimport {\n AgentProps,\n AgentFinalResponse,\n ConversationMessage,\n ParsedToolCall,\n ToolResult,\n ObservationType,\n ExecutionMetadata,\n MessageRole, // Keep for mapping history roles initially\n CallOptions,\n ModelCapability,\n LLMMetadata,\n ArtStandardPrompt, // Import new types\n ArtStandardMessageRole,\n A2ATask, // Added A2A task types\n A2ATaskStatus,\n A2ATaskPriority,\n A2AAgentInfo,\n // PromptContext, // Removed unused import after refactoring prompt construction\n // ThreadConfig, // Removed unused import (config accessed via ThreadContext)\n // ToolSchema, // Removed unused import\n // ThreadContext, // Removed unused import\n} from '@/types';\nimport { AgentPersona } from '@/types';\nimport { RuntimeProviderConfig } from '@/types/providers'; // Import RuntimeProviderConfig\nimport { generateUUID } from '@/utils/uuid';\nimport { ARTError, ErrorCode } from '@/errors';\nimport { Logger } from '@/utils/logger'; // Added Logger import\n\n/**\n * Defines the dependencies required by the PESAgent constructor.\n * These are typically provided by the AgentFactory during instantiation.\n */\nimport { AgentDiscoveryService } from '@/systems/a2a/AgentDiscoveryService';\nimport { TaskDelegationService } from '@/systems/a2a/TaskDelegationService';\n\nexport interface PESAgentDependencies {\n /** Manages thread configuration and state. */\n stateManager: StateManager;\n /**\n * Optional default system prompt string provided at the ART instance level.\n * This serves as a custom prompt part if no thread-specific or call-specific\n * system prompt is provided. It's appended to the agent's base system prompt.\n */\n // instanceDefaultCustomSystemPrompt?: string; // This will be replaced by the persona\n /** Manages conversation history. */\n conversationManager: ConversationManager;\n /** Registry for available tools. */\n toolRegistry: ToolRegistry;\n // /** Constructs prompts for LLM calls. */ // Removed\n // promptManager: PromptManager; // Removed\n /** Handles interaction with the LLM provider. */\n reasoningEngine: ReasoningEngine;\n /** Parses LLM responses. */\n outputParser: OutputParser;\n /** Records agent execution observations. */\n observationManager: ObservationManager;\n /** Orchestrates tool execution. */\n toolSystem: ToolSystem;\n /** Provides access to UI communication sockets. */\n uiSystem: UISystem; // Added UISystem dependency\n /** Repository for A2A tasks. */\n a2aTaskRepository: IA2ATaskRepository;\n /** Service for discovering A2A agents. */\n agentDiscoveryService?: AgentDiscoveryService | null;\n /** Service for delegating A2A tasks. */\n taskDelegationService?: TaskDelegationService | null;\n /** Resolver for standardized system prompt composition. */\n systemPromptResolver: import('@/core/interfaces').SystemPromptResolver;\n /** Optional: Defines the default identity and high-level guidance for the agent. */\n persona?: AgentPersona;\n}\n\nconst DEFAULT_PERSONA: AgentPersona = {\n name: 'Zoi',\n prompts: {\n planning: 'You are a helpful AI assistant. Your primary goal is to understand a user\\'s query, determine the intent, and create a clear plan to provide an accurate and helpful response. You can use tools to gather information if necessary.',\n synthesis: 'You are a helpful AI assistant named Art. Your primary goal is to synthesize the information gathered from tools and planning into a final, user-friendly response. Be clear, concise, and helpful.'\n }\n};\n\n/**\n * Implements the Plan-Execute-Synthesize (PES) agent orchestration logic.\n * This agent follows a structured approach:\n * 1. **Plan:** Understand the user query, determine intent, and create a plan (potentially involving tool calls).\n * 2. **Execute:** Run any necessary tools identified in the planning phase.\n * 3. **Synthesize:** Generate a final response based on the query, plan, and tool results.\n *\n * It constructs standardized prompts (`ArtStandardPrompt`) directly as JavaScript objects\n * for the `ReasoningEngine`. It processes the `StreamEvent` output from the reasoning engine for both planning and synthesis.\n *\n * // @see {PromptManager} // Removed\n * @see {ReasoningEngine}\n * @see {ArtStandardPrompt}\n * @see {StreamEvent}\n */\nexport class PESAgent implements IAgentCore {\n private readonly deps: PESAgentDependencies;\n private readonly persona: AgentPersona;\n\n /**\n * Creates an instance of the PESAgent.\n * @param {module:core/agents/pes-agent.PESAgentDependencies} dependencies - An object containing instances of all required subsystems (managers, registries, etc.).\n */\n constructor(dependencies: PESAgentDependencies) {\n this.deps = dependencies;\n // Deep merge the default persona with the provided one\n this.persona = {\n ...DEFAULT_PERSONA,\n ...dependencies.persona,\n prompts: {\n ...DEFAULT_PERSONA.prompts,\n ...dependencies.persona?.prompts,\n },\n };\n }\n\n /**\n * Executes the full Plan-Execute-Synthesize cycle for a given user query.\n *\n * **Workflow:**\n * 1. **Initiation & Config:** Loads thread configuration and resolves system prompt\n * 2. **Data Gathering:** Gathers history, available tools\n * 3. **Planning:** LLM call for planning and parsing\n * 4. **A2A Discovery & Delegation:** Identifies and delegates A2A tasks to remote agents\n * 5. **Tool Execution:** Executes identified local tool calls\n * 6. **Synthesis:** LLM call for final response generation including A2A results\n * 7. **Finalization:** Saves messages and cleanup\n *\n * @param {AgentProps} props - The input properties containing the user query, threadId, userId, traceId, etc.\n * @returns {Promise<AgentFinalResponse>} A promise resolving to the final response, including the AI message and execution metadata.\n * @throws {ARTError} If a critical error occurs that prevents the agent from completing the process.\n */\n async process(props: AgentProps): Promise<AgentFinalResponse> {\n const startTime = Date.now();\n const traceId = props.traceId ?? generateUUID();\n let status: ExecutionMetadata['status'] = 'success';\n let errorMessage: string | undefined;\n let llmCalls = 0;\n let toolCallsCount = 0;\n let finalAiMessage: ConversationMessage | undefined;\n let aggregatedLlmMetadata: LLMMetadata | undefined = undefined;\n\n let phase = 'initialization';\n try {\n // Stage 1: Load configuration and resolve system prompt\n phase = 'configuration';\n const { threadContext, planningSystemPrompt, synthesisSystemPrompt, runtimeProviderConfig, finalPersona } = await this._loadConfiguration(props, traceId);\n\n // Stage 2: Gather context data\n phase = 'context_gathering';\n const history = await this._gatherHistory(props.threadId, threadContext);\n const availableTools = await this._gatherTools(props.threadId);\n\n // Stage 3: Perform planning\n phase = 'planning';\n const { planningOutput, planningMetadata, planningContext } = await this._performPlanning(\n props, planningSystemPrompt, history, availableTools, runtimeProviderConfig, traceId\n );\n llmCalls++;\n if (planningMetadata) {\n aggregatedLlmMetadata = { ...(aggregatedLlmMetadata ?? {}), ...planningMetadata };\n }\n\n // Stage 4: Delegate A2A tasks based on the plan\n phase = 'a2a_delegation';\n const delegatedA2ATasks = await this._delegateA2ATasks(\n planningOutput, props.threadId, traceId\n );\n\n // Stage 4b: Wait for A2A task completion\n phase = 'a2a_completion';\n const completedA2ATasks = await this._waitForA2ACompletion(\n delegatedA2ATasks, props.threadId, traceId\n );\n\n // Stage 5: Execute local tools\n phase = 'tool_execution';\n const toolResults = await this._executeLocalTools(\n planningOutput.toolCalls, props.threadId, traceId\n );\n toolCallsCount = toolResults.length;\n if (toolResults.some(r => r.status === 'error')) {\n status = 'partial';\n Logger.warn(`[${traceId}] Partial success in tool execution.`);\n errorMessage = 'Tool execution errors occurred.';\n }\n\n // Stage 6: Perform synthesis\n phase = 'synthesis';\n const { finalResponseContent, synthesisMetadata, uiMetadata } = await this._performSynthesis(\n props, synthesisSystemPrompt, history, planningOutput, toolResults, completedA2ATasks, runtimeProviderConfig, traceId, finalPersona, planningContext\n );\n llmCalls++;\n if (synthesisMetadata) {\n aggregatedLlmMetadata = { ...(aggregatedLlmMetadata ?? {}), ...synthesisMetadata };\n }\n\n // Stage 7: Finalization\n phase = 'finalization';\n finalAiMessage = await this._finalize(props, finalResponseContent, traceId, uiMetadata);\n\n } catch (error: any) {\n const artError = (error instanceof ARTError)\n ? error\n : new ARTError(`An unexpected error occurred during agent processing: ${error.message}`, ErrorCode.UNKNOWN_ERROR, error);\n\n // Annotate error with the phase if it's not already set\n if (!artError.details) artError.details = {};\n artError.details.phase = artError.details.phase || phase;\n\n Logger.error(`[${traceId}] PESAgent process error in phase '${artError.details.phase}':`, artError);\n status = status === 'partial' ? 'partial' : 'error';\n errorMessage = artError.message;\n if (status === 'error') finalAiMessage = undefined;\n\n // Record top-level error observation, ensuring it's always an ARTError\n await this.deps.observationManager.record({\n threadId: props.threadId, traceId, type: ObservationType.ERROR,\n content: {\n phase: artError.details.phase,\n error: artError.message,\n code: artError.code,\n stack: artError.stack\n },\n metadata: { timestamp: Date.now() }\n }).catch(err => Logger.error(`[${traceId}] Failed to record top-level error observation:`, err));\n } finally {\n // Ensure state is saved even if errors occurred\n try {\n await this.deps.stateManager.saveStateIfModified(props.threadId);\n } catch(saveError: any) {\n Logger.error(`[${traceId}] Failed to save state during finalization:`, saveError);\n }\n }\n\n const endTime = Date.now();\n const metadata: ExecutionMetadata = {\n threadId: props.threadId,\n traceId: traceId,\n userId: props.userId,\n status: status,\n totalDurationMs: endTime - startTime,\n llmCalls: llmCalls,\n toolCalls: toolCallsCount,\n error: errorMessage,\n llmMetadata: aggregatedLlmMetadata,\n };\n\n if (!finalAiMessage && status !== 'success') {\n finalAiMessage = {\n messageId: generateUUID(),\n threadId: props.threadId,\n role: MessageRole.AI,\n content: errorMessage ?? \"Agent execution failed.\",\n timestamp: Date.now(),\n metadata: { traceId, error: true }\n };\n } else if (!finalAiMessage) {\n throw new ARTError(\"Agent finished with success status but no final message was generated.\", ErrorCode.UNKNOWN_ERROR);\n }\n\n return {\n response: finalAiMessage,\n metadata: metadata,\n };\n }\n\n /**\n * Loads thread configuration and resolves the system prompt hierarchy.\n * @private\n */\n private async _loadConfiguration(props: AgentProps, traceId: string) {\n Logger.debug(`[${traceId}] Stage 1: Initiation & Config`);\n \n const threadContext = await this.deps.stateManager.loadThreadContext(props.threadId, props.userId);\n if (!threadContext) {\n throw new ARTError(`Thread context not found for threadId: ${props.threadId}`, ErrorCode.THREAD_NOT_FOUND);\n }\n\n // Resolve persona hierarchy: call -> thread -> instance\n const callPersona = props.options?.persona;\n const threadPersona = await this.deps.stateManager.getThreadConfigValue<Partial<AgentPersona>>(props.threadId, 'persona');\n const instancePersona = this.persona;\n\n const finalPersona: AgentPersona = {\n name: callPersona?.name || threadPersona?.name || instancePersona.name,\n prompts: {\n planning: callPersona?.prompts?.planning || threadPersona?.prompts?.planning || instancePersona.prompts.planning,\n synthesis: callPersona?.prompts?.synthesis || threadPersona?.prompts?.synthesis || instancePersona.prompts.synthesis,\n },\n };\n\n // Resolve system prompts for each stage\n const planningSystemPrompt = await this.deps.systemPromptResolver.resolve({\n base: finalPersona.prompts.planning || '',\n thread: await this.deps.stateManager.getThreadConfigValue<any>(props.threadId, 'systemPrompt'),\n call: props.options?.systemPrompt\n }, traceId);\n\n const synthesisSystemPrompt = await this.deps.systemPromptResolver.resolve({\n base: finalPersona.prompts.synthesis || '',\n thread: await this.deps.stateManager.getThreadConfigValue<any>(props.threadId, 'systemPrompt'),\n call: props.options?.systemPrompt\n }, traceId);\n\n // Determine RuntimeProviderConfig\n const runtimeProviderConfig: RuntimeProviderConfig | undefined =\n props.options?.providerConfig || threadContext.config.providerConfig;\n\n if (!runtimeProviderConfig) {\n throw new ARTError(`RuntimeProviderConfig is missing in AgentProps.options or ThreadConfig for threadId: ${props.threadId}`, ErrorCode.INVALID_CONFIG);\n }\n\n return { \n threadContext, \n planningSystemPrompt, \n synthesisSystemPrompt, \n runtimeProviderConfig,\n finalPersona\n };\n }\n\n /**\n * Gathers conversation history for the current thread.\n * @private\n */\n private async _gatherHistory(threadId: string, threadContext: any) {\n Logger.debug(`[${threadContext.threadId || threadId}] Stage 2: Gathering History`);\n \n const historyOptions = { limit: threadContext.config.historyLimit };\n const rawHistory = await this.deps.conversationManager.getMessages(threadId, historyOptions);\n return this.formatHistoryForPrompt(rawHistory);\n }\n\n /**\n * Gathers available tools for the current thread.\n * @private\n */\n private async _gatherTools(threadId: string) {\n Logger.debug(`[${threadId}] Stage 2: Gathering Tools`);\n return await this.deps.toolRegistry.getAvailableTools({ enabledForThreadId: threadId });\n }\n\n /**\n * Performs the planning phase including LLM call and output parsing.\n * @private\n *\n * @remarks\n * The planning prompt instructs the LLM to produce a concise `title` (<= 10 words)\n * alongside `intent`, `plan`, and `toolCalls`. After parsing, a `TITLE` observation\n * is emitted (if present) for UI components to subscribe via `ObservationSocket`.\n */\n private async _performPlanning(\n props: AgentProps,\n systemPrompt: string,\n formattedHistory: ArtStandardPrompt,\n availableTools: any[],\n runtimeProviderConfig: RuntimeProviderConfig,\n traceId: string\n ) {\n Logger.debug(`[${traceId}] Stage 3: Pre-planning & A2A Discovery`);\n\n // --- A2A Pre-Discovery ---\n let candidateAgents: A2AAgentInfo[] = [];\n let a2aPromptSection = 'No candidate agents found for delegation.';\n if (this.deps.agentDiscoveryService) {\n try {\n // Simple heuristic to find a task type from the query.\n // This could be improved with a more sophisticated NLP model in the future.\n const potentialTaskType = props.query.split(' ')[0].toLowerCase();\n candidateAgents = await this.deps.agentDiscoveryService.findTopAgentsForTask(potentialTaskType, 3, traceId);\n\n if (candidateAgents.length > 0) {\n a2aPromptSection = `You can delegate tasks to other specialized agents. Here are the available candidates for this query:\\n${\n candidateAgents.map(agent =>\n `- Agent ID: ${agent.agentId}\\n Name: ${agent.agentName}\\n Capabilities: ${(agent.capabilities ?? []).join(', ')}`\n ).join('\\n')\n }\\nTo delegate, use the \"delegate_to_agent\" tool.`;\n }\n } catch (err: any) {\n Logger.warn(`[${traceId}] A2A pre-discovery failed, proceeding without candidate agents:`, err);\n a2aPromptSection = 'Agent discovery failed. Delegation is not available.';\n }\n } else {\n a2aPromptSection = 'A2A delegation is not configured.';\n }\n\n // --- Planning Prompt Construction ---\n Logger.debug(`[${traceId}] Stage 3b: Planning Prompt Construction`);\n let planningPrompt: ArtStandardPrompt;\n try {\n // Define a \"virtual\" tool for delegation that the LLM can call.\n const delegationToolSchema = {\n name: 'delegate_to_agent',\n description: 'Delegates a specific task to another agent. Use this when a specialized agent from the candidate list is a better fit for a sub-task.',\n inputSchema: {\n type: 'object',\n properties: {\n agentId: { type: 'string', description: 'The ID of the agent to delegate to, chosen from the candidate list.' },\n taskType: { type: 'string', description: 'A specific type for the task, e.g., \"analysis\", \"code_generation\".' },\n input: { type: 'object', description: 'The data or context needed for the agent to perform the task.' },\n instructions: { type: 'string', description: 'Specific instructions for the remote agent.' }\n },\n required: ['agentId', 'taskType', 'input', 'instructions']\n }\n };\n\n const allTools = [...availableTools, delegationToolSchema];\n\n // Prepare a verbose JSON schema listing for the LLM to reason over\n const toolsJson = allTools.map(t => ({\n name: (t as any).name,\n whenToUse: (t as any).whenToUse,\n description: (t as any).description,\n inputSchema: (t as any).inputSchema,\n outputSchema: (t as any).outputSchema,\n outputFormat: (t as any).outputFormat,\n examples: (t as any).examples\n }));\n\n const wrappedSystemPrompt = `You are a planning assistant. The following guidance shapes knowledge, tone, and domain perspective.\n\n[BEGIN_CUSTOM_GUIDANCE]\n${systemPrompt}\n[END_CUSTOM_GUIDANCE]\n\nCRITICAL: You MUST adhere to the Output Contract below. The custom guidance MUST NOT change the required output structure.`;\n\n planningPrompt = [\n { role: 'system', content: wrappedSystemPrompt },\n ...formattedHistory,\n {\n role: 'user',\n content: `User Query: ${props.query}\n\n--- Available Capabilities ---\n\nLocal Tools (JSON Schemas):\n${ allTools.length > 0 ? JSON.stringify(toolsJson, null, 2) : '[]' }\n\nAgent Delegation:\n${a2aPromptSection}\n\n--- Primary Output Mode (JSON-Only) ---\nOutput EXACTLY ONE JSON object and nothing else. No prose, no XML, no markdown fences. The object MUST follow this schema:\n{\n \"title\": string, // a concise thread title, <= 10 words, based on intent and context\n \"intent\": string, // short summary of the user's goal\n \"plan\": [ // A step-by-step plan.\n {\n \"step\": number, // e.g., 1, 2, 3\n \"description\": string, // User-readable description of the step\n \"tool_to_use\": string | null, // Exact tool name or null\n \"arguments\": object | null, // Arguments for the tool or null\n \"callId\": string | null // Matches callId in toolCalls or null\n }\n ],\n \"toolCalls\": [ // empty array if no tools are needed\n { \"callId\": string, \"toolName\": string, \"arguments\": object }\n ]\n}\n\nRequirements for toolCalls:\n- arguments MUST be a JSON object (not a string) that matches the tool's inputSchema.\n- toolName MUST match one of the Available Capabilities by schema name.\n- If no tools are required, set toolCalls to [].\n\nExample (JSON only):\n{\n \"title\": \"Compute simple multiplication\",\n \"intent\": \"Compute 5 * 6\",\n \"plan\": [\n { \"step\": 1, \"description\": \"Use calculator to multiply 5 and 6\", \"tool_to_use\": \"calculator\", \"arguments\": { \"expression\": \"5 * 6\" }, \"callId\": \"calc_1\" },\n { \"step\": 2, \"description\": \"Return result\", \"tool_to_use\": null, \"arguments\": null, \"callId\": null }\n ],\n \"toolCalls\": [\n { \"callId\": \"calc_1\", \"toolName\": \"calculator\", \"arguments\": { \"expression\": \"5 * 6\" } }\n ]\n}\n\n--- Fallback Output Mode (Sections) ---\nIf you cannot produce the JSON object above, then output these sections instead:\n\nTitle: [A single concise sentence (<= 10 words) capturing the thread title]\n\nIntent: [One or two sentences]\n\nPlan: [Bullet or numbered steps]\n\nTool Calls: [A JSON array only. Each item MUST be of the exact form {\"callId\": \"unique_id\", \"toolName\": \"tool_schema_name\", \"arguments\": { /* JSON object matching the tool's inputSchema */ }}. If no tools are needed, return []].\n\nInvalid Examples (do NOT do these):\n- Wrapping with markdown code fences or any fences\n- Wrapping with json(...): json([ ... ])\n- Placing inside XML tags such as <Response> or <Plan>\n- Setting arguments as a string: {\"arguments\": \"{ 'expression': '5*6' }\"}\n- Using unknown toolName not present in Available Capabilities\n`\n }\n ];\n } catch (err: any) {\n Logger.error(`[${traceId}] Failed to construct planning prompt object:`, err);\n throw new ARTError(`Failed to construct planning prompt object: ${err.message}`, ErrorCode.PROMPT_ASSEMBLY_FAILED, err);\n }\n\n // --- Planning LLM Call ---\n Logger.debug(`[${traceId}] Stage 3c: Planning LLM Call`);\n const planningOptions: CallOptions = {\n threadId: props.threadId, traceId, userId: props.userId, sessionId: props.sessionId,\n stream: true, callContext: 'AGENT_THOUGHT',\n requiredCapabilities: [ModelCapability.REASONING],\n providerConfig: runtimeProviderConfig,\n ...(props.options?.llmParams ?? {}),\n };\n\n let planningOutputText: string = '';\n let parsedPlanningOutput: { title?: string; intent?: string; plan?: string; toolCalls?: ParsedToolCall[]; thoughts?: string } = {};\n let planningStreamError: Error | null = null;\n let planningMetadata: LLMMetadata | undefined = undefined;\n let planningContext: {\n toolsList: { name: string; description?: string }[];\n a2aSummary: string;\n plannedToolCalls: ParsedToolCall[];\n rawPlanningText?: string;\n } = { toolsList: [], a2aSummary: '', plannedToolCalls: [] };\n\n try {\n await this.deps.observationManager.record({\n threadId: props.threadId, traceId, type: ObservationType.PLAN,\n content: { message: \"Preparing for planning LLM call.\" },\n metadata: { timestamp: Date.now() }\n });\n\n const planningStream = await this.deps.reasoningEngine.call(planningPrompt, planningOptions);\n\n await this.deps.observationManager.record({\n threadId: props.threadId, traceId, type: ObservationType.LLM_STREAM_START,\n content: { phase: 'planning' }, metadata: { timestamp: Date.now() }\n });\n\n for await (const event of planningStream) {\n this.deps.uiSystem.getLLMStreamSocket().notify(event, {\n targetThreadId: event.threadId, targetSessionId: event.sessionId\n });\n\n switch (event.type) {\n case 'TOKEN':\n planningOutputText += event.data;\n // Emit THOUGHTS observation for thinking tokens\n if (event.tokenType && String(event.tokenType).includes('THINKING')) {\n await this.deps.observationManager.record({\n threadId: props.threadId,\n traceId,\n type: ObservationType.THOUGHTS,\n content: { text: event.data },\n metadata: { phase: 'planning', tokenType: event.tokenType, timestamp: Date.now() }\n }).catch(err => Logger.error(`[${traceId}] Failed to record THOUGHTS (planning) observation:`, err));\n }\n break;\n case 'METADATA':\n planningMetadata = { ...(planningMetadata ?? {}), ...event.data };\n break;\n case 'ERROR':\n planningStreamError = event.data instanceof Error ? event.data : new Error(String(event.data));\n break;\n }\n if (planningStreamError) break;\n }\n\n if (planningStreamError) {\n throw new ARTError(`Planning phase stream error: ${planningStreamError.message}`, ErrorCode.PLANNING_FAILED, planningStreamError);\n }\n\n parsedPlanningOutput = await this.deps.outputParser.parsePlanningOutput(planningOutputText);\n // Build a compact planning context for downstream synthesis\n planningContext = {\n toolsList: availableTools.map((t: any) => ({ name: t.name, description: t.description })),\n a2aSummary: a2aPromptSection,\n plannedToolCalls: parsedPlanningOutput.toolCalls ?? [],\n rawPlanningText: planningOutputText\n };\n\n await this.deps.observationManager.record({\n threadId: props.threadId, traceId, type: ObservationType.INTENT,\n content: { intent: parsedPlanningOutput.intent }, metadata: { timestamp: Date.now() }\n });\n if (parsedPlanningOutput.title) {\n await this.deps.observationManager.record({\n threadId: props.threadId, traceId, type: ObservationType.TITLE,\n content: { title: parsedPlanningOutput.title }, metadata: { timestamp: Date.now() }\n });\n }\n await this.deps.observationManager.record({\n threadId: props.threadId, traceId, type: ObservationType.PLAN,\n content: { plan: parsedPlanningOutput.plan, rawOutput: planningOutputText },\n metadata: { timestamp: Date.now() }\n });\n if (parsedPlanningOutput.toolCalls && parsedPlanningOutput.toolCalls.length > 0) {\n await this.deps.observationManager.record({\n threadId: props.threadId, traceId, type: ObservationType.TOOL_CALL,\n content: { toolCalls: parsedPlanningOutput.toolCalls },\n metadata: { timestamp: Date.now() }\n });\n }\n\n } catch (err: any) {\n const errorMessage = `Planning phase failed: ${err.message}`;\n Logger.error(`[${traceId}] Planning Error:`, err);\n throw err instanceof ARTError ? err : new ARTError(errorMessage, ErrorCode.PLANNING_FAILED, err);\n }\n\n return { planningOutput: parsedPlanningOutput, planningMetadata, planningContext };\n }\n\n /**\n * Delegates A2A tasks identified in the planning phase.\n * @private\n */\n private async _delegateA2ATasks(\n planningOutput: { toolCalls?: ParsedToolCall[] },\n threadId: string,\n traceId: string\n ): Promise<A2ATask[]> {\n Logger.debug(`[${traceId}] Stage 4: A2A Task Delegation`);\n\n const delegationCalls = planningOutput.toolCalls?.filter(\n call => call.toolName === 'delegate_to_agent'\n ) ?? [];\n\n if (delegationCalls.length === 0) {\n Logger.debug(`[${traceId}] No A2A delegation calls in the plan.`);\n return [];\n }\n\n if (!this.deps.taskDelegationService || !this.deps.agentDiscoveryService) {\n Logger.warn(`[${traceId}] A2A services not available. Skipping delegation.`);\n return [];\n }\n\n const delegatedTasks: A2ATask[] = [];\n for (const call of delegationCalls) {\n try {\n const args = call.arguments;\n const { agentId, taskType, input, instructions } = args;\n\n // Find the full agent info. In a real scenario, we might cache this from the planning phase.\n const allAgents = await this.deps.agentDiscoveryService.discoverAgents(traceId);\n const targetAgent = allAgents.find(a => a.agentId === agentId);\n\n if (!targetAgent) {\n throw new Error(`Agent with ID \"${agentId}\" not found during delegation.`);\n }\n\n const now = Date.now();\n const a2aTask: A2ATask = {\n taskId: call.callId, // Use the tool call ID as the task ID for traceability\n threadId: threadId,\n status: A2ATaskStatus.PENDING,\n payload: { taskType, input, instructions, parameters: { threadId, traceId } },\n sourceAgent: { agentId: 'pes-agent', agentName: 'PES Agent', agentType: 'orchestrator' },\n targetAgent: targetAgent, // Assign the target agent\n priority: A2ATaskPriority.MEDIUM,\n metadata: {\n createdAt: now, updatedAt: now, initiatedBy: threadId, correlationId: traceId,\n retryCount: 0, maxRetries: 3, timeoutMs: 60000, tags: ['delegated', taskType]\n }\n };\n\n // Persist the task before delegating\n await this.deps.a2aTaskRepository.createTask(a2aTask);\n\n // Delegate the task\n const delegatedTask = await this.deps.taskDelegationService.delegateTask(a2aTask, traceId);\n if (delegatedTask) {\n delegatedTasks.push(delegatedTask);\n }\n } catch (err: any) {\n Logger.error(`[${traceId}] Failed to process and delegate A2A task for call ${call.callId}:`, err);\n await this.deps.observationManager.record({\n threadId, traceId, type: ObservationType.ERROR,\n content: { phase: 'a2a_delegation', error: `Delegation for call ${call.callId} failed: ${err.message}` },\n metadata: { timestamp: Date.now() }\n });\n }\n }\n\n Logger.info(`[${traceId}] Successfully initiated delegation for ${delegatedTasks.length}/${delegationCalls.length} A2A task(s).`);\n return delegatedTasks;\n }\n\n /**\n * Waits for A2A tasks to complete with configurable timeout.\n * Polls task status periodically and updates local repository with results.\n * @private\n */\n private async _waitForA2ACompletion(\n a2aTasks: A2ATask[],\n threadId: string,\n traceId: string,\n maxWaitTimeMs: number = 30000, // 30 seconds default\n pollIntervalMs: number = 2000 // 2 seconds default\n ): Promise<A2ATask[]> {\n if (a2aTasks.length === 0) {\n Logger.debug(`[${traceId}] No A2A tasks to wait for`);\n return a2aTasks;\n }\n\n Logger.debug(`[${traceId}] Waiting for ${a2aTasks.length} A2A task(s) to complete (timeout: ${maxWaitTimeMs}ms)`);\n \n const startTime = Date.now();\n const updatedTasks: A2ATask[] = [...a2aTasks];\n \n // Record observation for waiting start\n await this.deps.observationManager.record({\n threadId: threadId,\n traceId: traceId,\n type: ObservationType.TOOL_CALL, // Using TOOL_CALL as closest equivalent\n content: {\n phase: 'a2a_waiting',\n message: 'Started waiting for A2A task completion',\n taskCount: a2aTasks.length,\n maxWaitTimeMs: maxWaitTimeMs,\n pollIntervalMs: pollIntervalMs\n },\n metadata: { timestamp: Date.now() }\n }).catch(err => Logger.error(`[${traceId}] Failed to record A2A waiting observation:`, err));\n\n try {\n while ((Date.now() - startTime) < maxWaitTimeMs) {\n // Check if all tasks are completed\n const incompleteTasks = updatedTasks.filter(task => \n task.status !== A2ATaskStatus.COMPLETED && \n task.status !== A2ATaskStatus.FAILED &&\n task.status !== A2ATaskStatus.CANCELLED\n );\n\n if (incompleteTasks.length === 0) {\n Logger.info(`[${traceId}] All A2A tasks completed successfully`);\n break;\n }\n\n Logger.debug(`[${traceId}] Waiting for ${incompleteTasks.length} A2A task(s) to complete...`);\n\n // Poll each incomplete task for status updates\n for (let i = 0; i < updatedTasks.length; i++) {\n const task = updatedTasks[i];\n \n // Skip already completed tasks\n if (task.status === A2ATaskStatus.COMPLETED || \n task.status === A2ATaskStatus.FAILED ||\n task.status === A2ATaskStatus.CANCELLED) {\n continue;\n }\n\n try {\n // Get latest task status from repository (may have been updated by webhooks)\n const latestTask = await this.deps.a2aTaskRepository.getTask(task.taskId);\n if (latestTask) {\n updatedTasks[i] = latestTask;\n Logger.debug(`[${traceId}] Task ${task.taskId} status updated to: ${latestTask.status}`);\n }\n } catch (error: any) {\n Logger.warn(`[${traceId}] Failed to get updated status for task ${task.taskId}:`, error);\n }\n }\n\n // Wait before next poll cycle\n await new Promise(resolve => setTimeout(resolve, pollIntervalMs));\n }\n\n // Check final completion status\n const completedTasks = updatedTasks.filter(task => task.status === A2ATaskStatus.COMPLETED);\n const failedTasks = updatedTasks.filter(task => task.status === A2ATaskStatus.FAILED);\n const timeoutTasks = updatedTasks.filter(task => \n task.status !== A2ATaskStatus.COMPLETED && \n task.status !== A2ATaskStatus.FAILED &&\n task.status !== A2ATaskStatus.CANCELLED\n );\n\n const totalWaitTime = Date.now() - startTime;\n \n // Record completion observation\n await this.deps.observationManager.record({\n threadId: threadId,\n traceId: traceId,\n type: ObservationType.TOOL_CALL,\n content: {\n phase: 'a2a_waiting_complete',\n message: 'A2A task waiting completed',\n totalWaitTimeMs: totalWaitTime,\n completedTasks: completedTasks.length,\n failedTasks: failedTasks.length,\n timeoutTasks: timeoutTasks.length,\n success: timeoutTasks.length === 0\n },\n metadata: { timestamp: Date.now() }\n }).catch(err => Logger.error(`[${traceId}] Failed to record A2A waiting completion observation:`, err));\n\n if (timeoutTasks.length > 0) {\n Logger.warn(`[${traceId}] ${timeoutTasks.length} A2A task(s) did not complete within timeout (${maxWaitTimeMs}ms)`);\n }\n\n if (completedTasks.length > 0) {\n Logger.info(`[${traceId}] Successfully completed ${completedTasks.length} A2A task(s) in ${totalWaitTime}ms`);\n }\n\n return updatedTasks;\n\n } catch (error: any) {\n Logger.error(`[${traceId}] Error during A2A task waiting:`, error);\n \n // Record error observation\n await this.deps.observationManager.record({\n threadId: threadId,\n traceId: traceId,\n type: ObservationType.ERROR,\n content: {\n phase: 'a2a_waiting',\n error: error.message,\n stack: error.stack,\n waitTimeMs: Date.now() - startTime\n },\n metadata: { timestamp: Date.now() }\n }).catch(err => Logger.error(`[${traceId}] Failed to record A2A waiting error observation:`, err));\n\n // Don't fail the entire process for A2A waiting errors - return current state\n return updatedTasks;\n }\n }\n\n /**\n * Executes local tools identified during planning.\n * @private\n */\n private async _executeLocalTools(toolCalls: ParsedToolCall[] | undefined, threadId: string, traceId: string): Promise<ToolResult[]> {\n const localToolCalls = toolCalls?.filter(call => call.toolName !== 'delegate_to_agent') ?? [];\n\n if (localToolCalls.length === 0) {\n Logger.debug(`[${traceId}] Stage 5: Tool Execution (No local tool calls)`);\n return [];\n }\n\n Logger.debug(`[${traceId}] Stage 5: Tool Execution (${localToolCalls.length} calls)`);\n try {\n return await this.deps.toolSystem.executeTools(localToolCalls, threadId, traceId);\n } catch (err: any) {\n const errorMessage = `Tool execution phase failed: ${err.message}`;\n Logger.error(`[${traceId}] Tool Execution System Error:`, err);\n await this.deps.observationManager.record({\n threadId: threadId, traceId, type: ObservationType.ERROR,\n content: { phase: 'tool_execution', error: err.message, stack: err.stack },\n metadata: { timestamp: Date.now() }\n });\n throw new ARTError(errorMessage, ErrorCode.TOOL_EXECUTION_FAILED, err);\n }\n }\n\n /**\n * Performs the synthesis phase including LLM call for final response generation.\n * @private\n */\n private async _performSynthesis(\n props: AgentProps, \n systemPrompt: string, \n formattedHistory: ArtStandardPrompt, \n planningOutput: any, \n toolResults: ToolResult[], \n a2aTasks: A2ATask[],\n runtimeProviderConfig: RuntimeProviderConfig,\n traceId: string,\n finalPersona: AgentPersona,\n planningContext?: {\n toolsList: { name: string; description?: string }[];\n a2aSummary: string;\n plannedToolCalls: ParsedToolCall[];\n rawPlanningText?: string;\n }\n ) {\n Logger.debug(`[${traceId}] Stage 6: Synthesis Call`);\n \n // Record SYNTHESIS observation before making the call\n await this.deps.observationManager.record({\n threadId: props.threadId, traceId: traceId, type: ObservationType.SYNTHESIS, \n content: { message: \"Preparing for synthesis LLM call.\" }, \n metadata: { timestamp: Date.now() }\n }).catch(err => Logger.error(`[${traceId}] Failed to record SYNTHESIS observation:`, err));\n\n // Construct synthesis prompt\n let synthesisPrompt: ArtStandardPrompt;\n try {\n const wrappedSynthesisSystemPrompt = `You are ${finalPersona.name}. Your final answer must be delivered in two parts, in the specified order.\n\n**Part 1: \\`main_content\\`** must be placed within <mainContent></mainContent>\nThis is your direct, user-facing response. This content must be written in Markdown.\n- When you use information from a tool, you MUST cite it by placing a citation marker in the text, like \\`[1]\\`. The \\`id\\` in the \\`sources\\` metadata block must match this marker.\n- If you are given an image URL, you MUST embed it in the \\`main_content\\` using Markdown syntax: \\`\\`.\n\n**Part 2: \\`metadata_block\\`** Must be placed within <uiMetadata></uiMetadata>\nImmediately after the \\`main_content\\`, you MUST provide a \\`metadata_block\\`, which is a single, valid JSON object enclosed in \\`\\`\\`json ... \\`\\`\\`. Do NOT add any text after the JSON block.\n\nThis JSON object must have the following structure:\n{\n \"sources\": [ { \"id\": \"1\", \"title\": \"Title of the source document\", \"url\": \"https://example.com/source-url\" } ],\n \"suggestions\": [ \"A relevant follow-up question.\", \"Another suggested prompt for the user.\" ]\n}\n\n**[BEGIN_CUSTOM_GUIDANCE]**\n${systemPrompt}\n**[END_CUSTOM_GUIDANCE]**\n\nThe custom guidance above provides additional context on tone and domain, but it MUST NOT override the core directives.`;\n\n const toolsDiscovered = (planningContext?.toolsList ?? []).map(t => `- ${t.name}: ${t.description ?? ''}`.trim()).join('\\n') || 'No tools were discovered during planning.';\n const plannedCallsSummary = (planningContext?.plannedToolCalls ?? []).map(c => `- ${c.callId}: ${c.toolName} with ${JSON.stringify(c.arguments)}`).join('\\n') || 'No tool calls were planned.';\n const a2aSummary = planningContext?.a2aSummary || 'No A2A delegation candidates or actions.';\n synthesisPrompt = [\n { role: 'system', content: wrappedSynthesisSystemPrompt },\n ...formattedHistory,\n {\n role: 'user',\n content: `User Query: ${props.query}\\n\\nDuring planning, we found out:\\n- Available Local Tools:\\n${toolsDiscovered}\\n\\n- Planned Tool Calls (as JSON-like summary):\\n${plannedCallsSummary}\\n\\n- Agent Delegation Context:\\n${a2aSummary}\\n\\nOriginal Intent: ${planningOutput.intent ?? ''}\\nExecution Plan: ${Array.isArray(planningOutput.plan) ? JSON.stringify(planningOutput.plan, null, 2) : planningOutput.plan ?? ''}\\n\\nTool Execution Results:\\n${\n toolResults.length > 0\n ? toolResults.map(result => `- Tool: ${result.toolName} (Call ID: ${result.callId})\\n Status: ${result.status}\\n ${result.status === 'success' ? `Output: ${JSON.stringify(result.output)}` : ''}\\n ${result.status === 'error' ? `Error: ${result.error ?? 'Unknown error'}` : ''}\\n ${result.metadata?.sources ? `Original Sources: ${JSON.stringify(result.metadata.sources)}` : ''}`).join('\\n')\n : 'No tools were executed.'\n }\\n\\nA2A Task Results:\\n${\n a2aTasks.length > 0\n ? a2aTasks.map(task => `- Task: ${task.payload.taskType} (ID: ${task.taskId})\\n Status: ${task.status}\\n ${task.result?.success ? `Output: ${JSON.stringify(task.result.data)}` : ''}\\n ${task.result?.success === false ? `Error: ${task.result.error ?? 'Unknown error'}` : ''}\\n ${task.result?.metadata?.sources ? `Original Sources: ${JSON.stringify(task.result.metadata.sources)}` : ''}`).join('\\n')\n : 'No A2A tasks were delegated.'\n }\\n\\nSynthesize the final answer based on the directives in the system prompt. Give appropriate weight to the verified Tool Execution Results and any successful A2A Task Results. If tools failed, explain briefly and answer using best available evidence.`\n }\n ];\n } catch (err: any) {\n Logger.error(`[${traceId}] Failed to construct synthesis prompt object:`, err);\n throw new ARTError(`Failed to construct synthesis prompt object: ${err.message}`, ErrorCode.PROMPT_ASSEMBLY_FAILED, err);\n }\n\n Logger.debug(`[${traceId}] Stage 6b: Synthesis LLM Call`);\n \n const synthesisOptions: CallOptions = {\n threadId: props.threadId,\n traceId: traceId,\n userId: props.userId,\n sessionId: props.sessionId,\n stream: true,\n callContext: 'FINAL_SYNTHESIS',\n requiredCapabilities: [ModelCapability.TEXT],\n providerConfig: runtimeProviderConfig,\n ...(props.options?.llmParams ?? {}),\n };\n\n let finalResponseContent: string = '';\n let synthesisStreamError: Error | null = null;\n let synthesisMetadata: LLMMetadata | undefined = undefined;\n\n try {\n const synthesisStream = await this.deps.reasoningEngine.call(synthesisPrompt, synthesisOptions);\n\n // Record stream start\n await this.deps.observationManager.record({\n threadId: props.threadId, traceId, type: ObservationType.LLM_STREAM_START, \n content: { phase: 'synthesis' }, metadata: { timestamp: Date.now() }\n }).catch(err => Logger.error(`[${traceId}] Failed to record LLM_STREAM_START observation:`, err));\n\n // Consume the stream\n for await (const event of synthesisStream) {\n this.deps.uiSystem.getLLMStreamSocket().notify(event, { \n targetThreadId: event.threadId, targetSessionId: event.sessionId \n });\n\n switch (event.type) {\n case 'TOKEN':\n if (event.tokenType === 'FINAL_SYNTHESIS_LLM_RESPONSE' || event.tokenType === 'LLM_RESPONSE') {\n finalResponseContent += event.data;\n }\n // Emit THOUGHTS observation for thinking tokens during synthesis\n if (event.tokenType && String(event.tokenType).includes('THINKING')) {\n await this.deps.observationManager.record({\n threadId: props.threadId,\n traceId,\n type: ObservationType.THOUGHTS,\n content: { text: event.data },\n metadata: { phase: 'synthesis', tokenType: event.tokenType, timestamp: Date.now() }\n }).catch(err => Logger.error(`[${traceId}] Failed to record THOUGHTS (synthesis) observation:`, err));\n }\n break;\n case 'METADATA':\n synthesisMetadata = { ...(synthesisMetadata ?? {}), ...event.data };\n await this.deps.observationManager.record({\n threadId: props.threadId, traceId, type: ObservationType.LLM_STREAM_METADATA, \n content: event.data, metadata: { phase: 'synthesis', timestamp: Date.now() }\n }).catch(err => Logger.error(`[${traceId}] Failed to record LLM_STREAM_METADATA observation:`, err));\n break;\n case 'ERROR':\n synthesisStreamError = event.data instanceof Error ? event.data : new Error(String(event.data));\n Logger.error(`[${traceId}] Synthesis Stream Error:`, synthesisStreamError);\n await this.deps.observationManager.record({\n threadId: props.threadId, traceId, type: ObservationType.LLM_STREAM_ERROR, \n content: { phase: 'synthesis', error: synthesisStreamError.message, stack: synthesisStreamError.stack }, \n metadata: { timestamp: Date.now() }\n }).catch(err => Logger.error(`[${traceId}] Failed to record LLM_STREAM_ERROR observation:`, err));\n break;\n case 'END':\n await this.deps.observationManager.record({\n threadId: props.threadId, traceId, type: ObservationType.LLM_STREAM_END, \n content: { phase: 'synthesis' }, metadata: { timestamp: Date.now() }\n }).catch(err => Logger.error(`[${traceId}] Failed to record LLM_STREAM_END observation:`, err));\n break;\n }\n if (synthesisStreamError) break;\n }\n\n if (synthesisStreamError) {\n throw new ARTError(`Synthesis stream error: ${synthesisStreamError.message}`, ErrorCode.SYNTHESIS_FAILED, synthesisStreamError);\n }\n\n } catch (err: any) {\n const synthesisErrorMessage = `Synthesis phase failed: ${err.message}`;\n Logger.error(`[${traceId}] Synthesis Error:`, err);\n if (!synthesisStreamError) {\n await this.deps.observationManager.record({\n threadId: props.threadId, traceId, type: ObservationType.ERROR, \n content: { phase: 'synthesis', error: err.message, stack: err.stack }, \n metadata: { timestamp: Date.now() }\n });\n }\n throw err instanceof ARTError ? err : new ARTError(synthesisErrorMessage, ErrorCode.SYNTHESIS_FAILED, err);\n }\n\n // --- Response Parsing ---\n let mainContent = finalResponseContent;\n let uiMetadata: object | undefined = undefined;\n\n try {\n const metadataBlockRegex = /```json\\s*([\\s\\S]*?)\\s*```$/;\n const match = finalResponseContent.match(metadataBlockRegex);\n\n if (match && match[1]) {\n mainContent = finalResponseContent.replace(metadataBlockRegex, '').trim();\n uiMetadata = JSON.parse(match[1]);\n Logger.debug(`[${traceId}] Parsed metadata block from synthesis output.`);\n } else {\n Logger.warn(`[${traceId}] No metadata block found in synthesis output. Treating entire output as main content.`);\n }\n } catch (parseError: any) {\n Logger.error(`[${traceId}] Failed to parse metadata block from synthesis output:`, parseError);\n // Fallback to treating the whole response as content\n mainContent = finalResponseContent;\n uiMetadata = { error: 'Failed to parse metadata block', details: parseError.message };\n }\n\n return { finalResponseContent: mainContent, synthesisMetadata, uiMetadata };\n }\n\n /**\n * Finalizes the agent execution by saving the final message and performing cleanup.\n * @private\n */\n private async _finalize(props: AgentProps, finalResponseContent: string, traceId: string, uiMetadata?: object): Promise<ConversationMessage> {\n Logger.debug(`[${traceId}] Stage 7: Finalization`);\n \n const finalTimestamp = Date.now();\n const finalAiMessage: ConversationMessage = {\n messageId: generateUUID(),\n threadId: props.threadId,\n role: MessageRole.AI,\n content: finalResponseContent,\n timestamp: finalTimestamp,\n metadata: { traceId },\n };\n\n // Save AI response message\n await this.deps.conversationManager.addMessages(props.threadId, [finalAiMessage]);\n\n // Record final response observation\n await this.deps.observationManager.record({\n threadId: props.threadId,\n traceId,\n type: ObservationType.FINAL_RESPONSE,\n content: { \n message: finalAiMessage,\n uiMetadata: uiMetadata \n },\n metadata: { timestamp: finalTimestamp }\n });\n\n return finalAiMessage;\n }\n\n /**\n * Formats conversation history messages for direct inclusion in ArtStandardPrompt.\n * Converts internal MessageRole to ArtStandardMessageRole.\n * @param history - Array of ConversationMessage objects.\n * @returns Array of messages suitable for ArtStandardPrompt.\n */\n private formatHistoryForPrompt(history: ConversationMessage[]): ArtStandardPrompt {\n return history.map((msg) => {\n let role: ArtStandardMessageRole;\n switch (msg.role) {\n case MessageRole.USER:\n role = 'user';\n break;\n case MessageRole.AI:\n role = 'assistant';\n break;\n case MessageRole.SYSTEM:\n role = 'system';\n break;\n case MessageRole.TOOL:\n role = 'tool';\n break;\n default:\n Logger.warn(`Unhandled message role '${msg.role}' in formatHistoryForPrompt. Defaulting to 'user'.`);\n role = 'user';\n }\n return {\n role: role,\n content: msg.content,\n };\n }).filter(msg => msg.content);\n }\n}\n","import { StorageAdapter } from '@/core/interfaces';\nimport { FilterOptions } from '@/types';\n\n/**\n * An in-memory implementation of the `StorageAdapter` interface.\n * Stores all data in JavaScript Maps within the current process memory.\n * Data is **not persisted** and will be lost when the application session ends.\n *\n * Useful for:\n * - Unit and integration testing (fast, no external dependencies).\n * - Simple demos or examples where persistence isn't needed.\n * - Ephemeral agents that don't require long-term memory.\n *\n * It provides a simple key-value store for various data types used within the\n * ART framework, such as conversation history, agent state, and observations.\n *\n * @see {@link StorageAdapter} for the interface definition.\n */\nexport class InMemoryStorageAdapter implements StorageAdapter {\n private storage: Map<string, Map<string, any>> = new Map();\n\n /**\n * Creates an instance of InMemoryStorageAdapter.\n * @see StorageAdapter\n */\n constructor() {\n // No-op\n }\n\n /**\n * Initializes the adapter. This is a no-op for the in-memory adapter\n * and is provided for interface compatibility.\n * @param _config - Optional configuration (ignored by this adapter).\n * @returns A promise that resolves immediately.\n */\n async init(_config?: any): Promise<void> { // Renamed config to _config\n // No initialization needed for in-memory storage\n return Promise.resolve();\n }\n\n /**\n * Retrieves a single item (as a deep copy) from a specified collection by its ID.\n * @template T - The expected type of the retrieved item.\n * @param collection - The name of the data collection (e.g., 'messages', 'observations').\n * @param id - The unique ID of the item within the collection.\n * @returns A promise resolving to a deep copy of the item if found, or `null` otherwise.\n */\n async get<T>(collection: string, id: string): Promise<T | null> {\n const collectionMap = this.storage.get(collection);\n if (!collectionMap) {\n return null;\n }\n const item = collectionMap.get(id);\n // Return a deep copy to prevent accidental modification of the stored object\n return item ? JSON.parse(JSON.stringify(item)) : null;\n }\n\n /**\n * Saves (creates or updates) an item in a specified collection.\n * Stores a deep copy of the provided data to prevent external mutations.\n * @template T - The type of the data being saved.\n * @param collection - The name of the collection.\n * @param id - The unique ID for the item.\n * @param data - The data object to save.\n * @returns A promise that resolves when the data is saved in memory.\n */\n async set<T>(collection: string, id: string, data: T): Promise<void> {\n if (!this.storage.has(collection)) {\n this.storage.set(collection, new Map());\n }\n const collectionMap = this.storage.get(collection)!;\n // Store a deep copy to prevent external modifications affecting the store\n collectionMap.set(id, JSON.parse(JSON.stringify(data)));\n return Promise.resolve();\n }\n\n /**\n * Deletes an item from a specified collection using its ID.\n * If the collection or item does not exist, the operation completes silently.\n * @param collection - The name of the collection.\n * @param id - The unique ID of the item to delete.\n * @returns A promise that resolves when the deletion attempt is complete.\n */\n async delete(collection: string, id: string): Promise<void> {\n const collectionMap = this.storage.get(collection);\n if (collectionMap) {\n collectionMap.delete(id);\n }\n return Promise.resolve();\n }\n\n /**\n * Queries items within a collection based on provided filter options.\n * **Note:** This in-memory implementation provides basic filtering capabilities:\n * - Supports exact matches on top-level properties specified in `filterOptions.filter`.\n * - Supports limiting results via `filterOptions.limit`.\n * - **Does not** support sorting (`filterOptions.sort`), skipping (`filterOptions.skip`), complex operators (like $gt, $in), or nested property filtering.\n * @template T - The expected type of the items in the collection.\n * @param collection - The name of the collection to query.\n * @param filterOptions - Options for filtering and limiting the results.\n * @returns A promise resolving to an array of deep copies of the matching items.\n */\n async query<T>(collection: string, filterOptions: FilterOptions): Promise<T[]> {\n const collectionMap = this.storage.get(collection);\n if (!collectionMap) {\n return [];\n }\n\n let results = Array.from(collectionMap.values());\n\n // Basic filtering (exact match on top-level properties)\n if (filterOptions.filter) {\n results = results.filter(item => {\n for (const key in filterOptions.filter) {\n // eslint-disable-next-line no-prototype-builtins\n if (filterOptions.filter.hasOwnProperty(key)) {\n // Use type assertion carefully or add more robust checks\n if ((item as any)[key] !== (filterOptions.filter as any)[key]) {\n return false;\n }\n }\n }\n return true;\n });\n }\n\n // Basic limit\n if (typeof filterOptions.limit === 'number' && filterOptions.limit >= 0) {\n results = results.slice(0, filterOptions.limit);\n }\n\n // Return deep copies\n return JSON.parse(JSON.stringify(results));\n }\n\n /**\n * Removes all items from a specific collection within the in-memory store.\n * @param collection - The name of the collection to clear.\n * @returns A promise that resolves when the collection is cleared.\n */\n async clearCollection(collection: string): Promise<void> {\n this.storage.delete(collection);\n return Promise.resolve();\n }\n\n /**\n * Removes all collections and all data stored within the adapter instance.\n * Use with caution, especially during testing.\n * @returns A promise that resolves when all data is cleared.\n */\n async clearAll(): Promise<void> {\n this.storage.clear();\n return Promise.resolve();\n }\n}","import { StorageAdapter } from '@/core/interfaces';\nimport { FilterOptions } from '@/types';\nimport { Logger } from '@/utils/logger'; // Import Logger at top level\n\n// Default configuration\nconst DEFAULT_DB_NAME = 'ART_Framework_DB';\nconst DEFAULT_DB_VERSION = 1; // Increment this when object stores change\n\n/**\n * Configuration options for initializing the `IndexedDBStorageAdapter`.\n */\nexport interface IndexedDBConfig {\n /** The name of the IndexedDB database to use. Defaults to 'ART_Framework_DB'. */\n dbName?: string;\n /** The version of the database schema. Increment this when changing `objectStores` or indexes to trigger an upgrade. Defaults to 1. */\n dbVersion?: number;\n /** An array of strings specifying the names of the object stores (collections) required by the application. Core stores like 'conversations', 'observations', 'state' are usually added automatically. */\n objectStores: string[];\n}\n\n/**\n * An implementation of the `StorageAdapter` interface that uses the browser's\n * IndexedDB API for persistent, client-side storage.\n *\n * This adapter is suitable for web applications where conversation history,\n * agent state, and observations need to persist across sessions.\n *\n * **Important:** The `init()` method *must* be called and awaited before performing\n * any other database operations (get, set, delete, query).\n *\n * @see {@link StorageAdapter} for the interface it implements.\n * @see {@link IndexedDBConfig} for configuration options.\n */\nexport class IndexedDBStorageAdapter implements StorageAdapter {\n private db: IDBDatabase | null = null;\n private dbName: string;\n private dbVersion: number;\n private requiredObjectStores: Set<string>;\n private initPromise: Promise<void> | null = null;\n\n /**\n * Creates an instance of IndexedDBStorageAdapter.\n * Note: The database connection is not opened until `init()` is called.\n * @param {module:integrations/storage/indexedDB.IndexedDBConfig} config - Configuration options including database name, version, and required object stores.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API\n */\n constructor(config: IndexedDBConfig) {\n this.dbName = config.dbName || DEFAULT_DB_NAME;\n this.dbVersion = config.dbVersion || DEFAULT_DB_VERSION;\n // Ensure core stores used by default repositories are included\n this.requiredObjectStores = new Set([\n 'conversations', // Used by ConversationRepository\n 'observations', // Used by ObservationRepository\n 'state', // Used by StateRepository\n 'a2a_tasks', // Used by TaskStatusRepository\n ...(config.objectStores || []) // Add any user-defined stores\n ]);\n }\n\n /**\n * Opens the IndexedDB database connection and ensures the required object stores\n * are created or updated based on the configured `dbVersion`.\n * This method MUST be called and awaited successfully before using other adapter methods.\n * It handles the `onupgradeneeded` event to create stores.\n * @returns A promise that resolves when the database is successfully opened and ready, or rejects on error.\n */\n async init(): Promise<void> {\n // Prevent multiple initializations\n if (this.initPromise) {\n return this.initPromise;\n }\n\n this.initPromise = new Promise((resolve, reject) => {\n if (!('indexedDB' in window)) {\n Logger.error(\"IndexedDBStorageAdapter: IndexedDB not supported in this browser.\"); // Use Logger\n return reject(new Error(\"IndexedDB not supported\"));\n }\n\n const request = indexedDB.open(this.dbName, this.dbVersion);\n\n request.onerror = (event) => {\n Logger.error(`IndexedDBStorageAdapter: Database error: ${request.error}`, event); // Use Logger\n reject(new Error(`IndexedDB error: ${request.error?.message}`));\n };\n\n request.onsuccess = (event) => {\n this.db = (event.target as IDBOpenDBRequest).result;\n Logger.info(`IndexedDBStorageAdapter: Database '${this.dbName}' opened successfully (Version: ${this.db.version}).`); // Use Logger\n\n // Optional: Check if all required stores actually exist after opening\n const existingStores = new Set(Array.from(this.db.objectStoreNames));\n const missingStores = [...this.requiredObjectStores].filter(store => !existingStores.has(store));\n if (missingStores.length > 0) {\n Logger.warn(`IndexedDBStorageAdapter: The following required object stores were not found after opening DB version ${this.db.version}: ${missingStores.join(', ')}. This might happen if the DB version wasn't incremented after adding stores.`); // Use Logger\n // Depending on strictness, you might reject here\n }\n\n this.db.onerror = (errorEvent) => {\n // Generic error handler for the database connection\n Logger.error(`IndexedDBStorageAdapter: Generic database error:`, errorEvent); // Use Logger\n };\n resolve();\n };\n\n request.onupgradeneeded = (event) => {\n Logger.info(`IndexedDBStorageAdapter: Upgrading database '${this.dbName}' from version ${event.oldVersion} to ${event.newVersion}...`); // Use Logger\n this.db = (event.target as IDBOpenDBRequest).result;\n const transaction = (event.target as IDBOpenDBRequest).transaction; // Get transaction for upgrade\n\n if (!transaction) {\n Logger.error(\"IndexedDBStorageAdapter: Upgrade transaction is null!\"); // Use Logger\n reject(new Error(\"Upgrade transaction failed\"));\n return;\n }\n\n const existingStoreNames = new Set(Array.from(this.db.objectStoreNames));\n\n this.requiredObjectStores.forEach(storeName => {\n if (!existingStoreNames.has(storeName)) {\n Logger.info(`IndexedDBStorageAdapter: Creating object store '${storeName}'...`); // Use Logger\n // Use 'id' as the key path, assuming all stored objects will have an 'id' property.\n // If not, a different key strategy or autoIncrement might be needed.\n // For flexibility, we might need a config per store, but 'id' is common.\n this.db?.createObjectStore(storeName, { keyPath: 'id' });\n // TODO: Consider adding indexes here if needed for query performance based on FilterOptions\n // Example: store.createIndex('by_type', 'type', { unique: false });\n }\n // Handle index creation/updates or data migration if necessary for existing stores\n });\n\n // Example: Removing old stores if needed (use with caution)\n // existingStoreNames.forEach(storeName => {\n // if (!this.requiredObjectStores.has(storeName)) {\n // Logger.info(`IndexedDBStorageAdapter: Deleting old object store '${storeName}'...`); // Use Logger\n // this.db?.deleteObjectStore(storeName);\n // }\n // });\n\n Logger.info(`IndexedDBStorageAdapter: Database upgrade complete.`); // Use Logger\n // Note: onsuccess will be called automatically after onupgradeneeded completes.\n };\n\n request.onblocked = (event) => {\n // This event fires if the database is open in another tab/window with an older version\n Logger.warn(`IndexedDBStorageAdapter: Database open request blocked for '${this.dbName}'. Please close other tabs/connections using an older version of this database.`, event); // Use Logger\n reject(new Error(`IndexedDB open blocked for ${this.dbName}. Close other connections.`));\n };\n\n });\n\n return this.initPromise;\n }\n\n // --- Helper Method to get a transaction ---\n /**\n * Helper method to create and return an IndexedDB transaction.\n * Ensures the database is initialized and the requested store(s) exist.\n * @param storeName - The name of the object store or an array of store names for the transaction.\n * @param mode - The transaction mode ('readonly' or 'readwrite').\n * @returns The initiated IDBTransaction.\n * @throws {Error} If the database is not initialized or if a requested store does not exist.\n */\n private getTransaction(storeName: string | string[], mode: IDBTransactionMode): IDBTransaction {\n if (!this.db) {\n // It's crucial init() was awaited, but add runtime check.\n throw new Error(\"IndexedDBStorageAdapter: Database not initialized. Ensure init() was called and awaited.\");\n }\n // Check if the requested store exists\n const storesToCheck = Array.isArray(storeName) ? storeName : [storeName];\n storesToCheck.forEach(sName => {\n if (!this.db?.objectStoreNames.contains(sName)) {\n throw new Error(`IndexedDBStorageAdapter: Object store \"${sName}\" does not exist in the database.`);\n }\n });\n\n return this.db.transaction(storeName, mode);\n }\n\n // --- CRUD Methods ---\n\n /**\n * Retrieves a single item by its ID from the specified object store (collection).\n * @template T - The expected type of the retrieved item.\n * @param collection - The name of the object store.\n * @param id - The ID (key) of the item to retrieve.\n * @returns A promise resolving to a copy of the item if found, or `null` otherwise.\n * @throws {Error} If the database is not initialized, the store doesn't exist, or a database error occurs.\n */\n async get<T>(collection: string, id: string): Promise<T | null> {\n await this.init(); // Ensure DB is ready (init is idempotent)\n return new Promise((resolve, reject) => {\n try {\n const transaction = this.getTransaction(collection, 'readonly');\n const store = transaction.objectStore(collection);\n const request = store.get(id);\n\n request.onsuccess = () => {\n // Return a copy? IndexedDB usually returns structured clones already,\n // but explicit copy might be safer depending on usage.\n resolve(request.result ? { ...request.result } : null);\n };\n\n request.onerror = () => {\n Logger.error(`IndexedDBStorageAdapter: Error getting item '${id}' from '${collection}':`, request.error); // Use Logger\n reject(new Error(`Failed to get item: ${request.error?.message}`));\n };\n } catch (error) {\n reject(error); // Catch errors from getTransaction (e.g., store not found)\n }\n });\n }\n\n // Removed the 'extends { id: string }' constraint to match the interface\n /**\n * Saves (creates or updates) an item in the specified object store (collection).\n * Assumes the object store uses 'id' as its keyPath. The `id` parameter provided\n * should match the `id` property within the `data` object.\n * Uses `structuredClone` to store a deep copy.\n * @template T - The type of the data being saved. Must have an 'id' property.\n * @param collection - The name of the object store.\n * @param id - The unique ID of the item (should match `data.id`).\n * @param data - The data object to save. Must contain an `id` property matching the `id` parameter.\n * @returns A promise that resolves when the data is successfully saved.\n * @throws {Error} If the database is not initialized, the store doesn't exist, data is missing the 'id' property, or a database error occurs.\n */\n async set<T>(collection: string, id: string, data: T): Promise<void> {\n // Runtime check: Ensure data has the 'id' property matching the keyPath\n // We cast to 'any' here because T doesn't guarantee 'id' exists at compile time anymore.\n const dataAsAny = data as any;\n if (typeof dataAsAny.id === 'undefined') {\n return Promise.reject(new Error(`IndexedDBStorageAdapter: Data for collection '${collection}' must have an 'id' property matching the keyPath.`));\n }\n if (dataAsAny.id !== id) {\n Logger.warn(`IndexedDBStorageAdapter: Provided id ('${id}') and data.id ('${dataAsAny.id}') mismatch for collection '${collection}'. Using data.id as the key.`); // Use Logger\n // Optionally throw an error or enforce consistency based on project needs.\n // For now, we proceed using data.id as the key for the put operation.\n }\n\n\n await this.init(); // Ensure DB is ready\n return new Promise((resolve, reject) => {\n try {\n // Use structuredClone for a robust deep copy before storing\n const dataToStore = structuredClone(data);\n const transaction = this.getTransaction(collection, 'readwrite');\n const store = transaction.objectStore(collection);\n // Use the id from the data object itself, as it's the keyPath\n const request = store.put(dataToStore); // put = insert or update\n\n request.onsuccess = () => {\n resolve();\n };\n\n request.onerror = () => {\n // Use dataAsAny.id in the error message as it's the actual key used\n Logger.error(`IndexedDBStorageAdapter: Error setting item with id '${dataAsAny.id}' in '${collection}':`, request.error); // Use Logger\n reject(new Error(`Failed to set item: ${request.error?.message}`));\n };\n\n transaction.oncomplete = () => {\n // Transaction completed successfully (optional logging)\n };\n\n transaction.onerror = (event) => {\n // Use dataAsAny.id in the error message\n Logger.error(`IndexedDBStorageAdapter: Transaction error setting item with id '${dataAsAny.id}' in '${collection}':`, transaction.error, event); // Use Logger\n reject(new Error(`Transaction failed: ${transaction.error?.message}`));\n };\n } catch (error) {\n reject(error);\n }\n });\n }\n\n /**\n * Deletes an item from the specified object store (collection) by its ID.\n * @param collection - The name of the object store.\n * @param id - The ID (key) of the item to delete.\n * @returns A promise that resolves when the deletion is successful.\n * @throws {Error} If the database is not initialized, the store doesn't exist, or a database error occurs.\n */\n async delete(collection: string, id: string): Promise<void> {\n await this.init(); // Ensure DB is ready\n return new Promise((resolve, reject) => {\n try {\n const transaction = this.getTransaction(collection, 'readwrite');\n const store = transaction.objectStore(collection);\n const request = store.delete(id);\n\n request.onsuccess = () => {\n resolve();\n };\n\n request.onerror = () => {\n Logger.error(`IndexedDBStorageAdapter: Error deleting item '${id}' from '${collection}':`, request.error); // Use Logger\n reject(new Error(`Failed to delete item: ${request.error?.message}`));\n };\n\n transaction.onerror = (event) => {\n Logger.error(`IndexedDBStorageAdapter: Transaction error deleting item '${id}' from '${collection}':`, transaction.error, event); // Use Logger\n reject(new Error(`Transaction failed: ${transaction.error?.message}`));\n };\n } catch (error) {\n reject(error);\n }\n });\n }\n\n /**\n * Queries items within a collection based on provided filter options.\n * **Note:** This implementation uses `getAll()` and performs filtering, sorting,\n * and limiting **client-side**. For large datasets, performance may be suboptimal.\n * A more advanced version would leverage IndexedDB indexes and cursors for\n * efficient querying directly within the database.\n * Supports basic exact-match filtering and single-key sorting.\n * @template T - The expected type of the items in the collection.\n * @param collection - The name of the object store to query.\n * @param filterOptions - Options for filtering, sorting, skipping, and limiting results.\n * @returns A promise resolving to an array of deep copies of the matching items.\n * @throws {Error} If the database is not initialized, the store doesn't exist, or a database error occurs.\n * @remarks TODO: Implement more advanced querying using IndexedDB indexes and cursors.\n * This will improve performance for large datasets.\n */\n async query<T>(collection: string, filterOptions: FilterOptions): Promise<T[]> {\n await this.init(); // Ensure DB is ready\n return new Promise((resolve, reject) => {\n try {\n const transaction = this.getTransaction(collection, 'readonly');\n const store = transaction.objectStore(collection);\n const request = store.getAll(); // Get all records\n\n request.onsuccess = () => {\n let results: T[] = request.result || [];\n\n // Client-side filtering (basic exact match)\n if (filterOptions.filter) {\n results = results.filter(item => {\n for (const key in filterOptions.filter) {\n // eslint-disable-next-line no-prototype-builtins\n if (filterOptions.filter.hasOwnProperty(key)) {\n if ((item as any)[key] !== (filterOptions.filter as any)[key]) {\n return false;\n }\n }\n }\n return true;\n });\n }\n\n // Client-side sorting (basic single key)\n if (filterOptions.sort) {\n const sortKey = Object.keys(filterOptions.sort)[0];\n const sortDir = filterOptions.sort[sortKey];\n if (sortKey) {\n results.sort((a, b) => {\n const valA = (a as any)[sortKey];\n const valB = (b as any)[sortKey];\n if (valA < valB) return sortDir === 'asc' ? -1 : 1;\n if (valA > valB) return sortDir === 'asc' ? 1 : -1;\n return 0;\n });\n }\n }\n\n // Client-side skip/limit\n const skip = filterOptions.skip || 0;\n const limit = filterOptions.limit ?? Infinity; // Default to no limit if undefined\n results = results.slice(skip, skip + limit);\n\n\n // Return copies\n resolve(results.map(item => ({ ...item })));\n };\n\n request.onerror = () => {\n Logger.error(`IndexedDBStorageAdapter: Error querying collection '${collection}':`, request.error); // Use Logger\n reject(new Error(`Failed to query collection: ${request.error?.message}`));\n };\n } catch (error) {\n reject(error);\n }\n });\n }\n\n /**\n * Removes all items from a specific object store (collection).\n * @param collection - The name of the object store to clear.\n * @returns A promise that resolves when the collection is successfully cleared.\n * @throws {Error} If the database is not initialized, the store doesn't exist, or a database error occurs.\n */\n async clearCollection(collection: string): Promise<void> {\n await this.init(); // Ensure DB is ready\n return new Promise((resolve, reject) => {\n try {\n const transaction = this.getTransaction(collection, 'readwrite');\n const store = transaction.objectStore(collection);\n const request = store.clear();\n\n request.onsuccess = () => {\n resolve();\n };\n\n request.onerror = () => {\n Logger.error(`IndexedDBStorageAdapter: Error clearing collection '${collection}':`, request.error); // Use Logger\n reject(new Error(`Failed to clear collection: ${request.error?.message}`));\n };\n\n transaction.onerror = (event) => {\n Logger.error(`IndexedDBStorageAdapter: Transaction error clearing collection '${collection}':`, transaction.error, event); // Use Logger\n reject(new Error(`Transaction failed: ${transaction.error?.message}`));\n };\n } catch (error) {\n reject(error);\n }\n });\n }\n\n /**\n * Removes all data from all object stores managed by this adapter instance within the database.\n * Use with caution as this is destructive.\n * @returns A promise that resolves when all specified object stores have been cleared.\n * @throws {Error} If the database is not initialized or a transaction error occurs.\n */\n async clearAll(): Promise<void> {\n await this.init(); // Ensure DB is ready\n if (!this.db) {\n throw new Error(\"Database not initialized.\");\n }\n\n const storeNames = Array.from(this.db.objectStoreNames);\n if (storeNames.length === 0) {\n return Promise.resolve(); // Nothing to clear\n }\n\n return new Promise((resolve, reject) => {\n try {\n // Need a transaction covering all stores to clear\n const transaction = this.getTransaction(storeNames, 'readwrite');\n\n let clearCount = 0;\n const totalStores = storeNames.length;\n\n storeNames.forEach(storeName => {\n const request = transaction.objectStore(storeName).clear();\n request.onsuccess = () => {\n clearCount++;\n if (clearCount === totalStores) {\n // This might resolve before transaction.oncomplete\n }\n };\n request.onerror = () => {\n // Error on individual clear, transaction might still complete or abort\n Logger.error(`IndexedDBStorageAdapter: Error clearing object store '${storeName}':`, request.error); // Use Logger\n // Don't reject immediately, let transaction handle overall status\n };\n });\n\n transaction.oncomplete = () => {\n Logger.info(`IndexedDBStorageAdapter: All object stores cleared successfully.`); // Use Logger\n resolve();\n };\n\n transaction.onerror = (event) => {\n Logger.error(`IndexedDBStorageAdapter: Transaction error during clearAll:`, transaction.error, event); // Use Logger\n reject(new Error(`Failed to clear all stores: ${transaction.error?.message}`));\n };\n } catch (error) {\n reject(error);\n }\n });\n }\n}","import { IConversationRepository, StorageAdapter } from '@/core/interfaces';\nimport { ConversationMessage, MessageOptions } from '@/types';\n\n// Define the structure of the data as stored, including the 'id' field\ntype StoredConversationMessage = ConversationMessage & { id: string };\n\n/**\n * Implements the `IConversationRepository` interface, providing methods to\n * manage `ConversationMessage` objects using an underlying `StorageAdapter`.\n * Handles adding and retrieving conversation history for specific threads.\n *\n * It abstracts the underlying storage mechanism through the `StorageAdapter` interface,\n * allowing for different storage backends (e.g., in-memory, IndexedDB, Supabase)\n * to be used interchangeably.\n *\n * @see {@link IConversationRepository} for the interface it implements.\n * @see {@link StorageAdapter} for the storage backend interface.\n */\nexport class ConversationRepository implements IConversationRepository {\n private adapter: StorageAdapter;\n private readonly collectionName = 'conversations'; // Define the collection name\n\n /**\n * Creates an instance of ConversationRepository.\n * @param {StorageAdapter} storageAdapter - The configured `StorageAdapter` instance that will be used for persistence.\n */\n constructor(storageAdapter: StorageAdapter) {\n if (!storageAdapter) {\n throw new Error(\"ConversationRepository requires a valid StorageAdapter instance.\");\n }\n this.adapter = storageAdapter;\n // Note: Initialization of the adapter (adapter.init()) should be handled\n // at the application setup level (e.g., within AgentFactory or createArtInstance)\n // before the repository is used.\n }\n\n /**\n * Adds one or more `ConversationMessage` objects to the storage for a specific thread.\n * It uses the `messageId` as the primary key for storage, assuming the adapter's collection uses 'id' as keyPath.\n * @param {string} threadId - The ID of the thread these messages belong to. Used for potential filtering/querying and validation.\n * @param {ConversationMessage[]} messages - An array of `ConversationMessage` objects to add. Each message should have a unique `messageId`.\n * @returns {Promise<void>} A promise that resolves when all messages have been attempted to be saved.\n * @throws {Error} Propagates errors from the storage adapter's `set` method.\n */\n async addMessages(threadId: string, messages: ConversationMessage[]): Promise<void> {\n if (!messages || messages.length === 0) {\n return Promise.resolve();\n }\n\n // Use Promise.all to handle multiple async set operations concurrently\n const setPromises = messages.map(message => {\n if (message.threadId !== threadId) {\n console.warn(`ConversationRepository: Message ${message.messageId} has mismatching threadId (${message.threadId}) for repository operation on thread ${threadId}.`);\n // Decide on handling: throw error, skip message, or proceed? For now, proceed but log.\n }\n // Add the 'id' field mirroring 'messageId' for compatibility with keyPath='id' adapters\n const messageToStore: StoredConversationMessage = {\n ...message,\n id: message.messageId\n };\n return this.adapter.set<StoredConversationMessage>(this.collectionName, messageToStore.id, messageToStore);\n });\n\n await Promise.all(setPromises);\n }\n\n /**\n * Retrieves messages for a specific thread from the storage adapter.\n * This implementation fetches all messages for the thread and then applies\n * sorting, filtering (by timestamp), and limiting client-side.\n * For performance with very large histories, adapter-level querying/indexing would be preferable.\n * @param {string} threadId - The ID of the thread whose messages are to be retrieved.\n * @param {MessageOptions} [options] - Optional `MessageOptions` to control retrieval (limit, timestamp filters).\n * @returns {Promise<ConversationMessage[]>} A promise resolving to an array of `ConversationMessage` objects, sorted chronologically (ascending timestamp).\n * @throws {Error} Propagates errors from the storage adapter's `query` method.\n */\n async getMessages(threadId: string, options?: MessageOptions): Promise<ConversationMessage[]> {\n // Query the adapter for all messages matching the threadId\n const queryResults = await this.adapter.query<StoredConversationMessage>(this.collectionName, {\n filter: { threadId: threadId },\n // Add sorting at the adapter level if supported and efficient, otherwise sort client-side\n // sort: { timestamp: 'asc' } // Example if adapter supported it well\n });\n\n // Client-side filtering and sorting\n let filteredMessages = queryResults;\n\n // Sort by timestamp (ascending) - essential for correct history order\n filteredMessages.sort((a, b) => a.timestamp - b.timestamp);\n\n // Apply timestamp filters client-side\n if (options?.beforeTimestamp !== undefined) {\n filteredMessages = filteredMessages.filter(m => m.timestamp < options.beforeTimestamp!);\n }\n if (options?.afterTimestamp !== undefined) {\n filteredMessages = filteredMessages.filter(m => m.timestamp > options.afterTimestamp!);\n }\n\n // Apply limit client-side (usually applied last, after sorting/filtering)\n // If sorting descending, limit needs care. Assuming ascending sort for history.\n if (options?.limit !== undefined && options.limit > 0) {\n // Get the last 'limit' messages after sorting ascending\n filteredMessages = filteredMessages.slice(-options.limit);\n }\n\n // Remove the 'id' field before returning to match the ConversationMessage interface\n // Prefix 'id' with '_' because it's unused in the destructuring assignment.\n const finalMessages: ConversationMessage[] = filteredMessages.map(({ id: _id, ...rest }) => rest);\n\n return finalMessages;\n }\n}","import { IObservationRepository, StorageAdapter } from '@/core/interfaces';\nimport { Observation, ObservationFilter } from '@/types';\n\n// Observation already has an 'id' field, so no need for a separate Stored type usually.\n// However, ensure the StorageAdapter expects 'id' as the keyPath for the 'observations' store.\n\n/**\n * Implements the `IObservationRepository` interface, providing methods to\n * manage `Observation` objects using an underlying `StorageAdapter`.\n * Handles adding and retrieving observations for specific threads.\n *\n * It relies on a `StorageAdapter` to abstract the actual storage mechanism,\n * making it compatible with different backends like IndexedDB, Supabase, or\n * in-memory storage.\n *\n * @see {@link IObservationRepository} for the interface it implements.\n * @see {@link StorageAdapter} for the storage backend interface.\n */\nexport class ObservationRepository implements IObservationRepository {\n private adapter: StorageAdapter;\n private readonly collectionName = 'observations'; // Define the collection name\n\n /**\n * Creates an instance of ObservationRepository.\n * @param {StorageAdapter} storageAdapter - The configured `StorageAdapter` instance that will be used for persistence.\n */\n constructor(storageAdapter: StorageAdapter) {\n if (!storageAdapter) {\n throw new Error(\"ObservationRepository requires a valid StorageAdapter instance.\");\n }\n this.adapter = storageAdapter;\n // Note: Initialization of the adapter (adapter.init()) should be handled\n // at the application setup level (e.g., within AgentFactory or createArtInstance)\n // before the repository is used.\n }\n\n /**\n * Adds a single `Observation` object to the storage using its `id` as the key.\n * @param {Observation} observation - The `Observation` object to add. Must have a valid `id`.\n * @returns {Promise<void>} A promise that resolves when the observation has been saved.\n * @throws {Error} If the observation is missing an `id` or if the storage adapter fails.\n */\n async addObservation(observation: Observation): Promise<void> {\n // The observation object already has an 'id' property, which should match the keyPath.\n if (typeof observation.id === 'undefined') {\n return Promise.reject(new Error(`ObservationRepository: Observation must have an 'id' property.`));\n }\n await this.adapter.set<Observation>(this.collectionName, observation.id, observation);\n }\n\n /**\n * Retrieves observations for a specific thread from the storage adapter.\n * This implementation fetches all observations for the thread and then applies\n * client-side filtering (by type, timestamp) and sorting (by timestamp).\n * For performance with many observations, adapter-level querying/indexing would be preferable.\n * @param {string} threadId - The ID of the thread whose observations are to be retrieved.\n * @param {ObservationFilter} [filter] - Optional `ObservationFilter` criteria (e.g., `types`, `beforeTimestamp`, `afterTimestamp`).\n * @returns {Promise<Observation[]>} A promise resolving to an array of `Observation` objects matching the criteria, sorted chronologically (ascending timestamp).\n * @throws {Error} Propagates errors from the storage adapter's `query` method.\n */\n async getObservations(threadId: string, filter?: ObservationFilter): Promise<Observation[]> {\n // Query the adapter for all observations matching the threadId\n const queryResults = await this.adapter.query<Observation>(this.collectionName, {\n filter: { threadId: threadId },\n // Add sorting by timestamp at the adapter level if supported, otherwise sort client-side\n // sort: { timestamp: 'asc' }\n });\n\n // Client-side filtering and sorting\n let filteredObservations = queryResults;\n\n // Sort by timestamp (ascending) - useful for chronological view\n filteredObservations.sort((a, b) => a.timestamp - b.timestamp);\n\n // Apply type filter client-side\n if (filter?.types && filter.types.length > 0) {\n const typeSet = new Set(filter.types);\n filteredObservations = filteredObservations.filter(obs => typeSet.has(obs.type));\n }\n\n // Apply timestamp filters client-side\n if (filter?.beforeTimestamp !== undefined) {\n filteredObservations = filteredObservations.filter(obs => obs.timestamp < filter.beforeTimestamp!);\n }\n if (filter?.afterTimestamp !== undefined) {\n filteredObservations = filteredObservations.filter(obs => obs.timestamp > filter.afterTimestamp!);\n }\n\n // Note: Limit/Skip are not part of ObservationFilter in the current types,\n // but could be added if needed and handled here similarly to ConversationRepository.\n\n // Observations retrieved from storage should already match the Observation interface.\n // No need to remove 'id' like in ConversationRepository.\n return filteredObservations;\n }\n}","import { IStateRepository, StorageAdapter } from '@/core/interfaces';\nimport { ThreadContext, ThreadConfig, AgentState } from '@/types';\n\n// Define the structure of the data as stored, including the 'id' field (threadId)\ntype StoredThreadContext = ThreadContext & { id: string };\n\n/**\n * Implements the `IStateRepository` interface, providing methods to manage\n * `ThreadContext` (which includes `ThreadConfig` and `AgentState`) using an\n * underlying `StorageAdapter`. It stores the entire context object for each thread\n * under a key equal to the `threadId` within a designated collection (default: 'state').\n *\n * It uses a `StorageAdapter` to abstract the underlying storage, allowing for\n * flexibility in choosing storage backends (e.g., in-memory, IndexedDB, Supabase).\n * This repository is responsible for CRUD operations on thread state and configuration.\n *\n * @see {@link IStateRepository} for the interface it implements.\n * @see {@link StorageAdapter} for the storage backend interface.\n */\nexport class StateRepository implements IStateRepository {\n private adapter: StorageAdapter;\n private readonly collectionName = 'state'; // Define the collection name\n\n /**\n * Creates an instance of StateRepository.\n * @param {StorageAdapter} storageAdapter - The configured `StorageAdapter` instance used for persistence.\n */\n constructor(storageAdapter: StorageAdapter) {\n if (!storageAdapter) {\n throw new Error(\"StateRepository requires a valid StorageAdapter instance.\");\n }\n this.adapter = storageAdapter;\n // Note: Adapter initialization (adapter.init()) should be handled externally.\n }\n\n /**\n * Retrieves the complete `ThreadContext` (config and state) for a specific thread ID.\n * @param {string} threadId - The unique identifier of the thread.\n * @returns {Promise<ThreadContext | null>} A promise resolving to the `ThreadContext` object if found, or `null` otherwise.\n * @throws {Error} Propagates errors from the storage adapter's `get` method.\n */\n async getThreadContext(threadId: string): Promise<ThreadContext | null> {\n const storedContext = await this.adapter.get<StoredThreadContext>(this.collectionName, threadId);\n if (!storedContext) {\n return null;\n }\n // Remove the internal 'id' field before returning\n // Create a copy and delete the 'id' property to avoid ESLint unused var rule\n const context = { ...storedContext };\n delete (context as Partial<StoredThreadContext>).id; // Cast to allow deletion\n return context as ThreadContext; // Cast back to the expected return type\n }\n\n /**\n * Saves (or overwrites) the complete `ThreadContext` for a specific thread ID.\n * Ensures the context object includes the `threadId` as the `id` property for storage.\n * @param {string} threadId - The unique identifier of the thread.\n * @param {ThreadContext} context - The `ThreadContext` object to save. Must contain at least the `config` property.\n * @returns {Promise<void>} A promise that resolves when the context is successfully saved.\n * @throws {Error} If the context is missing the required `config` property or if the storage adapter fails.\n */\n async setThreadContext(threadId: string, context: ThreadContext): Promise<void> {\n if (!context || typeof context.config === 'undefined') {\n // Enforce that context must have at least a config part.\n return Promise.reject(new Error(\"StateRepository: ThreadContext must contain a 'config' property.\"));\n }\n const contextToStore: StoredThreadContext = {\n ...context,\n id: threadId, // Use threadId as the 'id' for storage keyPath\n };\n await this.adapter.set<StoredThreadContext>(this.collectionName, threadId, contextToStore);\n }\n\n /**\n * Retrieves only the `ThreadConfig` part of the context for a specific thread ID.\n * @param {string} threadId - The unique identifier of the thread.\n * @returns {Promise<ThreadConfig | null>} A promise resolving to the `ThreadConfig` object if found, or `null` otherwise.\n * @throws {Error} Propagates errors from the underlying `getThreadContext` call.\n */\n async getThreadConfig(threadId: string): Promise<ThreadConfig | null> {\n const context = await this.getThreadContext(threadId);\n return context?.config ?? null;\n }\n\n /**\n * Sets or updates only the `ThreadConfig` part of the context for a specific thread ID.\n * It fetches the existing context, replaces the `config` field, preserves the existing `state` (or sets it to null if none existed),\n * and then saves the entire updated `ThreadContext` back to storage.\n * @param {string} threadId - The unique identifier of the thread.\n * @param {ThreadConfig} config - The `ThreadConfig` object to save.\n * @returns {Promise<void>} A promise that resolves when the updated context is saved.\n * @throws {Error} Propagates errors from the underlying `getThreadContext` or `setThreadContext` calls.\n */\n async setThreadConfig(threadId: string, config: ThreadConfig): Promise<void> {\n const currentContext = await this.getThreadContext(threadId);\n const newContext: ThreadContext = {\n config: config,\n state: currentContext?.state ?? null, // Preserve existing state or set to null\n };\n await this.setThreadContext(threadId, newContext);\n }\n\n /**\n * Retrieves only the `AgentState` part of the context for a specific thread ID.\n * @param {string} threadId - The unique identifier of the thread.\n * @returns {Promise<AgentState | null>} A promise resolving to the `AgentState` object if found and not null, or `null` otherwise.\n * @throws {Error} Propagates errors from the underlying `getThreadContext` call.\n */\n async getAgentState(threadId: string): Promise<AgentState | null> {\n const context = await this.getThreadContext(threadId);\n return context?.state ?? null;\n }\n\n /**\n * Sets or updates only the `AgentState` part of the context for a specific thread ID.\n * It fetches the existing context, replaces the `state` field, preserves the existing `config`,\n * and then saves the entire updated `ThreadContext` back to storage.\n * **Important:** This method requires that a `ThreadConfig` already exists for the thread.\n * Attempting to set state for a thread without prior configuration will result in an error.\n * @param {string} threadId - The unique identifier of the thread.\n * @param {AgentState} state - The `AgentState` object to save.\n * @returns {Promise<void>} A promise that resolves when the updated context is saved.\n * @throws {Error} If no `ThreadConfig` exists for the `threadId`, or if errors occur during context retrieval or saving.\n */\n async setAgentState(threadId: string, state: AgentState): Promise<void> {\n const currentContext = await this.getThreadContext(threadId);\n if (!currentContext || !currentContext.config) {\n // Require config to exist before setting state.\n return Promise.reject(new Error(`StateRepository: Cannot set AgentState for thread '${threadId}' because no ThreadConfig exists. Set config first.`));\n }\n const newContext: ThreadContext = {\n config: currentContext.config, // Preserve existing config\n state: state,\n };\n await this.setThreadContext(threadId, newContext);\n }\n}","import { IA2ATaskRepository, StorageAdapter } from '@/core/interfaces';\nimport { A2ATask, A2ATaskStatus, A2ATaskPriority, ARTError, ErrorCode } from '@/types';\n\n// Define the structure of the data as stored, including the 'id' field (taskId)\ntype StoredA2ATask = A2ATask & { id: string };\n\n/**\n * Implements the `IA2ATaskRepository` interface, providing methods to manage\n * `A2ATask` objects using an underlying `StorageAdapter`. Handles creating,\n * retrieving, updating, and deleting A2A (Agent-to-Agent) tasks, as well as\n * filtering tasks by various criteria such as thread, agent, and status.\n *\n * @see {@link IA2ATaskRepository} for the interface it implements.\n * @see {@link StorageAdapter} for the storage backend interface.\n */\nexport class TaskStatusRepository implements IA2ATaskRepository {\n private adapter: StorageAdapter;\n private readonly collectionName = 'a2a_tasks'; // Define the collection name\n\n /**\n * Creates an instance of TaskStatusRepository.\n * @param {StorageAdapter} storageAdapter - The configured `StorageAdapter` instance used for persistence.\n */\n constructor(storageAdapter: StorageAdapter) {\n if (!storageAdapter) {\n throw new Error(\"TaskStatusRepository requires a valid StorageAdapter instance.\");\n }\n this.adapter = storageAdapter;\n // Note: Adapter initialization (adapter.init()) should be handled externally.\n }\n\n /**\n * Creates a new A2A task in the repository.\n * @param {A2ATask} task - The A2ATask object to create.\n * @returns {Promise<void>} A promise that resolves when the task is successfully stored.\n * @throws {ARTError} If the task cannot be created (e.g., duplicate taskId, validation errors).\n */\n async createTask(task: A2ATask): Promise<void> {\n if (!task || !task.taskId) {\n throw new ARTError('Task must have a valid taskId', ErrorCode.VALIDATION_ERROR);\n }\n\n // Check if task already exists\n const existingTask = await this.adapter.get<StoredA2ATask>(this.collectionName, task.taskId);\n if (existingTask) {\n throw new ARTError(`Task with ID '${task.taskId}' already exists`, ErrorCode.DUPLICATE_TASK_ID);\n }\n\n // Add the 'id' field mirroring 'taskId' for compatibility with keyPath='id' adapters\n const taskToStore: StoredA2ATask = {\n ...task,\n id: task.taskId\n };\n\n await this.adapter.set<StoredA2ATask>(this.collectionName, task.taskId, taskToStore);\n }\n\n /**\n * Retrieves an A2A task by its unique identifier.\n * @param {string} taskId - The unique identifier of the task.\n * @returns {Promise<A2ATask | null>} A promise resolving to the A2ATask object if found, or null if not found.\n * @throws {ARTError} If an error occurs during retrieval.\n */\n async getTask(taskId: string): Promise<A2ATask | null> {\n if (!taskId) {\n throw new ARTError('TaskId is required', ErrorCode.VALIDATION_ERROR);\n }\n\n try {\n const storedTask = await this.adapter.get<StoredA2ATask>(this.collectionName, taskId);\n if (!storedTask) {\n return null;\n }\n\n // Remove the internal 'id' field before returning\n const task = { ...storedTask };\n delete (task as Partial<StoredA2ATask>).id;\n return task as A2ATask;\n } catch (error) {\n throw new ARTError(`Failed to retrieve task '${taskId}': ${error}`, ErrorCode.REPOSITORY_ERROR);\n }\n }\n\n /**\n * Updates an existing A2A task with new information.\n * @param {string} taskId - The unique identifier of the task to update.\n * @param {Partial<A2ATask>} updates - Partial A2ATask object containing the fields to update.\n * @returns {Promise<void>} A promise that resolves when the task is successfully updated.\n * @throws {ARTError} If the task is not found or cannot be updated.\n */\n async updateTask(taskId: string, updates: Partial<A2ATask>): Promise<void> {\n if (!taskId) {\n throw new ARTError('TaskId is required', ErrorCode.VALIDATION_ERROR);\n }\n\n if (!updates || Object.keys(updates).length === 0) {\n throw new ARTError('Updates object cannot be empty', ErrorCode.VALIDATION_ERROR);\n }\n\n try {\n // Get the existing task\n const existingTask = await this.adapter.get<StoredA2ATask>(this.collectionName, taskId);\n if (!existingTask) {\n throw new ARTError(`Task with ID '${taskId}' not found`, ErrorCode.TASK_NOT_FOUND);\n }\n\n // Merge updates with existing task\n const updatedTask: StoredA2ATask = {\n ...existingTask,\n ...updates,\n taskId, // Ensure taskId cannot be changed\n id: taskId // Ensure consistency\n };\n\n // Update metadata if provided\n if (updates.metadata) {\n updatedTask.metadata = {\n ...existingTask.metadata,\n ...updates.metadata,\n lastUpdated: Date.now() // Always update timestamp\n };\n }\n\n await this.adapter.set<StoredA2ATask>(this.collectionName, taskId, updatedTask);\n } catch (error) {\n if (error instanceof ARTError) {\n throw error;\n }\n throw new ARTError(`Failed to update task '${taskId}': ${error}`, ErrorCode.REPOSITORY_ERROR);\n }\n }\n\n /**\n * Removes an A2A task from the repository.\n * @param {string} taskId - The unique identifier of the task to delete.\n * @returns {Promise<void>} A promise that resolves when the task is successfully deleted.\n * @throws {ARTError} If the task is not found or cannot be deleted.\n */\n async deleteTask(taskId: string): Promise<void> {\n if (!taskId) {\n throw new ARTError('TaskId is required', ErrorCode.VALIDATION_ERROR);\n }\n\n try {\n // Check if task exists\n const existingTask = await this.adapter.get<StoredA2ATask>(this.collectionName, taskId);\n if (!existingTask) {\n throw new ARTError(`Task with ID '${taskId}' not found`, ErrorCode.TASK_NOT_FOUND);\n }\n\n await this.adapter.delete(this.collectionName, taskId);\n } catch (error) {\n if (error instanceof ARTError) {\n throw error;\n }\n throw new ARTError(`Failed to delete task '${taskId}': ${error}`, ErrorCode.REPOSITORY_ERROR);\n }\n }\n\n /**\n * Retrieves tasks associated with a specific thread.\n * @param {string} threadId - The thread identifier to filter tasks.\n * @param {object} [filter] - Optional filter criteria for task status, priority, or assigned agent.\n * @returns {Promise<A2ATask[]>} A promise resolving to an array of A2ATask objects matching the criteria.\n */\n async getTasksByThread(\n threadId: string,\n filter?: {\n status?: A2ATaskStatus | A2ATaskStatus[];\n priority?: A2ATaskPriority;\n assignedAgentId?: string;\n }\n ): Promise<A2ATask[]> {\n if (!threadId) {\n throw new ARTError('ThreadId is required', ErrorCode.VALIDATION_ERROR);\n }\n\n try {\n // Query tasks for the specific thread\n const queryResults = await this.adapter.query<StoredA2ATask>(this.collectionName, {\n filter: { threadId: threadId }\n });\n\n // Apply additional client-side filtering\n let filteredTasks = queryResults;\n\n if (filter) {\n if (filter.status) {\n const statusArray = Array.isArray(filter.status) ? filter.status : [filter.status];\n filteredTasks = filteredTasks.filter(task => statusArray.includes(task.status));\n }\n\n if (filter.priority) {\n filteredTasks = filteredTasks.filter(task => task.priority === filter.priority);\n }\n\n if (filter.assignedAgentId) {\n filteredTasks = filteredTasks.filter(task => \n task.targetAgent?.agentId === filter.assignedAgentId\n );\n }\n }\n\n // Sort by creation timestamp (newest first)\n filteredTasks.sort((a, b) => (b.metadata?.createdAt || 0) - (a.metadata?.createdAt || 0));\n\n // Remove the 'id' field from results\n return this._removeIdField(filteredTasks);\n } catch (error) {\n throw new ARTError(`Failed to get tasks for thread '${threadId}': ${error}`, ErrorCode.REPOSITORY_ERROR);\n }\n }\n\n /**\n * Retrieves tasks assigned to a specific agent.\n * @param {string} agentId - The agent identifier to filter tasks.\n * @param {object} [filter] - Optional filter criteria for task status or priority.\n * @returns {Promise<A2ATask[]>} A promise resolving to an array of A2ATask objects assigned to the agent.\n */\n async getTasksByAgent(\n agentId: string,\n filter?: {\n status?: A2ATaskStatus | A2ATaskStatus[];\n priority?: A2ATaskPriority;\n }\n ): Promise<A2ATask[]> {\n if (!agentId) {\n throw new ARTError('AgentId is required', ErrorCode.VALIDATION_ERROR);\n }\n\n try {\n // Query all tasks and filter client-side (storage adapters may not support nested filtering)\n const queryResults = await this.adapter.query<StoredA2ATask>(this.collectionName, {\n filter: {} // Get all tasks, then filter client-side\n });\n\n // Filter by assigned agent\n let filteredTasks = queryResults.filter(task => \n task.targetAgent?.agentId === agentId\n );\n\n // Apply additional filters\n if (filter) {\n if (filter.status) {\n const statusArray = Array.isArray(filter.status) ? filter.status : [filter.status];\n filteredTasks = filteredTasks.filter(task => statusArray.includes(task.status));\n }\n\n if (filter.priority) {\n filteredTasks = filteredTasks.filter(task => task.priority === filter.priority);\n }\n }\n\n // Sort by creation timestamp (newest first)\n filteredTasks.sort((a, b) => (b.metadata?.createdAt || 0) - (a.metadata?.createdAt || 0));\n\n // Remove the 'id' field from results\n return this._removeIdField(filteredTasks);\n } catch (error) {\n throw new ARTError(`Failed to get tasks for agent '${agentId}': ${error}`, ErrorCode.REPOSITORY_ERROR);\n }\n }\n\n /**\n * Retrieves tasks based on their current status.\n * @param {A2ATaskStatus | A2ATaskStatus[]} status - The task status(es) to filter by.\n * @param {object} [options] - Optional query parameters like limit and pagination.\n * @returns {Promise<A2ATask[]>} A promise resolving to an array of A2ATask objects with the specified status.\n */\n async getTasksByStatus(\n status: A2ATaskStatus | A2ATaskStatus[],\n options?: { limit?: number; offset?: number }\n ): Promise<A2ATask[]> {\n if (!status) {\n throw new ARTError('Status is required', ErrorCode.VALIDATION_ERROR);\n }\n\n try {\n // Query all tasks (since we need to filter by status client-side)\n const queryResults = await this.adapter.query<StoredA2ATask>(this.collectionName, {\n filter: {} // Get all, then filter client-side\n });\n\n // Filter by status\n const statusArray = Array.isArray(status) ? status : [status];\n let filteredTasks = queryResults.filter(task => statusArray.includes(task.status));\n\n // Sort by creation timestamp (newest first)\n filteredTasks.sort((a, b) => (b.metadata?.createdAt || 0) - (a.metadata?.createdAt || 0));\n\n // Apply pagination\n if (options) {\n const offset = options.offset || 0;\n const limit = options.limit;\n \n if (offset > 0) {\n filteredTasks = filteredTasks.slice(offset);\n }\n \n if (limit && limit > 0) {\n filteredTasks = filteredTasks.slice(0, limit);\n }\n }\n\n // Remove the 'id' field from results\n return this._removeIdField(filteredTasks);\n } catch (error) {\n throw new ARTError(`Failed to get tasks by status: ${error}`, ErrorCode.REPOSITORY_ERROR);\n }\n }\n\n /**\n * Utility method to remove the internal 'id' field from stored tasks before returning them.\n * @private\n * @param {StoredA2ATask[]} tasks - Array of StoredA2ATask objects.\n * @returns {A2ATask[]} Array of A2ATask objects with 'id' field removed.\n */\n private _removeIdField(tasks: StoredA2ATask[]): A2ATask[] {\n return tasks.map(task => {\n const cleanTask = { ...task };\n delete (cleanTask as Partial<StoredA2ATask>).id;\n return cleanTask as A2ATask;\n });\n }\n} ","import { ConversationManager as IConversationManager, IConversationRepository } from '@/core/interfaces';\nimport { ConversationSocket } from '@/systems/ui/conversation-socket'; // Import the class\nimport { ConversationMessage, MessageOptions } from '@/types';\n\n/**\n * Manages the retrieval and addition of `ConversationMessage` objects for different threads,\n * interacting with an underlying `IConversationRepository` for persistence and notifying\n * the `ConversationSocket` of new messages.\n */\nexport class ConversationManager implements IConversationManager {\n private repository: IConversationRepository;\n private conversationSocket: ConversationSocket; // Add socket property\n\n /**\n * Creates an instance of ConversationManager.\n * @param {IConversationRepository} conversationRepository - The repository responsible for persisting conversation messages.\n * @param {ConversationSocket} conversationSocket - The socket instance used to notify the UI of new messages.\n */\n constructor(\n conversationRepository: IConversationRepository,\n conversationSocket: ConversationSocket\n ) {\n this.repository = conversationRepository;\n this.conversationSocket = conversationSocket;\n }\n\n /**\n * Adds one or more messages to a specific thread's history using the repository\n * and notifies the `ConversationSocket` for each added message.\n * @param {string} threadId - The ID of the thread to add messages to. Must not be empty.\n * @param {ConversationMessage[]} messages - An array of `ConversationMessage` objects to add.\n * @returns {Promise<void>} A promise that resolves when messages are saved and notifications are sent (or attempted).\n * @throws {Error} If `threadId` is empty. Repository errors might also propagate.\n */\n async addMessages(threadId: string, messages: ConversationMessage[]): Promise<void> {\n // Basic validation or preprocessing could happen here if needed.\n if (!threadId) {\n return Promise.reject(new Error(\"ConversationManager: threadId cannot be empty.\"));\n }\n if (!messages || messages.length === 0) {\n return Promise.resolve(); // Nothing to add\n }\n // Delegate to the repository\n await this.repository.addMessages(threadId, messages);\n\n // Notify socket for each added message\n messages.forEach(message => {\n // Assuming ConversationSocket has a method like notifyMessage or just notify\n // Use notify as per the TypedSocket interface\n try {\n this.conversationSocket.notify(message, { targetThreadId: threadId });\n } catch (error) {\n // Log error but don't let notification failure stop the flow\n console.error(`ConversationManager: Failed to notify message ${message.messageId} via socket for thread ${threadId}`, error);\n }\n });\n }\n\n /**\n * Retrieves messages from a specific thread's history using the repository.\n * @param {string} threadId - The ID of the thread whose history is needed. Must not be empty.\n * @param {MessageOptions} [options] - Optional parameters (`MessageOptions`) to control retrieval (e.g., limit, timestamp filters).\n * @returns {Promise<ConversationMessage[]>} A promise resolving to an array of `ConversationMessage` objects, typically ordered newest first by the repository.\n * @throws {Error} If `threadId` is empty. Repository errors might also propagate.\n */\n async getMessages(threadId: string, options?: MessageOptions): Promise<ConversationMessage[]> {\n if (!threadId) {\n return Promise.reject(new Error(\"ConversationManager: threadId cannot be empty.\"));\n }\n // Delegate to the repository\n const messages = await this.repository.getMessages(threadId, options);\n return messages;\n }\n\n // Optional future methods:\n // async clearHistory(threadId: string): Promise<void> { ... }\n // async deleteMessage(threadId: string, messageId: string): Promise<void> { ... }\n}","import { StateManager as IStateManager, IStateRepository } from '@/core/interfaces';\nimport { ThreadContext, ThreadConfig, AgentState, StateSavingStrategy } from '@/types';\n\n// Helper for deep cloning, as structuredClone might not be available in all environments\n// or might not handle all types perfectly (e.g., functions, though not expected in AgentState).\n// For simple JSON-like objects, JSON.parse(JSON.stringify(obj)) is a common approach.\nfunction deepClone<T>(obj: T): T {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n // For Date objects\n if (obj instanceof Date) {\n return new Date(obj.getTime()) as any;\n }\n // For Arrays\n if (Array.isArray(obj)) {\n return obj.map(item => deepClone(item)) as any;\n }\n // For Objects\n const clonedObj = {} as T;\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n clonedObj[key] = deepClone(obj[key]);\n }\n }\n return clonedObj;\n}\n\n\n/**\n * Manages thread-specific configuration (ThreadConfig) and state (AgentState)\n * using an underlying StateRepository. Supports explicit and implicit state saving strategies.\n */\nexport class StateManager implements IStateManager {\n private repository: IStateRepository;\n private strategy: StateSavingStrategy;\n private contextCache: Map<string, { originalStateSnapshot: string | null, context: ThreadContext }>;\n\n /**\n * Creates an instance of StateManager.\n * @param {IStateRepository} stateRepository - The repository for persisting state.\n * @param {StateSavingStrategy} [strategy='explicit'] - The state saving strategy to use.\n */\n constructor(\n stateRepository: IStateRepository,\n strategy: StateSavingStrategy = 'explicit' // Default to explicit\n ) {\n this.repository = stateRepository;\n this.strategy = strategy;\n this.contextCache = new Map();\n }\n\n /**\n * Loads the complete context (`ThreadConfig` and `AgentState`) for a specific thread.\n * If in 'implicit' state saving strategy, it caches the loaded context and a snapshot\n * of its AgentState for later comparison in `saveStateIfModified`.\n * @param {string} threadId - The unique identifier for the thread.\n * @param {string} [_userId] - Optional user identifier (currently unused).\n * @returns {Promise<ThreadContext>} A promise resolving to the `ThreadContext` object.\n * @throws {Error} If `threadId` is empty or if the repository fails to find the context.\n */\n async loadThreadContext(threadId: string, _userId?: string): Promise<ThreadContext> {\n if (!threadId) {\n throw new Error(\"StateManager: threadId cannot be empty for loadThreadContext.\");\n }\n\n // If in implicit mode and context is already cached for this cycle, return cached version.\n // This ensures the agent operates on the same object instance that will be checked for modifications.\n if (this.strategy === 'implicit' && this.contextCache.has(threadId)) {\n // console.debug(`StateManager (implicit): Returning cached context for ${threadId}`);\n return this.contextCache.get(threadId)!.context;\n }\n \n const contextFromRepo = await this.repository.getThreadContext(threadId);\n if (!contextFromRepo) {\n throw new Error(`StateManager: Thread context not found for threadId '${threadId}'. Application should call setThreadConfig first for new threads.`);\n }\n\n if (this.strategy === 'implicit') {\n // console.debug(`StateManager (implicit): Caching context for ${threadId}`);\n // Deep clone the context to prevent modifications to the repository's object if it's not already a clone.\n // The agent will modify this cloned object.\n const cachedContext = deepClone(contextFromRepo);\n const originalStateSnapshot = cachedContext.state ? JSON.stringify(cachedContext.state) : null;\n this.contextCache.set(threadId, { originalStateSnapshot, context: cachedContext });\n return cachedContext;\n } else {\n // In explicit mode, return the context directly. Agent is responsible for all saves.\n return contextFromRepo;\n }\n }\n\n /**\n * Checks if a specific tool is permitted for use within a given thread.\n * It loads the thread's context and checks the `enabledTools` array in the configuration.\n * @param {string} threadId - The ID of the thread.\n * @param {string} toolName - The name of the tool to check.\n * @returns {Promise<boolean>} A promise resolving to `true` if the tool is listed in the thread's `enabledTools` config, `false` otherwise or if the context/config cannot be loaded.\n */\n async isToolEnabled(threadId: string, toolName: string): Promise<boolean> {\n try {\n const context = await this.loadThreadContext(threadId); // Will use cache if implicit\n return context.config?.enabledTools?.includes(toolName) ?? false;\n } catch (error) {\n console.warn(`StateManager: Could not check if tool '${toolName}' is enabled for thread '${threadId}' because context failed to load: ${error}`);\n return false;\n }\n }\n\n /**\n * Retrieves a specific value from the thread's configuration (`ThreadConfig`).\n * Loads the context first (which might come from cache in implicit mode).\n * @template T - The expected type of the configuration value.\n * @param {string} threadId - The ID of the thread.\n * @param {string} key - The top-level configuration key.\n * @returns {Promise<T | undefined>} A promise resolving to the configuration value, or `undefined`.\n */\n async getThreadConfigValue<T>(threadId: string, key: string): Promise<T | undefined> {\n const context = await this.loadThreadContext(threadId); // Will use cache if implicit\n\n if (!context.config) {\n return undefined;\n }\n if (key in context.config) {\n return (context.config as any)[key] as T | undefined;\n } else {\n return undefined;\n }\n }\n\n /**\n * Persists the thread's `AgentState` if it has been modified.\n * Behavior depends on the `stateSavingStrategy`:\n * - 'explicit': This method is a no-op for `AgentState` persistence and logs a warning.\n * - 'implicit': Compares the current `AgentState` (from the cached `ThreadContext` modified by the agent)\n * with the snapshot taken during `loadThreadContext`. If different, saves the state\n * to the repository and updates the snapshot.\n * @param {string} threadId - The ID of the thread whose state might need saving.\n * @returns {Promise<void>} A promise that resolves when the state is saved or the operation is skipped.\n */\n async saveStateIfModified(threadId: string): Promise<void> {\n if (!threadId) {\n throw new Error(\"StateManager: threadId cannot be empty for saveStateIfModified.\");\n }\n\n if (this.strategy === 'explicit') {\n console.warn(`StateManager (explicit): saveStateIfModified called for thread ${threadId}. AgentState must be saved explicitly using setAgentState(). This method is a no-op for AgentState in explicit mode.`);\n return Promise.resolve();\n }\n\n // Implicit strategy\n const cachedData = this.contextCache.get(threadId);\n if (!cachedData) {\n console.warn(`StateManager (implicit): saveStateIfModified called for thread ${threadId}, but context was not loaded or cached in this StateManager instance for this cycle. State will not be saved implicitly.`);\n return Promise.resolve();\n }\n\n const currentState = cachedData.context.state; // This is the potentially modified state\n const currentStateSnapshot = currentState ? JSON.stringify(currentState) : null;\n\n if (currentStateSnapshot !== cachedData.originalStateSnapshot) {\n // console.debug(`StateManager (implicit): AgentState for thread ${threadId} has changed. Saving...`);\n if (currentState === null) {\n // This case should ideally be handled by setAgentState(threadId, null) if we want to allow nulling out state.\n // For now, if it becomes null and was not null, we treat it as a change.\n // The repository's setAgentState should handle null appropriately if it's allowed.\n // However, our setAgentState currently throws if state is null.\n // This implies that if an agent wants to clear state, it should set it to an empty object or similar.\n // For implicit, if it becomes null, we might need to decide if repository.deleteAgentState is a thing.\n // For now, we'll assume if it's null, it means \"remove it\" or \"set to null\".\n // Let's assume repository.setAgentState can handle null to clear.\n console.warn(`StateManager (implicit): AgentState for thread ${threadId} became null. Attempting to save null state.`);\n }\n if (currentState !== null) { // Only save if not null, as our setAgentState doesn't allow null\n await this.repository.setAgentState(threadId, currentState);\n cachedData.originalStateSnapshot = currentStateSnapshot; // Update snapshot after successful save\n // console.debug(`StateManager (implicit): AgentState for thread ${threadId} saved and snapshot updated.`);\n } else {\n // If current state is null, and original was not, this is a change.\n // However, our current setAgentState throws on null.\n // This indicates a design consideration: how should \"clearing\" state be handled implicitly?\n // For now, we won't call repository.setAgentState with null to avoid the error.\n // This means if an agent sets context.state = null in implicit mode, it won't be persisted by saveStateIfModified.\n // They would need to use setAgentState with a non-null value (e.g., { data: null, version: ... }).\n console.warn(`StateManager (implicit): AgentState for thread ${threadId} is null. Implicit save will not persist null state due to setAgentState constraints. Use setAgentState with a valid object to clear or update.`);\n }\n } else {\n // console.debug(`StateManager (implicit): No changes detected in AgentState for thread ${threadId}.`);\n }\n return Promise.resolve();\n }\n \n /**\n * Sets or completely replaces the configuration (`ThreadConfig`) for a specific thread\n * by calling the underlying state repository. This also clears any cached context for the thread.\n * @param {string} threadId - The ID of the thread.\n * @param {ThreadConfig} config - The complete `ThreadConfig` object.\n * @returns {Promise<void>} A promise that resolves when the configuration is saved.\n */\n async setThreadConfig(threadId: string, config: ThreadConfig): Promise<void> {\n if (!threadId || !config) {\n throw new Error(\"StateManager: threadId and config are required for setThreadConfig.\");\n }\n await this.repository.setThreadConfig(threadId, config);\n // If context was cached, it's now potentially stale regarding config.\n // And its originalStateSnapshot might be based on a context that no longer fully matches repo.\n // For simplicity, clear it. Next loadThreadContext will re-fetch and re-cache if implicit.\n if (this.contextCache.has(threadId)) {\n this.contextCache.delete(threadId);\n // console.debug(`StateManager: Cleared cached context for ${threadId} after setThreadConfig.`);\n }\n }\n\n /**\n * Explicitly sets or updates the AgentState for a specific thread by calling the underlying state repository.\n * If in 'implicit' mode, this also updates the cached snapshot to prevent `saveStateIfModified`\n * from re-saving the same state immediately.\n * @param {string} threadId - The unique identifier of the thread.\n * @param {AgentState} state - The AgentState object to save. Must not be undefined or null.\n * @returns {Promise<void>} A promise that resolves when the state is saved.\n * @throws {Error} If threadId or state is undefined/null, or if the repository fails.\n */\n async setAgentState(threadId: string, state: AgentState): Promise<void> {\n if (!threadId) {\n throw new Error(\"StateManager: threadId cannot be empty for setAgentState.\");\n }\n if (typeof state === 'undefined' || state === null) {\n throw new Error(\"StateManager: state cannot be undefined or null for setAgentState.\");\n }\n \n await this.repository.setAgentState(threadId, state);\n // console.debug(`StateManager: Explicitly set agent state for ${threadId} in repository.`);\n\n if (this.strategy === 'implicit') {\n const cachedData = this.contextCache.get(threadId);\n if (cachedData) {\n // Update the cached context's state and its snapshot\n cachedData.context.state = deepClone(state); // Ensure cache has a clone\n cachedData.originalStateSnapshot = JSON.stringify(state);\n // console.debug(`StateManager (implicit): Updated cached context and snapshot for ${threadId} after explicit setAgentState.`);\n } else {\n // If not in cache, it means loadThreadContext wasn't called for this thread in this cycle,\n // or it's explicit mode. For implicit, if setAgentState is called without prior load,\n // there's no \"original\" snapshot to compare against for saveStateIfModified later in this cycle.\n // However, the state *is* saved in the repo. Next loadThreadContext will pick it up.\n // console.debug(`StateManager (implicit): setAgentState called for ${threadId} which was not in cache. State saved to repo.`);\n }\n }\n }\n \n /**\n * Enables specific tools for a conversation thread by adding them to the thread's enabled tools list.\n * This method loads the current thread configuration, updates the enabledTools array,\n * and persists the changes. Cache is invalidated to ensure fresh data on next load.\n * @param {string} threadId - The unique identifier of the thread.\n * @param {string[]} toolNames - Array of tool names to enable for this thread.\n * @returns {Promise<void>} A promise that resolves when the tools are enabled.\n * @throws {Error} If threadId is empty, toolNames is empty, or if the repository fails.\n */\n async enableToolsForThread(threadId: string, toolNames: string[]): Promise<void> {\n if (!threadId) {\n throw new Error(\"StateManager: threadId cannot be empty for enableToolsForThread.\");\n }\n if (!toolNames || toolNames.length === 0) {\n throw new Error(\"StateManager: toolNames cannot be empty for enableToolsForThread.\");\n }\n\n // Load current context to get existing config\n const context = await this.loadThreadContext(threadId);\n if (!context.config) {\n throw new Error(`StateManager: No ThreadConfig found for threadId '${threadId}'. Cannot enable tools without existing configuration.`);\n }\n\n // Create updated config with additional enabled tools\n const currentEnabledTools = context.config.enabledTools || [];\n const newEnabledTools = [...new Set([...currentEnabledTools, ...toolNames])]; // Remove duplicates\n\n const updatedConfig: ThreadConfig = {\n ...context.config,\n enabledTools: newEnabledTools\n };\n\n // Save updated config and clear cache\n await this.setThreadConfig(threadId, updatedConfig);\n // console.debug(`StateManager: Enabled tools [${toolNames.join(', ')}] for thread ${threadId}.`);\n }\n\n /**\n * Disables specific tools for a conversation thread by removing them from the thread's enabled tools list.\n * This method loads the current thread configuration, updates the enabledTools array,\n * and persists the changes. Cache is invalidated to ensure fresh data on next load.\n * @param {string} threadId - The unique identifier of the thread.\n * @param {string[]} toolNames - Array of tool names to disable for this thread.\n * @returns {Promise<void>} A promise that resolves when the tools are disabled.\n * @throws {Error} If threadId is empty, toolNames is empty, or if the repository fails.\n */\n async disableToolsForThread(threadId: string, toolNames: string[]): Promise<void> {\n if (!threadId) {\n throw new Error(\"StateManager: threadId cannot be empty for disableToolsForThread.\");\n }\n if (!toolNames || toolNames.length === 0) {\n throw new Error(\"StateManager: toolNames cannot be empty for disableToolsForThread.\");\n }\n\n // Load current context to get existing config\n const context = await this.loadThreadContext(threadId);\n if (!context.config) {\n throw new Error(`StateManager: No ThreadConfig found for threadId '${threadId}'. Cannot disable tools without existing configuration.`);\n }\n\n // Create updated config with tools removed\n const currentEnabledTools = context.config.enabledTools || [];\n const newEnabledTools = currentEnabledTools.filter(tool => !toolNames.includes(tool));\n\n const updatedConfig: ThreadConfig = {\n ...context.config,\n enabledTools: newEnabledTools\n };\n\n // Save updated config and clear cache\n await this.setThreadConfig(threadId, updatedConfig);\n // console.debug(`StateManager: Disabled tools [${toolNames.join(', ')}] for thread ${threadId}.`);\n }\n\n /**\n * Gets the list of currently enabled tools for a specific thread.\n * This is a convenience method that loads the thread context and returns the enabledTools array.\n * @param {string} threadId - The unique identifier of the thread.\n * @returns {Promise<string[]>} A promise that resolves to an array of enabled tool names, or empty array if no tools are enabled.\n * @throws {Error} If the thread context cannot be loaded.\n */\n async getEnabledToolsForThread(threadId: string): Promise<string[]> {\n if (!threadId) {\n throw new Error(\"StateManager: threadId cannot be empty for getEnabledToolsForThread.\");\n }\n\n const context = await this.loadThreadContext(threadId);\n return context.config?.enabledTools || [];\n }\n\n /**\n * Clears the internal context cache. Useful if the underlying storage is manipulated externally\n * during an agent's processing cycle, though this is generally not recommended.\n * Or for testing purposes.\n */\n public clearCache(): void {\n this.contextCache.clear();\n // console.debug(\"StateManager: Internal context cache cleared.\");\n }\n\n // Potential future methods:\n // async updateThreadConfig(threadId: string, updates: Partial<ThreadConfig>): Promise<void> { ... }\n // async updateAgentState(threadId: string, updates: Partial<AgentState>): Promise<void> { ... }\n }","import { ObservationManager as ObservationManagerInterface, IObservationRepository } from '@/core/interfaces'; // Import the interface defined in core/interfaces\nimport { ObservationSocket } from '../ui/observation-socket'; // Import the class implementation\nimport { Observation, ObservationFilter } from '@/types'; // Kept ObservationType and Omit removed\nimport { generateUUID } from '@/utils/uuid'; // Assuming UUID utility exists as per Phase 0.9\nimport { Logger } from '@/utils/logger'; // Import Logger\n\n/**\n * Manages the lifecycle of agent observations: creation, persistence, retrieval, and notification.\n *\n * @remarks\n * It provides methods to record and retrieve observations, which are crucial for\n * debugging, monitoring, and analyzing agent behavior. The manager uses a\n * repository pattern to abstract the underlying storage mechanism.\n *\n * @see {@link ObservationManagerInterface} for the interface definition.\n * @see {@link IObservationRepository} for the storage repository interface.\n */\nexport class ObservationManager implements ObservationManagerInterface { // Implement the imported interface\n private observationRepository: IObservationRepository;\n private observationSocket: ObservationSocket;\n\n /**\n * Creates an instance of ObservationManager.\n *\n * @param observationRepository The repository for persisting observations.\n * @param observationSocket The socket for notifying UI about new observations.\n */\n constructor(observationRepository: IObservationRepository, observationSocket: ObservationSocket) {\n this.observationRepository = observationRepository;\n this.observationSocket = observationSocket;\n }\n\n /**\n * Creates, persists, and broadcasts a new observation record based on the provided data.\n *\n * @remarks\n * Automatically generates a unique `id`, `timestamp`, and a default `title`.\n * Uses the injected {@link IObservationRepository} for persistence and {@link ObservationSocket} for notification.\n *\n * @param observationData An object containing the core data for the observation (`threadId`, `type`, `content`, `metadata`, etc.), excluding fields generated by the manager (`id`, `timestamp`, `title`).\n * @returns A promise that resolves when the observation has been successfully saved and notified, or rejects if a critical error occurs during persistence. Notification errors are logged but generally do not cause rejection.\n */\n async record(observationData: Omit<Observation, 'id' | 'timestamp' | 'title'>): Promise<void> { // Corrected Omit and Promise syntax\n const observation: Observation = {\n ...observationData,\n id: generateUUID(),\n timestamp: Date.now(),\n // Generate a simple title based on the type for now\n title: `${observationData.type} Recorded`,\n };\n\n try {\n await this.observationRepository.addObservation(observation); // Assuming addObservation exists on IObservationRepository\n // Use the generic notify method from TypedSocket interface\n Logger.debug(`[ObservationManager] Notifying ObservationSocket for obsId: ${observation.id}, type: ${observation.type}`); // Log before notify\n this.observationSocket.notify(observation, { targetThreadId: observation.threadId });\n Logger.debug(`[ObservationManager] ObservationSocket notified for obsId: ${observation.id}`); // Log after notify\n } catch (error) {\n console.error(\"Error recording observation:\", error);\n // Decide on error handling strategy - rethrow, log, or generate an ERROR observation?\n // For now, just logging. Consider adding an ERROR observation itself.\n throw error; // Rethrowing for now so the caller is aware\n }\n }\n\n /**\n * Retrieves historical observations stored for a specific thread, using the repository.\n *\n * @remarks\n * Allows filtering based on criteria defined in {@link ObservationFilter}.\n *\n * @param threadId The ID of the thread whose observations are to be retrieved.\n * @param filter Optional criteria (`ObservationFilter`) to filter the observations (e.g., by type, timestamp).\n * @returns A promise resolving to an array of {@link Observation} objects matching the criteria.\n * @throws If the repository encounters an error during retrieval.\n */\n async getObservations(threadId: string, filter?: ObservationFilter): Promise<Observation[]> {\n try {\n // Assuming repository has a 'findObservations' method that accepts threadId and filter\n // Assuming repository has a method matching this signature\n return await this.observationRepository.getObservations(threadId, filter); // Assuming repository method is getObservations\n } catch (error) {\n console.error(`Error retrieving observations for thread ${threadId}:`, error);\n throw error; // Rethrowing for now\n }\n }\n}","// src/systems/tool/ToolRegistry.ts\nimport { ToolRegistry as IToolRegistry, IToolExecutor, StateManager } from '@/core/interfaces'; // Added StateManager import\nimport { ToolSchema } from '@/types';\nimport { Logger } from '@/utils/logger';\n\n/**\n * A simple in-memory implementation of the `ToolRegistry` interface.\n * Stores tool executors in a Map, keyed by the tool's unique name.\n */\nexport class ToolRegistry implements IToolRegistry {\n private executors: Map<string, IToolExecutor> = new Map();\n private stateManager: StateManager | undefined; // Added stateManager property\n\n /**\n * Creates an instance of ToolRegistry.\n * @param stateManager - Optional StateManager instance for advanced filtering.\n */\n constructor(stateManager?: StateManager) {\n this.stateManager = stateManager;\n Logger.debug(`ToolRegistry initialized ${stateManager ? 'with' : 'without'} StateManager.`);\n }\n\n /**\n * Registers a tool executor instance, making it available for lookup via `getToolExecutor`.\n * If a tool with the same name (from `executor.schema.name`) already exists, it will be overwritten, and a warning will be logged.\n * @param executor - The instance of the class implementing `IToolExecutor`. Must have a valid schema with a name.\n * @returns A promise that resolves when the tool is registered.\n * @throws {Error} If the provided executor or its schema is invalid.\n */\n async registerTool(executor: IToolExecutor): Promise<void> {\n if (!executor || !executor.schema || !executor.schema.name) {\n Logger.error('ToolRegistry: Attempted to register an invalid tool executor.');\n throw new Error('Invalid tool executor provided for registration.');\n }\n const toolName = executor.schema.name;\n if (this.executors.has(toolName)) {\n Logger.warn(`ToolRegistry: Overwriting existing tool registration for \"${toolName}\".`);\n }\n this.executors.set(toolName, executor);\n Logger.debug(`ToolRegistry: Registered tool \"${toolName}\".`);\n }\n\n /**\n * Retrieves a registered tool executor instance by its unique name.\n * @param toolName - The `name` property defined in the tool's schema.\n * @returns A promise resolving to the `IToolExecutor` instance, or `undefined` if no tool with that name is registered.\n */\n async getToolExecutor(toolName: string): Promise<IToolExecutor | undefined> {\n const executor = this.executors.get(toolName);\n if (!executor) {\n Logger.debug(`ToolRegistry: Tool \"${toolName}\" not found.`);\n }\n return executor;\n }\n\n /**\n * Retrieves the schemas of all currently registered tools.\n * Retrieves the schemas of available tools, optionally filtering by those enabled for a specific thread.\n * If `filter.enabledForThreadId` is provided and a `StateManager` was injected, it attempts to load the thread's configuration\n * and return only the schemas for tools listed in `enabledTools`. Otherwise, it returns all registered tool schemas.\n * @param filter - Optional filter criteria. `enabledForThreadId` triggers filtering based on thread config.\n * @returns A promise resolving to an array containing the `ToolSchema` of the available tools based on the filter.\n */\n async getAvailableTools(filter?: { enabledForThreadId?: string }): Promise<ToolSchema[]> {\n const allExecutors = Array.from(this.executors.values());\n const allSchemas = allExecutors.map(executor => executor.schema);\n\n if (filter?.enabledForThreadId && this.stateManager) {\n const threadId = filter.enabledForThreadId;\n Logger.debug(`ToolRegistry: Attempting to filter tools for threadId: ${threadId}`);\n try {\n // Assuming loadThreadContext returns null/undefined if not found or lacks config\n const threadContext = await this.stateManager.loadThreadContext(threadId);\n const enabledToolNames = threadContext?.config?.enabledTools;\n\n if (enabledToolNames && Array.isArray(enabledToolNames)) {\n Logger.debug(`ToolRegistry: Found enabled tools for thread ${threadId}: ${enabledToolNames.join(', ')}`);\n const enabledExecutors = allExecutors.filter(executor =>\n enabledToolNames.includes(executor.schema.name)\n );\n const enabledSchemas = enabledExecutors.map(executor => executor.schema);\n Logger.debug(`ToolRegistry: Returning ${enabledSchemas.length} enabled tool schemas for thread ${threadId}.`);\n return enabledSchemas;\n } else {\n Logger.warn(`ToolRegistry: No specific enabledTools found for thread ${threadId} or config missing. Returning all tools.`);\n }\n } catch (error: any) {\n Logger.error(`ToolRegistry: Error loading thread config for ${threadId}: ${error.message}. Returning all tools.`);\n // Fallback to returning all tools in case of error loading config\n }\n } else if (filter?.enabledForThreadId && !this.stateManager) {\n Logger.warn('ToolRegistry: Filtering by enabledForThreadId requested, but StateManager was not provided. Returning all tools.');\n }\n\n // Default: return all schemas if no filtering is applied or possible\n Logger.debug(`ToolRegistry: Returning all ${allSchemas.length} registered tool schemas.`);\n return allSchemas;\n }\n\n /**\n * Removes all registered tool executors from the registry.\n * Primarily useful for resetting state during testing or specific application scenarios.\n * @returns A promise that resolves when all tools have been cleared.\n */\n async clearAllTools(): Promise<void> {\n this.executors.clear();\n Logger.debug('ToolRegistry: Cleared all registered tools.');\n }\n\n /**\n * Unregister a single tool by name.\n */\n async unregisterTool(toolName: string): Promise<void> {\n if (this.executors.delete(toolName)) {\n Logger.debug(`ToolRegistry: Unregistered tool \"${toolName}\".`);\n }\n }\n\n /**\n * Unregister tools matching a predicate; returns count removed.\n */\n async unregisterTools(predicate: (schema: ToolSchema) => boolean): Promise<number> {\n let removed = 0;\n for (const [name, exec] of Array.from(this.executors.entries())) {\n try {\n if (predicate(exec.schema)) {\n this.executors.delete(name);\n removed++;\n }\n } catch {\n // ignore predicate errors\n }\n }\n if (removed > 0) {\n Logger.debug(`ToolRegistry: Unregistered ${removed} tool(s) via predicate.`);\n }\n return removed;\n }\n}","/**\n * @module utils/validation\n * Provides a utility function for validating data against JSON schemas using the Ajv library.\n */\nimport Ajv, { ValidateFunction, ErrorObject } from 'ajv';\nimport { Logger } from '@/utils/logger';\n\n// Initialize Ajv\n// We can configure Ajv options here if needed (e.g., strict mode, allErrors)\nconst ajv = new Ajv({ allErrors: true });\n\n// Cache compiled validation functions for performance\nconst compiledValidators: Map<string, ValidateFunction> = new Map();\n\n/**\n * Validates data against a given JSON schema using the Ajv library.\n *\n * @remarks\n * It caches compiled validation functions based on the schema's string representation\n * to improve performance for repeated validations against the same schema.\n *\n * @param schema - The JSON schema object to validate against.\n * @param data - The data object to be validated.\n * @returns An object containing the validation result.\n *\n * @example\n * const schema = { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] };\n * const validData = { name: 'ART' };\n * const invalidData = { name: 123 };\n *\n * const { isValid, errors } = validateJsonSchema(schema, validData); // isValid: true, errors: null\n * const { isValid: isInvalid, errors: errorDetails } = validateJsonSchema(schema, invalidData); // isInvalid: false, errors: [...]\n */\nexport function validateJsonSchema(schema: object, data: any): { isValid: boolean; errors: ErrorObject[] | null } {\n // Use a string representation of the schema as the cache key\n const schemaKey = JSON.stringify(schema);\n let validate: ValidateFunction;\n\n if (compiledValidators.has(schemaKey)) {\n validate = compiledValidators.get(schemaKey)!;\n Logger.debug('Using cached JSON schema validator.');\n } else {\n try {\n validate = ajv.compile(schema);\n compiledValidators.set(schemaKey, validate);\n Logger.debug('Compiled and cached new JSON schema validator.');\n } catch (error: any) {\n Logger.error(`Failed to compile JSON schema: ${error.message}`, { schema, error });\n // If schema compilation fails, treat validation as failed\n return {\n isValid: false,\n errors: [{\n keyword: 'compilation',\n instancePath: '',\n schemaPath: '',\n params: {},\n message: `Schema compilation failed: ${error.message}`\n }]\n };\n }\n }\n\n const isValid = validate(data);\n\n if (isValid) {\n return { isValid: true, errors: null };\n } else {\n Logger.warn('JSON schema validation failed.', { errors: validate.errors, data });\n return { isValid: false, errors: validate.errors || [] }; // Ensure errors is always an array\n }\n}\n\n/**\n * Clears the internal cache of compiled JSON schema validators.\n * This might be useful in testing scenarios or if schemas are dynamically updated\n * in a way that requires recompilation.\n */\nexport function clearJsonSchemaValidatorCache(): void {\n compiledValidators.clear();\n Logger.debug('Cleared JSON schema validator cache.');\n}","// src/systems/tool/ToolSystem.ts\nimport { ToolSystem as IToolSystem, ToolRegistry, StateManager, IToolExecutor, ObservationManager } from '@/core/interfaces'; // Added ObservationManager\nimport { ParsedToolCall, ToolResult, ExecutionContext, ObservationType } from '@/types'; // Added ObservationType\nimport { validateJsonSchema } from '@/utils/validation';\nimport { Logger } from '@/utils/logger';\n// import { v4 as uuidv4 } from 'uuid'; // Removed unused import\n\n/**\n * Implements the `ToolSystem` interface, responsible for orchestrating the execution\n * of tool calls requested by the agent's plan. It handles verification, validation,\n * execution via registered executors, and observation recording.\n */\nexport class ToolSystem implements IToolSystem {\n private toolRegistry: ToolRegistry;\n private stateManager: StateManager;\n private observationManager: ObservationManager; // Add when implementing observations\n\n /**\n * Creates an instance of the ToolSystem.\n * @param toolRegistry - The registry used to look up tool executors.\n * @param stateManager - The manager used to check if tools are enabled for a thread.\n * @param observationManager - The manager used to record TOOL_EXECUTION observations.\n * @throws {Error} If any of the required dependencies are missing.\n */\n constructor(\n toolRegistry: ToolRegistry,\n stateManager: StateManager,\n observationManager: ObservationManager\n ) {\n if (!toolRegistry) throw new Error('ToolSystem constructor requires a ToolRegistry instance.');\n if (!stateManager) throw new Error('ToolSystem constructor requires a StateManager instance.');\n if (!observationManager) throw new Error('ToolSystem constructor requires an ObservationManager instance.');\n\n this.toolRegistry = toolRegistry;\n this.stateManager = stateManager;\n this.observationManager = observationManager;\n Logger.info('ToolSystem initialized.');\n }\n\n /**\n /**\n * Executes a sequence of planned tool calls, handling verification, validation,\n * execution, and observation recording for each call.\n * Calls are typically executed sequentially in the order they appear in the `toolCalls` array.\n * @param toolCalls - An array of `ParsedToolCall` objects generated during the planning phase.\n * @param threadId - The ID of the current thread, used for context and checking tool permissions via `StateManager`.\n * @param traceId - Optional trace ID for correlating observations.\n * @returns A promise resolving to an array of `ToolResult` objects, one for each attempted tool call.\n * Each `ToolResult` indicates the success or failure of the individual call.\n * This method itself generally does not throw errors for individual tool failures, but logs them and includes them in the results. It might throw if a critical internal error occurs.\n */\n async executeTools(\n toolCalls: ParsedToolCall[],\n threadId: string,\n traceId?: string\n ): Promise<ToolResult[]> {\n const results: ToolResult[] = [];\n Logger.debug(`ToolSystem executing ${toolCalls.length} tool calls for thread ${threadId}`, { traceId });\n\n for (const call of toolCalls) {\n let result: ToolResult | null = null;\n let executor: IToolExecutor | undefined;\n const toolName = call.toolName;\n const callId = call.callId; // Use the ID from the planning output\n\n try {\n // 1. Check if tool is enabled for the thread\n const isEnabled = await this.stateManager.isToolEnabled(threadId, toolName);\n if (!isEnabled) {\n throw new Error(`Tool \"${toolName}\" is not enabled for thread \"${threadId}\".`);\n }\n\n // 2. Get the tool executor\n executor = await this.toolRegistry.getToolExecutor(toolName);\n if (!executor) {\n throw new Error(`Tool \"${toolName}\" not found in registry.`);\n }\n\n // 3. Validate arguments against the tool's schema\n const validationResult = validateJsonSchema(executor.schema.inputSchema, call.arguments);\n if (!validationResult.isValid) {\n const errorMessages = validationResult.errors?.map(e => `${e.instancePath || 'input'} ${e.message}`).join(', ') || 'Unknown validation error';\n throw new Error(`Invalid arguments for tool \"${toolName}\": ${errorMessages}`);\n }\n\n // 4. Execute the tool\n Logger.debug(`Executing tool \"${toolName}\" with callId \"${callId}\"`, { args: call.arguments, threadId, traceId });\n const executionContext: ExecutionContext = { threadId, traceId }; // Add userId if available/needed\n // TODO: Implement basic timeout mechanism\n const executionResult = await executor.execute(call.arguments, executionContext);\n\n // Ensure the result has the correct callId and toolName (executor might not set it)\n result = {\n ...executionResult,\n callId: callId,\n toolName: toolName,\n };\n Logger.debug(`Tool \"${toolName}\" execution successful`, { callId, result: result.output, threadId, traceId });\n\n } catch (error: any) {\n Logger.error(`Tool \"${toolName}\" execution failed for callId \"${callId}\": ${error.message}`, { error, threadId, traceId });\n result = {\n callId: callId,\n toolName: toolName,\n status: 'error',\n error: error.message || 'Unknown execution error',\n };\n }\n\n // Record TOOL_EXECUTION observation\n if (result) { // Ensure result is not null before recording\n this.observationManager.record({\n threadId: threadId,\n traceId: traceId,\n type: ObservationType.TOOL_EXECUTION,\n content: result, // The ToolResult object itself\n metadata: { timestamp: Date.now(), callId: call.callId } // Include callId for correlation\n }).catch(err => Logger.error(`Failed to record TOOL_EXECUTION observation for callId ${call.callId}:`, err));\n\n results.push(result);\n } else {\n // This case should ideally not happen if the try/catch always assigns to result\n Logger.error(`ToolSystem finished processing call ${call.callId} but result object was null.`);\n }\n }\n\n return results;\n }\n}","// src/systems/reasoning/PromptManager.ts\nimport { PromptManager as PromptManagerInterface } from '@/core/interfaces';\nimport { ArtStandardPrompt, PromptBlueprint, PromptContext } from '@/types';\nimport { ArtStandardPromptSchema } from '@/types/schemas'; // Import Zod schema (Reverted - trying this path again)\nimport { ARTError, ErrorCode } from '@/errors';\nimport { Logger } from '@/utils/logger';\nimport { ZodError } from 'zod'; // Import ZodError for type checking\nimport mustache from 'mustache';\n\n// --- Define Prompt Fragments ---\n// Store fragments in a simple object for now. Could be loaded from files later.\nconst PROMPT_FRAGMENTS: Record<string, string> = {\n // PES Agent Fragments\n pes_system_default: `You are a helpful AI assistant. You need to understand a user's query, potentially use tools to gather information, and then synthesize a final response.`,\n pes_planning_instructions: `Based on the user query and conversation history, identify the user's intent and create a plan to fulfill it using the available tools if necessary.`,\n pes_tool_format_instructions: `Respond in the following format:\\nIntent: [Briefly describe the user's goal]\\nPlan: [Provide a step-by-step plan. If tools are needed, list them clearly.]\\nTool Calls: [Output *only* the JSON array of tool calls required by the assistant, matching the ArtStandardMessage tool_calls format: [{\\\\\"id\\\\\": \\\\\"call_abc123\\\\\", \\\\\"type\\\\\": \\\\\"function\\\\\", \\\\\"function\\\\\": {\\\\\"name\\\\\": \\\\\"tool_name\\\\\", \\\\\"arguments\\\\\": \\\\\"{\\\\\\\\\\\\\"arg1\\\\\\\\\\\\\": \\\\\\\\\\\\\"value1\\\\\\\\\\\\\"}\\\\\"}}] or [] if no tools are needed. Do not add any other text in this section.]`,\n pes_synthesis_instructions: `Based on the user query, the plan, and the results of any tool executions, synthesize a final response to the user.\\nIf the tools failed or provided unexpected results, explain the issue and try to answer based on available information or ask for clarification.`,\n // Add other common fragments as needed\n};\n// -----------------------------\n\n/**\n * Implements the PromptManager interface for the hybrid approach.\n * Provides named prompt fragments and validates prompt objects.\n */\nexport class PromptManager implements PromptManagerInterface {\n\n // No constructor needed for this simple implementation\n\n /**\n * Retrieves a named prompt fragment.\n * Basic substitution using {{key}} is supported via context.\n *\n * @param name - The unique identifier for the fragment.\n * @param context - Optional data for simple variable substitution.\n * @returns The processed prompt fragment string.\n * @throws {ARTError} If the fragment is not found.\n */\n getFragment(name: string, context?: Record<string, any>): string {\n const fragment = PROMPT_FRAGMENTS[name];\n if (fragment === undefined) {\n Logger.error(`[PromptManager] Prompt fragment not found: ${name}`);\n throw new ARTError(`Prompt fragment not found: ${name}`, ErrorCode.PROMPT_FRAGMENT_NOT_FOUND);\n }\n\n // Basic substitution (replace {{key}} with context[key])\n if (context) {\n return fragment.replace(/\\{\\{([^}]+)\\}\\}/g, (match, key) => {\n const trimmedKey = key.trim();\n const value = context[trimmedKey];\n // Return value if found, otherwise keep the original {{key}}\n return value !== undefined ? String(value) : match;\n });\n }\n\n return fragment;\n }\n\n /**\n * Validates a constructed prompt object against the standard schema.\n *\n * @param prompt - The ArtStandardPrompt object constructed by the agent.\n * @returns The validated prompt object (potentially after normalization if the schema does that).\n * @throws {ARTError} If validation fails (can be caught and wrapped in ARTError).\n */\n validatePrompt(prompt: ArtStandardPrompt): ArtStandardPrompt {\n try {\n // Use parse, which throws on failure\n const validatedPrompt = ArtStandardPromptSchema.parse(prompt);\n return validatedPrompt;\n } catch (error: any) {\n if (error instanceof ZodError) {\n Logger.error(`[PromptManager] Prompt validation failed:`, error.errors);\n throw new ARTError(\n `Constructed prompt failed validation: ${error.message}`,\n ErrorCode.PROMPT_VALIDATION_FAILED,\n error // Include Zod error details\n );\n }\n // Wrap unexpected errors\n Logger.error(`[PromptManager] Unexpected error during prompt validation:`, error);\n throw new ARTError(\n `Unexpected error during prompt validation: ${error.message}`,\n ErrorCode.PROMPT_VALIDATION_FAILED, // Use same code for now\n error\n );\n }\n }\n\n /**\n * Assembles a prompt using a Mustache template (blueprint) and context data.\n * Renders the template with the provided context and parses the result as an ArtStandardPrompt.\n *\n * @param blueprint - The Mustache template containing the prompt structure.\n * @param context - The context data to inject into the template.\n * @returns A promise resolving to the assembled ArtStandardPrompt.\n * @throws {ARTError} If template rendering or JSON parsing fails.\n */\n async assemblePrompt(blueprint: PromptBlueprint, context: PromptContext): Promise<ArtStandardPrompt> {\n try {\n // Render the Mustache template with the context\n const renderedTemplate = mustache.render(blueprint.template, context);\n \n // Parse the rendered template as JSON\n let parsedPrompt: any;\n try {\n parsedPrompt = JSON.parse(renderedTemplate);\n } catch (parseError: any) {\n Logger.error(`[PromptManager] Failed to parse rendered template as JSON:`, parseError);\n throw new ARTError(\n `Failed to parse rendered template as JSON: ${parseError.message}`,\n ErrorCode.PROMPT_ASSEMBLY_FAILED,\n parseError\n );\n }\n\n // Ensure the parsed result is an array\n if (!Array.isArray(parsedPrompt)) {\n Logger.error(`[PromptManager] Rendered template is not an array:`, parsedPrompt);\n throw new ARTError(\n `Rendered template is not an array: ${typeof parsedPrompt}`,\n ErrorCode.PROMPT_ASSEMBLY_FAILED\n );\n }\n\n // Return the assembled prompt (cast to ArtStandardPrompt)\n return parsedPrompt as ArtStandardPrompt;\n \n } catch (error: any) {\n // If it's already an ARTError, re-throw it\n if (error instanceof ARTError) {\n throw error;\n }\n \n // Otherwise, wrap in ARTError\n Logger.error(`[PromptManager] Failed to render prompt template:`, error);\n throw new ARTError(\n `Failed to render prompt template: ${error.message}`,\n ErrorCode.PROMPT_ASSEMBLY_FAILED,\n error\n );\n }\n }\n}","// src/systems/reasoning/SystemPromptResolver.ts\nimport { SystemPromptResolver as ISystemPromptResolver } from '@/core/interfaces';\nimport { SystemPromptsRegistry, SystemPromptOverride, SystemPromptMergeStrategy } from '@/types';\nimport { PromptManager } from './PromptManager';\nimport { Logger } from '@/utils/logger';\n\nfunction applyStrategy(base: string, addition: string, strategy: SystemPromptMergeStrategy | undefined): string {\n const s = strategy || 'append';\n switch (s) {\n case 'prepend':\n return `${addition}\\n\\n${base}`;\n case 'append':\n default:\n return `${base}\\n\\n${addition}`;\n }\n}\n\nfunction normalizeOverride(input?: string | SystemPromptOverride): SystemPromptOverride | undefined {\n if (!input) return undefined;\n if (typeof input === 'string') {\n return { content: input, strategy: 'append' };\n }\n return input;\n}\n\n/**\n * Resolves layered system prompts using append/prepend-only merge.\n * Note: 'replace' is intentionally unsupported to prevent custom prompts\n * from overriding framework-required structural contracts.\n */\nexport class SystemPromptResolver implements ISystemPromptResolver {\n private readonly registry?: SystemPromptsRegistry;\n private readonly promptManager: PromptManager;\n\n constructor(promptManager: PromptManager, registry?: SystemPromptsRegistry) {\n this.promptManager = promptManager;\n this.registry = registry;\n }\n\n async resolve(input: { base: string; instance?: string | SystemPromptOverride; thread?: string | SystemPromptOverride; call?: string | SystemPromptOverride; }, traceId?: string): Promise<string> {\n let finalPrompt = input.base;\n\n const levels: Array<{ src: string; ov?: SystemPromptOverride }> = [\n { src: 'instance', ov: normalizeOverride(input.instance) },\n { src: 'thread', ov: normalizeOverride(input.thread) },\n { src: 'call', ov: normalizeOverride(input.call) },\n ];\n\n for (const lvl of levels) {\n const ov = lvl.ov;\n if (!ov) continue;\n\n let rendered = '';\n // Tag-based preset\n if (ov.tag && this.registry?.specs?.[ov.tag]) {\n const spec = this.registry.specs[ov.tag];\n const variables = { ...(spec.defaultVariables || {}), ...(ov.variables || {}) };\n rendered = this.renderTemplate(spec.template, variables);\n finalPrompt = applyStrategy(finalPrompt, rendered, ov.strategy || spec.mergeStrategy || 'append');\n Logger.debug?.(`[${traceId || 'no-trace'}] Applied system prompt tag '${ov.tag}' with strategy '${ov.strategy || spec.mergeStrategy || 'append'}'.`);\n }\n // Freeform content\n else if (ov.content) {\n rendered = ov.content;\n finalPrompt = applyStrategy(finalPrompt, rendered, ov.strategy || 'append');\n Logger.debug?.(`[${traceId || 'no-trace'}] Applied freeform system prompt with strategy '${ov.strategy || 'append'}'.`);\n }\n // No-op if neither tag nor content\n }\n\n return finalPrompt;\n }\n\n private renderTemplate(template: string, variables: Record<string, any>): string {\n // Replace fragments first: {{fragment:name}}\n const withFragments = template.replace(/\\{\\{\\s*fragment:([^}]+)\\s*\\}\\}/g, (_m, name) => {\n try {\n return this.promptManager.getFragment(String(name).trim());\n } catch {\n return '';\n }\n });\n // Replace simple variables: {{var}}\n return withFragments.replace(/\\{\\{\\s*([^}:]+)\\s*\\}\\}/g, (_m, key) => {\n const v = variables[String(key).trim()];\n return v !== undefined ? String(v) : '';\n });\n }\n}\n\n\n","// src/systems/reasoning/ReasoningEngine.ts\nimport {\n ReasoningEngine as IReasoningEngine,\n // Removed ProviderAdapter import\n} from '@/core/interfaces';\nimport { FormattedPrompt, CallOptions, StreamEvent } from '@/types';\nimport { IProviderManager, ManagedAdapterAccessor, RuntimeProviderConfig } from '@/types/providers'; // Import ProviderManager types and RuntimeProviderConfig\nimport { Logger } from '@/utils/logger';\n\n/**\n * Default implementation of the `ReasoningEngine` interface.\n * This class uses the `ProviderManager` to dynamically obtain `ProviderAdapter` instances\n * based on the runtime configuration provided in `CallOptions`.\n *\n * It abstracts the details of interacting with a specific LLM provider by using a\n * `ProviderAdapter`. This allows the agent to switch between different LLM providers\n * (like OpenAI, Anthropic, Gemini) without changing its core logic.\n *\n * @see {@link IReasoningEngine} for the interface definition.\n * @see {@link ProviderAdapter} for the adapter interface to different LLM providers.\n */\nexport class ReasoningEngine implements IReasoningEngine {\n private providerManager: IProviderManager; // Replaced adapter with providerManager\n\n /**\n * Creates an instance of the ReasoningEngine.\n * @param providerManager - The `ProviderManager` instance used to obtain adapter instances at runtime.\n */\n constructor(providerManager: IProviderManager) {\n this.providerManager = providerManager;\n Logger.info('ReasoningEngine initialized with ProviderManager');\n }\n\n /**\n * Executes an LLM call by obtaining a `ProviderAdapter` instance from the `ProviderManager`\n * based on the `providerConfig` in `CallOptions`, and then delegating the call to the adapter.\n * Ensures the adapter instance is released back to the manager after the call.\n * @param prompt - The prompt to send to the LLM, potentially formatted specifically for the provider by the `PromptManager`.\n * @param options - Options controlling the LLM call, including mandatory `threadId`, tracing IDs, model parameters, streaming flags, and the crucial `providerConfig`.\n * @returns An AsyncIterable of StreamEvent objects, as returned by the adapter.\n * @throws {ARTError | Error} Re-throws any error encountered during adapter acquisition or initial call setup.\n */\n async call(prompt: FormattedPrompt, options: CallOptions): Promise<AsyncIterable<StreamEvent>> {\n const providerConfig: RuntimeProviderConfig = options.providerConfig; // Extract providerConfig\n\n if (!providerConfig) {\n throw new Error(\"CallOptions must include 'providerConfig' for multi-provider architecture.\");\n }\n\n Logger.debug(`ReasoningEngine requesting adapter for provider: ${providerConfig.providerName}, model: ${providerConfig.modelId}`, { threadId: options.threadId, traceId: options.traceId, stream: options.stream });\n\n let accessor: ManagedAdapterAccessor;\n try {\n // Obtain a managed adapter instance from the ProviderManager\n accessor = await this.providerManager.getAdapter(providerConfig);\n Logger.debug(`ReasoningEngine obtained adapter for signature: ${accessor.adapter.providerName}`, { threadId: options.threadId, traceId: options.traceId });\n } catch (error: any) {\n Logger.error(`ReasoningEngine failed to get adapter: ${error.message}`, { error, threadId: options.threadId, traceId: options.traceId });\n // Re-throw errors from getAdapter (e.g., unknown provider, limits, conflicts)\n throw error;\n }\n\n // Use a try...finally block to ensure the adapter is released after stream consumption\n try {\n // Delegate the call to the obtained adapter instance\n const streamResult = await accessor.adapter.call(prompt, options);\n\n // Wrap the AsyncIterable to ensure release() is called when iteration is done or errors\n const releasingGenerator = (async function*() {\n try {\n for await (const event of streamResult) {\n yield event;\n }\n } finally {\n // This block executes when the generator finishes (stream consumed) or is exited (break, return, throw)\n accessor.release();\n Logger.debug(`ReasoningEngine released adapter for signature: ${accessor.adapter.providerName}`, { threadId: options.threadId, traceId: options.traceId });\n }\n })();\n\n return releasingGenerator;\n\n } catch (error: any) {\n Logger.error(`ReasoningEngine encountered an error during adapter call or stream processing: ${error.message}`, { error, threadId: options.threadId, traceId: options.traceId });\n\n // Ensure release is called even if the initial call() or stream setup fails\n accessor.release();\n Logger.debug(`ReasoningEngine released adapter after error for signature: ${accessor.adapter.providerName}`, { threadId: options.threadId, traceId: options.traceId });\n\n // Re-throw the error to be handled by the Agent Core\n throw error;\n }\n }\n}","/**\n * @module utils/xml-matcher\n * Provides a utility class for incrementally parsing and extracting content\n * from XML-like text streams. It's designed to be robust against malformed or\n * incomplete XML.\n */\n\n/**\n * Represents a chunk of text processed by {@link XmlMatcher}, indicating whether\n * it was part of the matched XML tag's content or outside of it.\n *\n * @interface XmlMatcherChunk\n */\nexport interface XmlMatcherChunk {\n /**\n * True if this chunk was inside the matched XML tag, false otherwise.\n * @property {boolean} matched\n */\n matched: boolean;\n /**\n * The text content of this chunk.\n * @property {string} data\n */\n data: string;\n}\n\n/**\n * A utility class to find and extract content within a specific XML tag from a stream of text.\n *\n * @remarks\n * It processes text chunks incrementally and yields segments, marking whether each segment\n * was inside or outside the specified XML tag.\n *\n * @example\n * // Given tagName 'think', and input \"Some text <think>this is a thought</think> and more text.\",\n * // it would yield:\n * // - { matched: false, data: \"Some text \" }\n * // - { matched: true, data: \"this is a thought\" }\n * // - { matched: false, data: \" and more text.\" }\n *\n * @class XmlMatcher\n * @template Result - The type of the transformed chunk, defaults to {@link XmlMatcherChunk}.\n */\nexport class XmlMatcher<Result = XmlMatcherChunk> {\n private index = 0;\n private currentChunks: XmlMatcherChunk[] = [];\n private cachedBuffer: string[] = [];\n private isCurrentlyMatched: boolean = false;\n private tagDepth = 0;\n private pointer = 0; // Tracks overall character position for the `position` logic\n\n /**\n * Constructs an XmlMatcher.\n *\n * @param tagName The name of the XML tag to match (e.g., \"think\").\n * @param transform An optional function to transform the yielded {@link XmlMatcherChunk} into a custom Result type.\n * @param position The character position in the input stream at which matching should begin.\n * If 0, matching starts immediately. If greater than 0, characters before this\n * position are treated as unmatched text until the tag is encountered at or after\n * this position. This is useful if the tag is expected after some preamble.\n */\n constructor(\n readonly tagName: string,\n readonly transform?: (chunk: XmlMatcherChunk) => Result,\n readonly position = 0, // Character position to start active matching\n ) {}\n\n private S_TEXT = 0;\n private S_TAG_OPEN = 1; // Expecting tag name or '/'\n private S_TAG_NAME = 2; // Matching tag name characters\n private S_TAG_CLOSING_SLASH = 3; // Found '</', expecting tag name\n private S_IGNORE_UNTIL_GT = 4; // Inside a tag, but not the one we are tracking (e.g. attributes)\n\n private state: number = this.S_TEXT;\n\n\n private collectCurrentCache(newMatchStatus?: boolean): void {\n if (this.cachedBuffer.length === 0) {\n if (newMatchStatus !== undefined && this.currentChunks.length > 0) {\n // If there's a status change but no new data, ensure the last chunk reflects the old status.\n // This is more about ensuring the `isCurrentlyMatched` reflects the status of yielded data.\n }\n return;\n }\n\n const data = this.cachedBuffer.join(\"\");\n this.cachedBuffer = [];\n const statusToUse = newMatchStatus === undefined ? this.isCurrentlyMatched : !newMatchStatus; // if newMatchStatus is defined, it means we are exiting a state\n\n const lastChunk = this.currentChunks.length > 0 ? this.currentChunks[this.currentChunks.length - 1] : null;\n\n if (lastChunk && lastChunk.matched === statusToUse) {\n lastChunk.data += data;\n } else {\n this.currentChunks.push({\n matched: statusToUse,\n data: data,\n });\n }\n }\n\n private flushProcessedChunks(): Result[] {\n const chunksToYield = this.currentChunks;\n this.currentChunks = [];\n if (this.transform) {\n return chunksToYield.map(this.transform);\n }\n return chunksToYield as unknown as Result[];\n }\n\n /**\n * Processes an incoming chunk of text.\n *\n * @param chunk The text chunk to process.\n * @returns An array of transformed results based on the matched segments.\n */\n update(chunk: string): Result[] {\n for (let i = 0; i < chunk.length; i++) {\n const char = chunk[i];\n this.pointer++;\n\n if (this.state === this.S_TEXT) {\n if (char === '<' && (this.pointer > this.position || this.isCurrentlyMatched || this.tagDepth > 0) ) {\n this.collectCurrentCache();\n this.state = this.S_TAG_OPEN;\n this.cachedBuffer.push(char);\n } else {\n this.cachedBuffer.push(char);\n }\n } else if (this.state === this.S_TAG_OPEN) { // After '<'\n this.cachedBuffer.push(char);\n if (char === '/') {\n this.state = this.S_TAG_CLOSING_SLASH;\n this.index = 0;\n } else if (char.match(/[a-zA-Z]/)) { // Start of a tag name\n this.state = this.S_TAG_NAME;\n this.index = 0;\n // Re-evaluate this char in S_TAG_NAME state\n this.cachedBuffer.pop(); // Remove char from buffer as it's part of tag name\n i--; // Reprocess this character\n } else { // Not a valid tag start after '<' (e.g., '< foo'), treat as text\n this.state = this.S_TEXT;\n }\n } else if (this.state === this.S_TAG_NAME) { // Matching opening tag name\n if (this.index < this.tagName.length && char === this.tagName[this.index]) {\n this.cachedBuffer.push(char);\n this.index++;\n } else if (char === '>' && this.index === this.tagName.length) { // Matched full <tagName>\n this.cachedBuffer.push(char);\n this.collectCurrentCache(true); // Content before this tag was not matched\n this.isCurrentlyMatched = true;\n this.tagDepth++;\n this.state = this.S_TEXT;\n this.cachedBuffer = []; // Clear buffer like <think>\n } else if ((char === ' ' || char === '\\t' || char === '\\n' || char === '\\r' || char === '>') && this.index === this.tagName.length) {\n // Tag name matched, now expecting attributes or '>'\n this.cachedBuffer.push(char);\n if (char === '>') { // Self-closing or no attributes <tagName>\n this.collectCurrentCache(true);\n this.isCurrentlyMatched = true;\n this.tagDepth++;\n this.state = this.S_TEXT;\n this.cachedBuffer = [];\n } else { // Attributes might follow\n this.state = this.S_IGNORE_UNTIL_GT;\n }\n }\n else { // Mismatch or other tag\n this.state = this.S_IGNORE_UNTIL_GT; // Treat as part of some other tag\n this.cachedBuffer.push(char);\n }\n } else if (this.state === this.S_TAG_CLOSING_SLASH) { // After '</'\n this.cachedBuffer.push(char);\n if (this.index < this.tagName.length && char === this.tagName[this.index]) {\n this.index++;\n } else if (char === '>' && this.index === this.tagName.length) { // Matched full </tagName>\n this.collectCurrentCache(false); // Content before this was matched\n this.tagDepth--;\n this.isCurrentlyMatched = (this.tagDepth > 0);\n this.state = this.S_TEXT;\n this.cachedBuffer = []; // Clear buffer like </think>\n } else { // Mismatch or other closing tag\n this.state = this.S_IGNORE_UNTIL_GT; // Treat as part of some other tag\n }\n } else if (this.state === this.S_IGNORE_UNTIL_GT) {\n this.cachedBuffer.push(char);\n if (char === '>') { // End of an ignored tag\n this.state = this.S_TEXT;\n }\n }\n }\n return this.flushProcessedChunks();\n }\n\n /**\n * Finalizes processing, flushing any remaining buffered text.\n *\n * @param chunk An optional final text chunk to process.\n * @returns An array of transformed results.\n */\n final(chunk?: string): Result[] {\n if (chunk) {\n this.update(chunk); // Process final chunk, which will also call flushProcessedChunks\n }\n this.collectCurrentCache(); // Collect any remaining data in buffer\n return this.flushProcessedChunks();\n }\n}","// src/systems/reasoning/OutputParser.ts\nimport * as z from 'zod'; // Import Zod\nimport { OutputParser as IOutputParser } from '@/core/interfaces';\nimport { ParsedToolCall } from '@/types';\nimport { Logger } from '@/utils/logger'; // Import the Logger class\nimport { XmlMatcher } from '@/utils/xml-matcher'; // Import XmlMatcher\n\n// Define Zod schema for a single tool call\nconst parsedToolCallSchema = z.object({\n callId: z.string().min(1), // Ensure callId is a non-empty string\n toolName: z.string().min(1), // Ensure toolName is a non-empty string\n arguments: z.unknown(), // Arguments must exist but can be any type; specific tools validate further\n});\n\n// Define Zod schema for an array of tool calls\nconst toolCallsSchema = z.array(parsedToolCallSchema);\n\n/**\n * Default implementation of the `OutputParser` interface.\n * - Planning: Extracts Intent, Plan, and Tool Calls from the LLM output while ignoring any\n * custom formatting constraints that apps may add. Tool Calls MUST be a JSON array where each\n * item conforms to { callId: string, toolName: string, arguments: object }. If Tool Calls\n * appears but contains no items, returns []. If the section is absent, leaves `toolCalls` undefined.\n * - Synthesis: Returns the final response text (trimmed).\n *\n * This enforces the framework-level Output Contract and keeps the structure provider-agnostic\n * and tool-type-agnostic (native and MCP tools share the same interface).\n *\n * It is responsible for parsing the raw string output from a Large Language Model (LLM)\n * and converting it into a structured format that the ART agent can understand and act upon.\n * This includes extracting the agent's intent, the plan, and any tool calls it intends to make.\n *\n * @see {@link IOutputParser} for the interface definition.\n */\nexport class OutputParser implements IOutputParser {\n /**\n * Parses the raw string output from the planning LLM call to extract structured information.\n *\n * This method performs the following steps:\n * 1. Uses `XmlMatcher` to identify and extract content within `<think>...</think>` tags.\n * The extracted content is aggregated into the `thoughts` field of the result.\n * 2. Attempts a JSON-first parse (Option 2): tries to parse a single JSON object containing\n * `{ title?, intent, plan, toolCalls }`. If successful, returns immediately.\n * 3. Falls back to the section-based parser (Option 1): parses `Title:`, `Intent:`, `Plan:`, and `Tool Calls:`\n * sections from the remaining content. Includes tolerant fallbacks for common wrappers (e.g., code fences).\n *\n * The `title` value should be a concise sentence with no more than 10 words.\n */\n async parsePlanningOutput(output: string): Promise<{\n title?: string;\n intent?: string;\n plan?: string;\n toolCalls?: ParsedToolCall[];\n thoughts?: string; // Add thoughts to the return type\n }> {\n const result: {\n title?: string;\n intent?: string;\n plan?: string;\n toolCalls?: ParsedToolCall[];\n thoughts?: string;\n } = {};\n\n let processedOutput = output;\n const thoughtsList: string[] = [];\n\n // Use XmlMatcher to extract <think> tags first\n // The XmlMatcher will process the entire `output` string.\n // We assume `output` is the full aggregated string from the LLM's planning phase.\n const xmlMatcher = new XmlMatcher('think');\n const chunks = xmlMatcher.final(output); // Process the whole string at once\n\n let nonThinkingContent = \"\";\n chunks.forEach(chunk => {\n if (chunk.matched) {\n thoughtsList.push(chunk.data.trim());\n } else {\n nonThinkingContent += chunk.data;\n }\n });\n\n if (thoughtsList.length > 0) {\n result.thoughts = thoughtsList.join(\"\\n\\n---\\n\\n\"); // Join multiple thoughts\n }\n\n // Now parse Title, Intent, Plan, Tool Calls from the non-thinking content\n processedOutput = nonThinkingContent;\n\n // --- Option 2: JSON-first parsing for a single object ---\n const tryParsePlanningJson = (raw: string): { title?: string; intent?: string; plan?: string; toolCalls?: ParsedToolCall[] } | null => {\n if (!raw) return null;\n let s = raw.trim();\n // Remove code fences if present\n s = s.replace(/^```(?:json)?\\s*/i, '').replace(/\\s*```$/i, '').trim();\n // Remove a leading 'json' token on its own line\n s = s.replace(/^json\\s*/i, '').trim();\n // If it doesn't start with {, try to slice between first { and last }\n if (!s.startsWith('{') && s.includes('{') && s.includes('}')) {\n const first = s.indexOf('{');\n const last = s.lastIndexOf('}');\n if (first >= 0 && last > first) {\n s = s.slice(first, last + 1);\n }\n }\n try {\n const obj: any = JSON.parse(s);\n if (!obj || (typeof obj !== 'object')) return null;\n const out: { title?: string; intent?: string; plan?: string; toolCalls?: ParsedToolCall[] } = {};\n if (typeof obj.title === 'string') out.title = obj.title;\n if (typeof obj.intent === 'string') out.intent = obj.intent;\n if (Array.isArray(obj.plan)) out.plan = obj.plan.join('\\n');\n else if (typeof obj.plan === 'string') out.plan = obj.plan;\n if (Array.isArray(obj.toolCalls)) {\n const validation = toolCallsSchema.safeParse(obj.toolCalls);\n if (validation.success) out.toolCalls = validation.data as ParsedToolCall[];\n else out.toolCalls = [];\n }\n // Accept if at least one of the expected fields exists\n if (out.title || out.intent || out.plan || out.toolCalls) return out;\n return null;\n } catch {\n return null;\n }\n };\n\n const jsonParsed = tryParsePlanningJson(processedOutput);\n if (jsonParsed) {\n result.title = jsonParsed.title;\n result.intent = jsonParsed.intent;\n result.plan = jsonParsed.plan;\n result.toolCalls = jsonParsed.toolCalls;\n return result;\n }\n\n // --- Fallback: section-based parsing (Option 1) ---\n // Robustly extract sections from the processedOutput (non-thinking part)\n const titleMatch = processedOutput.match(/Title:\\s*([\\s\\S]*?)(Intent:|Plan:|Tool Calls:|$)/i);\n result.title = titleMatch?.[1]?.trim();\n\n const intentMatch = processedOutput.match(/Intent:\\s*([\\s\\S]*?)(Plan:|Tool Calls:|$)/i);\n result.intent = intentMatch?.[1]?.trim();\n\n const planMatch = processedOutput.match(/Plan:\\s*([\\s\\S]*?)(Tool Calls:|$)/i);\n result.plan = planMatch?.[1]?.trim();\n\n const toolCallsMatch = processedOutput.match(/Tool Calls:\\s*([\\s\\S]*?)$/i);\n const toolCallsString = toolCallsMatch?.[1]?.trim();\n\n // Initialize toolCalls to indicate no valid calls found yet\n result.toolCalls = undefined;\n\n if (toolCallsString) {\n let jsonArrayString: string | null = null;\n let parsedJson: any = null;\n\n // 1. Find JSON Array: Look for ```json[...]``` or ```[...]``` or [...]\n // Regex explanation:\n // - ```(?:json)?\\s* : Optional markdown fence start (```json or ```)\n // - (\\[[\\s\\S]*?\\]) : Capture group 1: The JSON array content (non-greedy)\n // - \\s*``` : Optional markdown fence end\n // - | : OR\n // - (\\[[\\s\\S]*?\\]) : Capture group 2: A standalone JSON array (non-greedy)\n const jsonRegex = /```(?:json)?\\s*(\\[[\\s\\S]*?\\])\\s*```|(\\[[\\s\\S]*?\\])/;\n const jsonMatch = toolCallsString.match(jsonRegex);\n\n if (jsonMatch) {\n // Prioritize fenced match (group 1), fallback to standalone match (group 2)\n jsonArrayString = jsonMatch[1] ? jsonMatch[1].trim() : jsonMatch[2] ? jsonMatch[2].trim() : null;\n } else {\n Logger.debug(`OutputParser: No JSON array found in Tool Calls section. Content: ${toolCallsString}`);\n }\n\n\n // 2. Parse JSON (if found)\n if (jsonArrayString) {\n try {\n // Attempt to remove trailing comma just before the closing bracket\n const cleanedJsonString = jsonArrayString.replace(/,\\s*(?=]$)/, '');\n parsedJson = JSON.parse(cleanedJsonString);\n } catch (error) {\n Logger.error(`OutputParser: Failed to parse extracted JSON array. Error: ${error}. Extracted Content: ${jsonArrayString}. Original Content: ${toolCallsString}`);\n // Keep parsedJson as null, will default to empty array later\n }\n }\n\n // 3. Validate with Zod (if parsed)\n if (parsedJson !== null) {\n const validationResult = toolCallsSchema.safeParse(parsedJson);\n if (validationResult.success) {\n // Explicitly cast validated data to ParsedToolCall[] to resolve TS inference issue\n result.toolCalls = validationResult.data as ParsedToolCall[];\n } else {\n Logger.warn(`OutputParser: Tool Calls JSON structure validation failed. Errors: ${validationResult.error.toString()}. Parsed Content: ${JSON.stringify(parsedJson)}`);\n result.toolCalls = []; // Default to empty array on validation failure\n }\n } else {\n // JSON parsing failed or no JSON array found\n // If toolCallsString existed but we couldn't parse/validate, default to empty array\n result.toolCalls = [];\n }\n } else {\n // If the \"Tool Calls:\" section exists but is empty or just whitespace after it\n if (toolCallsMatch) {\n result.toolCalls = [];\n }\n // If the \"Tool Calls:\" section doesn't exist at all, toolCalls remains undefined\n }\n\n // Handle cases where sections might be missing entirely from the non-thinking content\n if (!result.title && !result.intent && !result.plan && (result.toolCalls === undefined || result.toolCalls.length === 0) && !result.thoughts) {\n Logger.warn(`OutputParser: Could not parse any structured data (Title, Intent, Plan, Tool Calls, Thoughts) from planning output. Original output: ${output}`);\n // If nothing structured is found, but there were thoughts, that's still a partial parse.\n // If no thoughts AND no other structure, then it's a more complete failure to parse structure.\n // If the original output was just thoughts, result.thoughts would be populated.\n // If original output had thoughts and other text that wasn't parsable, result.thoughts would be populated.\n // This warning triggers if even thoughts couldn't be extracted AND other sections are also missing.\n // If only thoughts were present, result.thoughts would exist, and this condition might not be met.\n // Let's refine the condition: if no standard sections (intent, plan, toolCalls) are found in `processedOutput`\n if (!result.title && !result.intent && !result.plan && (result.toolCalls === undefined || result.toolCalls.length === 0)) {\n Logger.debug(`OutputParser: No Title, Intent, Plan, or Tool Calls found in non-thinking content part: ${processedOutput}`);\n }\n } else if (!result.title && !result.intent && !result.plan && !result.toolCalls && !result.thoughts) {\n // This case means absolutely nothing was parsed, not even thoughts.\n Logger.warn(`OutputParser: Complete failure to parse any structured data or thoughts from planning output: ${output}`);\n }\n\n\n return result;\n }\n\n /**\n /**\n * Parses the raw string output from the synthesis LLM call to extract the final, user-facing response content.\n * This default implementation simply trims whitespace from the input string.\n * More complex implementations could potentially remove specific tags or formatting if needed.\n * @param output - The raw string response from the synthesis LLM call.\n * @returns A promise resolving to the cleaned, final response string.\n */\n async parseSynthesisOutput(output: string): Promise<string> {\n // Basic implementation: return the trimmed output.\n // Future versions might parse more complex structures if needed.\n return output.trim();\n }\n}","// src/systems/ui/observation-socket.ts\nimport { TypedSocket } from './typed-socket';\nimport { Observation, ObservationType, ObservationFilter } from '@/types';\nimport { Logger } from '@/utils/logger';\nimport { IObservationRepository } from '@/core/interfaces'; // Assuming this exists\n\n/**\n * A specialized TypedSocket for handling Observation data.\n * Allows filtering by ObservationType.\n * Can optionally fetch historical observations from a repository.\n */\nexport class ObservationSocket extends TypedSocket<Observation, ObservationType | ObservationType[]> {\n private observationRepository?: IObservationRepository;\n\n constructor(observationRepository?: IObservationRepository) {\n super(); // No logger instance needed\n this.observationRepository = observationRepository;\n Logger.debug('ObservationSocket initialized.');\n }\n\n /**\n * Notifies subscribers about a new observation.\n * @param observation - The observation data.\n */\n notifyObservation(observation: Observation): void {\n Logger.debug(`Notifying Observation: ${observation.id} (${observation.type}) for thread ${observation.threadId}`);\n super.notify(\n observation,\n { targetThreadId: observation.threadId },\n (data, filter) => {\n if (!filter) return true; // No filter, always notify\n if (Array.isArray(filter)) {\n return filter.includes(data.type); // Check if type is in the array\n }\n return data.type === filter; // Check for single type match\n }\n );\n }\n\n /**\n * Retrieves historical observations, optionally filtered by type and thread.\n * Requires an ObservationRepository to be configured.\n * @param filter - Optional ObservationType or array of types to filter by.\n * @param options - Optional threadId and limit.\n * @returns A promise resolving to an array of observations.\n */\n async getHistory(\n filter?: ObservationType | ObservationType[],\n options?: { threadId?: string; limit?: number }\n ): Promise<Observation[]> {\n if (!this.observationRepository) {\n Logger.warn('Cannot getHistory for ObservationSocket: ObservationRepository not configured.');\n return [];\n }\n if (!options?.threadId) {\n Logger.warn('Cannot getHistory for ObservationSocket: threadId is required.');\n return [];\n }\n\n Logger.debug(`Getting history for ObservationSocket: Thread ${options.threadId}, Filter: ${JSON.stringify(filter)}, Limit: ${options.limit}`);\n\n // Construct the ObservationFilter for the repository method\n const observationFilter: ObservationFilter = {};\n\n if (filter) {\n observationFilter.types = Array.isArray(filter) ? filter : [filter];\n }\n // Note: The limit option is not part of the ObservationFilter type.\n // It's expected that the IObservationRepository implementation\n // will handle limiting when querying the underlying StorageAdapter,\n // potentially by accepting limit directly or translating from options.\n // Sorting is also handled by the repository implementation.\n if (options.limit !== undefined) {\n // We don't assign options.limit to observationFilter directly.\n // The getObservations implementation needs to handle the limit.\n Logger.debug(`Limit requested: ${options.limit}. Repository implementation must handle this.`);\n }\n\n\n try {\n // Call the correct repository method\n const observations = await this.observationRepository.getObservations(\n options.threadId,\n observationFilter\n );\n // The repository method likely returns observations in a standard order (e.g., chronological or reverse chronological).\n // Assuming reverse chronological (newest first) based on common usage.\n return observations;\n } catch (error) {\n Logger.error(`Error fetching observation history for thread ${options.threadId} with filter ${JSON.stringify(observationFilter)}:`, error);\n return [];\n }\n }\n}","// src/systems/ui/conversation-socket.ts\nimport { TypedSocket } from './typed-socket';\nimport { ConversationMessage, MessageRole } from '@/types';\nimport { Logger } from '@/utils/logger';\nimport { IConversationRepository } from '@/core/interfaces'; // Assuming this exists\n\n/**\n * A specialized TypedSocket for handling ConversationMessage data.\n * Allows filtering by MessageRole.\n * Can optionally fetch historical messages from a repository.\n */\nexport class ConversationSocket extends TypedSocket<ConversationMessage, MessageRole | MessageRole[]> {\n private conversationRepository?: IConversationRepository;\n\n constructor(conversationRepository?: IConversationRepository) {\n super(); // No logger instance needed\n this.conversationRepository = conversationRepository;\n Logger.debug('ConversationSocket initialized.');\n }\n\n /**\n * Notifies subscribers about a new conversation message.\n * @param message - The conversation message data.\n */\n notifyMessage(message: ConversationMessage): void {\n Logger.debug(`Notifying Message: ${message.messageId} (${message.role}) for thread ${message.threadId}`);\n super.notify(\n message,\n { targetThreadId: message.threadId },\n (data, filter) => {\n if (!filter) return true; // No filter, always notify\n if (Array.isArray(filter)) {\n return filter.includes(data.role); // Check if role is in the array\n }\n return data.role === filter; // Check for single role match\n }\n );\n }\n\n /**\n * Retrieves historical messages, optionally filtered by role and thread.\n * Requires a ConversationRepository to be configured.\n * @param filter - Optional MessageRole or array of roles to filter by.\n * @param options - Optional threadId and limit.\n * @returns A promise resolving to an array of messages.\n */\n async getHistory(\n filter?: MessageRole | MessageRole[],\n options?: { threadId?: string; limit?: number } // Add other MessageOptions if needed\n ): Promise<ConversationMessage[]> {\n if (!this.conversationRepository) {\n Logger.warn('Cannot getHistory for ConversationSocket: ConversationRepository not configured.');\n return [];\n }\n if (!options?.threadId) {\n Logger.warn('Cannot getHistory for ConversationSocket: threadId is required.');\n return [];\n }\n\n Logger.debug(`Getting history for ConversationSocket: Thread ${options.threadId}, Filter: ${JSON.stringify(filter)}, Limit: ${options.limit}`);\n\n // Construct the MessageOptions for the repository method\n // Note: The IConversationRepository.getMessages interface uses MessageOptions,\n // which currently only defines limit and timestamps. Filtering by role needs\n // to be handled either within the repository implementation or client-side after fetching.\n // For now, we pass limit and assume the repository handles it. Role filtering is omitted here.\n const messageOptions: { limit?: number } = {};\n if (options.limit !== undefined) {\n messageOptions.limit = options.limit;\n }\n\n // TODO: If role filtering is crucial, the IConversationRepository interface\n // and its implementations might need updating to support filtering by role.\n if (filter) {\n Logger.warn(`Role filtering requested for ConversationSocket.getHistory, but not directly supported by IConversationRepository.getMessages. Fetching all roles up to limit.`);\n }\n\n try {\n const messages = await this.conversationRepository.getMessages(\n options.threadId,\n messageOptions\n );\n // Messages are typically returned in chronological order (oldest first).\n return messages;\n } catch (error) {\n Logger.error(`Error fetching message history for thread ${options.threadId}:`, error);\n return [];\n }\n }\n}","// src/systems/ui/ui-system.ts\nimport {\n UISystem as IUISystem,\n IObservationRepository,\n IConversationRepository,\n IA2ATaskRepository\n} from '@/core/interfaces';\nimport { ObservationSocket } from './observation-socket';\nimport { ConversationSocket } from './conversation-socket';\nimport { LLMStreamSocket } from './llm-stream-socket'; // Import the new socket\nimport { A2ATaskSocket } from './a2a-task-socket';\nimport { Logger } from '@/utils/logger';\n\n/**\n * Provides access to the UI communication sockets (Observation, Conversation, LLM Stream, and A2A Task).\n * Instantiates the sockets with their required dependencies.\n */\nexport class UISystem implements IUISystem {\n private observationSocketInstance: ObservationSocket;\n private conversationSocketInstance: ConversationSocket;\n private llmStreamSocketInstance: LLMStreamSocket; // Add the new socket instance\n private a2aTaskSocketInstance: A2ATaskSocket;\n\n /**\n * Creates an instance of UISystem.\n * @param observationRepository - Repository for observation data, passed to ObservationSocket.\n * @param conversationRepository - Repository for conversation data, passed to ConversationSocket.\n * @param a2aTaskRepository - Optional repository for A2A task data, passed to A2ATaskSocket.\n */\n constructor(\n observationRepository: IObservationRepository,\n conversationRepository: IConversationRepository,\n a2aTaskRepository?: IA2ATaskRepository\n ) {\n this.observationSocketInstance = new ObservationSocket(observationRepository);\n this.conversationSocketInstance = new ConversationSocket(conversationRepository);\n this.llmStreamSocketInstance = new LLMStreamSocket(); // Instantiate the new socket\n this.a2aTaskSocketInstance = new A2ATaskSocket(a2aTaskRepository);\n Logger.debug('UISystem initialized with Observation, Conversation, LLM Stream, and A2A Task sockets.');\n }\n\n /**\n * Gets the singleton instance of the ObservationSocket.\n * @returns The ObservationSocket instance.\n */\n getObservationSocket(): ObservationSocket {\n return this.observationSocketInstance;\n }\n\n /**\n * Gets the singleton instance of the ConversationSocket.\n * @returns The ConversationSocket instance.\n */\n getConversationSocket(): ConversationSocket {\n return this.conversationSocketInstance;\n }\n\n /**\n * Gets the singleton instance of the LLMStreamSocket.\n * @returns The LLMStreamSocket instance.\n */\n getLLMStreamSocket(): LLMStreamSocket {\n return this.llmStreamSocketInstance;\n }\n\n /**\n * Gets the singleton instance of the A2ATaskSocket.\n * @returns The A2ATaskSocket instance.\n */\n getA2ATaskSocket(): A2ATaskSocket {\n return this.a2aTaskSocketInstance;\n }\n}","import { IAuthStrategy } from '@/core/interfaces';\nimport { ARTError, ErrorCode } from '@/errors';\nimport { Logger } from '@/utils/logger';\n\n/**\n * Central authentication manager for handling multiple authentication strategies.\n * Manages registration and retrieval of different auth strategies for secure connections\n * to remote services like MCP servers and A2A agents.\n */\nexport class AuthManager {\n private strategies = new Map<string, IAuthStrategy>();\n\n constructor() {\n Logger.info('AuthManager initialized.');\n }\n\n /**\n * Registers an authentication strategy with the given ID.\n * @param strategyId - Unique identifier for the strategy (e.g., 'default_zyntopia_auth', 'api_key_strategy')\n * @param strategy - Implementation of IAuthStrategy\n * @throws {ARTError} If strategyId is empty or null\n */\n public registerStrategy(strategyId: string, strategy: IAuthStrategy): void {\n if (!strategyId || strategyId.trim() === '') {\n throw new ARTError('Strategy ID cannot be empty or null', ErrorCode.INVALID_CONFIG);\n }\n\n if (this.strategies.has(strategyId)) {\n Logger.warn(`AuthManager: Overwriting existing auth strategy with ID: ${strategyId}`);\n }\n \n this.strategies.set(strategyId, strategy);\n Logger.debug(`AuthManager: Registered strategy '${strategyId}'.`);\n }\n\n /**\n * Retrieves authentication headers from the specified strategy.\n * @param strategyId - The ID of the registered strategy to use\n * @returns Promise resolving to authentication headers\n * @throws {ARTError} If strategy is not found or authentication fails\n */\n public async getHeaders(strategyId: string): Promise<Record<string, string>> {\n const strategy = this.strategies.get(strategyId);\n if (!strategy) {\n // Convention: If a Zyntopia-related auth is needed but not found, guide the developer.\n if (strategyId.includes('zyntopia')) {\n Logger.error(`AuthManager: Strategy '${strategyId}' not found. Did you register a ZyntopiaOAuthStrategy with the ID 'default_zyntopia_auth'?`);\n }\n throw new ARTError(`Authentication strategy with ID '${strategyId}' not found.`, ErrorCode.INVALID_CONFIG);\n }\n\n try {\n return await strategy.getAuthHeaders();\n } catch (error) {\n const message = `Failed to get authentication headers from strategy '${strategyId}'`;\n Logger.error(message, error);\n throw new ARTError(message, ErrorCode.LLM_PROVIDER_ERROR, error instanceof Error ? error : new Error(String(error)));\n }\n }\n\n /**\n * Checks if a strategy with the given ID is registered.\n * @param strategyId - The ID to check\n * @returns True if the strategy exists, false otherwise\n */\n public hasStrategy(strategyId: string): boolean {\n return this.strategies.has(strategyId);\n }\n\n /**\n * Lists all registered strategy IDs.\n * @returns Array of registered strategy IDs\n */\n public getRegisteredStrategyIds(): string[] {\n return Array.from(this.strategies.keys());\n }\n\n /**\n * Removes a registered strategy.\n * @param strategyId - The ID of the strategy to remove\n * @returns True if strategy was removed, false if it didn't exist\n */\n public removeStrategy(strategyId: string): boolean {\n const removed = this.strategies.delete(strategyId);\n if (removed) {\n Logger.debug(`AuthManager: Removed strategy '${strategyId}'.`);\n }\n return removed;\n }\n\n /**\n * Clears all registered strategies.\n * Useful for testing or complete reconfiguration.\n */\n public clearAllStrategies(): void {\n const count = this.strategies.size;\n this.strategies.clear();\n Logger.debug(`AuthManager: Cleared ${count} strategies.`);\n }\n\n /**\n * Initiates the login flow for a specific strategy.\n * @param {string} strategyId - The ID of the strategy to use for login.\n * @returns {Promise<void>} A promise that resolves when the login process is initiated.\n * @throws {ARTError} If the strategy is not found or does not support login.\n */\n public async login(strategyId: string): Promise<void> {\n const strategy = this.strategies.get(strategyId);\n if (!strategy || !strategy.login) {\n throw new ARTError(`Login not supported for strategy '${strategyId}'.`, ErrorCode.INVALID_CONFIG);\n }\n await strategy.login();\n }\n\n /**\n * Handles the redirect from an OAuth provider.\n * @param {string} strategyId - The ID of the strategy that initiated the redirect.\n * @returns {Promise<void>} A promise that resolves when the redirect has been handled.\n * @throws {ARTError} If the strategy is not found or does not support handling redirects.\n */\n public async handleRedirect(strategyId: string): Promise<void> {\n const strategy = this.strategies.get(strategyId);\n if (!strategy || !strategy.handleRedirect) {\n throw new ARTError(`handleRedirect not supported for strategy '${strategyId}'.`, ErrorCode.INVALID_CONFIG);\n }\n await strategy.handleRedirect();\n }\n\n /**\n * Logs the user out of a specific strategy.\n * @param {string} strategyId - The ID of the strategy to use for logout.\n * @throws {ARTError} If the strategy is not found or does not support logout.\n */\n public logout(strategyId: string): void {\n const strategy = this.strategies.get(strategyId);\n if (!strategy || !strategy.logout) {\n throw new ARTError(`Logout not supported for strategy '${strategyId}'.`, ErrorCode.INVALID_CONFIG);\n }\n strategy.logout();\n }\n\n /**\n * Checks if the user is authenticated with a specific strategy.\n * @param {string} strategyId - The ID of the strategy to check.\n * @returns {Promise<boolean>} A promise that resolves to true if authenticated, false otherwise.\n */\n public async isAuthenticated(strategyId: string): Promise<boolean> {\n const strategy = this.strategies.get(strategyId);\n if (!strategy || !strategy.isAuthenticated) {\n return false;\n }\n return await strategy.isAuthenticated();\n }\n}","import { IToolExecutor } from '@/core/interfaces';\nimport { ToolSchema, ToolResult, ExecutionContext } from '@/types';\nimport { Logger } from '@/utils/logger';\nimport { McpManager } from './McpManager';\nimport { McpServerConfig, McpToolDefinition } from './types';\nimport { CallToolResultSchema } from '@modelcontextprotocol/sdk/types.js';\n\n/**\n * A proxy tool that wraps an MCP server tool and implements the {@link IToolExecutor} interface.\n *\n * @remarks\n * This allows MCP server tools to be used seamlessly within the ART Framework.\n *\n * @see {@link McpManager} for the system that manages these proxy tools.\n * @see {@link IToolExecutor} for the interface it implements.\n *\n * @class McpProxyTool\n */\nexport class McpProxyTool implements IToolExecutor {\n public readonly schema: ToolSchema;\n \n private card: McpServerConfig;\n private toolDefinition: McpToolDefinition;\n private mcpManager: McpManager;\n\n /**\n * Creates an instance of McpProxyTool.\n *\n * @param card Configuration for the MCP server hosting this tool.\n * @param toolDefinition The tool definition from the MCP server.\n * @param mcpManager The MCP manager for managing connections.\n */\n constructor(card: McpServerConfig, toolDefinition: McpToolDefinition, mcpManager: McpManager) {\n this.card = card;\n this.toolDefinition = toolDefinition;\n this.mcpManager = mcpManager;\n\n // Convert MCP tool definition to ART ToolSchema\n this.schema = {\n name: `mcp_${card.id}_${toolDefinition.name}`,\n description: toolDefinition.description || `Tool ${toolDefinition.name} from ${card.displayName || card.id}`,\n inputSchema: toolDefinition.inputSchema,\n outputSchema: toolDefinition.outputSchema\n };\n\n Logger.debug(`McpProxyTool: Created proxy for tool \"${toolDefinition.name}\" from server \"${card.displayName}\"`);\n }\n\n /**\n * Executes the tool by making a request to the MCP server.\n *\n * @param input Validated input arguments for the tool.\n * @param context Execution context containing threadId, traceId, etc.\n * @returns A promise resolving to the tool result.\n */\n async execute(input: any, context: ExecutionContext): Promise<ToolResult> {\n const startTime = Date.now();\n \n try {\n Logger.debug(`McpProxyTool: Execution requested for \"${this.schema.name}\". Getting or creating connection...`);\n const client = await this.mcpManager.getOrCreateConnection(this.card.id);\n\n Logger.debug(`McpProxyTool: Connection ready. Executing tool \"${this.toolDefinition.name}\" on server \"${this.card.displayName}\"`);\n const response = await client.callTool(this.toolDefinition.name, input);\n \n const duration = Date.now() - startTime;\n \n // Validate the raw response against the SDK's schema for robustness.\n // If validation fails, it will throw an error that is caught below.\n const validatedResponse = CallToolResultSchema.parse(response);\n \n // Adapt the response to the ToolResult format\n // This is a generic adaptation, specific tools might require more tailored logic\n // based on the shape of their response.\n const output = typeof validatedResponse === 'object' && validatedResponse !== null ? validatedResponse : { value: validatedResponse };\n\n return {\n callId: context.traceId || 'unknown',\n toolName: this.schema.name,\n status: 'success',\n output: [output], // Assuming the output should be wrapped in an array\n metadata: { \n executionTime: duration, \n mcpServer: { id: this.card.id, name: this.card.displayName },\n rawResponse: response \n }\n };\n } catch (error: any) {\n const duration = Date.now() - startTime;\n Logger.error(`McpProxyTool: Failed to execute tool \"${this.toolDefinition.name}\": ${error.message}`);\n return {\n callId: context.traceId || 'unknown',\n toolName: this.schema.name,\n status: 'error',\n error: `MCP execution failed: ${error.message}`,\n metadata: { executionTime: duration, mcpServer: { id: this.card.id, name: this.card.displayName }, originalError: error instanceof Error ? error.stack : String(error) }\n };\n }\n }\n\n /**\n * Gets the original tool name from the MCP server.\n *\n * @returns The original tool name.\n */\n getOriginalToolName(): string {\n return this.toolDefinition.name;\n }\n\n /**\n * Gets the MCP server configuration.\n *\n * @returns The server configuration.\n */\n getServerConfig(): McpServerConfig {\n return { ...this.card };\n }\n\n /**\n * Gets the MCP tool definition.\n *\n * @returns The tool definition.\n */\n getToolDefinition(): McpToolDefinition {\n return { ...this.toolDefinition };\n }\n} ","import { Logger } from '@/utils/logger';\nimport { ArtMcpConfig, McpServerConfig } from './types';\n\n/**\n * Manages the MCP configuration, handling loading, validation, and saving to localStorage.\n * It ensures that the MCP connection details are always available and well-formed.\n */\nexport class ConfigManager {\n private configKey = 'art_mcp_config';\n private config: ArtMcpConfig;\n\n /**\n * Initializes the ConfigManager by loading the configuration from localStorage.\n */\n constructor() {\n this.config = this.loadConfig();\n }\n\n /**\n * Loads the MCP configuration from localStorage, creating a default if none exists.\n * @private\n * @returns {ArtMcpConfig} The loaded or created MCP configuration.\n */\n private loadConfig(): ArtMcpConfig {\n try {\n const storedConfig = localStorage.getItem(this.configKey);\n if (storedConfig) {\n const rawConfig = JSON.parse(storedConfig) as ArtMcpConfig;\n const validatedConfig = this.validateAndFixConfig(rawConfig);\n \n // If config was fixed, save it back\n if (JSON.stringify(validatedConfig) !== JSON.stringify(rawConfig)) {\n Logger.info(`ConfigManager: Config was automatically validated and fixed`);\n this.writeConfig(validatedConfig);\n }\n return validatedConfig;\n }\n } catch (error: any) {\n Logger.error(`ConfigManager: Error reading or parsing config from localStorage: ${error.message}`);\n }\n \n Logger.info(`ConfigManager: Configuration not found in localStorage. Creating a new default config.`);\n const defaultConfig = this.createDefaultConfig();\n this.writeConfig(defaultConfig);\n return defaultConfig;\n }\n\n /**\n * Validates the loaded configuration and fixes any inconsistencies.\n * @private\n * @param {ArtMcpConfig} config - The configuration to validate.\n * @returns {ArtMcpConfig} The validated and fixed configuration.\n */\n private validateAndFixConfig(config: ArtMcpConfig): ArtMcpConfig {\n const cleanConfig: ArtMcpConfig = {\n mcpServers: {}\n };\n\n // Process each server entry\n for (const [serverId, serverConfig] of Object.entries(config.mcpServers)) {\n // Skip corrupted entries\n if (serverId === '[object Object]' || typeof serverConfig !== 'object' || !serverConfig) {\n Logger.warn(`ConfigManager: Removing corrupted entry: \"${serverId}\"`);\n continue;\n }\n\n // Ensure the server config has all required fields\n const fixedConfig: McpServerConfig = {\n id: serverConfig.id || serverId,\n type: serverConfig.type || 'streamable-http',\n enabled: serverConfig.enabled !== false, // Default to true\n displayName: serverConfig.displayName || serverId,\n description: serverConfig.description || `MCP server: ${serverId}`,\n connection: serverConfig.connection,\n installation: serverConfig.installation,\n timeout: serverConfig.timeout || 30000,\n tools: serverConfig.tools || [], // Add missing tools array\n resources: serverConfig.resources || [], // Add missing resources array\n resourceTemplates: serverConfig.resourceTemplates || [] // Add missing resourceTemplates array\n };\n\n // For Tavily specifically, ensure it has the proper tools definition\n if (serverId === 'tavily_search_stdio' && (!fixedConfig.tools || fixedConfig.tools.length === 0)) {\n fixedConfig.tools = [\n {\n name: 'tavily-search',\n description: 'A powerful web search tool that provides comprehensive, real-time results using Tavily\\'s AI search engine.',\n inputSchema: {\n type: 'object',\n properties: {\n query: { type: 'string', description: 'Search query' },\n search_depth: { type: 'string', enum: ['basic', 'advanced'], description: 'The depth of the search. It can be \\'basic\\' or \\'advanced\\'', default: 'basic' },\n topic: { type: 'string', enum: ['general', 'news'], description: 'The category of the search', default: 'general' },\n max_results: { type: 'number', description: 'The maximum number of search results to return', default: 10, minimum: 5, maximum: 20 },\n include_raw_content: { type: 'boolean', description: 'Include the cleaned and parsed HTML content of each search result', default: false }\n },\n required: ['query']\n }\n },\n {\n name: 'tavily-extract',\n description: 'A powerful web content extraction tool that retrieves and processes raw content from specified URLs.',\n inputSchema: {\n type: 'object',\n properties: {\n urls: { type: 'array', items: { type: 'string' }, description: 'List of URLs to extract content from' },\n extract_depth: { type: 'string', enum: ['basic', 'advanced'], description: 'Depth of extraction - \\'basic\\' or \\'advanced\\'', default: 'basic' },\n include_images: { type: 'boolean', description: 'Include a list of images extracted from the urls in the response', default: false }\n },\n required: ['urls']\n }\n }\n ];\n Logger.info(`ConfigManager: Added tools definition for Tavily server`);\n }\n\n cleanConfig.mcpServers[serverId] = fixedConfig;\n }\n\n return cleanConfig;\n }\n\n /**\n * Creates a default MCP configuration.\n * @private\n * @returns {ArtMcpConfig} The default MCP configuration.\n */\n private createDefaultConfig(): ArtMcpConfig {\n // Default to a remote, streamable-http Tavily server\n const tavilyCard: McpServerConfig = {\n id: \"tavily_search_remote\",\n type: \"streamable-http\",\n enabled: true,\n displayName: \"Tavily Search (Remote)\",\n description: \"Provides AI-powered search and web content extraction tools via a remote server.\",\n connection: {\n url: \"https://mcp.tavily.com/v1/stream\", // This is a placeholder URL\n authStrategyId: \"tavily_api_key\" // Assumes an ApiKeyStrategy is configured\n },\n tools: [\n {\n name: \"tavily-search\",\n description: \"A powerful web search tool...\",\n inputSchema: { /* ... schema ... */ }\n },\n {\n name: \"tavily-extract\",\n description: \"A powerful web content extraction tool...\",\n inputSchema: { /* ... schema ... */ }\n }\n ],\n resources: [],\n resourceTemplates: []\n };\n return { mcpServers: { \"tavily_search_remote\": tavilyCard } };\n }\n\n /**\n * Writes the MCP configuration to localStorage.\n * @private\n * @param {ArtMcpConfig} config - The configuration to write.\n */\n private writeConfig(config: ArtMcpConfig): void {\n try {\n localStorage.setItem(this.configKey, JSON.stringify(config, null, 2));\n Logger.debug(`ConfigManager: Configuration saved to localStorage.`);\n } catch (error: any) {\n Logger.error(`ConfigManager: Failed to write to localStorage: ${error.message}`);\n // Don't throw in browser context, as it could break the app\n }\n }\n\n /**\n * Gets the current MCP configuration.\n * @returns {ArtMcpConfig} The current MCP configuration.\n */\n public getConfig(): ArtMcpConfig {\n return this.config;\n }\n\n /**\n * Sets the configuration for a specific server and saves it.\n * @param {string} serverId - The ID of the server to configure.\n * @param {McpServerConfig} serverConfig - The configuration for the server.\n */\n public setServerConfig(serverId: string, serverConfig: McpServerConfig): void {\n this.config.mcpServers[serverId] = serverConfig;\n this.writeConfig(this.config);\n Logger.info(`ConfigManager: Updated configuration for server \"${serverId}\"`);\n }\n\n /**\n * Removes the configuration for a specific server and saves the changes.\n * @param {string} serverId - The ID of the server to remove.\n */\n public removeServerConfig(serverId: string): void {\n if (this.config.mcpServers[serverId]) {\n delete this.config.mcpServers[serverId];\n this.writeConfig(this.config);\n Logger.info(`ConfigManager: Removed configuration for server \"${serverId}\"`);\n } else {\n Logger.warn(`ConfigManager: Attempted to remove non-existent server config \"${serverId}\"`);\n }\n }\n} ","// Lazy import to avoid SSR/bundling path issues if SDK evolves\nimport { Client } from '@modelcontextprotocol/sdk/client/index.js'\nimport { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'\nimport { Logger } from '@/utils/logger';\nimport { ARTError, ErrorCode } from '@/errors';\n\n/**\n * @function base64UrlEncode\n * Encodes a buffer into a Base64URL string.\n * @param {Uint8Array} buffer - The buffer to encode.\n * @returns {string} The Base64URL encoded string.\n */\nfunction base64UrlEncode(buffer: Uint8Array): string {\n let s = ''\n for (let i = 0; i < buffer.length; i++) s += String.fromCharCode(buffer[i])\n return btoa(s).replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_')\n}\n\n/**\n * @function sha256Base64Url\n * Hashes a string using SHA-256 and encodes it as Base64URL.\n * @param {string} input - The string to hash.\n * @returns {Promise<string>} A promise that resolves to the Base64URL encoded hash.\n */\nasync function sha256Base64Url(input: string): Promise<string> {\n const data = new TextEncoder().encode(input)\n const digest = await crypto.subtle.digest('SHA-256', data)\n return base64UrlEncode(new Uint8Array(digest))\n}\n\n/**\n * @function generateRandomString\n * Generates a random string of a given length.\n * @param {number} [length=64] - The length of the string to generate.\n * @returns {string} The generated random string.\n */\nfunction generateRandomString(length = 64): string {\n const array = new Uint8Array(length)\n crypto.getRandomValues(array)\n return Array.from(array, (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\n/**\n * @class TokenManager\n * Manages OAuth tokens, including loading, updating, clearing, and refreshing them.\n */\nexport class TokenManager {\n private accessToken: string | null = null\n private refreshToken: string | null = null\n private expiresAt: number | null = null\n private clientId: string | null = null\n constructor(private oauthConfig: { token_endpoint?: string }) {}\n\n /**\n * Loads tokens from session storage.\n */\n load() {\n this.accessToken = sessionStorage.getItem('access_token')\n this.refreshToken = sessionStorage.getItem('refresh_token')\n const exp = sessionStorage.getItem('token_expires_at')\n if (exp) this.expiresAt = parseInt(exp, 10)\n this.clientId = localStorage.getItem('mcp_client_id')\n }\n\n /**\n * Sets the client ID.\n * @param {string} id - The client ID.\n */\n setClientId(id: string) { this.clientId = id }\n\n /**\n * Updates the tokens and stores them in session storage.\n * @param {any} token - The token object.\n */\n update(token: any) {\n this.accessToken = token.access_token\n if (token.refresh_token) this.refreshToken = token.refresh_token\n if (token.expires_in) this.expiresAt = Date.now() + token.expires_in * 1000\n sessionStorage.setItem('access_token', this.accessToken || '')\n if (this.refreshToken) sessionStorage.setItem('refresh_token', this.refreshToken)\n if (this.expiresAt) sessionStorage.setItem('token_expires_at', String(this.expiresAt))\n }\n\n /**\n * Clears the tokens from memory and session storage.\n */\n clear() {\n this.accessToken = null\n this.refreshToken = null\n this.expiresAt = null\n sessionStorage.removeItem('access_token')\n sessionStorage.removeItem('refresh_token')\n sessionStorage.removeItem('token_expires_at')\n }\n\n /**\n * Gets the access token.\n * @returns {string | null} The access token.\n */\n getAccessToken() { return this.accessToken }\n\n /**\n * Checks if the token needs to be refreshed.\n * @returns {boolean} True if the token needs to be refreshed, false otherwise.\n */\n needsRefresh(): boolean {\n if (!this.expiresAt) return false\n return Date.now() >= this.expiresAt - 5 * 60 * 1000\n }\n\n /**\n * Refreshes the access token using the refresh token.\n * @returns {Promise<void>}\n */\n async refresh(): Promise<void> {\n if (!this.refreshToken) throw new Error('No refresh token available')\n if (!this.oauthConfig.token_endpoint) throw new Error('Missing token endpoint')\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: this.refreshToken,\n })\n if (this.clientId) body.set('client_id', this.clientId)\n const res = await fetch(this.oauthConfig.token_endpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body,\n })\n if (!res.ok) {\n this.clear()\n throw new Error('Token refresh failed')\n }\n const token = await res.json()\n this.update(token)\n }\n\n /**\n * Checks if the user is authenticated.\n * @returns {boolean} True if the user is authenticated, false otherwise.\n */\n isAuthenticated(): boolean {\n return !!this.accessToken && (this.expiresAt ? this.expiresAt > Date.now() : true)\n }\n}\n\n/**\n * @class McpClientController\n * Controls the MCP client, including OAuth flow, connection, and tool calls.\n */\nexport class McpClientController {\n public baseUrl: URL\n private scopes: string[]\n private client: Client | null = null\n private transport: StreamableHTTPClientTransport | null = null\n private oauthDiscovery: any = null\n private tokenManager: TokenManager | null = null\n private sessionId: string | null = null\n private readonly protocolVersion: string = '2025-06-18'\n\n /**\n * Creates an instance of McpClientController.\n * @private\n * @param {string} baseUrl - The base URL of the MCP server.\n * @param {string[]} [scopes] - The OAuth scopes to request.\n */\n private constructor(baseUrl: string, scopes?: string[]) {\n this.baseUrl = new URL(baseUrl)\n this.scopes = scopes ?? ['read', 'write']\n }\n\n /**\n * Creates a new instance of McpClientController.\n * @param {string} baseUrl - The base URL of the MCP server.\n * @param {string[]} [scopes] - The OAuth scopes to request.\n * @returns {McpClientController} A new instance of McpClientController.\n */\n static create(baseUrl: string, scopes?: string[]): McpClientController {\n return new McpClientController(baseUrl, scopes)\n }\n\n /**\n * Discovers the authorization server metadata.\n * @private\n * @returns {Promise<void>}\n */\n private async discoverAuthorizationServer(): Promise<void> {\n if (this.oauthDiscovery) return\n\n // HACK: Bypassing full discovery flow to avoid WWW-Authenticate CORS issues.\n // This assumes the MCP server itself hosts the AS metadata endpoint.\n const asMetadataUrl = new URL('/.well-known/oauth-authorization-server', this.baseUrl).toString()\n const asMetadataRes = await fetch(asMetadataUrl)\n if (!asMetadataRes.ok) throw new ARTError(`Failed to fetch authorization server metadata from ${asMetadataUrl}`, ErrorCode.NETWORK_ERROR)\n this.oauthDiscovery = await asMetadataRes.json()\n sessionStorage.setItem('mcp_oauth_discovery', JSON.stringify(this.oauthDiscovery))\n\n /*\n const probeRes = await fetch(this.baseUrl.toString(), { method: 'GET' })\n\n if (probeRes.status !== 401) {\n throw new Error('MCP server did not respond with 401 Unauthorized. Cannot discover authorization server.')\n }\n\n const wwwAuthHeader = probeRes.headers.get('WWW-Authenticate')\n if (!wwwAuthHeader) throw new Error('Missing WWW-Authenticate header in 401 response')\n\n const metadataUrlMatch = /resource_metadata=\"([^\"]+)\"/.exec(wwwAuthHeader)\n if (!metadataUrlMatch) throw new Error('Could not find resource_metadata in WWW-Authenticate header')\n\n const resourceMetadataUrl = metadataUrlMatch[1]\n const resourceMetadataRes = await fetch(resourceMetadataUrl)\n if (!resourceMetadataRes.ok) throw new Error('Failed to fetch resource metadata')\n const resourceMetadata = await resourceMetadataRes.json()\n\n if (!resourceMetadata.authorization_servers || resourceMetadata.authorization_servers.length === 0) {\n throw new Error('No authorization_servers found in resource metadata')\n }\n\n const authorizationServerUrl = resourceMetadata.authorization_servers[0]\n const asMetadataUrl = new URL('/.well-known/oauth-authorization-server', authorizationServerUrl).toString()\n\n const asMetadataRes = await fetch(asMetadataUrl)\n if (!asMetadataRes.ok) throw new Error('Failed to fetch authorization server metadata')\n this.oauthDiscovery = await asMetadataRes.json()\n sessionStorage.setItem('mcp_oauth_discovery', JSON.stringify(this.oauthDiscovery))\n */\n }\n\n /**\n * Registers the client with the authorization server.\n * @private\n * @returns {Promise<string>} A promise that resolves to the client ID.\n */\n private async registerClient(): Promise<string> {\n if (!this.oauthDiscovery?.registration_endpoint) {\n // Assume pre-registered public client if dynamic registration not available\n const existing = localStorage.getItem('mcp_client_id')\n if (existing) return existing\n const randomId = 'public-' + generateRandomString(16)\n localStorage.setItem('mcp_client_id', randomId)\n return randomId\n }\n const body = {\n client_name: 'MCP Browser Demo',\n redirect_uris: [location.origin + '/callback'],\n grant_types: ['authorization_code', 'refresh_token'],\n response_types: ['code'],\n token_endpoint_auth_method: 'none',\n application_type: 'web',\n }\n const res = await fetch(this.oauthDiscovery.registration_endpoint, {\n method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),\n })\n if (!res.ok) throw new ARTError('Client registration failed', ErrorCode.EXTERNAL_SERVICE_ERROR)\n const data = await res.json()\n localStorage.setItem('mcp_client_id', data.client_id)\n return data.client_id\n }\n\n /**\n * Starts the OAuth flow by redirecting the user to the authorization server.\n * @returns {Promise<void>}\n */\n async startOAuth() {\n await this.discoverAuthorizationServer()\n if (!this.oauthDiscovery) throw new ARTError('Could not discover OAuth server details.', ErrorCode.INVALID_CONFIG)\n const clientId = await this.registerClient()\n const codeVerifier = base64UrlEncode(crypto.getRandomValues(new Uint8Array(64)))\n const codeChallenge = await sha256Base64Url(codeVerifier)\n sessionStorage.setItem('code_verifier', codeVerifier)\n const state = generateRandomString(16)\n sessionStorage.setItem('state', state)\n const authUrl = new URL(this.oauthDiscovery.authorization_endpoint)\n authUrl.searchParams.set('response_type', 'code')\n authUrl.searchParams.set('client_id', clientId)\n authUrl.searchParams.set('redirect_uri', location.origin + '/callback')\n authUrl.searchParams.set('scope', this.scopes.join(' '))\n authUrl.searchParams.set('code_challenge', codeChallenge)\n authUrl.searchParams.set('code_challenge_method', 'S256')\n authUrl.searchParams.set('state', state)\n authUrl.searchParams.set('resource', this.baseUrl.toString().replace(/\\/$/, ''))\n window.location.href = authUrl.toString()\n }\n\n /**\n * Handles the OAuth callback, exchanging the authorization code for an access token.\n * @returns {Promise<boolean>} A promise that resolves to true if the callback was handled, false otherwise.\n */\n async maybeHandleCallback(): Promise<boolean> {\n const url = new URL(window.location.href)\n const isCallback = url.pathname === '/callback' && (url.searchParams.get('code') || url.searchParams.get('error'))\n if (!isCallback) return false\n\n // Load discovery doc from session storage, assuming it was stored during startOAuth\n const discoveryDoc = sessionStorage.getItem('mcp_oauth_discovery')\n if (discoveryDoc) this.oauthDiscovery = JSON.parse(discoveryDoc)\n else await this.discoverAuthorizationServer() // Fallback just in case\n\n if (!this.oauthDiscovery) throw new ARTError('Could not determine OAuth server details for callback.', ErrorCode.INVALID_CONFIG)\n\n const code = url.searchParams.get('code')\n const state = url.searchParams.get('state')\n if (!code) throw new ARTError('Authorization code missing', ErrorCode.VALIDATION_ERROR)\n if (state !== sessionStorage.getItem('state')) throw new ARTError('State mismatch', ErrorCode.VALIDATION_ERROR)\n const clientId = localStorage.getItem('mcp_client_id') || (await this.registerClient())\n const codeVerifier = sessionStorage.getItem('code_verifier') || ''\n const body = new URLSearchParams({\n grant_type: 'authorization_code',\n code,\n code_verifier: codeVerifier,\n redirect_uri: location.origin + '/callback',\n client_id: clientId,\n })\n body.set('resource', this.baseUrl.toString().replace(/\\/$/, ''))\n\n const res = await fetch(this.oauthDiscovery.token_endpoint, {\n method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body,\n })\n if (!res.ok) {\n const err = await res.json().catch(() => ({}))\n throw new ARTError('Token exchange failed: ' + (err.error_description || err.error || res.status), ErrorCode.EXTERNAL_SERVICE_ERROR)\n }\n const token = await res.json()\n this.tokenManager = new TokenManager(this.oauthDiscovery)\n this.tokenManager.setClientId(clientId)\n this.tokenManager.update(token)\n sessionStorage.removeItem('code_verifier')\n sessionStorage.removeItem('state')\n history.replaceState({}, '', '/')\n return true\n }\n\n /**\n * Loads an existing session from session storage.\n */\n loadExistingSession() {\n const discoveryDoc = sessionStorage.getItem('mcp_oauth_discovery')\n if (discoveryDoc) this.oauthDiscovery = JSON.parse(discoveryDoc)\n this.tokenManager = new TokenManager(this.oauthDiscovery || {})\n this.tokenManager.load()\n this.sessionId = sessionStorage.getItem('mcp_session_id')\n }\n\n /**\n * Checks if the user is authenticated.\n * @returns {boolean} True if the user is authenticated, false otherwise.\n */\n isAuthenticated(): boolean {\n if (!this.tokenManager) return false\n return this.tokenManager.isAuthenticated()\n }\n\n /**\n * Connects to the MCP server.\n * @returns {Promise<void>}\n */\n async connect(): Promise<void> {\n if (!this.client) {\n const customFetch = async (url: RequestInfo | URL, options?: RequestInit): Promise<Response> => {\n this.tokenManager?.load()\n if (this.tokenManager?.needsRefresh()) {\n await this.tokenManager.refresh().catch((err) => {\n Logger.error('Token refresh failed:', err);\n // Optionally, trigger a full re-authentication flow\n })\n }\n\n const headers = new Headers(options?.headers)\n headers.set('Authorization', `Bearer ${this.tokenManager?.getAccessToken() || ''}`)\n headers.set('Accept', 'application/json, text/event-stream')\n headers.set('MCP-Protocol-Version', this.protocolVersion)\n if (this.sessionId) {\n headers.set('Mcp-Session-Id', this.sessionId)\n }\n\n const newOptions: RequestInit = { ...options, headers }\n const response = await fetch(url, newOptions)\n\n const sessionIdHeader = response.headers.get('Mcp-Session-Id')\n if (sessionIdHeader) {\n this.sessionId = sessionIdHeader\n sessionStorage.setItem('mcp_session_id', sessionIdHeader)\n }\n return response\n }\n\n this.transport = new StreamableHTTPClientTransport(this.baseUrl, { fetch: customFetch })\n this.client = new Client({ name: 'mcp-browser-demo', version: '1.0.0' })\n await this.client.connect(this.transport)\n }\n }\n\n /**\n * Ensures that the client is connected to the MCP server.\n * @returns {Promise<void>}\n */\n async ensureConnected(): Promise<void> {\n if (!this.client) await this.connect()\n }\n\n /**\n * Lists the available tools on the MCP server.\n * @returns {Promise<{ name: string; description?: string }[]>} A promise that resolves to a list of tools.\n */\n async listTools(): Promise<{ name: string; description?: string }[]> {\n if (!this.client) throw new ARTError('Not connected', ErrorCode.NOT_CONNECTED)\n const res = await this.client.listTools()\n return res.tools?.map((t: any) => ({ name: t.name, description: t.description })) ?? []\n }\n\n /**\n * Calls a tool on the MCP server.\n * @param {string} name - The name of the tool to call.\n * @param {any} args - The arguments to pass to the tool.\n * @returns {Promise<any>} A promise that resolves to the result of the tool call.\n */\n async callTool(name: string, args: any): Promise<any> {\n if (!this.client) throw new ARTError('Not connected', ErrorCode.NOT_CONNECTED)\n try {\n const result = await this.client.callTool({ name, arguments: args })\n return result\n } catch (e: any) {\n // Retry once if unauthorized and refresh is possible\n if (String(e?.message || '').includes('401') && this.tokenManager) {\n await this.tokenManager.refresh().catch((err) => {\n Logger.error('Token refresh failed during tool call:', err);\n throw e; // Re-throw original error if refresh fails\n })\n const result = await this.client.callTool({ name, arguments: args })\n return result\n }\n throw e\n }\n }\n\n /**\n * Logs out from the MCP server and clears the session.\n * @returns {Promise<void>}\n */\n async logout(): Promise<void> {\n try {\n if (this.transport) {\n const headers: Record<string, string> = {}\n const token = this.tokenManager?.getAccessToken()\n if (token) headers['Authorization'] = `Bearer ${token}`\n if (this.sessionId) headers['Mcp-Session-Id'] = this.sessionId\n await fetch(this.baseUrl.toString(), { method: 'DELETE', headers }).catch(() => {})\n }\n } finally {\n this.client = null\n this.transport = null\n this.tokenManager?.clear()\n this.sessionId = null\n sessionStorage.removeItem('mcp_session_id')\n sessionStorage.removeItem('mcp_oauth_discovery')\n }\n }\n}\n","import { ToolRegistry, StateManager } from '@/core/interfaces';\nimport { ARTError, ErrorCode } from '@/errors';\nimport { Logger } from '@/utils/logger';\nimport { AuthManager } from '../auth/AuthManager';\nimport { McpProxyTool } from './McpProxyTool';\nimport { ConfigManager } from './ConfigManager';\nimport { McpServerConfig, StreamableHttpConnection } from './types';\nimport { McpClientController } from './McpClient';\nimport { hasInstall, install, getAllowedInfo, requestHosts, getInstallUrl } from 'art-mcp-permission-manager'\n\n/**\n * Manages MCP (Model Context Protocol) server connections and tool registration.\n *\n * @remarks\n * The `McpManager` is responsible for:\n * - Connecting to configured MCP servers.\n * - Discovering available tools from servers.\n * - Creating proxy tools that wrap MCP server tools.\n * - Registering proxy tools with the {@link ToolRegistry}.\n * - Managing server health and status.\n * - Handling thread-specific tool activation/deactivation.\n *\n * This enables dynamic tool loading from external MCP servers while maintaining\n * seamless integration with the ART Framework's tool system.\n *\n * @see {@link McpProxyTool} for the tool wrapper implementation.\n * @see {@link McpClientController} for the underlying client implementation.\n *\n * @class McpManager\n */\nexport class McpManager {\n private configManager: ConfigManager;\n private toolRegistry: ToolRegistry;\n private authManager?: AuthManager;\n private activeConnections: Map<string, McpClientController> = new Map();\n\n /**\n * Creates an instance of McpManager.\n *\n * @param toolRegistry The tool registry to register proxy tools with.\n * @param _stateManager The state manager (not currently used).\n * @param authManager The authentication manager.\n */\n constructor(toolRegistry: ToolRegistry, _stateManager: StateManager, authManager?: AuthManager) {\n this.configManager = new ConfigManager();\n this.toolRegistry = toolRegistry;\n this.authManager = authManager;\n Logger.info(`McpManager: Hub initialized. Will load tools from config catalog.`);\n }\n\n /**\n * Initializes the McpManager, discovers and registers tools from configured servers.\n *\n * @param mcpConfig The MCP configuration.\n * @param [mcpConfig.enabled=true] Whether MCP is enabled.\n * @param mcpConfig.discoveryEndpoint The endpoint for discovering MCP servers.\n * @returns A promise that resolves when initialization is complete.\n */\n async initialize(mcpConfig?: { enabled?: boolean; discoveryEndpoint?: string }): Promise<void> {\n if (!mcpConfig?.enabled) {\n Logger.info('McpManager: MCP is disabled. Skipping initialization.');\n return;\n }\n\n Logger.info('McpManager: Initializing from multiple sources...');\n \n // 1. Get local config MCPCards\n const localServerConfigs = this.configManager.getConfig().mcpServers;\n Logger.info(`McpManager: Found ${Object.keys(localServerConfigs).length} servers in local config`);\n \n // 2. Discover remote MCPCards from Zyntopia API\n let discoveredServerConfigs: McpServerConfig[] = [];\n try {\n discoveredServerConfigs = await this.discoverAvailableServers(mcpConfig.discoveryEndpoint);\n Logger.info(`McpManager: Discovered ${discoveredServerConfigs.length} servers from discovery API`);\n } catch (error: any) {\n Logger.warn(`McpManager: Discovery API failed, continuing with local config only: ${error.message}`);\n }\n \n // 3. Merge all server configurations (local + discovered)\n const allServerConfigs = new Map<string, McpServerConfig>();\n \n // Add local configs first\n for (const [serverId, config] of Object.entries(localServerConfigs)) {\n allServerConfigs.set(serverId, config);\n }\n \n // Add discovered configs (with conflict resolution)\n for (const discoveredConfig of discoveredServerConfigs) {\n if (allServerConfigs.has(discoveredConfig.id)) {\n Logger.info(`McpManager: Server \"${discoveredConfig.id}\" exists in both local config and discovery API. Using local config.`);\n } else {\n allServerConfigs.set(discoveredConfig.id, discoveredConfig);\n Logger.info(`McpManager: Added discovered server \"${discoveredConfig.id}\" to available servers`);\n }\n }\n \n // 4. Register proxy tools based on current card hints only (non-blocking).\n // Live discovery and PKCE prompting can happen later during explicit install or first use.\n let registeredToolCount = 0;\n for (const [, card] of allServerConfigs) {\n if (!card.enabled) continue;\n const toolsToRegister = card.tools || [];\n if (Array.isArray(toolsToRegister)) {\n for (const toolDef of toolsToRegister) {\n const proxyTool = new McpProxyTool(card, toolDef as any, this);\n await this.toolRegistry.registerTool(proxyTool);\n registeredToolCount++;\n }\n }\n }\n\n Logger.info(`McpManager: Initialization complete. Registered ${registeredToolCount} proxy tools from ${allServerConfigs.size} total servers.`);\n }\n\n /**\n * Shuts down all active MCP connections.\n *\n * @returns A promise that resolves when all connections are shut down.\n */\n async shutdown(): Promise<void> {\n Logger.info('McpManager: Shutting down all active connections...');\n const disconnectionPromises = Array.from(this.activeConnections.values()).map(client => client.logout());\n await Promise.allSettled(disconnectionPromises);\n this.activeConnections.clear();\n Logger.info('McpManager: Shutdown complete.');\n }\n\n /**\n * Gets an existing connection or creates a new one for a given server ID.\n *\n * @param serverId The ID of the server to connect to.\n * @returns A promise that resolves to the MCP client controller.\n */\n public async getOrCreateConnection(serverId: string): Promise<McpClientController> {\n if (this.activeConnections.has(serverId)) {\n const existingClient = this.activeConnections.get(serverId)!;\n if (existingClient.isAuthenticated()) {\n await existingClient.ensureConnected();\n return existingClient;\n }\n }\n\n Logger.info(`McpManager: No active connection for \"${serverId}\". Creating one on-demand...`);\n const card = this.configManager.getConfig().mcpServers[serverId];\n if (!card) {\n throw new ARTError(`Configuration for server \"${serverId}\" not found.`, ErrorCode.SERVER_NOT_FOUND);\n }\n\n if (card.type !== 'streamable-http') {\n throw new ARTError(`Unsupported transport type \"${card.type}\" for server \"${serverId}\". Only 'streamable-http' is supported in the browser.`, ErrorCode.UNSUPPORTED_TRANSPORT);\n }\n\n const conn = card.connection as StreamableHttpConnection;\n\n await this.ensureCorsAccess(conn.url);\n\n const scopes = conn.oauth?.scopes;\n const client = McpClientController.create(conn.url, Array.isArray(scopes) ? scopes : (scopes ? [scopes] : undefined));\n\n const handled = await client.maybeHandleCallback();\n if(handled) {\n Logger.info(`McpManager: OAuth callback for server \"${serverId}\" handled successfully.`);\n }\n\n client.loadExistingSession();\n\n if(!client.isAuthenticated()) {\n await client.startOAuth();\n // The above call will redirect, so the code below might not be reached in that flow.\n // If it is (e.g. pop-up), we need to wait for authentication.\n await this.waitForAuth(client, 180000); // Wait for up to 3 minutes\n }\n \n await client.connect();\n\n this.activeConnections.set(serverId, client);\n Logger.info(`McpManager: On-demand connection for \"${serverId}\" established successfully.`);\n return client;\n }\n \n /**\n * Ensures that the application has CORS access to the target URL.\n *\n * @private\n * @param targetUrl The URL to check for CORS access.\n * @returns A promise that resolves when CORS access is confirmed or granted.\n */\n private async ensureCorsAccess(targetUrl: string): Promise<void> {\n if (!hasInstall()) {\n const opened = install({ browser: 'auto' });\n if (!opened) {\n const url = getInstallUrl();\n // In a real app, you'd show this in a dialog, not an alert\n alert('ART MCP requires a companion browser extension for CORS. Please install it: ' + url);\n throw new ARTError('Companion extension not installed.', ErrorCode.CORS_EXTENSION_REQUIRED);\n }\n throw new ARTError('Companion extension installation started. Please complete it and retry.', ErrorCode.CORS_EXTENSION_REQUIRED);\n }\n\n const { hostname } = new URL(targetUrl);\n const info = await getAllowedInfo();\n\n if (!info.enabled || (info.type === 'specific' && !info.hosts?.includes(hostname))) {\n const res = await requestHosts({ hosts: [hostname] });\n if (res !== 'accept') {\n throw new ARTError(`User did not grant permission for ${hostname}.`, ErrorCode.CORS_PERMISSION_REQUIRED);\n }\n }\n }\n\n // --- Discovery & Installation (Future Implementation) ---\n\n /**\n * Searches a discovery service for available MCP servers.\n *\n * @param [discoveryEndpoint] The URL of the discovery service.\n * @returns A promise resolving to an array of McpServerConfig.\n */\n async discoverAvailableServers(discoveryEndpoint?: string): Promise<McpServerConfig[]> {\n const url = discoveryEndpoint || 'http://localhost:4200/api/services'; // Default Zyntopia endpoint\n Logger.info(`McpManager: Discovering servers from ${url}...`);\n \n try {\n await this.ensureCorsAccess(url);\n const response = await fetch(url, {\n method: 'GET',\n headers: {\n 'Accept': 'application/json',\n 'User-Agent': 'ART-Framework-MCP/2.0'\n },\n // Add timeout to prevent hanging\n signal: AbortSignal.timeout(10000) // 10 second timeout\n });\n \n if (!response.ok) {\n throw new Error(`Discovery API returned ${response.status}: ${response.statusText}`);\n }\n \n const data = await response.json();\n \n // Filter for MCP services and convert to MCPCards\n const mcpServices = Array.isArray(data) ? data : (data.services || []);\n const mcpCards: McpServerConfig[] = mcpServices\n .filter((service: any) => service.service_type === 'MCP_SERVICE')\n .map((service: any) => this.convertServiceToMcpCard(service))\n .filter((card: McpServerConfig | null) => card !== null) as McpServerConfig[];\n \n Logger.info(`McpManager: Successfully discovered ${mcpCards.length} MCP servers from discovery API`);\n return mcpCards;\n \n } catch (error: any) {\n Logger.error(`McpManager: Failed to discover servers from ${url}: ${error.message}`);\n throw new ARTError(`Discovery API failed: ${error.message}`, ErrorCode.NETWORK_ERROR);\n }\n }\n \n /**\n * Converts a Zyntopia service entry to an McpServerConfig.\n *\n * @private\n * @param service The service entry to convert.\n * @returns The converted McpServerConfig or null if conversion fails.\n */\n private convertServiceToMcpCard(service: any): McpServerConfig | null {\n try {\n // Basic validation\n if (!service.id || !service.name || !service.connection) {\n Logger.warn(`McpManager: Skipping invalid service entry: missing required fields`);\n return null;\n }\n \n const mcpCard: McpServerConfig = {\n id: service.id,\n type: service.connection.type === 'sse' ? 'streamable-http' : service.connection.type,\n enabled: service.enabled !== false, // Default to enabled unless explicitly disabled\n displayName: service.name,\n description: service.description || `MCP service: ${service.name}`,\n connection: service.connection,\n timeout: service.timeout || 10000,\n tools: service.tools || [],\n resources: service.resources || [],\n resourceTemplates: service.resourceTemplates || [],\n installation: service.installation\n };\n \n Logger.debug(`McpManager: Converted service \"${service.id}\" to MCPCard`);\n return mcpCard;\n \n } catch (error: any) {\n Logger.warn(`McpManager: Failed to convert service to MCPCard: ${error.message}`);\n return null;\n }\n }\n\n // The generateAndInstallCard method is removed as it is based on the stdio transport,\n // which is not supported in a browser-only environment.\n\n /**\n * Installs a server by persisting its config, discovering tools via MCP, and\n * registering proxy tools. Returns the finalized config with accurate tools.\n *\n * @param server The server configuration to install.\n * @returns A promise that resolves to the finalized server configuration.\n */\n public async installServer(server: McpServerConfig): Promise<McpServerConfig> {\n // Save initial config\n this.configManager.setServerConfig(server.id, server);\n try {\n const conn = server.connection as StreamableHttpConnection;\n await this.ensureCorsAccess(conn.url);\n\n let client: McpClientController;\n try {\n client = await this.getOrCreateConnection(server.id);\n } catch (e: any) {\n // This might happen if startOAuth redirects. The user will need to try again.\n Logger.warn(`McpManager: Could not connect during install for \"${server.id}\": ${e?.message || e}. The user may need to complete authentication and retry.`);\n // We still save the server config, just without the live tools.\n return server;\n }\n\n const liveTools = await client.listTools();\n const normalized = (liveTools || []).map(t => ({ name: t.name, description: t.description } as any));\n const updated = { ...server, tools: normalized } as McpServerConfig;\n \n this.configManager.setServerConfig(server.id, updated);\n \n for (const t of normalized) {\n await this.toolRegistry.registerTool(new McpProxyTool(updated, t as any, this));\n }\n \n Logger.info(`McpManager: Installed server \"${server.id}\" with ${normalized.length} discovered tool(s).`);\n return updated;\n\n } catch (e: any) {\n Logger.warn(`McpManager: Could not complete live discovery during install for \"${server.id}\": ${e?.message || e}. Falling back to provided tools.`);\n const fallback = server.tools || [];\n for (const t of fallback) {\n await this.toolRegistry.registerTool(new McpProxyTool(server, t as any, this));\n }\n return server;\n }\n }\n\n /**\n * Waits for the client to be authenticated.\n *\n * @private\n * @param client The MCP client controller.\n * @param timeoutMs The timeout in milliseconds.\n * @returns A promise that resolves when the client is authenticated.\n * @throws {ARTError} If the authentication window times out.\n */\n private async waitForAuth(client: McpClientController, timeoutMs: number): Promise<void> {\n const start = Date.now();\n while (Date.now() - start < timeoutMs) {\n if (client.isAuthenticated()) {\n return;\n }\n await new Promise(r => setTimeout(r, 1000));\n }\n throw new ARTError('Authentication window timed out.', ErrorCode.TIMEOUT);\n }\n\n /**\n * Uninstalls a server: disconnects, removes registered proxy tools, and deletes config.\n *\n * @param serverId The ID of the server to uninstall.\n * @returns A promise that resolves when the server is uninstalled.\n */\n public async uninstallServer(serverId: string): Promise<void> {\n try {\n // Unregister tools by name prefix\n const prefix = `mcp_${serverId}_`;\n if ((this.toolRegistry as any).unregisterTools) {\n await (this.toolRegistry as any).unregisterTools((schema: any) => typeof schema?.name === 'string' && schema.name.startsWith(prefix));\n }\n\n // Disconnect\n const client = this.activeConnections.get(serverId);\n if (client) {\n await client.logout();\n this.activeConnections.delete(serverId);\n }\n\n // Remove config\n this.configManager.removeServerConfig(serverId);\n Logger.info(`McpManager: Server \"${serverId}\" uninstalled.`);\n } catch (e: any) {\n Logger.warn(`McpManager: Uninstall encountered issues for \"${serverId}\": ${e?.message || e}`);\n this.configManager.removeServerConfig(serverId);\n }\n }\n}","import { Logger } from '@/utils/logger';\nimport { ARTError, ErrorCode } from '@/errors';\nimport { A2AAgentInfo } from '@/types';\n\n/**\n * Interface for A2A Agent Card as defined in the A2A protocol standards.\n * This represents the digital \"business card\" that agents use to advertise their capabilities.\n */\nexport interface A2AAgentCard {\n /** Unique identifier for the agent */\n id: string;\n /** Human-readable name of the agent */\n name: string;\n /** Version of the agent */\n version: string;\n /** Brief description of what the agent does */\n description: string;\n /** Agent category (e.g., 'healthcare', 'research', 'analytics') */\n category: string;\n /** Base endpoint URL for A2A communication */\n endpoint: string;\n /** Array of capabilities the agent can perform */\n capabilities: string[];\n /** Authentication requirements */\n authentication: {\n type: string;\n required: boolean;\n };\n /** Input schema definition */\n inputSchema?: {\n type: string;\n properties: Record<string, any>;\n };\n /** Output schema definition */\n outputSchema?: {\n type: string;\n properties: Record<string, any>;\n };\n /** Rate limiting information */\n rateLimits?: {\n requestsPerMinute: number;\n };\n /** Tags for categorization */\n tags?: string[];\n}\n\n/**\n * Response structure from the discovery endpoint\n */\nexport interface DiscoveryResponse {\n services: Array<{\n id: string;\n service_type: string;\n card_data: A2AAgentCard;\n status: string;\n owner_id?: string;\n created_at: string;\n updated_at: string;\n }>;\n count: number;\n timestamp: string;\n}\n\n/**\n * Configuration for the AgentDiscoveryService\n */\nexport interface AgentDiscoveryConfig {\n /** Base URL for the discovery endpoint. If not provided, a default will be used. */\n discoveryEndpoint?: string;\n /** Timeout for discovery requests in milliseconds */\n timeoutMs?: number;\n /** Whether to cache discovered agents */\n enableCaching?: boolean;\n /** Cache TTL in milliseconds */\n cacheTtlMs?: number;\n}\n\n/**\n * Service for discovering A2A protocol compatible agents.\n * Implements the A2A discovery standards for finding and identifying compatible agents.\n */\nexport class AgentDiscoveryService {\n private readonly config: Required<AgentDiscoveryConfig>;\n private agentCache: Map<string, { agents: A2AAgentInfo[]; timestamp: number }> = new Map();\n\n /**\n * Creates an instance of AgentDiscoveryService.\n * @param {Partial<AgentDiscoveryConfig>} config - The configuration for the service.\n * @see A2AAgentCard\n */\n constructor(config?: Partial<AgentDiscoveryConfig>) {\n this.config = {\n discoveryEndpoint: 'https://api.zyntopia.com/a2a/discover', // Default endpoint\n timeoutMs: 10000, // 10 seconds default\n enableCaching: true,\n cacheTtlMs: 300000, // 5 minutes default\n ...config\n };\n \n Logger.debug(`AgentDiscoveryService initialized with endpoint: ${this.config.discoveryEndpoint}`);\n }\n\n /**\n * Discovers all available A2A agents from the discovery endpoint.\n * @param traceId - Optional trace ID for request tracking\n * @returns Promise resolving to array of discovered A2A agents\n * @throws {ARTError} If discovery fails or no agents are found\n */\n async discoverAgents(traceId?: string): Promise<A2AAgentInfo[]> {\n const cacheKey = 'all_agents';\n \n // Check cache first if enabled\n if (this.config.enableCaching) {\n const cached = this.getCachedAgents(cacheKey);\n if (cached) {\n Logger.debug(`[${traceId}] Returning ${cached.length} cached A2A agents`);\n return cached;\n }\n }\n\n try {\n Logger.debug(`[${traceId}] Discovering A2A agents from: ${this.config.discoveryEndpoint}`);\n \n // Create AbortController for timeout handling\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.config.timeoutMs);\n\n const response = await fetch(this.config.discoveryEndpoint, {\n method: 'GET',\n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n },\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n throw new ARTError(\n `Discovery endpoint returned ${response.status}: ${response.statusText}`,\n ErrorCode.EXTERNAL_SERVICE_ERROR\n );\n }\n\n const discoveryData: DiscoveryResponse = await response.json();\n \n // Filter for A2A agents only\n const a2aServices = discoveryData.services.filter(\n service => service.service_type === 'A2A_AGENT' && service.status === 'active'\n );\n\n if (a2aServices.length === 0) {\n Logger.warn(`[${traceId}] No active A2A agents found in discovery response`);\n return [];\n }\n\n // Transform to A2AAgentInfo format\n const agents = a2aServices.map(service => this.transformToA2AAgentInfo(service.card_data));\n \n // Cache the results\n if (this.config.enableCaching) {\n this.setCachedAgents(cacheKey, agents);\n }\n\n Logger.info(`[${traceId}] Discovered ${agents.length} A2A agents: ${agents.map(a => a.agentName).join(', ')}`);\n return agents;\n\n } catch (error: any) {\n if (error.name === 'AbortError') {\n throw new ARTError(\n `Agent discovery request timed out after ${this.config.timeoutMs}ms`,\n ErrorCode.TIMEOUT\n );\n }\n \n if (error instanceof ARTError) {\n throw error;\n }\n\n throw new ARTError(\n `Failed to discover A2A agents: ${error.message}`,\n ErrorCode.EXTERNAL_SERVICE_ERROR,\n error\n );\n }\n }\n\n /**\n * Finds the top K A2A agents for a specific task type, ranked by suitability.\n * This method acts as a pre-filter, returning a list of the most promising candidates\n * for an LLM to make the final selection from.\n * @param taskType - The type of task (e.g., 'analysis', 'research', 'generation')\n * @param topK - The maximum number of agents to return.\n * @param traceId - Optional trace ID for request tracking.\n * @returns Promise resolving to a ranked array of matching agents.\n * @remarks TODO: Revisit and enhance the scoring algorithm.\n */\n async findTopAgentsForTask(taskType: string, topK: number = 3, traceId?: string): Promise<A2AAgentInfo[]> {\n const agents = await this.discoverAgents(traceId);\n \n if (agents.length === 0) {\n Logger.warn(`[${traceId}] No A2A agents available for task type: ${taskType}`);\n return [];\n }\n\n // TODO: This scoring algorithm is a foundational heuristic. Revisit and enhance this\n // frequently. Future optimizations could include:\n // 1. LLM-based semantic scoring for more nuanced understanding.\n // 2. Incorporating a \"specialization score\" to reward agents with fewer, more focused capabilities.\n // 3. Factoring in agent metadata (name, description, tags) for contextual relevance.\n // 4. Caching individual agent scores for performance.\n\n // Score agents based on capability relevance to the task type\n const scoredAgents = agents.map(agent => {\n const capabilities = agent.capabilities || [];\n let totalScore = 0;\n const matchedCapabilities: string[] = [];\n\n for (const capability of capabilities) {\n const capLower = capability.toLowerCase();\n const taskLower = taskType.toLowerCase();\n let capabilityScore = 0;\n\n // Exact match with task type\n if (capLower === taskLower) {\n capabilityScore = 10;\n }\n // Capability contains task type\n else if (capLower.includes(taskLower)) {\n capabilityScore = 8;\n }\n // Task type contains capability (e.g., capability \"research\" matches task \"medical_research\")\n else if (taskLower.includes(capLower)) {\n capabilityScore = 6;\n }\n // Semantic similarity for common patterns\n else {\n // Check for semantic relationships\n const semanticScore = this.calculateSemanticScore(capLower, taskLower);\n capabilityScore = semanticScore;\n }\n\n if (capabilityScore > 0) {\n totalScore += capabilityScore;\n matchedCapabilities.push(capability);\n }\n }\n\n return {\n agent,\n score: totalScore,\n matchedCapabilities\n };\n });\n\n // Filter out agents with no score, sort by score (highest first), and take the top K\n const topMatches = scoredAgents\n .filter(a => a.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, topK);\n\n if (topMatches.length === 0) {\n Logger.warn(`[${traceId}] No suitable A2A agent found for task type: ${taskType}`);\n return [];\n }\n\n Logger.debug(`[${traceId}] Found ${topMatches.length} candidate agents for task type \"${taskType}\":`);\n topMatches.forEach(match => {\n Logger.debug(` - ${match.agent.agentName} (Score: ${match.score}, Matched: ${match.matchedCapabilities.join(', ')})`);\n });\n\n return topMatches.map(match => match.agent);\n }\n\n /**\n * Calculates semantic similarity score between capability and task type.\n * This uses common word patterns to identify relationships without hardcoded mappings.\n * @private\n */\n private calculateSemanticScore(capability: string, taskType: string): number {\n // Common semantic relationships\n const semanticPairs = [\n // Analysis-related\n ['analysis', 'analyze'], ['analysis', 'examine'], ['analysis', 'evaluate'],\n ['statistical', 'statistics'], ['data', 'information'],\n \n // Research-related \n ['research', 'investigate'], ['research', 'study'], ['research', 'explore'],\n ['medical', 'health'], ['web', 'online'], ['literature', 'document'],\n \n // Generation-related\n ['generation', 'generate'], ['generation', 'create'], ['generation', 'produce'],\n ['report', 'document'], ['visualization', 'visual'], ['chart', 'graph'],\n \n // Computation-related\n ['computation', 'compute'], ['computation', 'calculate'], ['computation', 'process'],\n ['mathematical', 'math'], ['algorithm', 'algorithmic'],\n \n // Transformation-related\n ['transformation', 'transform'], ['conversion', 'convert'], ['translation', 'translate'],\n \n // Validation-related\n ['validation', 'validate'], ['verification', 'verify'], ['testing', 'test']\n ];\n\n for (const [word1, word2] of semanticPairs) {\n if ((capability.includes(word1) && taskType.includes(word2)) ||\n (capability.includes(word2) && taskType.includes(word1))) {\n return 4; // Medium semantic match\n }\n }\n\n // Check for common word roots (basic stemming)\n const getWordRoot = (word: string) => {\n return word.replace(/ing$|ed$|er$|tion$|sion$|ment$|ness$|ly$|al$/, '');\n };\n\n const capWords = capability.split(/[_\\s-]/).map(getWordRoot);\n const taskWords = taskType.split(/[_\\s-]/).map(getWordRoot);\n\n for (const capWord of capWords) {\n for (const taskWord of taskWords) {\n if (capWord.length > 3 && taskWord.length > 3 && \n (capWord.includes(taskWord) || taskWord.includes(capWord))) {\n return 3; // Lower semantic match\n }\n }\n }\n\n return 0; // No semantic relationship found\n }\n\n /**\n * Finds agents by specific capabilities.\n * @param capabilities - Array of required capabilities\n * @param traceId - Optional trace ID for request tracking\n * @returns Promise resolving to agents that have all specified capabilities\n */\n async findAgentsByCapabilities(capabilities: string[], traceId?: string): Promise<A2AAgentInfo[]> {\n const agents = await this.discoverAgents(traceId);\n \n const matchingAgents = agents.filter(agent => {\n return capabilities.every(requiredCap => \n agent.capabilities?.some(agentCap => \n agentCap.toLowerCase().includes(requiredCap.toLowerCase()) ||\n requiredCap.toLowerCase().includes(agentCap.toLowerCase())\n )\n );\n });\n\n Logger.debug(`[${traceId}] Found ${matchingAgents.length} agents matching capabilities: ${capabilities.join(', ')}`);\n return matchingAgents;\n }\n\n /**\n * Clears the agent cache.\n */\n clearCache(): void {\n this.agentCache.clear();\n Logger.debug('Agent discovery cache cleared');\n }\n\n /**\n * Gets cached agents if they exist and are not expired.\n * @private\n */\n private getCachedAgents(cacheKey: string): A2AAgentInfo[] | null {\n const cached = this.agentCache.get(cacheKey);\n if (!cached) return null;\n\n const isExpired = Date.now() - cached.timestamp > this.config.cacheTtlMs;\n if (isExpired) {\n this.agentCache.delete(cacheKey);\n return null;\n }\n\n return cached.agents;\n }\n\n /**\n * Sets agents in cache with current timestamp.\n * @private\n */\n private setCachedAgents(cacheKey: string, agents: A2AAgentInfo[]): void {\n this.agentCache.set(cacheKey, {\n agents,\n timestamp: Date.now()\n });\n }\n\n /**\n * Transforms an A2A Agent Card to the ART framework's A2AAgentInfo format.\n * @private\n */\n private transformToA2AAgentInfo(card: A2AAgentCard): A2AAgentInfo {\n return {\n agentId: card.id,\n agentName: card.name,\n agentType: card.category || 'unknown',\n endpoint: card.endpoint,\n capabilities: card.capabilities || [],\n status: 'available' // Assume available since it was returned by discovery\n };\n }\n} ","// src/systems/a2a/TaskDelegationService.ts\n\nimport { Logger } from '@/utils/logger';\nimport { ARTError, ErrorCode } from '@/errors';\nimport { A2ATask, A2ATaskStatus, A2AAgentInfo, A2ATaskResult, A2ATaskMetadata } from '@/types';\nimport { IA2ATaskRepository } from '@/core/interfaces';\n// AgentDiscoveryService is no longer used here; discovery is handled by PESAgent.\n\n/**\n * Configuration options for the TaskDelegationService\n */\nexport interface TaskDelegationConfig {\n /** Default timeout for task delegation requests in milliseconds */\n defaultTimeoutMs?: number;\n /** Maximum number of retry attempts for failed requests */\n maxRetries?: number;\n /** Base delay between retry attempts in milliseconds */\n retryDelayMs?: number;\n /** Whether to use exponential backoff for retries */\n useExponentialBackoff?: boolean;\n /** The base callback URL for receiving A2A task updates. */\n callbackUrl?: string;\n}\n\n/**\n * Response structure for A2A task submission according to A2A protocol\n */\nexport interface TaskSubmissionResponse {\n /** Whether the task was successfully submitted */\n success: boolean;\n /** The unique task ID assigned by the remote agent */\n taskId: string;\n /** Current status of the submitted task */\n status: A2ATaskStatus;\n /** Optional message from the remote agent */\n message?: string;\n /** Estimated completion time in milliseconds (if provided) */\n estimatedCompletionMs?: number;\n /** Additional metadata from the remote agent */\n metadata?: Record<string, any>;\n}\n\n/**\n * Response structure for A2A task status queries\n */\nexport interface TaskStatusResponse {\n /** The task ID */\n taskId: string;\n /** Current status of the task */\n status: A2ATaskStatus;\n /** Progress percentage (0-100) if available */\n progress?: number;\n /** Task result if completed */\n result?: A2ATaskResult;\n /** Error information if failed */\n error?: string;\n /** Additional metadata */\n metadata?: Record<string, any>;\n}\n\n/**\n * Service responsible for delegating A2A tasks to remote agents.\n * Implements the A2A protocol for task submission, tracking, and completion.\n * \n * This service handles:\n * - Finding suitable agents for specific task types\n * - Submitting tasks to remote agents via HTTP API\n * - Tracking task status and handling updates\n * - Managing task lifecycle according to A2A protocol\n * - Error handling and retry logic\n * - Integration with local task repository for persistence\n */\nexport class TaskDelegationService {\n private readonly config: Required<TaskDelegationConfig>;\n private readonly taskRepository: IA2ATaskRepository;\n\n /**\n * Creates an instance of TaskDelegationService.\n * @param {IA2ATaskRepository} taskRepository - The repository for persisting task status.\n * @param {TaskDelegationConfig} [config={}] - Configuration for the service.\n */\n constructor(\n taskRepository: IA2ATaskRepository,\n config: TaskDelegationConfig = {}\n ) {\n this.taskRepository = taskRepository;\n \n // Set default configuration\n this.config = {\n defaultTimeoutMs: config.defaultTimeoutMs ?? 30000, // 30 seconds\n maxRetries: config.maxRetries ?? 3,\n retryDelayMs: config.retryDelayMs ?? 1000, // 1 second\n useExponentialBackoff: config.useExponentialBackoff ?? true,\n callbackUrl: config.callbackUrl ?? 'http://localhost:3000/api/a2a/callback'\n };\n\n Logger.debug('TaskDelegationService initialized with config:', this.config);\n }\n\n /**\n * Delegates a list of A2A tasks to suitable remote agents.\n * For each task, finds the best agent and submits the task.\n * \n * @param {A2ATask[]} tasks - Array of A2A tasks to delegate\n * @param {string} [traceId] - Optional trace ID for request tracking\n * @returns {Promise<A2ATask[]>} Promise resolving to array of successfully delegated tasks\n */\n async delegateTasks(tasks: A2ATask[], traceId?: string): Promise<A2ATask[]> {\n if (tasks.length === 0) {\n Logger.debug(`[${traceId}] No tasks to delegate`);\n return [];\n }\n\n Logger.info(`[${traceId}] Starting delegation of ${tasks.length} A2A task(s)`);\n const delegatedTasks: A2ATask[] = [];\n\n for (const task of tasks) {\n try {\n const delegatedTask = await this.delegateTask(task, traceId);\n if (delegatedTask) {\n delegatedTasks.push(delegatedTask);\n }\n } catch (error: any) {\n Logger.error(`[${traceId}] Failed to delegate task ${task.taskId}:`, error);\n // Continue with other tasks even if one fails\n }\n }\n\n Logger.info(`[${traceId}] Successfully delegated ${delegatedTasks.length}/${tasks.length} task(s)`);\n return delegatedTasks;\n }\n\n /**\n * Delegates a single A2A task to a suitable remote agent.\n * \n * @param {A2ATask} task - The A2A task to delegate\n * @param {string} [traceId] - Optional trace ID for request tracking\n * @returns {Promise<A2ATask | null>} Promise resolving to the updated task or null if delegation failed\n */\n async delegateTask(task: A2ATask, traceId?: string): Promise<A2ATask | null> {\n Logger.debug(`[${traceId}] Delegating task ${task.taskId} of type \"${task.payload.taskType}\"`);\n\n try {\n // Step 1: Validate that a target agent has been assigned to the task\n const targetAgent = task.targetAgent;\n if (!targetAgent) {\n throw new ARTError(\n `Task ${task.taskId} cannot be delegated without a targetAgent.`,\n ErrorCode.VALIDATION_ERROR\n );\n }\n\n Logger.debug(`[${traceId}] Confirmed target agent \"${targetAgent.agentName}\" for task ${task.taskId}`);\n\n // Step 2: Submit task to the remote agent\n const submissionResponse = await this.submitTaskToAgent(task, targetAgent, traceId);\n\n // Step 3: Update local task with delegation information\n const now = Date.now();\n const updatedTask: A2ATask = {\n ...task,\n status: submissionResponse.status,\n // targetAgent is already set\n metadata: {\n ...task.metadata,\n updatedAt: now,\n startedAt: submissionResponse.status === A2ATaskStatus.IN_PROGRESS ? now : task.metadata.startedAt,\n tags: [...(task.metadata.tags || []), 'delegated'],\n delegatedAt: now,\n estimatedCompletionMs: submissionResponse.estimatedCompletionMs\n }\n };\n\n // Step 4: Persist the updated task\n // Note: The task should already exist in a PENDING state. We update it.\n await this.taskRepository.updateTask(updatedTask.taskId, updatedTask);\n \n Logger.info(`[${traceId}] Successfully delegated task ${task.taskId} to agent \"${targetAgent.agentName}\" (status: ${submissionResponse.status})`);\n return updatedTask;\n\n } catch (error: any) {\n Logger.error(`[${traceId}] Task delegation failed for ${task.taskId}:`, error);\n \n // Update task status to failed and persist\n try {\n await this.taskRepository.updateTask(task.taskId, {\n status: A2ATaskStatus.FAILED,\n metadata: {\n ...task.metadata,\n updatedAt: Date.now(),\n completedAt: Date.now(),\n tags: [...(task.metadata.tags || []), 'delegation_failed']\n },\n result: {\n success: false,\n error: `Delegation failed: ${error.message}`,\n metadata: { errorType: 'delegation_error', timestamp: Date.now() }\n }\n });\n } catch (persistError: any) {\n Logger.error(`[${traceId}] Failed to persist task failure for ${task.taskId}:`, persistError);\n }\n\n // Re-throw the original error to be handled by the caller (e.g., PESAgent)\n throw error instanceof ARTError ? error : new ARTError(\n `Failed to delegate task ${task.taskId}: ${error.message}`,\n ErrorCode.DELEGATION_FAILED,\n error\n );\n }\n }\n\n /**\n * Submits a task to a specific remote agent using A2A protocol.\n * \n * @private\n * @param {A2ATask} task - The A2A task to submit\n * @param {A2AAgentInfo} targetAgent - The target agent to submit the task to\n * @param {string} [traceId] - Optional trace ID for request tracking\n * @returns {Promise<TaskSubmissionResponse>} Promise resolving to the submission response\n */\n private async submitTaskToAgent(\n task: A2ATask, \n targetAgent: A2AAgentInfo, \n traceId?: string\n ): Promise<TaskSubmissionResponse> {\n if (!targetAgent.endpoint) {\n throw new ARTError(\n `Target agent \"${targetAgent.agentName}\" has no endpoint configured`,\n ErrorCode.VALIDATION_ERROR\n );\n }\n\n const taskSubmissionUrl = `${targetAgent.endpoint.replace(/\\/$/, '')}/tasks`;\n \n // Prepare the task submission payload according to A2A protocol\n const submissionPayload = {\n taskId: task.taskId,\n taskType: task.payload.taskType,\n input: task.payload.input,\n instructions: task.payload.instructions,\n parameters: task.payload.parameters,\n priority: task.priority,\n sourceAgent: task.sourceAgent,\n timeoutMs: task.metadata.timeoutMs,\n maxRetries: task.metadata.maxRetries,\n callbackUrl: this.generateCallbackUrl(task.taskId), // For webhook notifications\n metadata: {\n traceId: traceId,\n submittedAt: Date.now(),\n sourceTimestamp: task.metadata.createdAt\n }\n };\n\n Logger.debug(`[${traceId}] Submitting task ${task.taskId} to ${taskSubmissionUrl}`);\n\n let lastError: Error = new Error('Unknown error');\n let attempt = 0;\n\n // Retry loop with exponential backoff\n while (attempt <= this.config.maxRetries) {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.config.defaultTimeoutMs);\n\n const response = await fetch(taskSubmissionUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'ART-Framework-A2A/1.0.0',\n 'X-Trace-ID': traceId || '',\n ...(targetAgent.authentication?.type === 'bearer' && targetAgent.authentication.token \n ? { 'Authorization': `Bearer ${targetAgent.authentication.token}` }\n : {}),\n ...(targetAgent.authentication?.type === 'api_key' && targetAgent.authentication.apiKey \n ? { 'X-API-Key': targetAgent.authentication.apiKey }\n : {})\n },\n body: JSON.stringify(submissionPayload),\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n const responseData: TaskSubmissionResponse = await response.json();\n \n // Validate the response structure\n if (!responseData.taskId || !responseData.status) {\n throw new Error('Invalid response format from remote agent');\n }\n\n Logger.debug(`[${traceId}] Task ${task.taskId} submitted successfully to \"${targetAgent.agentName}\" (remote task ID: ${responseData.taskId})`);\n return responseData;\n\n } catch (error: any) {\n lastError = error;\n attempt++;\n\n if (error.name === 'AbortError') {\n Logger.warn(`[${traceId}] Task submission timed out for ${task.taskId} (attempt ${attempt}/${this.config.maxRetries + 1})`);\n } else {\n Logger.warn(`[${traceId}] Task submission failed for ${task.taskId} (attempt ${attempt}/${this.config.maxRetries + 1}):`, error.message);\n }\n\n // Don't retry if we've exhausted attempts\n if (attempt > this.config.maxRetries) {\n break;\n }\n\n // Calculate delay with exponential backoff\n const delay = this.config.useExponentialBackoff \n ? this.config.retryDelayMs * Math.pow(2, attempt - 1)\n : this.config.retryDelayMs;\n\n Logger.debug(`[${traceId}] Retrying task submission in ${delay}ms...`);\n await new Promise(resolve => setTimeout(resolve, delay));\n }\n }\n\n throw new ARTError(\n `Failed to submit task ${task.taskId} to agent \"${targetAgent.agentName}\" after ${this.config.maxRetries + 1} attempts: ${lastError.message}`,\n ErrorCode.EXTERNAL_SERVICE_ERROR,\n lastError\n );\n }\n\n /**\n * Checks the status of a delegated task from the remote agent.\n * \n * @param {A2ATask} task - The A2A task to check status for\n * @param {string} [traceId] - Optional trace ID for request tracking\n * @returns {Promise<TaskStatusResponse | null>} Promise resolving to the current task status\n */\n async checkTaskStatus(task: A2ATask, traceId?: string): Promise<TaskStatusResponse | null> {\n if (!task.targetAgent?.endpoint) {\n Logger.warn(`[${traceId}] Cannot check status for task ${task.taskId}: no target agent endpoint`);\n return null;\n }\n\n const statusUrl = `${task.targetAgent.endpoint.replace(/\\/$/, '')}/tasks/${task.taskId}`;\n \n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.config.defaultTimeoutMs);\n\n const response = await fetch(statusUrl, {\n method: 'GET',\n headers: {\n 'User-Agent': 'ART-Framework-A2A/1.0.0',\n 'X-Trace-ID': traceId || '',\n ...(task.targetAgent.authentication?.type === 'bearer' && task.targetAgent.authentication.token \n ? { 'Authorization': `Bearer ${task.targetAgent.authentication.token}` }\n : {}),\n ...(task.targetAgent.authentication?.type === 'api_key' && task.targetAgent.authentication.apiKey \n ? { 'X-API-Key': task.targetAgent.authentication.apiKey }\n : {})\n },\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n if (response.status === 404) {\n Logger.warn(`[${traceId}] Task ${task.taskId} not found on remote agent`);\n return null;\n }\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n const statusData: TaskStatusResponse = await response.json();\n Logger.debug(`[${traceId}] Task ${task.taskId} status: ${statusData.status}`);\n \n return statusData;\n\n } catch (error: any) {\n Logger.error(`[${traceId}] Failed to check status for task ${task.taskId}:`, error);\n return null;\n }\n }\n\n /**\n * Updates a local A2A task based on remote status information.\n * \n * @param {A2ATask} task - The local A2A task to update\n * @param {TaskStatusResponse} statusResponse - The status response from the remote agent\n * @param {string} [traceId] - Optional trace ID for request tracking\n * @returns {Promise<A2ATask>} Promise resolving to the updated task\n */\n async updateTaskFromRemoteStatus(\n task: A2ATask, \n statusResponse: TaskStatusResponse, \n traceId?: string\n ): Promise<A2ATask> {\n const now = Date.now();\n const updatedMetadata: A2ATaskMetadata = {\n ...task.metadata,\n updatedAt: now\n };\n\n const updates: Partial<A2ATask> = {\n status: statusResponse.status,\n metadata: updatedMetadata\n };\n\n // Handle completion\n if (statusResponse.status === A2ATaskStatus.COMPLETED && statusResponse.result) {\n updates.result = statusResponse.result;\n updatedMetadata.completedAt = now;\n }\n\n // Handle failure\n if (statusResponse.status === A2ATaskStatus.FAILED && statusResponse.error) {\n updates.result = {\n success: false,\n error: statusResponse.error,\n metadata: { remoteError: true, timestamp: now }\n };\n updatedMetadata.completedAt = now;\n }\n\n // Update additional metadata\n if (statusResponse.metadata) {\n Object.assign(updatedMetadata, statusResponse.metadata);\n }\n\n // Update the updates object with the final metadata\n updates.metadata = updatedMetadata;\n\n await this.taskRepository.updateTask(task.taskId, updates);\n \n Logger.debug(`[${traceId}] Updated task ${task.taskId} with remote status: ${statusResponse.status}`);\n return { ...task, ...updates };\n }\n\n /**\n * Generates a callback URL for webhook notifications.\n * This would typically point to an endpoint in the local system.\n * \n * @private\n * @param {string} taskId - The task ID to generate callback URL for\n * @returns {string} The callback URL string\n */\n private generateCallbackUrl(taskId: string): string {\n const baseUrl = this.config.callbackUrl.replace(/\\/$/, ''); // Remove trailing slash\n return `${baseUrl}/${taskId}`;\n }\n\n /**\n * Cancels a delegated task on the remote agent.\n * \n * @param {A2ATask} task - The A2A task to cancel\n * @param {string} [traceId] - Optional trace ID for request tracking\n * @returns {Promise<boolean>} Promise resolving to whether cancellation was successful\n */\n async cancelTask(task: A2ATask, traceId?: string): Promise<boolean> {\n if (!task.targetAgent?.endpoint) {\n Logger.warn(`[${traceId}] Cannot cancel task ${task.taskId}: no target agent endpoint`);\n return false;\n }\n\n const cancelUrl = `${task.targetAgent.endpoint.replace(/\\/$/, '')}/tasks/${task.taskId}`;\n \n try {\n const response = await fetch(cancelUrl, {\n method: 'DELETE',\n headers: {\n 'User-Agent': 'ART-Framework-A2A/1.0.0',\n 'X-Trace-ID': traceId || '',\n ...(task.targetAgent.authentication?.type === 'bearer' && task.targetAgent.authentication.token \n ? { 'Authorization': `Bearer ${task.targetAgent.authentication.token}` }\n : {}),\n ...(task.targetAgent.authentication?.type === 'api_key' && task.targetAgent.authentication.apiKey \n ? { 'X-API-Key': task.targetAgent.authentication.apiKey }\n : {})\n }\n });\n\n if (response.ok) {\n // Update local task status\n await this.taskRepository.updateTask(task.taskId, {\n status: A2ATaskStatus.CANCELLED,\n metadata: {\n ...task.metadata,\n updatedAt: Date.now(),\n completedAt: Date.now()\n }\n });\n\n Logger.info(`[${traceId}] Successfully cancelled task ${task.taskId}`);\n return true;\n } else {\n Logger.warn(`[${traceId}] Failed to cancel task ${task.taskId}: HTTP ${response.status}`);\n return false;\n }\n\n } catch (error: any) {\n Logger.error(`[${traceId}] Error cancelling task ${task.taskId}:`, error);\n return false;\n }\n }\n} ","// src/core/agent-factory.ts\nimport {\n IAgentCore,\n StorageAdapter,\n IConversationRepository,\n IObservationRepository,\n IStateRepository,\n IA2ATaskRepository,\n ConversationManager,\n StateManager,\n ObservationManager,\n ToolRegistry,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n type IToolExecutor, // type-only import\n PromptManager,\n // ProviderAdapter, // Removed direct ProviderAdapter interface import\n ReasoningEngine,\n OutputParser,\n ToolSystem,\n UISystem\n // Removed ObservationSocket, ConversationSocket interface imports\n} from '@/core/interfaces';\nimport { IProviderManager } from '@/types/providers'; // Corrected path\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { ProviderManagerConfig } from '@/types/providers'; // type-only import\n// Import ArtInstanceConfig and StateSavingStrategy\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport { ArtInstanceConfig, StateSavingStrategy } from '@/types';\nimport { ProviderManagerImpl } from '@/systems/reasoning/ProviderManagerImpl'; // Corrected path\nimport { PESAgent } from '@/core/agents/pes-agent';\n\n// Import concrete implementations (assuming paths)\n// Storage Adapters\nimport { InMemoryStorageAdapter } from '@/integrations/storage/inMemory'; // Corrected path\nimport { IndexedDBStorageAdapter } from '@/integrations/storage/indexedDB'; // Corrected path\n// Repositories\nimport { ConversationRepository } from '@/systems/context/repositories/ConversationRepository'; // Corrected path\nimport { ObservationRepository } from '@/systems/context/repositories/ObservationRepository'; // Corrected path - Moved from observation system\nimport { StateRepository } from '@/systems/context/repositories/StateRepository'; // Corrected path\nimport { TaskStatusRepository } from '@/systems/context/repositories/TaskStatusRepository'; // A2A task repository\n// Managers\nimport { ConversationManager as ConversationManagerImpl } from '@/systems/context/managers/ConversationManager'; // Corrected path\nimport { StateManager as StateManagerImpl } from '@/systems/context/managers/StateManager'; // Corrected path\nimport { ObservationManager as ObservationManagerImpl } from '@/systems/observation/observation-manager'; // Correct path\n// Tool System\nimport { ToolRegistry as ToolRegistryImpl } from '@/systems/tool/ToolRegistry'; // Correct path\nimport { ToolSystem as ToolSystemImpl } from '@/systems/tool/ToolSystem'; // Correct path\n// Reasoning System\nimport { PromptManager as PromptManagerImpl } from '@/systems/reasoning/PromptManager'; // Correct path\nimport { SystemPromptResolver as SystemPromptResolverImpl } from '@/systems/reasoning/SystemPromptResolver';\nimport { ReasoningEngine as ReasoningEngineImpl } from '@/systems/reasoning/ReasoningEngine'; // Correct path\nimport { OutputParser as OutputParserImpl } from '@/systems/reasoning/OutputParser'; // Correct path\n// Provider Adapters are now managed by ProviderManagerImpl\n// UI System\nimport { UISystem as UISystemImpl } from '@/systems/ui/ui-system'; // Correct path\n// Auth and MCP Systems\nimport { AuthManager } from '@/systems/auth/AuthManager'; // Import AuthManager\nimport { McpManager } from '@/systems/mcp/McpManager'; // Import McpManager\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { McpManagerConfig } from '@/systems/mcp/types'; // type-only import for McpManagerConfig\nimport { AgentDiscoveryService } from '@/systems/a2a/AgentDiscoveryService';\nimport { TaskDelegationService } from '@/systems/a2a/TaskDelegationService';\n// Removed direct imports of concrete socket classes - they will be accessed via UISystem instance\n// Removed unused type imports: Observation, ConversationMessage, ObservationType, MessageRole\nimport { Logger } from '@/utils/logger'; // Import Logger\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { LogLevel } from '@/utils/logger'; // type-only import\n\n\n/**\n * Configuration for the Storage System adapter.\n */\nexport interface StorageConfig {\n /** Specifies the type of storage adapter to use. */\n type: 'memory' | 'indexedDB';\n /** The name of the database to use (required for 'indexedDB'). */\n dbName?: string;\n /** Optional: Database version for schema migrations (for 'indexedDB'). Defaults might apply. */\n version?: number;\n /** Optional: Advanced configuration for IndexedDB object stores and indexes. Defaults are usually sufficient. */\n objectStores?: any[]; // Define a more specific type if possible\n // Add other adapter-specific config options as needed\n}\n\n/**\n * Configuration for the Reasoning System provider adapter.\n */\nexport interface ReasoningConfig {\n /** The identifier of the LLM provider to use. */\n provider: 'openai' | 'gemini' | 'anthropic' | 'openrouter' | 'deepseek'; // Add others as implemented\n /** The API key for the selected provider. Handle securely (e.g., via environment variables). */\n apiKey: string;\n /** Optional: The default model ID to use for this provider if not specified elsewhere (e.g., in ThreadConfig). */\n model?: string;\n /** Optional: Custom base URL for the provider's API (e.g., for proxies or self-hosted models). */\n baseURL?: string;\n /** Optional: Default parameters to pass to the LLM provider on each call (e.g., temperature). */\n defaultParams?: Record<string, any>;\n // Add other provider-specific options as needed\n}\n\n/**\n * Configuration object required by the AgentFactory and createArtInstance function.\n * This will now use ArtInstanceConfig from types.ts which includes stateSavingStrategy.\n */\n// export interface AgentFactoryConfig { // Commented out, will use ArtInstanceConfig\n// /** Configuration for the storage adapter. */\n// storage: StorageConfig;\n// /** Configuration for the Provider Manager, defining available adapters and rules. */\n// providers: ProviderManagerConfig; // Changed from reasoning: ReasoningConfig\n// /** Optional array of tool executor instances to register at initialization. */\n// tools?: IToolExecutor[];\n// /** Optional: Specify a different Agent Core implementation class (defaults to PESAgent). */\n// agentCore?: new (dependencies: any) => IAgentCore;\n// /** Optional: Configuration for the logger. */\n// logger?: { level?: LogLevel }; // Assuming LogLevel enum exists\n// // TODO: Add other potential global configurations (e.g., default ThreadConfig, UI system options)\n// }\n\n/**\n * Handles the instantiation and wiring of all core ART framework components based on provided configuration.\n * This class performs the dependency injection needed to create a functional `ArtInstance`.\n * It's typically used internally by the `createArtInstance` function.\n */\nexport class AgentFactory {\n private config: ArtInstanceConfig; // Changed to ArtInstanceConfig\n private storageAdapter: StorageAdapter | null = null;\n private uiSystem: UISystem | null = null;\n private conversationRepository: IConversationRepository | null = null;\n private observationRepository: IObservationRepository | null = null;\n private stateRepository: IStateRepository | null = null;\n private a2aTaskRepository: IA2ATaskRepository | null = null;\n private conversationManager: ConversationManager | null = null;\n private stateManager: StateManager | null = null;\n private observationManager: ObservationManager | null = null;\n private toolRegistry: ToolRegistry | null = null;\n // private providerAdapter: ProviderAdapter | null = null; // Replaced with providerManager\n private providerManager: IProviderManager | null = null; // Added providerManager\n private reasoningEngine: ReasoningEngine | null = null;\n private promptManager: PromptManager | null = null;\n private outputParser: OutputParser | null = null;\n private systemPromptResolver: any | null = null;\n private toolSystem: ToolSystem | null = null;\n private authManager: AuthManager | null = null;\n private mcpManager: McpManager | null = null;\n private agentDiscoveryService: AgentDiscoveryService | null = null;\n private taskDelegationService: TaskDelegationService | null = null;\n\n\n /**\n * Creates a new AgentFactory instance.\n * @param config - The configuration specifying which adapters and components to use.\n */\n constructor(config: ArtInstanceConfig) { // Changed to ArtInstanceConfig\n this.config = config;\n // Basic validation\n if (!config.storage) throw new Error(\"ArtInstanceConfig requires 'storage' configuration.\");\n if (!config.providers) throw new Error(\"ArtInstanceConfig requires 'providers' configuration.\");\n }\n\n /**\n * Asynchronously initializes all core components based on the configuration.\n * This includes setting up the storage adapter, repositories, managers, tool registry,\n * reasoning engine, and UI system.\n * This method MUST be called before `createAgent()`.\n * @returns A promise that resolves when initialization is complete.\n * @throws {Error} If configuration is invalid or initialization fails for a component.\n */\n async initialize(): Promise<void> {\n // --- Initialize Storage ---\n if ('type' in this.config.storage) { // Type guard for storage config object\n const storageConfig = this.config.storage; // storageConfig is now { type: 'memory' | 'indexedDB', ... }\n switch (storageConfig.type) {\n case 'indexedDB':\n this.storageAdapter = new IndexedDBStorageAdapter({\n dbName: storageConfig.dbName || 'ARTDB',\n objectStores: storageConfig.objectStores || ['conversations', 'observations', 'state', 'a2a_tasks']\n });\n break;\n case 'memory':\n default:\n this.storageAdapter = new InMemoryStorageAdapter();\n break;\n }\n } else { // It's a pre-configured StorageAdapter instance\n this.storageAdapter = this.config.storage;\n }\n await this.storageAdapter!.init?.(); // Add non-null assertion\n\n // --- Initialize Repositories ---\n // Add non-null assertions assuming storageAdapter is initialized above\n this.conversationRepository = new ConversationRepository(this.storageAdapter!);\n this.observationRepository = new ObservationRepository(this.storageAdapter!);\n this.stateRepository = new StateRepository(this.storageAdapter!);\n this.a2aTaskRepository = new TaskStatusRepository(this.storageAdapter!);\n\n // --- Initialize UI System ---\n // UISystem constructor expects repositories, not sockets\n this.uiSystem = new UISystemImpl(this.observationRepository!, this.conversationRepository!, this.a2aTaskRepository || undefined); // Pass repositories including A2A task repository\n\n // --- Initialize Managers ---\n // Pass the actual socket instances obtained from the initialized uiSystem\n this.conversationManager = new ConversationManagerImpl(this.conversationRepository!, this.uiSystem.getConversationSocket());\n // Pass the stateSavingStrategy to StateManagerImpl constructor\n const strategy = this.config.stateSavingStrategy || 'explicit'; // Default to 'explicit'\n this.stateManager = new StateManagerImpl(this.stateRepository!, strategy);\n this.observationManager = new ObservationManagerImpl(this.observationRepository!, this.uiSystem.getObservationSocket());\n\n // --- Initialize Tool Registry & Register Tools ---\n // Pass the initialized StateManager to the ToolRegistry constructor\n this.toolRegistry = new ToolRegistryImpl(this.stateManager!);\n if (this.config.tools) {\n for (const tool of this.config.tools) {\n await this.toolRegistry!.registerTool(tool); // Add non-null assertion\n }\n }\n\n // --- Initialize Provider Manager ---\n // ProviderManagerImpl likely needs configuration for *all* potential providers.\n // The current AgentFactoryConfig only holds one reasoning config. This needs refactoring\n // for a true multi-provider setup where the manager knows all potential credentials/configs.\n // For now, instantiate it simply to fix the type error. Runtime provider selection might fail\n // Pass the provider configuration from the main config\n this.providerManager = new ProviderManagerImpl(this.config.providers);\n Logger.info(\"ProviderManager initialized.\");\n\n\n // --- Initialize Reasoning Components ---\n this.reasoningEngine = new ReasoningEngineImpl(this.providerManager!); // Pass ProviderManager\n this.promptManager = new PromptManagerImpl(); // Basic implementation for now\n // Initialize SystemPromptResolver with registry from config if provided\n const registry = (this.config as any).systemPrompts as import('../types').SystemPromptsRegistry | undefined;\n this.systemPromptResolver = new SystemPromptResolverImpl(this.promptManager as any, registry);\n this.outputParser = new OutputParserImpl(); // Basic implementation for now\n\n // --- Initialize Tool System ---\n // Inject ToolRegistry, StateManager, and ObservationManager into ToolSystem\n this.toolSystem = new ToolSystemImpl(this.toolRegistry!, this.stateManager!, this.observationManager!); // Added observationManager\n\n // --- Initialize Auth Manager ---\n if (this.config.authConfig?.enabled) {\n this.authManager = new AuthManager();\n // Register any pre-configured strategies\n if (this.config.authConfig.strategies) {\n for (const { id, strategy } of this.config.authConfig.strategies) {\n this.authManager.registerStrategy(id, strategy);\n }\n }\n Logger.info(\"AuthManager initialized.\");\n }\n\n // --- Initialize A2A Services ---\n if (this.config.a2aConfig) {\n this.agentDiscoveryService = new AgentDiscoveryService({\n discoveryEndpoint: this.config.a2aConfig.discoveryEndpoint,\n });\n this.taskDelegationService = new TaskDelegationService(\n this.a2aTaskRepository!,\n { callbackUrl: this.config.a2aConfig.callbackUrl }\n );\n Logger.info(\"A2A Services (Discovery, Delegation) initialized.\");\n }\n\n // --- Initialize MCP Manager ---\n if (this.config.mcpConfig) {\n if (!this.toolRegistry || !this.stateManager) {\n throw new Error(\"MCP Manager requires ToolRegistry and StateManager to be initialized first.\");\n }\n // McpManager now reads its own config from the file system and discovers from Zyntopia.\n this.mcpManager = new McpManager(\n this.toolRegistry,\n this.stateManager,\n this.authManager || undefined\n );\n // Initialize with both local config and Zyntopia discovery\n await this.mcpManager.initialize(this.config.mcpConfig);\n Logger.info(\"McpManager Hub initialized with local config and Zyntopia discovery.\");\n }\n }\n\n /**\n * Creates an instance of the configured Agent Core (e.g., `PESAgent`) and injects\n * all necessary initialized dependencies (managers, systems, etc.).\n * Requires `initialize()` to have been successfully called beforehand.\n * @returns An instance implementing the `IAgentCore` interface.\n * @throws {Error} If `initialize()` was not called or if essential components failed to initialize.\n */\n createAgent(): IAgentCore {\n // Check for all required components after initialization\n if (!this.stateManager || !this.conversationManager || !this.toolRegistry ||\n !this.promptManager || !this.reasoningEngine || !this.outputParser ||\n !this.observationManager || !this.toolSystem || !this.providerManager ||\n !this.a2aTaskRepository) { // Check A2A task repository\n throw new Error(\"AgentFactory not fully initialized. Call initialize() before creating an agent.\");\n }\n\n // Pass dependencies to the agent constructor\n // This object's structure should align with what the Agent Core implementation expects (e.g., PESAgentDependencies)\n const dependencies = {\n stateManager: this.stateManager,\n conversationManager: this.conversationManager,\n toolRegistry: this.toolRegistry,\n promptManager: this.promptManager,\n reasoningEngine: this.reasoningEngine,\n outputParser: this.outputParser,\n observationManager: this.observationManager,\n toolSystem: this.toolSystem,\n uiSystem: this.uiSystem!, // Include the UI System (non-null assertion)\n systemPromptResolver: this.systemPromptResolver,\n a2aTaskRepository: this.a2aTaskRepository, // Include A2A task repository\n authManager: this.authManager, // Include Auth Manager (may be null if not configured)\n mcpManager: this.mcpManager, // Include MCP Manager (may be null if not configured)\n agentDiscoveryService: this.agentDiscoveryService, // Include A2A Discovery Service\n taskDelegationService: this.taskDelegationService, // Include A2A Delegation Service\n persona: this.config.persona, // Pass the persona from the main config\n // Note: providerAdapter is used by reasoningEngine, not directly by agent core usually\n };\n\n // Instantiate the specified Agent Core or default to PESAgent\n const AgentCoreImplementation = this.config.agentCore || PESAgent;\n const agent = new AgentCoreImplementation(dependencies);\n return agent;\n }\n\n // --- Getters for initialized components (primarily for createArtInstance) ---\n /** Gets the initialized Storage Adapter instance. */\n getStorageAdapter(): StorageAdapter | null { return this.storageAdapter; }\n /** Gets the initialized UI System instance. */\n getUISystem(): UISystem | null { return this.uiSystem; }\n /** Gets the initialized Tool Registry instance. */\n getToolRegistry(): ToolRegistry | null { return this.toolRegistry; }\n /** Gets the initialized State Manager instance. */\n getStateManager(): StateManager | null { return this.stateManager; }\n /** Gets the initialized Conversation Manager instance. */\n getConversationManager(): ConversationManager | null { return this.conversationManager; }\n /** Gets the initialized Observation Manager instance. */\n getObservationManager(): ObservationManager | null { return this.observationManager; }\n /** Gets the initialized Auth Manager instance. */\n getAuthManager(): AuthManager | null { return this.authManager; }\n /** Gets the initialized MCP Manager instance. */\n getMcpManager(): McpManager | null { return this.mcpManager; }\n // Add getters for other components like reasoningEngine, toolSystem if needed\n}\n\n// --- Convenience Factory Function ---\nimport { ArtInstance } from '@/core/interfaces'; // Import the new interface\n\n/**\n * High-level factory function to create and initialize a complete ART framework instance.\n * This simplifies the setup process by handling the instantiation and wiring of all\n * necessary components based on the provided configuration.\n * @param config - The configuration object specifying storage, reasoning, tools, etc.\n * @returns A promise that resolves to a ready-to-use `ArtInstance` object, providing access to the core `process` method and essential managers/systems.\n * @throws {Error} If initialization fails (e.g., invalid config, storage connection error).\n * @example\n * const art = await createArtInstance({\n * storage: { type: 'indexedDB', dbName: 'myAgentDb' },\n * reasoning: { provider: 'openai', apiKey: '...' },\n * tools: [new CalculatorTool()]\n * });\n * const response = await art.process({ query: \"Calculate 5*5\", threadId: \"thread1\" });\n */\nexport async function createArtInstance(config: ArtInstanceConfig): Promise<ArtInstance> { // Changed to ArtInstanceConfig\n const factory = new AgentFactory(config);\n await factory.initialize();\n const agentCore = factory.createAgent();\n\n // Retrieve initialized components from the factory\n const uiSystem = factory.getUISystem();\n const stateManager = factory.getStateManager(); // Assuming getStateManager getter exists\n const conversationManager = factory.getConversationManager(); // Assuming getter exists\n const toolRegistry = factory.getToolRegistry(); // Assuming getter exists\n const observationManager = factory.getObservationManager(); // Assuming getter exists\n const authManager = factory.getAuthManager();\n\n // Ensure all required components were initialized\n if (!uiSystem || !stateManager || !conversationManager || !toolRegistry || !observationManager) {\n throw new Error(\"Failed to initialize one or more core components within AgentFactory.\");\n }\n\n return {\n process: agentCore.process.bind(agentCore), // Bind the process method\n uiSystem: uiSystem,\n stateManager: stateManager,\n conversationManager: conversationManager,\n toolRegistry: toolRegistry,\n observationManager: observationManager,\n authManager: authManager,\n };\n}","import { StorageAdapter } from '@/core/interfaces';\nimport { FilterOptions } from '@/types';\nimport { Logger } from '@/utils/logger';\n\nexport interface SupabaseConfig {\n /** Supabase project URL, e.g., https://xyzcompany.supabase.co */\n url: string;\n /** Supabase anon or service key. Prefer service key on server-side only. */\n apiKey: string;\n /** Optional schema name (default 'public'). */\n schema?: string;\n /**\n * Table names to use. These map ART collections to Supabase.\n * If you customize collection names in repositories, adjust accordingly.\n */\n tables?: {\n conversations?: string;\n observations?: string;\n state?: string;\n a2a_tasks?: string;\n };\n /**\n * Optional: pass a pre-initialized Supabase client (from @supabase/supabase-js)\n * Useful in environments where you already manage the client and auth.\n */\n client?: any;\n}\n\n/**\n * A Supabase-backed StorageAdapter implementation.\n *\n * Expectations/assumptions:\n * - Each collection maps to a table with a primary key column named 'id' (text/uuid).\n * - We store JSON columns for flexible data where needed. However, repositories\n * store fully shaped rows; this adapter just persists and retrieves whole objects.\n * - For query(), we implement basic equality filters per FilterOptions.filter keys,\n * plus limit/skip and a single-key sort.\n */\nexport class SupabaseStorageAdapter implements StorageAdapter {\n private client: any | null = null;\n private config!: SupabaseConfig;\n private schema: string = 'public';\n private tables = {\n conversations: 'conversations',\n observations: 'observations',\n state: 'state',\n a2a_tasks: 'a2a_tasks',\n };\n\n /**\n * Creates an instance of SupabaseStorageAdapter.\n * @see SupabaseConfig\n */\n constructor(config: SupabaseConfig) {\n this.configure(config);\n }\n\n /**\n * Configures the adapter with the provided Supabase settings.\n * @private\n * @param {SupabaseConfig} config - The configuration for the adapter.\n */\n private configure(config: SupabaseConfig) {\n this.config = config;\n if (config.schema) this.schema = config.schema;\n if (config.tables) {\n this.tables = { ...this.tables, ...config.tables };\n }\n this.client = config.client ?? null;\n }\n\n /**\n * Initializes the Supabase client if it hasn't been provided already.\n * @returns {Promise<void>} A promise that resolves when the client is initialized.\n */\n async init(): Promise<void> {\n if (this.client) return; // Already provided\n try {\n // Lazy import to avoid bundling if unused\n const { createClient } = await import('@supabase/supabase-js');\n this.client = createClient(this.config.url, this.config.apiKey, {\n db: { schema: this.schema },\n auth: { persistSession: false },\n });\n Logger.info('SupabaseStorageAdapter: Client initialized.');\n } catch (err: any) {\n Logger.error('SupabaseStorageAdapter: Failed to initialize client', err);\n throw err;\n }\n }\n\n /**\n * Maps a collection name to a Supabase table name.\n * @private\n * @param {string} collection - The name of the collection.\n * @returns {string} The name of the Supabase table.\n */\n private tableForCollection(collection: string): string {\n // Allow direct pass-through for custom collections; otherwise map known ones\n switch (collection) {\n case 'conversations':\n return this.tables.conversations;\n case 'observations':\n return this.tables.observations;\n case 'state':\n return this.tables.state;\n case 'a2a_tasks':\n return this.tables.a2a_tasks;\n default:\n return collection; // Use collection name as-is for custom use\n }\n }\n\n /**\n * Retrieves a single item from a collection by its ID.\n * @template T\n * @param {string} collection - The name of the collection.\n * @param {string} id - The ID of the item to retrieve.\n * @returns {Promise<T | null>} A promise that resolves with the item, or null if not found.\n */\n async get<T>(collection: string, id: string): Promise<T | null> {\n await this.init();\n const table = this.tableForCollection(collection);\n const { data, error } = await this.client\n .from(table)\n .select('*')\n .eq('id', id)\n .limit(1)\n .maybeSingle();\n if (error) {\n Logger.error(`SupabaseStorageAdapter: get error for ${table}/${id}`, error);\n throw new Error(error.message);\n }\n return (data ? { ...data } : null) as T | null;\n }\n\n /**\n * Saves (upserts) an item in a collection.\n * @template T\n * @param {string} collection - The name of the collection.\n * @param {string} id - The ID of the item to save.\n * @param {T} data - The data to save.\n * @returns {Promise<void>} A promise that resolves when the item is saved.\n */\n async set<T>(collection: string, id: string, data: T): Promise<void> {\n await this.init();\n const table = this.tableForCollection(collection);\n const row: any = { ...(data as any) };\n if (typeof row.id === 'undefined') {\n throw new Error(`SupabaseStorageAdapter: Data for collection '${collection}' must have an 'id' property.`);\n }\n // Upsert by primary key 'id'\n const { error } = await this.client\n .from(table)\n .upsert(row, { onConflict: 'id' });\n if (error) {\n Logger.error(`SupabaseStorageAdapter: set error for ${table}/${id}`, error);\n throw new Error(error.message);\n }\n }\n\n /**\n * Deletes an item from a collection by its ID.\n * @param {string} collection - The name of the collection.\n * @param {string} id - The ID of the item to delete.\n * @returns {Promise<void>} A promise that resolves when the item is deleted.\n */\n async delete(collection: string, id: string): Promise<void> {\n await this.init();\n const table = this.tableForCollection(collection);\n const { error } = await this.client\n .from(table)\n .delete()\n .eq('id', id);\n if (error) {\n Logger.error(`SupabaseStorageAdapter: delete error for ${table}/${id}`, error);\n throw new Error(error.message);\n }\n }\n\n /**\n * Queries items in a collection.\n * @template T\n * @param {string} collection - The name of the collection.\n * @param {FilterOptions} filterOptions - The options for filtering, sorting, and pagination.\n * @returns {Promise<T[]>} A promise that resolves with an array of items.\n */\n async query<T>(collection: string, filterOptions: FilterOptions): Promise<T[]> {\n await this.init();\n const table = this.tableForCollection(collection);\n let query = this.client.from(table).select('*');\n\n // Basic equality filters: key = value\n if (filterOptions?.filter) {\n for (const [key, value] of Object.entries(filterOptions.filter)) {\n // For array filter, use 'in'\n if (Array.isArray(value)) {\n query = query.in(key, value);\n } else if (value !== undefined && value !== null) {\n query = query.eq(key, value);\n }\n }\n }\n\n // Sorting: single key supported (choose first)\n if (filterOptions?.sort) {\n const [sortKey, sortDir] = Object.entries(filterOptions.sort)[0] || [];\n if (sortKey) {\n query = query.order(sortKey, { ascending: sortDir === 'asc' });\n }\n }\n\n // Pagination\n const skip = filterOptions?.skip || 0;\n const limit = filterOptions?.limit ?? null;\n if (limit !== null && limit >= 0) {\n query = query.range(skip, skip + Math.max(0, limit) - 1);\n } else if (skip > 0) {\n // Supabase requires a range; if only skip is provided without limit, we pick a large window\n query = query.range(skip, skip + 9999);\n }\n\n const { data, error } = await query;\n if (error) {\n Logger.error(`SupabaseStorageAdapter: query error for ${table}`, error);\n throw new Error(error.message);\n }\n return (data ?? []).map((row: any) => ({ ...row })) as T[];\n }\n\n /**\n * Clears all items from a collection.\n * @param {string} collection - The name of the collection.\n * @returns {Promise<void>} A promise that resolves when the collection is cleared.\n */\n async clearCollection(collection: string): Promise<void> {\n await this.init();\n const table = this.tableForCollection(collection);\n const { error } = await this.client.from(table).delete().neq('id', null);\n if (error) {\n Logger.error(`SupabaseStorageAdapter: clearCollection error for ${table}`, error);\n throw new Error(error.message);\n }\n }\n\n /**\n * Clears all items from all collections.\n * @returns {Promise<void>} A promise that resolves when all collections are cleared.\n */\n async clearAll(): Promise<void> {\n await this.init();\n const tables = Object.values(this.tables);\n for (const table of tables) {\n const { error } = await this.client.from(table).delete().neq('id', null);\n if (error) {\n Logger.error(`SupabaseStorageAdapter: clearAll error for ${table}`, error);\n throw new Error(error.message);\n }\n }\n }\n}\n\n\n","// src/adapters/reasoning/gemini.ts\n// Use correct import based on documentation for @google/genai\nimport { GoogleGenAI, Content, Part, GenerationConfig, GenerateContentResponse } from \"@google/genai\"; // Import SDK components\nimport { ProviderAdapter } from '@/core/interfaces';\nimport {\n ArtStandardPrompt, // Use the new standard type\n // ArtStandardMessage, // Removed unused import\n // ArtStandardMessageRole, // Removed unused import\n CallOptions,\n StreamEvent,\n LLMMetadata,\n // Removed ConversationMessage, MessageRole as they are replaced by ArtStandard types for input\n} from '@/types';\nimport { Logger } from '@/utils/logger';\nimport { ARTError, ErrorCode } from '@/errors'; // Import ARTError and ErrorCode\n\n// Define expected options for the Gemini adapter constructor\n/**\n * Configuration options required for the `GeminiAdapter`.\n */\nexport interface GeminiAdapterOptions {\n /** Your Google AI API key (e.g., from Google AI Studio). Handle securely. */\n apiKey: string;\n /** The default Gemini model ID to use (e.g., 'gemini-1.5-flash-latest', 'gemini-pro'). Defaults to 'gemini-1.5-flash-latest' if not provided. */\n model?: string;\n /** Optional: Override the base URL for the Google Generative AI API. */\n apiBaseUrl?: string; // Note: Not directly used by SDK basic setup\n /** Optional: Specify the API version to use (e.g., 'v1beta'). Defaults to 'v1beta'. */\n apiVersion?: string; // Note: Not directly used by SDK basic setup\n}\n\n\nexport class GeminiAdapter implements ProviderAdapter {\n readonly providerName = 'gemini';\n private apiKey: string;\n private defaultModel: string; // Renamed for clarity\n private genAI: GoogleGenAI; // Stores the initialized GoogleGenAI SDK instance.\n\n /**\n * Creates an instance of GeminiAdapter.\n * @param {GeminiAdapterOptions} options - Configuration options for the adapter.\n * @throws {Error} If `apiKey` is missing in the options.\n * @see https://ai.google.dev/api/rest\n */\n constructor(options: GeminiAdapterOptions) {\n if (!options.apiKey) {\n throw new Error('GeminiAdapter requires an apiKey in options.');\n }\n this.apiKey = options.apiKey;\n this.defaultModel = options.model || 'gemini-1.5-flash-latest'; // Use a common default like flash\n // Initialize the SDK\n // Use correct constructor based on documentation\n this.genAI = new GoogleGenAI({ apiKey: this.apiKey });\n // Note: apiBaseUrl and apiVersion from options are not directly used by the SDK in this basic setup.\n // Advanced SDK configuration might allow proxies if needed.\n Logger.debug(`GeminiAdapter initialized with default model: ${this.defaultModel}`);\n }\n\n /**\n * Makes a call to the configured Gemini model.\n * Translates the `ArtStandardPrompt` into the Gemini API format, sends the request\n * using the `@google/genai` SDK, and yields `StreamEvent` objects representing\n * the response (tokens, metadata, errors, end signal).\n *\n * Handles both streaming and non-streaming requests based on `options.stream`.\n *\n * Thinking tokens (Gemini):\n * - On supported Gemini models (e.g., `gemini-2.5-*`), you can enable thought output via `config.thinkingConfig`.\n * - This adapter reads provider-specific flags from the call options:\n * - `options.gemini.thinking.includeThoughts: boolean` — when `true`, requests thought (reasoning) output.\n * - `options.gemini.thinking.thinkingBudget?: number` — optional token budget for thinking.\n * - When enabled and supported, the adapter will attempt to differentiate thought vs response parts and set\n * `StreamEvent.tokenType` accordingly:\n * - For planning calls (`callContext === 'AGENT_THOUGHT'`): `AGENT_THOUGHT_LLM_THINKING` or `AGENT_THOUGHT_LLM_RESPONSE`.\n * - For synthesis calls (`callContext === 'FINAL_SYNTHESIS'`): `FINAL_SYNTHESIS_LLM_THINKING` or `FINAL_SYNTHESIS_LLM_RESPONSE`.\n * - `LLMMetadata.thinkingTokens` will be populated if the provider reports separate thinking token usage.\n * - If the SDK/model does not expose thought parts, the adapter falls back to labeling tokens as `...LLM_RESPONSE`.\n *\n * @param {ArtStandardPrompt} prompt - The standardized prompt messages.\n * @param {CallOptions} options - Options for the LLM call, including streaming preference, model override, and execution context.\n * @returns {Promise<AsyncIterable<StreamEvent>>} An async iterable that yields `StreamEvent` objects.\n * - `TOKEN`: Contains a chunk of the response text. `tokenType` indicates if it's part of agent thought or final synthesis.\n * When Gemini thinking is enabled and available, `tokenType` may be one of the `...LLM_THINKING` or\n * `...LLM_RESPONSE` variants to separate thought vs response tokens.\n * - `METADATA`: Contains information like stop reason, token counts, and timing, yielded once at the end.\n * - `ERROR`: Contains any error encountered during translation, SDK call, or response processing.\n * - `END`: Signals the completion of the stream.\n * @see {ArtStandardPrompt}\n * @see {CallOptions}\n * @see {StreamEvent}\n * @see {LLMMetadata}\n * @see https://ai.google.dev/api/rest/v1beta/models/generateContent\n *\n * @example\n * // Enable Gemini thinking (if supported by the selected model)\n * const stream = await geminiAdapter.call(prompt, {\n * threadId,\n * stream: true,\n * callContext: 'FINAL_SYNTHESIS',\n * providerConfig, // your RuntimeProviderConfig\n * gemini: {\n * thinking: { includeThoughts: true, thinkingBudget: 8096 }\n * }\n * });\n * for await (const evt of stream) {\n * if (evt.type === 'TOKEN') {\n * // evt.tokenType may be FINAL_SYNTHESIS_LLM_THINKING or FINAL_SYNTHESIS_LLM_RESPONSE\n * }\n * }\n */\n async call(prompt: ArtStandardPrompt, options: CallOptions): Promise<AsyncIterable<StreamEvent>> {\n const { threadId, traceId = `gemini-trace-${Date.now()}`, sessionId, stream, callContext, model: modelOverride } = options;\n const modelToUse = modelOverride || this.defaultModel;\n\n // --- Format Payload for SDK ---\n let contents: Content[];\n try {\n contents = this.translateToGemini(prompt); // Use the new translation function\n } catch (error: any) {\n Logger.error(`Error translating ArtStandardPrompt to Gemini format: ${error.message}`, { error, threadId, traceId });\n // Immediately yield error and end if translation fails\n const generator = async function*(): AsyncIterable<StreamEvent> {\n yield { type: 'ERROR', data: error instanceof Error ? error : new Error(String(error)), threadId, traceId, sessionId };\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n }\n return generator();\n }\n\n const generationConfig: GenerationConfig = { // Use SDK GenerationConfig type\n temperature: options.temperature,\n maxOutputTokens: options.max_tokens || options.maxOutputTokens, // Allow both snake_case and camelCase\n topP: options.top_p || options.topP,\n topK: options.top_k || options.topK,\n stopSequences: options.stop || options.stop_sequences || options.stopSequences,\n // candidateCount: options.n // Map 'n' if needed\n };\n // Remove undefined generationConfig parameters\n Object.keys(generationConfig).forEach(key =>\n generationConfig[key as keyof GenerationConfig] === undefined &&\n delete generationConfig[key as keyof GenerationConfig]\n );\n // Build optional thinking configuration from CallOptions (feature flag)\n // Expecting shape: options.gemini?.thinking?.{ includeThoughts?: boolean; thinkingBudget?: number }\n const includeThoughts: boolean = !!(options as any)?.gemini?.thinking?.includeThoughts;\n const thinkingBudget: number | undefined = (options as any)?.gemini?.thinking?.thinkingBudget;\n // Merge into a requestConfig that is leniently typed to allow SDK preview fields\n const requestConfig: any = includeThoughts\n ? {\n ...generationConfig,\n thinkingConfig: {\n includeThoughts: true,\n ...(thinkingBudget !== undefined ? { thinkingBudget } : {}),\n },\n }\n : { ...generationConfig };\n // --- End Format Payload ---\n\n Logger.debug(`Calling Gemini SDK with model ${modelToUse}, stream: ${!!stream}`, { threadId, traceId });\n\n // Capture 'this.genAI' for use inside the generator function\n const genAIInstance = this.genAI;\n // Use an async generator function\n const generator = async function*(): AsyncIterable<StreamEvent> {\n const startTime = Date.now(); // Use const\n let timeToFirstTokenMs: number | undefined;\n let streamUsageMetadata: any = undefined; // Variable to hold aggregated usage metadata from stream\n let streamFinishReason: string | undefined; // Will hold finishReason from the LAST chunk\n let lastChunk: GenerateContentResponse | undefined = undefined; // Variable to store the last chunk\n // Removed unused aggregatedResponseText\n \n try {\n // --- Handle Streaming Response using SDK ---\n if (stream) {\n // Let TypeScript infer the type of streamResult\n // Use the new SDK pattern: genAI.models.generateContentStream\n const streamResult = await genAIInstance.models.generateContentStream({ // Use captured instance\n model: modelToUse, // Pass model name here\n contents,\n config: requestConfig, // Pass merged config including optional thinkingConfig\n });\n\n // Process the stream by iterating directly over streamResult (based on docs)\n for await (const chunk of streamResult) {\n lastChunk = chunk; // Store the current chunk as the potential last one\n if (!timeToFirstTokenMs) {\n timeToFirstTokenMs = Date.now() - startTime;\n }\n // Prefer structured parts if available to differentiate thinking vs response\n const candidate = (chunk as any)?.candidates?.[0];\n const parts = candidate?.content?.parts;\n if (Array.isArray(parts) && parts.length > 0) {\n for (const part of parts) {\n const partText: string | undefined = (part as any)?.text;\n if (!partText) continue;\n const isThought: boolean = !!(\n (part as any)?.thought ||\n (part as any)?.metadata?.thought ||\n (part as any)?.inlineMetadata?.thought\n );\n const tokenType = callContext === 'AGENT_THOUGHT'\n ? (isThought ? 'AGENT_THOUGHT_LLM_THINKING' : 'AGENT_THOUGHT_LLM_RESPONSE')\n : (isThought ? 'FINAL_SYNTHESIS_LLM_THINKING' : 'FINAL_SYNTHESIS_LLM_RESPONSE');\n yield { type: 'TOKEN', data: partText, threadId, traceId, sessionId, tokenType };\n }\n } else {\n const textPart = (chunk as any).text; // Access as property (fallback)\n if (textPart) {\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n yield { type: 'TOKEN', data: textPart, threadId, traceId, sessionId, tokenType };\n }\n }\n // Log potential usage metadata if available in chunks (less common)\n // Capture usage metadata if present in chunks\n if (chunk.usageMetadata) {\n // Note: Based on testing, usageMetadata usually appears only in the *last* chunk,\n // but we check here just in case the behavior changes or varies.\n Logger.debug(\"Gemini stream chunk usageMetadata:\", { usageMetadata: chunk.usageMetadata, threadId, traceId });\n // Simple merge/overwrite for now, might need more sophisticated aggregation\n streamUsageMetadata = { ...(streamUsageMetadata || {}), ...chunk.usageMetadata };\n }\n }\n\n // NOTE: The new SDK stream example doesn't show accessing a final .response\n // We might need to aggregate metadata from chunks or handle it differently.\n // For now, remove the finalResponse logic and associated metadata yield for streaming.\n // We still need to yield END.\n const totalGenerationTimeMs = Date.now() - startTime; // Keep total time calculation\n Logger.debug(\"Gemini stream finished processing chunks.\", { totalGenerationTimeMs, threadId, traceId });\n\n // TODO: Revisit how to get final metadata (stopReason, token counts) for streams if needed.\n // --- Extract metadata from the LAST chunk AFTER the loop ---\n if (lastChunk) {\n streamFinishReason = lastChunk.candidates?.[0]?.finishReason;\n streamUsageMetadata = lastChunk.usageMetadata; // Get metadata directly from last chunk\n Logger.debug(\"Gemini stream - Extracted from last chunk:\", { finishReason: streamFinishReason, usageMetadata: streamUsageMetadata, threadId, traceId });\n } else {\n Logger.warn(\"Gemini stream - No last chunk found after loop.\", { threadId, traceId });\n }\n // --- End extraction from last chunk ---\n \n // Yield final METADATA using values extracted from the last chunk\n const finalUsage = streamUsageMetadata || {}; // Use extracted metadata or empty object\n const metadata: LLMMetadata = {\n stopReason: streamFinishReason, // Use finishReason from last chunk\n inputTokens: finalUsage?.promptTokenCount,\n outputTokens: finalUsage?.candidatesTokenCount, // Or totalTokenCount? Check SDK details\n thinkingTokens: finalUsage?.thinkingTokenCount ?? finalUsage?.thoughtTokens,\n timeToFirstTokenMs: timeToFirstTokenMs,\n totalGenerationTimeMs: totalGenerationTimeMs,\n providerRawUsage: finalUsage, // Use usage from last chunk\n traceId: traceId,\n };\n yield { type: 'METADATA', data: metadata, threadId, traceId, sessionId };\n \n // --- Handle Non-Streaming Response using SDK ---\n } else {\n // Use the new SDK pattern: genAIInstance.models.generateContent\n // Revert direct parameter passing\n const result: GenerateContentResponse = await genAIInstance.models.generateContent({ // Use captured instance\n model: modelToUse, // Pass model name here\n contents,\n config: requestConfig, // Use merged config including optional thinkingConfig\n });\n // Removed incorrect line: const response = result.response;\n const firstCandidate = result.candidates?.[0]; // Access directly from result\n const responseText = result.text; // Access as a property\n const finishReason = firstCandidate?.finishReason;\n const usageMetadata = result.usageMetadata; // Access directly from result\n const totalGenerationTimeMs = Date.now() - startTime;\n\n\n // If structured parts are present, prefer splitting into thought vs response tokens\n const nonStreamParts = (firstCandidate as any)?.content?.parts;\n if (Array.isArray(nonStreamParts) && nonStreamParts.length > 0) {\n for (const part of nonStreamParts) {\n const partText: string | undefined = (part as any)?.text;\n if (!partText) continue;\n const isThought: boolean = !!(\n (part as any)?.thought ||\n (part as any)?.metadata?.thought ||\n (part as any)?.inlineMetadata?.thought\n );\n const tokenType = callContext === 'AGENT_THOUGHT'\n ? (isThought ? 'AGENT_THOUGHT_LLM_THINKING' : 'AGENT_THOUGHT_LLM_RESPONSE')\n : (isThought ? 'FINAL_SYNTHESIS_LLM_THINKING' : 'FINAL_SYNTHESIS_LLM_RESPONSE');\n yield { type: 'TOKEN', data: partText.trim(), threadId, traceId, sessionId, tokenType };\n }\n } else if (!firstCandidate || !responseText) {\n if (result.promptFeedback?.blockReason) { // Access directly from result\n Logger.error('Gemini SDK call blocked.', { feedback: result.promptFeedback, threadId, traceId });\n yield { type: 'ERROR', data: new Error(`Gemini API call blocked: ${result.promptFeedback.blockReason}`), threadId, traceId, sessionId };\n return;\n }\n Logger.error('Invalid response structure from Gemini SDK: No text content found', { responseData: result, threadId, traceId }); // Log the whole result\n yield { type: 'ERROR', data: new Error('Invalid response structure from Gemini SDK: No text content found.'), threadId, traceId, sessionId };\n return;\n } else {\n // Yield TOKEN (fallback single text)\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'LLM_RESPONSE';\n yield { type: 'TOKEN', data: responseText.trim(), threadId, traceId, sessionId, tokenType };\n }\n\n // Yield METADATA\n const metadata: LLMMetadata = {\n stopReason: finishReason,\n inputTokens: usageMetadata?.promptTokenCount,\n outputTokens: usageMetadata?.candidatesTokenCount,\n thinkingTokens: (usageMetadata as any)?.thinkingTokenCount ?? (usageMetadata as any)?.thoughtTokens,\n totalGenerationTimeMs: totalGenerationTimeMs,\n providerRawUsage: usageMetadata,\n traceId: traceId,\n };\n yield { type: 'METADATA', data: metadata, threadId, traceId, sessionId };\n }\n\n // Yield END signal\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n\n } catch (error: any) {\n Logger.error(`Error during Gemini SDK call: ${error.message}`, { error, threadId, traceId });\n yield { type: 'ERROR', data: error instanceof Error ? error : new Error(String(error)), threadId, traceId, sessionId };\n // Ensure END is yielded even after an error\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n }\n };\n\n return generator();\n }\n\n /**\n * Translates the provider-agnostic `ArtStandardPrompt` into the Gemini API's `Content[]` format.\n *\n * Key translations:\n * - `system` role: Merged into the first `user` message.\n * - `user` role: Maps to Gemini's `user` role.\n * - `assistant` role: Maps to Gemini's `model` role. Handles text content and `tool_calls` (mapped to `functionCall`).\n * - `tool_result` role: Maps to Gemini's `user` role with a `functionResponse` part.\n * - `tool_request` role: Skipped (implicitly handled by `assistant`'s `tool_calls`).\n *\n * Adds validation to ensure the conversation doesn't start with a 'model' role.\n *\n * @private\n * @param {ArtStandardPrompt} artPrompt - The input `ArtStandardPrompt` array.\n * @returns {Content[]} The `Content[]` array formatted for the Gemini API.\n * @throws {ARTError} If translation encounters an issue, such as a `tool_result` missing required fields (ErrorCode.PROMPT_TRANSLATION_FAILED).\n * @see https://ai.google.dev/api/rest/v1beta/Content\n */\n private translateToGemini(artPrompt: ArtStandardPrompt): Content[] {\n const geminiContents: Content[] = [];\n\n // System prompt handling: Gemini prefers system instructions via specific parameters or\n // potentially as the first part of the first 'user' message. For simplicity,\n // we'll merge the system prompt content into the first user message if present.\n let systemPromptContent: string | null = null;\n\n for (const message of artPrompt) {\n let role: 'user' | 'model';\n const parts: Part[] = [];\n\n switch (message.role) {\n case 'system':\n // Store system prompt content to potentially merge later.\n if (typeof message.content === 'string') {\n systemPromptContent = message.content;\n } else {\n Logger.warn(`GeminiAdapter: Ignoring non-string system prompt content.`, { content: message.content });\n }\n continue; // Don't add a separate 'system' role message\n\n case 'user': { // Added braces to fix ESLint error\n role = 'user';\n let userContent = '';\n // Prepend system prompt if this is the first user message\n if (systemPromptContent) {\n userContent += systemPromptContent + \"\\n\\n\";\n systemPromptContent = null; // Clear after merging\n }\n if (typeof message.content === 'string') {\n userContent += message.content;\n } else {\n Logger.warn(`GeminiAdapter: Stringifying non-string user content.`, { content: message.content });\n userContent += JSON.stringify(message.content);\n }\n parts.push({ text: userContent });\n break;\n } // Added braces\n\n case 'assistant':\n role = 'model';\n // Handle text content\n if (typeof message.content === 'string' && message.content.trim() !== '') {\n parts.push({ text: message.content });\n }\n // Handle tool calls (function calls in Gemini)\n if (message.tool_calls && message.tool_calls.length > 0) {\n message.tool_calls.forEach(toolCall => {\n if (toolCall.type === 'function') {\n parts.push({\n functionCall: {\n name: toolCall.function.name,\n args: JSON.parse(toolCall.function.arguments || '{}'), // Gemini expects parsed args object\n }\n });\n } else {\n Logger.warn(`GeminiAdapter: Skipping unsupported tool call type: ${toolCall.type}`);\n }\n });\n }\n // If assistant message has neither content nor tool calls, add empty text part? Gemini might require it.\n if (parts.length === 0) {\n parts.push({ text: \"\" }); // Add empty text part if no content or tool calls\n }\n break;\n\n case 'tool_result':\n role = 'user'; // Gemini expects tool results within a 'user' role message\n if (!message.tool_call_id || !message.name) {\n throw new ARTError(\n `GeminiAdapter: 'tool_result' message missing required 'tool_call_id' or 'name'.`,\n ErrorCode.PROMPT_TRANSLATION_FAILED\n );\n }\n parts.push({\n functionResponse: {\n name: message.name, // Tool name\n response: {\n // Gemini expects the result content under a 'content' key within 'response'\n // The content should be the stringified output/error from ArtStandardMessage.content\n content: message.content // Assuming content is already stringified result/error\n }\n }\n });\n break;\n\n case 'tool_request':\n // This role is implicitly handled by 'tool_calls' in the preceding 'assistant' message.\n Logger.debug(`GeminiAdapter: Skipping 'tool_request' role message as it's handled by assistant's tool_calls.`);\n continue; // Skip this message\n\n default:\n Logger.warn(`GeminiAdapter: Skipping message with unhandled role: ${message.role}`);\n continue;\n }\n\n geminiContents.push({ role, parts });\n }\n\n // Handle case where system prompt was provided but no user message followed\n if (systemPromptContent) {\n Logger.warn(\"GeminiAdapter: System prompt provided but no user message found to merge it into. Adding as a separate initial user message.\");\n geminiContents.unshift({ role: 'user', parts: [{ text: systemPromptContent }] });\n }\n\n // Gemini specific validation: Ensure conversation doesn't start with 'model'\n if (geminiContents.length > 0 && geminiContents[0].role === 'model') {\n Logger.warn(\"Gemini conversation history starts with 'model' role. Prepending a dummy 'user' turn.\", { firstRole: geminiContents[0].role });\n geminiContents.unshift({ role: 'user', parts: [{ text: \"(Initial context)\" }] }); // Prepend a generic user turn\n }\n\n return geminiContents;\n }\n}","// src/integrations/reasoning/openai.ts\nimport OpenAI from 'openai';\nimport { ProviderAdapter, ToolSchema } from '@/core/interfaces';\nimport {\n ArtStandardPrompt,\n ArtStandardMessage,\n CallOptions,\n StreamEvent,\n LLMMetadata,\n} from '@/types';\nimport { Logger } from '@/utils/logger';\nimport { ARTError, ErrorCode } from '@/errors';\n\n// Default model configuration\nconst OPENAI_DEFAULT_MODEL_ID = 'gpt-4o';\nconst OPENAI_DEFAULT_MAX_TOKENS = 4096;\nconst OPENAI_DEFAULT_TEMPERATURE = 0.7;\n\n/**\n * Configuration options required for the `OpenAIAdapter`.\n */\nexport interface OpenAIAdapterOptions {\n /** Your OpenAI API key. Handle securely. */\n apiKey: string;\n /** The default OpenAI model ID to use (e.g., 'gpt-4o', 'gpt-5', 'gpt-5-mini'). */\n model?: string;\n /** Optional: Override the base URL for the OpenAI API (e.g., for Azure OpenAI or custom proxies). */\n apiBaseUrl?: string;\n /** Optional: Default maximum tokens for responses. */\n defaultMaxTokens?: number;\n /** Optional: Default temperature for responses. */\n defaultTemperature?: number;\n}\n\n// Types for OpenAI Responses API\ninterface OpenAIResponsesInputMessage {\n role: 'user' | 'assistant';\n content: Array<{\n type: 'input_text' | 'output_text' | 'input_image';\n text?: string;\n image_url?: string;\n }>;\n}\n\ninterface OpenAIResponsesPayload {\n model: string;\n input: OpenAIResponsesInputMessage[];\n instructions?: string; // System prompt goes here\n temperature?: number;\n max_output_tokens?: number;\n stream?: boolean;\n store?: boolean;\n reasoning?: {\n effort?: 'low' | 'medium' | 'high';\n summary?: 'auto' | 'concise' | 'detailed';\n };\n tools?: OpenAIResponsesTool[];\n}\n\ninterface OpenAIResponsesTool {\n type: 'function';\n function: {\n name: string;\n description: string;\n parameters: object; // JSON Schema\n };\n}\n\ninterface OpenAIResponsesUsage {\n input_tokens?: number;\n output_tokens?: number;\n output_tokens_details?: {\n reasoning_tokens?: number;\n };\n total_tokens?: number;\n}\n\ninterface OpenAIResponsesResponse {\n id: string;\n object: string;\n created: number;\n model: string;\n output?: Array<{\n type: 'message' | 'reasoning';\n id?: string;\n content?: Array<{\n type: 'output_text';\n text: string;\n }>;\n summary?: Array<{\n type: 'summary_text';\n text: string;\n }>;\n }>;\n status: 'completed' | 'incomplete' | 'failed';\n usage?: OpenAIResponsesUsage;\n}\n\n/**\n * Implements the `ProviderAdapter` interface for interacting with OpenAI's\n * Responses API (supports reasoning models like GPT-5 family and other models).\n *\n * Handles formatting requests, parsing responses, streaming, reasoning token detection, and tool use.\n * Uses the official OpenAI SDK with the new Responses API for full reasoning model support.\n *\n * @see {@link ProviderAdapter} for the interface definition.\n * @see {@link OpenAIAdapterOptions} for configuration options.\n */\nexport class OpenAIAdapter implements ProviderAdapter {\n readonly providerName = 'openai';\n private client: OpenAI;\n private defaultModel: string;\n private defaultMaxTokens: number;\n private defaultTemperature: number;\n\n /**\n * Creates an instance of the OpenAIAdapter.\n * @param options - Configuration options including the API key and optional model/baseURL/defaults.\n * @throws {ARTError} If the API key is missing.\n */\n constructor(options: OpenAIAdapterOptions) {\n if (!options.apiKey) {\n throw new ARTError('OpenAIAdapter requires an apiKey in options.', ErrorCode.INVALID_CONFIG);\n }\n\n this.client = new OpenAI({\n apiKey: options.apiKey,\n baseURL: options.apiBaseUrl || undefined,\n });\n\n this.defaultModel = options.model || OPENAI_DEFAULT_MODEL_ID;\n this.defaultMaxTokens = options.defaultMaxTokens || OPENAI_DEFAULT_MAX_TOKENS;\n this.defaultTemperature = options.defaultTemperature || OPENAI_DEFAULT_TEMPERATURE;\n\n Logger.debug(`OpenAIAdapter initialized with model: ${this.defaultModel}`);\n }\n\n /**\n * Sends a request to the OpenAI Responses API.\n * Translates `ArtStandardPrompt` to the Responses API format and handles streaming/reasoning.\n *\n * @param {ArtStandardPrompt} prompt - The standardized prompt messages.\n * @param {CallOptions} options - Call options, including streaming, reasoning options, and model parameters.\n * @returns {Promise<AsyncIterable<StreamEvent>>} A promise resolving to an AsyncIterable of StreamEvent objects.\n */\n async call(prompt: ArtStandardPrompt, options: CallOptions): Promise<AsyncIterable<StreamEvent>> {\n const {\n threadId,\n traceId = `openai-trace-${Date.now()}`,\n sessionId,\n stream = false,\n callContext,\n model: modelOverride,\n tools: availableArtTools,\n providerConfig,\n } = options;\n\n const modelToUse = providerConfig?.modelId || modelOverride || this.defaultModel;\n\n // Extract OpenAI specific parameters\n const openaiApiParams = providerConfig?.adapterOptions || {};\n const maxTokens = openaiApiParams.max_tokens || openaiApiParams.maxTokens || options.max_tokens || options.maxOutputTokens || this.defaultMaxTokens;\n const temperature = openaiApiParams.temperature ?? options.temperature ?? this.defaultTemperature;\n \n // Extract reasoning configuration from options\n const openaiOptions = (options as any).openai || {};\n const reasoningEffort = openaiOptions.reasoning?.effort || 'medium';\n const reasoningSummary = openaiOptions.reasoning?.summary || 'auto';\n\n let systemPrompt: string | undefined;\n let responsesInput: OpenAIResponsesInputMessage[];\n try {\n const translationResult = this.translateToResponsesFormat(prompt);\n systemPrompt = translationResult.systemPrompt;\n responsesInput = translationResult.input;\n } catch (error: any) {\n Logger.error(`Error translating ArtStandardPrompt to OpenAI Responses format: ${error.message}`, { error, threadId, traceId });\n const artError = error instanceof ARTError ? error : new ARTError(`Prompt translation failed: ${error.message}`, ErrorCode.PROMPT_TRANSLATION_FAILED, error);\n const errorGenerator = async function* (): AsyncIterable<StreamEvent> {\n yield { type: 'ERROR', data: artError, threadId, traceId, sessionId };\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n };\n return errorGenerator();\n }\n\n const openaiTools: OpenAIResponsesTool[] | undefined = availableArtTools\n ? this.translateArtToolsToOpenAI(availableArtTools)\n : undefined;\n\n const requestBody: OpenAIResponsesPayload = {\n model: modelToUse,\n input: responsesInput,\n instructions: systemPrompt,\n temperature: temperature,\n max_output_tokens: maxTokens,\n stream: stream,\n store: true, // Enable conversation continuity\n reasoning: {\n effort: reasoningEffort,\n summary: reasoningSummary,\n },\n tools: openaiTools,\n };\n\n // Remove undefined keys from the request body\n Object.keys(requestBody).forEach(key => {\n const K = key as keyof OpenAIResponsesPayload;\n if (requestBody[K] === undefined) {\n delete requestBody[K];\n }\n });\n\n Logger.debug(`Calling OpenAI Responses API with model ${modelToUse}`, { stream, tools: !!openaiTools, threadId, traceId });\n\n // Use an async generator function\n const generator = async function* (this: OpenAIAdapter): AsyncIterable<StreamEvent> {\n try {\n const startTime = Date.now();\n let timeToFirstTokenMs: number | undefined;\n \n if (stream) {\n // Use the OpenAI SDK's responses.create method for streaming\n const streamInstance = await (this.client as any).responses.create({\n ...requestBody,\n stream: true,\n });\n\n let accumulatedText = \"\";\n let accumulatedReasoning = \"\";\n let finalStopReason: string | undefined;\n let finalUsage: OpenAIResponsesUsage | undefined;\n let accumulatedToolCalls: any[] = [];\n\n // Process the stream\n for await (const event of streamInstance) {\n if (timeToFirstTokenMs === undefined) {\n timeToFirstTokenMs = Date.now() - startTime;\n }\n\n // Handle reasoning deltas\n if (event.type === 'response.reasoning.delta' || event.type === 'response.reasoning_text.delta') {\n if (event.delta) {\n accumulatedReasoning += event.delta;\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_THINKING' : 'FINAL_SYNTHESIS_LLM_THINKING';\n yield { type: 'TOKEN', data: event.delta, threadId, traceId, sessionId, tokenType };\n }\n }\n // Handle reasoning summary deltas\n else if (event.type === 'response.reasoning_summary.delta' || event.type === 'response.reasoning_summary_text.delta') {\n if (event.delta) {\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_THINKING' : 'FINAL_SYNTHESIS_LLM_THINKING';\n yield { type: 'TOKEN', data: event.delta, threadId, traceId, sessionId, tokenType };\n }\n }\n // Handle text/output deltas\n else if (event.type === 'response.text.delta' || event.type === 'response.output_text.delta') {\n if (event.delta) {\n accumulatedText += event.delta;\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n yield { type: 'TOKEN', data: event.delta, threadId, traceId, sessionId, tokenType };\n }\n }\n // Handle output item additions (alternative format for complete items)\n else if (event.type === 'response.output_item.added') {\n if (event.item) {\n if (event.item.type === 'text' && event.item.text) {\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n yield { type: 'TOKEN', data: event.item.text, threadId, traceId, sessionId, tokenType };\n } else if (event.item.type === 'reasoning' && event.item.text) {\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_THINKING' : 'FINAL_SYNTHESIS_LLM_THINKING';\n yield { type: 'TOKEN', data: event.item.text, threadId, traceId, sessionId, tokenType };\n } else if (event.item.type === 'message' && event.item.content) {\n for (const content of event.item.content) {\n if (content.type === 'output_text' && content.text) {\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n yield { type: 'TOKEN', data: content.text, threadId, traceId, sessionId, tokenType };\n }\n }\n }\n }\n }\n // Handle completion events with usage data\n else if (event.type === 'response.done' || event.type === 'response.completed') {\n if (event.response?.usage) {\n finalUsage = event.response.usage;\n }\n if (event.response?.status) {\n // Map status to finish reason\n finalStopReason = event.response.status === 'completed' ? 'stop' : event.response.status;\n }\n }\n // Handle error events\n else if (event.type === 'response.error' || event.type === 'error') {\n const errorMessage = event.error?.message || event.message || 'Unknown OpenAI Responses API error';\n throw new ARTError(`OpenAI Responses API Error: ${errorMessage}`, ErrorCode.LLM_PROVIDER_ERROR, new Error(errorMessage));\n }\n }\n\n // Yield final metadata for streaming\n const totalGenerationTimeMs = Date.now() - startTime;\n const metadata: LLMMetadata = {\n inputTokens: finalUsage?.input_tokens,\n outputTokens: finalUsage?.output_tokens,\n thinkingTokens: finalUsage?.output_tokens_details?.reasoning_tokens,\n stopReason: finalStopReason,\n timeToFirstTokenMs,\n totalGenerationTimeMs,\n providerRawUsage: finalUsage,\n traceId: traceId,\n };\n yield { type: 'METADATA', data: metadata, threadId, traceId, sessionId };\n\n } else {\n // Non-streaming response using the Responses API\n const response = await (this.client as any).responses.create({\n ...requestBody,\n stream: false,\n }) as OpenAIResponsesResponse;\n\n Logger.debug(`OpenAI Responses API call successful (non-streaming). Status: ${response.status}`, { threadId, traceId });\n\n let responseText = \"\";\n let reasoningText = \"\";\n const toolUseBlocks: any[] = [];\n\n // Extract content from response\n if (response.output && Array.isArray(response.output)) {\n for (const outputItem of response.output) {\n if (outputItem.type === 'message' && outputItem.content) {\n for (const content of outputItem.content) {\n if (content.type === 'output_text') {\n responseText += content.text;\n }\n }\n } else if (outputItem.type === 'reasoning' && outputItem.summary) {\n for (const summary of outputItem.summary) {\n if (summary.type === 'summary_text') {\n reasoningText += summary.text;\n }\n }\n }\n }\n }\n\n // Yield reasoning tokens first if available\n if (reasoningText.trim()) {\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_THINKING' : 'FINAL_SYNTHESIS_LLM_THINKING';\n yield { type: 'TOKEN', data: reasoningText.trim(), threadId, traceId, sessionId, tokenType };\n }\n\n // Then yield response tokens\n if (responseText.trim()) {\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n yield { type: 'TOKEN', data: responseText.trim(), threadId, traceId, sessionId, tokenType };\n }\n\n // Handle tool calls if present\n if (toolUseBlocks.length > 0) {\n const toolData = toolUseBlocks.map(tu => ({\n type: 'tool_use',\n id: tu.id,\n name: tu.name,\n input: tu.input,\n }));\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n yield { type: 'TOKEN', data: toolData, threadId, traceId, sessionId, tokenType };\n }\n\n // Yield metadata for non-streaming\n if (response.usage) {\n const totalGenerationTimeMs = Date.now() - startTime;\n const metadata: LLMMetadata = {\n inputTokens: response.usage.input_tokens,\n outputTokens: response.usage.output_tokens,\n thinkingTokens: response.usage.output_tokens_details?.reasoning_tokens,\n stopReason: response.status === 'completed' ? 'stop' : response.status,\n totalGenerationTimeMs,\n providerRawUsage: { usage: response.usage, status: response.status },\n traceId: traceId,\n };\n yield { type: 'METADATA', data: metadata, threadId, traceId, sessionId };\n }\n }\n\n // Yield END signal for both streaming and non-streaming\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n\n } catch (error: any) {\n Logger.error(`Error during OpenAI Responses API call: ${error.message}`, { error, threadId, traceId });\n const artError = error instanceof ARTError ? error :\n (error instanceof Error && error.message.includes('OpenAI') ? \n new ARTError(`OpenAI API Error: ${error.message}`, ErrorCode.LLM_PROVIDER_ERROR, error) :\n new ARTError(error.message || 'Unknown OpenAI adapter error', ErrorCode.LLM_PROVIDER_ERROR, error));\n yield { type: 'ERROR', data: artError, threadId, traceId, sessionId };\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n }\n }.bind(this);\n\n return generator();\n }\n\n /**\n * Optional: Method for graceful shutdown\n */\n async shutdown(): Promise<void> {\n Logger.debug(`OpenAIAdapter shutdown called.`);\n // Clean up any resources if needed\n }\n\n /**\n * Translates the provider-agnostic `ArtStandardPrompt` into the OpenAI Responses API format.\n * Extracts system prompt separately and formats messages as input array.\n *\n * @private\n * @param {ArtStandardPrompt} artPrompt - The input `ArtStandardPrompt` array.\n * @returns {{ systemPrompt?: string; input: OpenAIResponsesInputMessage[] }} An object containing the extracted system prompt and the array of Responses API formatted input messages.\n * @throws {ARTError} If translation encounters an issue.\n */\n private translateToResponsesFormat(artPrompt: ArtStandardPrompt): { systemPrompt?: string; input: OpenAIResponsesInputMessage[] } {\n let systemPrompt: string | undefined;\n const input: OpenAIResponsesInputMessage[] = [];\n\n for (const artMsg of artPrompt) {\n if (artMsg.role === 'system') {\n const systemText = (typeof artMsg.content === 'string') ? artMsg.content : String(artMsg.content);\n if (!systemPrompt) {\n systemPrompt = systemText;\n } else {\n Logger.warn(`OpenAIAdapter: Multiple system messages found. Appending to existing system prompt.`);\n systemPrompt += `\\n${systemText}`;\n }\n continue;\n }\n\n const translatedContent = this.mapArtMessageToResponsesContent(artMsg);\n if (translatedContent) {\n input.push(translatedContent);\n }\n }\n\n return { systemPrompt, input };\n }\n\n /**\n * Maps a single `ArtStandardMessage` to OpenAI Responses API input format.\n *\n * @private\n * @param {ArtStandardMessage} artMsg - The ART standard message to map.\n * @returns {OpenAIResponsesInputMessage | null} The translated message for the Responses API, or null if should be skipped.\n * @throws {ARTError} If tool call arguments are not valid JSON.\n */\n private mapArtMessageToResponsesContent(artMsg: ArtStandardMessage): OpenAIResponsesInputMessage | null {\n switch (artMsg.role) {\n case 'user':\n case 'tool_result': {\n // Both user and tool_result messages become 'user' role in Responses API\n const content: Array<{ type: 'input_text'; text: string }> = [];\n \n if (artMsg.role === 'tool_result') {\n // Format tool result with context\n const toolResultText = `Tool result for ${artMsg.name || 'unknown tool'}: ${String(artMsg.content)}`;\n content.push({ type: 'input_text', text: toolResultText });\n } else {\n // Regular user message\n const userText = typeof artMsg.content === 'string' ? artMsg.content : String(artMsg.content);\n content.push({ type: 'input_text', text: userText });\n }\n\n return { role: 'user', content };\n }\n\n case 'assistant': {\n const content: Array<{ type: 'output_text'; text: string }> = [];\n \n // Handle text content\n if (typeof artMsg.content === 'string' && artMsg.content.trim() !== '') {\n content.push({ type: 'output_text', text: artMsg.content });\n }\n\n // Handle tool calls - convert to text description for Responses API\n if (artMsg.tool_calls && artMsg.tool_calls.length > 0) {\n const toolCallsText = artMsg.tool_calls.map(tc => {\n try {\n const args = JSON.parse(tc.function.arguments || '{}');\n return `Called tool ${tc.function.name} with arguments: ${JSON.stringify(args)}`;\n } catch (e: any) {\n throw new ARTError(\n `OpenAIAdapter: Failed to parse tool call arguments for tool ${tc.function.name} (ID: ${tc.id}). Arguments must be valid JSON. Error: ${e.message}`,\n ErrorCode.PROMPT_TRANSLATION_FAILED, e\n );\n }\n }).join('\\n');\n \n if (content.length > 0) {\n content[0].text += '\\n\\n' + toolCallsText;\n } else {\n content.push({ type: 'output_text', text: toolCallsText });\n }\n }\n\n // If no content at all, add empty text\n if (content.length === 0) {\n content.push({ type: 'output_text', text: '' });\n }\n\n return { role: 'assistant', content };\n }\n\n case 'tool_request': {\n // Skip tool_request messages - they're handled by assistant's tool_calls\n Logger.debug(`OpenAIAdapter: Skipping 'tool_request' role message as it's handled by assistant's tool_calls.`);\n return null;\n }\n\n default: {\n Logger.warn(`OpenAIAdapter: Skipping message with unhandled role: ${artMsg.role}`);\n return null;\n }\n }\n }\n\n /**\n * Translates an array of `ToolSchema` from the ART framework format to OpenAI's Responses API tool format.\n * @private\n * @param {ToolSchema[]} artTools - An array of ART tool schemas.\n * @returns {OpenAIResponsesTool[]} An array of tools formatted for the OpenAI Responses API.\n * @throws {ARTError} If a tool's `inputSchema` is invalid.\n */\n private translateArtToolsToOpenAI(artTools: ToolSchema[]): OpenAIResponsesTool[] {\n return artTools.map(artTool => {\n if (!artTool.inputSchema || typeof artTool.inputSchema !== 'object') {\n throw new ARTError(`Invalid inputSchema definition for tool '${artTool.name}'. Expected a JSON schema object.`, ErrorCode.INVALID_CONFIG);\n }\n return {\n type: 'function',\n function: {\n name: artTool.name,\n description: artTool.description,\n parameters: artTool.inputSchema,\n },\n };\n });\n }\n}","// src/adapters/reasoning/anthropic.ts\nimport { Anthropic } from '@anthropic-ai/sdk';\nimport { ProviderAdapter, ToolSchema } from '@/core/interfaces';\nimport {\n ArtStandardPrompt,\n ArtStandardMessage,\n CallOptions,\n StreamEvent,\n LLMMetadata,\n} from '@/types';\nimport { Logger } from '@/utils/logger';\nimport { ARTError, ErrorCode } from '@/errors';\n\n// Default model if not specified\nconst ANTHROPIC_DEFAULT_MODEL_ID = 'claude-3-7-sonnet-20250219';\nconst ANTHROPIC_DEFAULT_MAX_TOKENS = 4096;\n\n/**\n * Configuration options required for the `AnthropicAdapter`.\n */\nexport interface AnthropicAdapterOptions {\n /** Your Anthropic API key. Handle securely. */\n apiKey: string;\n /** The default Anthropic model ID to use (e.g., 'claude-3-opus-20240229', 'claude-3-5-sonnet-20240620'). */\n model?: string;\n /** Optional: Override the base URL for the Anthropic API. */\n apiBaseUrl?: string;\n /** Optional: Default maximum tokens for responses. */\n defaultMaxTokens?: number;\n /** Optional: Default temperature for responses. */\n defaultTemperature?: number;\n}\n\n// Types for Anthropic API interaction using the SDK\ntype AnthropicSDKMessageParam = Anthropic.Messages.MessageParam;\ntype AnthropicSDKContentBlockParam = Anthropic.Messages.TextBlockParam | Anthropic.Messages.ImageBlockParam | Anthropic.Messages.ToolUseBlockParam | Anthropic.Messages.ToolResultBlockParam;\ntype AnthropicSDKTool = Anthropic.Tool;\ntype AnthropicSDKToolUseBlock = Anthropic.ToolUseBlock;\n\n/**\n * Implements the `ProviderAdapter` interface for interacting with Anthropic's\n * Messages API (Claude models) using the official SDK.\n *\n * Handles formatting requests, parsing responses, streaming, and tool use.\n *\n * @see {@link ProviderAdapter} for the interface definition.\n * @see {@link AnthropicAdapterOptions} for configuration options.\n */\nexport class AnthropicAdapter implements ProviderAdapter {\n readonly providerName = 'anthropic';\n private client: Anthropic;\n private defaultModel: string;\n private defaultMaxTokens: number;\n private defaultTemperature?: number;\n\n /**\n * Creates an instance of the AnthropicAdapter.\n * @param options - Configuration options including the API key and optional model/baseURL/defaults.\n * @throws {ARTError} If the API key is missing.\n */\n constructor(options: AnthropicAdapterOptions) {\n if (!options.apiKey) {\n throw new ARTError('AnthropicAdapter requires an apiKey in options.', ErrorCode.INVALID_CONFIG);\n }\n\n this.client = new Anthropic({\n apiKey: options.apiKey,\n baseURL: options.apiBaseUrl || undefined,\n });\n\n this.defaultModel = options.model || ANTHROPIC_DEFAULT_MODEL_ID;\n this.defaultMaxTokens = options.defaultMaxTokens || ANTHROPIC_DEFAULT_MAX_TOKENS;\n this.defaultTemperature = options.defaultTemperature;\n\n Logger.debug(`AnthropicAdapter initialized with model: ${this.defaultModel}`);\n }\n\n /**\n * Sends a request to the Anthropic Messages API.\n * Translates `ArtStandardPrompt` to the Anthropic format and handles streaming and tool use.\n *\n * @param {ArtStandardPrompt} prompt - The standardized prompt messages.\n * @param {CallOptions} options - Call options, including `threadId`, `traceId`, `stream`, `callContext`,\n * `model` (override), `tools` (available tools), and Anthropic-specific\n * generation parameters from `providerConfig.adapterOptions`.\n * @returns {Promise<AsyncIterable<StreamEvent>>} A promise resolving to an AsyncIterable of StreamEvent objects.\n */\n async call(prompt: ArtStandardPrompt, options: CallOptions): Promise<AsyncIterable<StreamEvent>> {\n const {\n threadId,\n traceId = `anthropic-trace-${Date.now()}`,\n sessionId,\n stream = false,\n callContext,\n model: modelOverride,\n tools: availableArtTools,\n providerConfig,\n } = options;\n\n const modelToUse = providerConfig?.modelId || modelOverride || this.defaultModel;\n\n // Extract Anthropic specific parameters from providerConfig.adapterOptions or options\n const anthropicApiParams = providerConfig?.adapterOptions || {};\n const maxTokens = anthropicApiParams.max_tokens || anthropicApiParams.maxTokens || options.max_tokens || options.maxOutputTokens || this.defaultMaxTokens;\n const temperature = anthropicApiParams.temperature ?? options.temperature ?? this.defaultTemperature;\n const topP = anthropicApiParams.top_p || anthropicApiParams.topP || options.top_p || options.topP;\n const topK = anthropicApiParams.top_k || anthropicApiParams.topK || options.top_k || options.topK;\n const stopSequences = anthropicApiParams.stop_sequences || anthropicApiParams.stopSequences || options.stop || options.stop_sequences || options.stopSequences;\n // Anthropic thinking config for Claude 3.7 Sonnet (reasoning): { type: 'enabled', budget_tokens?: number }\n const thinking = anthropicApiParams.thinking || options.thinking;\n\n if (!maxTokens) {\n const err = new ARTError(\"Anthropic API requires 'max_tokens'.\", ErrorCode.INVALID_CONFIG);\n const errorGenerator = async function* (): AsyncIterable<StreamEvent> {\n yield { type: 'ERROR', data: err, threadId, traceId, sessionId };\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n };\n return errorGenerator();\n }\n\n let systemPrompt: string | undefined;\n let anthropicMessages: AnthropicSDKMessageParam[];\n try {\n const translationResult = this.translateToAnthropicSdk(prompt);\n systemPrompt = translationResult.systemPrompt;\n anthropicMessages = translationResult.messages;\n } catch (error: any) {\n Logger.error(`Error translating ArtStandardPrompt to Anthropic SDK format: ${error.message}`, { error, threadId, traceId });\n const artError = error instanceof ARTError ? error : new ARTError(`Prompt translation failed: ${error.message}`, ErrorCode.PROMPT_TRANSLATION_FAILED, error);\n const errorGenerator = async function* (): AsyncIterable<StreamEvent> {\n yield { type: 'ERROR', data: artError, threadId, traceId, sessionId };\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n };\n return errorGenerator();\n }\n\n const anthropicTools: AnthropicSDKTool[] | undefined = availableArtTools\n ? this.translateArtToolsToAnthropic(availableArtTools)\n : undefined;\n\n const requestBody: Anthropic.Messages.MessageCreateParams = {\n model: modelToUse,\n messages: anthropicMessages,\n max_tokens: maxTokens,\n system: systemPrompt,\n temperature: temperature,\n top_p: topP,\n top_k: topK,\n stop_sequences: stopSequences,\n // pass-through optional provider features\n thinking: thinking as any,\n stream: stream,\n tools: anthropicTools,\n };\n\n // Remove undefined keys from the request body\n Object.keys(requestBody).forEach(key => {\n const K = key as keyof Anthropic.Messages.MessageCreateParams;\n if (requestBody[K] === undefined) {\n delete requestBody[K];\n }\n });\n\n Logger.debug(`Calling Anthropic API with model ${modelToUse}`, { stream, tools: !!anthropicTools, threadId, traceId });\n\n // Use an async generator function\n const generator = async function* (this: AnthropicAdapter): AsyncIterable<StreamEvent> {\n try {\n const startTime = Date.now();\n let timeToFirstTokenMs: number | undefined;\n if (stream) {\n const streamInstance = await this.client.messages.create(\n requestBody as Anthropic.Messages.MessageCreateParamsStreaming,\n this.getRequestOptions(modelToUse)\n );\n\n let accumulatedText = \"\";\n const accumulatedToolUses: Array<{ id: string; name: string; input: any }> = [];\n const toolUseAcc = new Map<number, { id: string; name: string; chunks: string[] }>();\n const thinkingBlockIndexes = new Set<number>();\n let currentInputTokens: number | undefined;\n let currentOutputTokens: number | undefined;\n let finalStopReason: string | null = null;\n const finalUsage: Partial<Anthropic.Messages.Usage> = {\n input_tokens: undefined,\n output_tokens: undefined\n };\n\n let initialMetadata: LLMMetadata | undefined;\n let deltaMetadata: LLMMetadata | undefined;\n\n for await (const event of streamInstance) {\n switch (event.type) {\n case 'message_start':\n Logger.debug('Anthropic stream: message_start', { usage: event.message.usage, threadId, traceId });\n finalUsage.input_tokens = event.message.usage.input_tokens;\n finalUsage.output_tokens = event.message.usage.output_tokens;\n currentInputTokens = finalUsage.input_tokens;\n currentOutputTokens = finalUsage.output_tokens;\n\n initialMetadata = {\n inputTokens: currentInputTokens,\n outputTokens: currentOutputTokens,\n providerRawUsage: { usage: { ...event.message.usage } },\n traceId: traceId,\n };\n yield { type: 'METADATA', data: initialMetadata, threadId, traceId, sessionId };\n break;\n\n case 'content_block_start':\n Logger.debug('Anthropic stream: content_block_start', { index: event.index, block: event.content_block, threadId, traceId });\n // Track thinking blocks for correct token typing\n if ((event as any).content_block?.type === 'thinking') {\n thinkingBlockIndexes.add(event.index);\n const thinkingText = (event.content_block as any).thinking || '';\n if (thinkingText) {\n if (timeToFirstTokenMs === undefined) timeToFirstTokenMs = Date.now() - startTime;\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_THINKING' : 'FINAL_SYNTHESIS_LLM_THINKING';\n yield { type: 'TOKEN', data: thinkingText, threadId, traceId, sessionId, tokenType };\n }\n }\n // Initialize tool_use accumulation for this block index\n if ((event as any).content_block?.type === 'tool_use') {\n const block = event.content_block as Anthropic.ToolUseBlock;\n toolUseAcc.set(event.index, { id: block.id, name: block.name, chunks: [] });\n }\n break;\n\n case 'content_block_delta':\n Logger.debug('Anthropic stream: content_block_delta', { index: event.index, delta: event.delta, threadId, traceId });\n if (event.delta.type === 'text_delta') {\n const textDelta = event.delta.text;\n accumulatedText += textDelta;\n if (timeToFirstTokenMs === undefined) timeToFirstTokenMs = Date.now() - startTime;\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n yield { type: 'TOKEN', data: textDelta, threadId, traceId, sessionId, tokenType };\n } else if ((event.delta as any).type === 'thinking_delta') {\n const thinkingDelta = (event.delta as any).thinking || '';\n if (thinkingDelta) {\n if (timeToFirstTokenMs === undefined) timeToFirstTokenMs = Date.now() - startTime;\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_THINKING' : 'FINAL_SYNTHESIS_LLM_THINKING';\n yield { type: 'TOKEN', data: thinkingDelta, threadId, traceId, sessionId, tokenType };\n }\n } else if ((event.delta as any).type === 'input_json_delta') {\n const entry = toolUseAcc.get(event.index);\n if (entry) {\n const partial = (event.delta as any).partial_json ?? '';\n if (partial) entry.chunks.push(partial);\n }\n }\n break;\n\n case 'content_block_stop':\n Logger.debug('Anthropic stream: content_block_stop', { index: event.index, threadId, traceId });\n // Finalize tool_use input assembly for this block index\n if (toolUseAcc.has(event.index)) {\n const entry = toolUseAcc.get(event.index)!;\n const joined = entry.chunks.join('');\n let parsed: any = {};\n try {\n parsed = joined ? JSON.parse(joined) : {};\n } catch {\n // leave as empty object if parse fails\n }\n accumulatedToolUses.push({ id: entry.id, name: entry.name, input: parsed });\n toolUseAcc.delete(event.index);\n }\n break;\n\n case 'message_delta':\n Logger.debug('Anthropic stream: message_delta', { delta: event.delta, usage: event.usage, threadId, traceId });\n finalStopReason = event.delta.stop_reason ?? finalStopReason;\n if (event.usage.output_tokens !== undefined && event.usage.output_tokens !== null) {\n finalUsage.output_tokens = event.usage.output_tokens;\n }\n currentOutputTokens = finalUsage.output_tokens;\n\n deltaMetadata = {\n inputTokens: currentInputTokens,\n outputTokens: currentOutputTokens,\n stopReason: event.delta.stop_reason ?? undefined,\n providerRawUsage: {\n usage: {\n input_tokens: currentInputTokens,\n output_tokens: event.usage.output_tokens ?? undefined,\n },\n delta: event.delta\n },\n traceId: traceId,\n };\n yield { type: 'METADATA', data: deltaMetadata, threadId, traceId, sessionId };\n break;\n\n case 'message_stop': {\n Logger.debug('Anthropic stream: message_stop. Using accumulated data.', { threadId, traceId });\n // Flush any remaining tool_use blocks (defensive)\n for (const [idx, entry] of toolUseAcc.entries()) {\n const joined = entry.chunks.join('');\n let parsed: any = {};\n try {\n parsed = joined ? JSON.parse(joined) : {};\n } catch (e) {\n Logger.warn('AnthropicAdapter: Failed to parse tool_use input JSON in final flush.', { error: e, threadId, traceId });\n }\n accumulatedToolUses.push({ id: entry.id, name: entry.name, input: parsed });\n toolUseAcc.delete(idx);\n }\n\n if (finalStopReason === 'tool_use' && accumulatedToolUses.length > 0) {\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n const toolData = accumulatedToolUses.map(tu => ({\n type: 'tool_use',\n id: tu.id,\n name: tu.name,\n input: tu.input,\n }));\n if (accumulatedText.trim()) {\n yield { type: 'TOKEN', data: [{ type: 'text', text: accumulatedText.trim() }, ...toolData], threadId, traceId, sessionId, tokenType };\n } else {\n yield { type: 'TOKEN', data: toolData, threadId, traceId, sessionId, tokenType };\n }\n } else if (accumulatedText.trim()) {\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n yield { type: 'TOKEN', data: accumulatedText.trim(), threadId, traceId, sessionId, tokenType };\n }\n\n const totalGenerationTimeMs = Date.now() - startTime;\n const finalMetadataReport: LLMMetadata = {\n inputTokens: finalUsage.input_tokens ?? undefined,\n outputTokens: finalUsage.output_tokens ?? undefined,\n stopReason: finalStopReason ?? undefined,\n timeToFirstTokenMs,\n totalGenerationTimeMs,\n providerRawUsage: {\n usage: {\n input_tokens: finalUsage.input_tokens ?? undefined,\n output_tokens: finalUsage.output_tokens ?? undefined,\n },\n stop_reason: finalStopReason,\n },\n traceId: traceId,\n };\n yield { type: 'METADATA', data: finalMetadataReport, threadId, traceId, sessionId };\n break;\n }\n default: {\n Logger.warn('Anthropic stream: unhandled raw stream event type', { eventType: (event as any).type, event, threadId, traceId });\n break;\n }\n }\n }\n } else {\n const response = await this.client.messages.create(\n requestBody as Anthropic.Messages.MessageCreateParamsNonStreaming,\n this.getRequestOptions(modelToUse)\n );\n\n Logger.debug(`Anthropic API call successful (non-streaming). Stop Reason: ${response.stop_reason}`, { threadId, traceId });\n\n let responseText = \"\";\n const toolUseBlocks: AnthropicSDKToolUseBlock[] = [];\n\n response.content.forEach((block: Anthropic.Messages.ContentBlock) => {\n if (block.type === 'text') {\n responseText += block.text;\n } else if (block.type === 'tool_use') {\n toolUseBlocks.push(block);\n }\n });\n responseText = responseText.trim();\n\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n\n if (response.stop_reason === 'tool_use' && toolUseBlocks.length > 0) {\n const toolData = toolUseBlocks.map(tu => ({\n type: 'tool_use',\n id: tu.id,\n name: tu.name,\n input: tu.input,\n }));\n if (responseText) {\n yield { type: 'TOKEN', data: [{type: 'text', text: responseText}, ...toolData], threadId, traceId, sessionId, tokenType };\n } else {\n yield { type: 'TOKEN', data: toolData, threadId, traceId, sessionId, tokenType };\n }\n } else if (responseText) {\n yield { type: 'TOKEN', data: responseText, threadId, traceId, sessionId, tokenType };\n } else if (response.stop_reason !== 'tool_use') {\n Logger.warn('Anthropic API (non-streaming): Empty response text and not a tool_use stop_reason.', { response, threadId, traceId });\n }\n\n if (response.usage) {\n const metadata: LLMMetadata = {\n inputTokens: response.usage.input_tokens,\n outputTokens: response.usage.output_tokens,\n stopReason: response.stop_reason ?? undefined,\n totalGenerationTimeMs: Date.now() - startTime,\n providerRawUsage: { usage: response.usage, stop_reason: response.stop_reason, stop_sequence: response.stop_sequence },\n traceId: traceId,\n };\n yield { type: 'METADATA', data: metadata, threadId, traceId, sessionId };\n }\n }\n\n // Yield END signal for both streaming and non-streaming\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n\n } catch (error: any) {\n Logger.error(`Error during Anthropic API call: ${error.message}`, { error, threadId, traceId });\n const artError = error instanceof ARTError ? error :\n (error instanceof Anthropic.APIError ? new ARTError(`Anthropic API Error (${error.status}): ${error.message}`, ErrorCode.LLM_PROVIDER_ERROR, error) :\n new ARTError(error.message || 'Unknown Anthropic adapter error', ErrorCode.LLM_PROVIDER_ERROR, error));\n yield { type: 'ERROR', data: artError, threadId, traceId, sessionId };\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n }\n }.bind(this);\n\n return generator();\n }\n\n /**\n * Optional: Method for graceful shutdown\n */\n async shutdown(): Promise<void> {\n Logger.debug(`AnthropicAdapter shutdown called.`);\n // Clean up any resources if needed\n }\n\n /**\n * Prepares request options, adding Anthropic beta headers if applicable for features like prompt caching.\n * @private\n * @param {string} modelId - The model ID being used for the request, to determine which beta features may apply.\n * @returns {Anthropic.RequestOptions} The request options object, potentially with custom headers.\n */\n private getRequestOptions(modelId: string): Anthropic.RequestOptions {\n const betas: string[] = [];\n // Add beta features as needed\n if (modelId.startsWith(\"claude-3-5-sonnet\") || modelId.startsWith(\"claude-3-opus\")) {\n // Example: betas.push(\"prompt-caching-2024-07-31\");\n }\n\n if (betas.length > 0) {\n return { headers: { \"anthropic-beta\": betas.join(\",\") } };\n }\n return {};\n }\n\n /**\n * Translates the provider-agnostic `ArtStandardPrompt` into the Anthropic SDK Messages format.\n * It handles system prompts, message merging for consecutive roles, and validates message structure.\n *\n * @private\n * @param {ArtStandardPrompt} artPrompt - The input `ArtStandardPrompt` array.\n * @returns {{ systemPrompt?: string; messages: Anthropic.Messages.MessageParam[] }} An object containing the extracted system prompt and the array of Anthropic-formatted messages.\n * @throws {ARTError} If translation encounters an issue, such as multiple system messages or invalid message roles.\n */\n private translateToAnthropicSdk(artPrompt: ArtStandardPrompt): { systemPrompt?: string; messages: Anthropic.Messages.MessageParam[] } {\n let systemPrompt: string | undefined;\n const messages: Anthropic.Messages.MessageParam[] = [];\n let currentRoleInternal: 'user' | 'assistant' | null = null;\n\n for (const artMsg of artPrompt) {\n if (artMsg.role === 'system') {\n const systemText = (typeof artMsg.content === 'string') ? artMsg.content : String(artMsg.content);\n if (!systemPrompt) {\n systemPrompt = systemText;\n } else {\n Logger.warn(`AnthropicAdapter: Multiple system messages found. Appending to existing system prompt.`);\n systemPrompt += `\\n${systemText}`;\n }\n continue;\n }\n\n const translatedContent = this.mapArtMessageToAnthropicContent(artMsg);\n const messageRoleToPush: 'user' | 'assistant' = (artMsg.role === 'user' || artMsg.role === 'tool_result') ? 'user' : 'assistant';\n\n if (currentRoleInternal === messageRoleToPush && messages.length > 0) {\n const lastMessage = messages[messages.length - 1];\n \n let currentLastMessageContentArray: Anthropic.Messages.ContentBlockParam[];\n if (typeof lastMessage.content === 'string') {\n currentLastMessageContentArray = [{ type: 'text', text: lastMessage.content } as Anthropic.Messages.TextBlockParam];\n } else {\n currentLastMessageContentArray = lastMessage.content;\n }\n\n const contentToMergeArray: Anthropic.Messages.ContentBlockParam[] =\n typeof translatedContent === 'string'\n ? [{ type: 'text', text: translatedContent } as Anthropic.Messages.TextBlockParam]\n : translatedContent;\n\n const mergedContent: Anthropic.Messages.ContentBlockParam[] = [...currentLastMessageContentArray, ...contentToMergeArray];\n lastMessage.content = mergedContent;\n Logger.debug(`AnthropicAdapter: Merged consecutive ${messageRoleToPush} messages.`);\n } else {\n messages.push({ role: messageRoleToPush, content: translatedContent });\n currentRoleInternal = messageRoleToPush;\n }\n }\n\n // Anthropic requires the first message to be 'user' if messages exist and no system prompt.\n if (!systemPrompt && messages.length > 0 && messages[0].role !== 'user') {\n Logger.warn(\"AnthropicAdapter: Prompt does not start with user message and has no system prompt. Prepending an empty user message for compatibility.\");\n messages.unshift({ role: 'user', content: '(Previous turn context)'});\n }\n \n // Ensure conversation doesn't end on an assistant message if expecting tool results\n const lastArtMsg = artPrompt[artPrompt.length -1];\n if (lastArtMsg?.role === 'assistant' && lastArtMsg.tool_calls && lastArtMsg.tool_calls.length > 0) {\n Logger.debug(\"AnthropicAdapter: Prompt ends with assistant requesting tool calls.\");\n }\n\n return { systemPrompt, messages };\n }\n\n /**\n * Maps a single `ArtStandardMessage` to Anthropic SDK's content format.\n * This can be a simple string or an array of `ContentBlockParam` for complex content\n * like tool calls and tool results.\n *\n * @private\n * @param {ArtStandardMessage} artMsg - The ART standard message to map.\n * @returns {string | AnthropicSDKContentBlockParam[]} The translated content for the Anthropic API.\n * @throws {ARTError} If tool call arguments are not valid JSON or if a tool result is missing its ID.\n */\n private mapArtMessageToAnthropicContent(artMsg: ArtStandardMessage): string | AnthropicSDKContentBlockParam[] {\n const blocks: AnthropicSDKContentBlockParam[] = [];\n\n // Handle text content\n if (artMsg.content && typeof artMsg.content === 'string' && artMsg.content.trim() !== '') {\n blocks.push({ type: 'text', text: artMsg.content });\n } else if (artMsg.content && typeof artMsg.content !== 'string' && artMsg.role !== 'tool_result' && (!artMsg.tool_calls || artMsg.tool_calls.length === 0) ) {\n Logger.warn(`AnthropicAdapter: Non-string, non-tool_result, non-tool_call-only content for role ${artMsg.role}, stringifying.`, { content: artMsg.content });\n blocks.push({ type: 'text', text: JSON.stringify(artMsg.content) });\n }\n\n // Handle tool_calls for assistant messages (these become 'tool_use' blocks)\n if (artMsg.role === 'assistant' && artMsg.tool_calls && artMsg.tool_calls.length > 0) {\n artMsg.tool_calls.forEach(tc => {\n if (tc.type === 'function') {\n try {\n blocks.push({\n type: 'tool_use',\n id: tc.id,\n name: tc.function.name,\n input: JSON.parse(tc.function.arguments || '{}'),\n });\n } catch (e: any) {\n throw new ARTError(\n `AnthropicAdapter: Failed to parse tool call arguments for tool ${tc.function.name} (ID: ${tc.id}). Arguments must be valid JSON. Error: ${e.message}`,\n ErrorCode.PROMPT_TRANSLATION_FAILED, e\n );\n }\n } else {\n Logger.warn(`AnthropicAdapter: Skipping non-function tool_call type: ${tc.type}`);\n }\n });\n }\n\n // Handle tool_result messages (these become 'tool_result' blocks)\n if (artMsg.role === 'tool_result') {\n if (!artMsg.tool_call_id) {\n throw new ARTError(\"AnthropicAdapter: 'tool_result' message missing required 'tool_call_id'.\", ErrorCode.PROMPT_TRANSLATION_FAILED);\n }\n const toolResultBlock: Anthropic.ToolResultBlockParam = {\n type: 'tool_result',\n tool_use_id: artMsg.tool_call_id,\n };\n\n if (typeof artMsg.content === 'string') {\n toolResultBlock.content = artMsg.content;\n } else if (Array.isArray(artMsg.content) && artMsg.content.every(c => typeof c === 'object' && c.type === 'text' && typeof c.text === 'string')) {\n toolResultBlock.content = artMsg.content.map(c => ({type: 'text', text: (c as any).text}));\n } else if (artMsg.content !== null && artMsg.content !== undefined) {\n toolResultBlock.content = JSON.stringify(artMsg.content);\n }\n\n blocks.push(toolResultBlock);\n }\n\n // If only one text block and no other block types, Anthropic SDK allows content to be a simple string.\n if (blocks.length === 1 && blocks[0].type === 'text') {\n return (blocks[0] as Anthropic.TextBlockParam).text;\n }\n \n // If blocks is empty, return empty string\n if (blocks.length === 0) {\n return \"\";\n }\n\n return blocks;\n }\n\n /**\n * Translates an array of `ToolSchema` from the ART framework format to Anthropic's specific tool format.\n * @private\n * @param {ToolSchema[]} artTools - An array of ART tool schemas.\n * @returns {AnthropicSDKTool[]} An array of tools formatted for the Anthropic API.\n * @throws {ARTError} If a tool's `inputSchema` is invalid.\n */\n private translateArtToolsToAnthropic(artTools: ToolSchema[]): AnthropicSDKTool[] {\n return artTools.map(artTool => {\n if (!artTool.inputSchema || typeof artTool.inputSchema !== 'object') {\n throw new ARTError(`Invalid inputSchema definition for tool '${artTool.name}'. Expected a JSON schema object.`, ErrorCode.INVALID_CONFIG);\n }\n return {\n name: artTool.name,\n description: artTool.description,\n input_schema: artTool.inputSchema as Anthropic.Tool.InputSchema,\n };\n });\n }\n}","// src/adapters/reasoning/openrouter.ts\nimport { ProviderAdapter } from '@/core/interfaces';\nimport {\n ArtStandardPrompt,\n ArtStandardMessage,\n CallOptions,\n StreamEvent,\n LLMMetadata,\n ToolSchema,\n} from '@/types';\nimport { Logger } from '@/utils/logger';\nimport { ARTError, ErrorCode } from '@/errors';\n\n// Using OpenAI-compatible structures, as OpenRouter adheres to them.\n// Based on https://openrouter.ai/docs#api-reference-chat-completions\ninterface OpenRouterMessage {\n role: 'system' | 'user' | 'assistant' | 'tool';\n content: string | null;\n name?: string;\n tool_calls?: OpenRouterToolCall[];\n tool_call_id?: string;\n}\n\ninterface OpenRouterToolCall {\n id: string;\n type: 'function';\n function: {\n name: string;\n arguments: string; // Stringified JSON\n };\n}\n\ninterface OpenRouterTool {\n type: 'function';\n function: {\n name: string;\n description: string;\n parameters: object; // JSON Schema\n };\n}\n\ninterface OpenRouterChatCompletionPayload {\n model: string;\n messages: OpenRouterMessage[];\n temperature?: number;\n max_tokens?: number;\n top_p?: number;\n frequency_penalty?: number;\n presence_penalty?: number;\n stop?: string | string[];\n stream?: boolean;\n stream_options?: { include_usage: boolean };\n tools?: OpenRouterTool[];\n tool_choice?: 'auto' | 'any' | 'none' | { type: 'function'; function: { name: string } };\n // OpenRouter specific extensions\n provider?: {\n order?: string[];\n only?: string[];\n allow_fallbacks?: boolean;\n };\n transforms?: string[];\n reasoning?: {\n exclude?: boolean;\n effort?: 'low' | 'medium' | 'high';\n tokens?: number;\n };\n // Legacy toggle allowed by OpenRouter; maps to reasoning include/exclude\n include_reasoning?: boolean;\n}\n\n// See https://openrouter.ai/docs/use-cases/usage-accounting\ninterface OpenRouterUsage {\n completion_tokens?: number;\n completion_tokens_details?: {\n reasoning_tokens?: number;\n };\n prompt_tokens?: number;\n prompt_tokens_details?: {\n cached_tokens?: number;\n };\n total_tokens?: number;\n cost?: number;\n cost_details?: {\n upstream_inference_cost?: number;\n };\n}\n\ninterface OpenRouterChatCompletionResponse {\n id: string;\n object: string;\n created: number;\n model: string;\n choices: {\n index: number;\n message: OpenRouterMessage;\n finish_reason: string;\n }[];\n usage?: OpenRouterUsage;\n}\n\nexport interface OpenRouterAdapterOptions {\n apiKey: string;\n model: string;\n apiBaseUrl?: string;\n siteUrl?: string;\n appName?: string;\n}\n\nexport class OpenRouterAdapter implements ProviderAdapter {\n readonly providerName = 'openrouter';\n private apiKey: string;\n private model: string;\n private apiBaseUrl: string;\n private siteUrl?: string;\n private appName?: string;\n\n constructor(options: OpenRouterAdapterOptions) {\n if (!options.apiKey) {\n throw new Error('OpenRouterAdapter requires an apiKey in options.');\n }\n if (!options.model) {\n throw new Error('OpenRouterAdapter requires a model identifier in options (e.g., \\'google/gemini-pro\\').');\n }\n this.apiKey = options.apiKey;\n this.model = options.model;\n this.apiBaseUrl = options.apiBaseUrl || 'https://openrouter.ai/api/v1';\n this.siteUrl = options.siteUrl;\n this.appName = options.appName;\n Logger.debug(`OpenRouterAdapter initialized for model: ${this.model}`);\n }\n\n async call(prompt: ArtStandardPrompt, options: CallOptions): Promise<AsyncIterable<StreamEvent>> {\n const {\n threadId,\n traceId = `openrouter-trace-${Date.now()}`,\n sessionId,\n stream,\n callContext,\n model: modelOverride,\n tools: artTools,\n } = options;\n const modelToUse = modelOverride || this.model;\n\n let openAiMessages: OpenRouterMessage[];\n let openAiTools: OpenRouterTool[] | undefined;\n try {\n openAiMessages = this.translateToOpenAI(prompt);\n if (artTools && artTools.length > 0) {\n openAiTools = this.translateArtToolsToOpenAI(artTools);\n }\n } catch (error: any) {\n Logger.error(`Error translating prompt/tools for OpenRouter: ${error.message}`, { error, threadId, traceId });\n const generator = async function* (): AsyncIterable<StreamEvent> {\n const err =\n error instanceof ARTError\n ? error\n : new ARTError(`Prompt translation failed: ${error.message}`, ErrorCode.PROMPT_TRANSLATION_FAILED, error);\n yield { type: 'ERROR', data: err, threadId, traceId, sessionId };\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n };\n return generator();\n }\n\n const openRouterOptions = (options as any).openrouter || {};\n // Determine legacy include_reasoning flag per OpenRouter docs\n const includeReasoning: boolean | undefined =\n typeof openRouterOptions?.include_reasoning === 'boolean'\n ? openRouterOptions.include_reasoning\n : (openRouterOptions?.reasoning\n ? (openRouterOptions.reasoning.exclude === true ? false : true)\n : undefined);\n\n const payload: OpenRouterChatCompletionPayload = {\n model: modelToUse,\n messages: openAiMessages,\n temperature: options.temperature,\n max_tokens: options.max_tokens || options.maxOutputTokens,\n top_p: options.top_p || options.topP,\n stop: options.stop || options.stop_sequences || options.stopSequences,\n stream: !!stream,\n ...(stream ? { stream_options: { include_usage: true } } : {}),\n tools: openAiTools,\n tool_choice: options.tool_choice,\n // OpenRouter specific fields from options\n provider: openRouterOptions.provider,\n transforms: openRouterOptions.useMiddleOutTransform === false ? undefined : ['middle-out'],\n reasoning: openRouterOptions.reasoning,\n ...(includeReasoning !== undefined ? { include_reasoning: includeReasoning } : {}),\n };\n\n Object.keys(payload).forEach(\n (key) => payload[key as keyof OpenRouterChatCompletionPayload] === undefined && delete payload[key as keyof OpenRouterChatCompletionPayload],\n );\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n };\n if (this.siteUrl) headers['HTTP-Referer'] = this.siteUrl;\n if (this.appName) headers['X-Title'] = this.appName;\n\n const apiUrl = `${this.apiBaseUrl}/chat/completions`;\n Logger.debug(`Calling OpenRouter API: ${apiUrl} with model ${modelToUse}, stream: ${!!stream}`, { threadId, traceId });\n\n try {\n const response = await fetch(apiUrl, {\n method: 'POST',\n headers: headers,\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const errorBody = await response.text();\n const err = new ARTError(\n `OpenRouter API request failed: ${response.status} ${response.statusText} - ${errorBody}`,\n ErrorCode.LLM_PROVIDER_ERROR,\n new Error(errorBody),\n );\n const errorGenerator = async function* (): AsyncIterable<StreamEvent> {\n yield { type: 'ERROR', data: err, threadId, traceId, sessionId };\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n };\n return errorGenerator();\n }\n\n if (stream && response.body) {\n return this.processStream(response.body, options);\n } else {\n const data = (await response.json()) as OpenRouterChatCompletionResponse;\n return this.processNonStreamingResponse(data, options);\n }\n } catch (error: any) {\n Logger.error(`Error during OpenRouter API call: ${error.message}`, { error, threadId, traceId });\n const artError = error instanceof ARTError ? error : new ARTError(error.message, ErrorCode.LLM_PROVIDER_ERROR, error);\n const errorGenerator = async function* (): AsyncIterable<StreamEvent> {\n yield { type: 'ERROR', data: artError, threadId, traceId, sessionId };\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n };\n return errorGenerator();\n }\n }\n\n private async *processStream(\n stream: ReadableStream<Uint8Array>,\n options: CallOptions,\n ): AsyncIterable<StreamEvent> {\n const { threadId, traceId, sessionId, callContext } = options;\n const tid = (threadId || '') as string;\n const trid = (traceId || '') as string;\n const sid = (sessionId || '') as string;\n\n const startTime = Date.now();\n let timeToFirstTokenMs: number | undefined;\n let finalStopReason: string | undefined;\n let finalUsage: OpenRouterUsage | undefined;\n const aggregatedToolCalls: any[] = [];\n\n // Use TextDecoder + getReader to avoid DOM lib typing issues\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n while (true) {\n try {\n const { value, done } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() || ''; // Keep incomplete line in buffer\n\n for (const raw of lines) {\n const line = raw.trim();\n if (!line || !line.startsWith('data: ')) continue;\n\n const dataContent = line.substring(6);\n if (dataContent === '[DONE]') {\n // End of stream signal\n break;\n }\n\n const chunk = JSON.parse(dataContent);\n if (chunk?.error) {\n throw new ARTError(\n `OpenRouter stream error: ${chunk.error?.message ?? 'unknown'}`,\n ErrorCode.LLM_PROVIDER_ERROR,\n new Error(JSON.stringify(chunk.error)),\n );\n }\n\n const choice = chunk.choices?.[0];\n if (!choice) continue;\n\n if (timeToFirstTokenMs === undefined) {\n timeToFirstTokenMs = Date.now() - startTime;\n }\n\n const delta = choice.delta ?? {};\n\n // 1) Reasoning text (simple field)\n if (typeof delta.reasoning === 'string' && delta.reasoning.length > 0) {\n const tokenType = callContext === 'AGENT_THOUGHT'\n ? 'AGENT_THOUGHT_LLM_THINKING'\n : 'FINAL_SYNTHESIS_LLM_THINKING';\n yield { type: 'TOKEN', data: delta.reasoning, threadId: tid, traceId: trid, sessionId: sid, tokenType };\n }\n\n // 2) Reasoning details array (normalized across providers)\n const reasoningDetails = (delta as any).reasoning_details;\n if (Array.isArray(reasoningDetails)) {\n for (const rd of reasoningDetails) {\n // Prefer raw reasoning.text, else summarize/ignore encrypted\n if (rd?.type === 'reasoning.text' && typeof rd.text === 'string' && rd.text.length > 0) {\n const tokenType = callContext === 'AGENT_THOUGHT'\n ? 'AGENT_THOUGHT_LLM_THINKING'\n : 'FINAL_SYNTHESIS_LLM_THINKING';\n yield { type: 'TOKEN', data: rd.text, threadId: tid, traceId: trid, sessionId: sid, tokenType };\n } else if (rd?.type === 'reasoning.summary' && typeof rd.summary === 'string' && rd.summary.length > 0) {\n const tokenType = callContext === 'AGENT_THOUGHT'\n ? 'AGENT_THOUGHT_LLM_THINKING'\n : 'FINAL_SYNTHESIS_LLM_THINKING';\n yield { type: 'TOKEN', data: rd.summary, threadId: tid, traceId: trid, sessionId: sid, tokenType };\n }\n // Encrypted or unknown formats are ignored for token streaming\n }\n }\n\n // 3) Content delta (normal response tokens)\n if (typeof delta.content === 'string' && delta.content.length > 0) {\n const tokenType = callContext === 'AGENT_THOUGHT'\n ? 'AGENT_THOUGHT_LLM_RESPONSE'\n : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n yield { type: 'TOKEN', data: delta.content, threadId: tid, traceId: trid, sessionId: sid, tokenType };\n }\n\n // 4) Tool call deltas\n if (Array.isArray(delta.tool_calls)) {\n for (const tcDelta of delta.tool_calls) {\n if (typeof tcDelta?.index === 'number') {\n if (!aggregatedToolCalls[tcDelta.index]) aggregatedToolCalls[tcDelta.index] = {};\n if (tcDelta.id) aggregatedToolCalls[tcDelta.index].id = tcDelta.id;\n if (tcDelta.type) aggregatedToolCalls[tcDelta.index].type = tcDelta.type;\n if (tcDelta.function) {\n const dst = (aggregatedToolCalls[tcDelta.index].function ||= {});\n if (tcDelta.function.name) dst.name = tcDelta.function.name;\n if (typeof tcDelta.function.arguments === 'string') {\n dst.arguments = (dst.arguments || '') + tcDelta.function.arguments;\n }\n }\n }\n }\n }\n\n // 5) Finish/usage\n if (choice.finish_reason) finalStopReason = choice.finish_reason;\n if (chunk.usage) finalUsage = chunk.usage as OpenRouterUsage;\n }\n } catch (error: any) {\n const artError =\n error instanceof ARTError\n ? error\n : new ARTError(`Error reading OpenRouter stream: ${error.message}`, ErrorCode.LLM_PROVIDER_ERROR, error);\n yield { type: 'ERROR', data: artError, threadId: tid, traceId: trid, sessionId: sid };\n return; // End generation on error\n }\n }\n\n // If the stream ended with tool_calls, emit accumulated calls\n if (finalStopReason === 'tool_calls' && aggregatedToolCalls.length > 0) {\n const toolData = aggregatedToolCalls.map((tc) => ({\n type: 'tool_use',\n id: String(tc?.id ?? ''),\n name: String(tc?.function?.name ?? ''),\n input: JSON.parse((tc?.function?.arguments as string | undefined) ?? '{}'),\n }));\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n yield { type: 'TOKEN', data: toolData, threadId: tid, traceId: trid, sessionId: sid, tokenType };\n }\n\n const totalGenerationTimeMs = Date.now() - startTime;\n const metadata: LLMMetadata = {\n stopReason: finalStopReason,\n inputTokens: finalUsage?.prompt_tokens,\n outputTokens: finalUsage?.completion_tokens,\n thinkingTokens: finalUsage?.completion_tokens_details?.reasoning_tokens,\n timeToFirstTokenMs,\n totalGenerationTimeMs,\n providerRawUsage: { ...finalUsage, finish_reason: finalStopReason },\n traceId: trid,\n };\n yield { type: 'METADATA', data: metadata, threadId: tid, traceId: trid, sessionId: sid };\n yield { type: 'END', data: null, threadId: tid, traceId: trid, sessionId: sid };\n }\n\n private async *processNonStreamingResponse(\n data: OpenRouterChatCompletionResponse,\n options: CallOptions,\n ): AsyncIterable<StreamEvent> {\n const { threadId, traceId, sessionId, callContext } = options;\n const tid = (threadId || '') as string;\n const trid = (traceId || '') as string;\n const sid = (sessionId || '') as string;\n\n const firstChoice = data.choices?.[0];\n\n if (!firstChoice?.message) {\n const err = new ARTError(\n 'Invalid response structure from OpenRouter API: No message found.',\n ErrorCode.LLM_PROVIDER_ERROR,\n new Error(JSON.stringify(data)),\n );\n yield { type: 'ERROR', data: err, threadId: tid, traceId: trid, sessionId: sid };\n yield { type: 'END', data: null, threadId: tid, traceId: trid, sessionId: sid };\n return;\n }\n\n const responseMessage: any = firstChoice.message;\n\n // Emit reasoning (non-streaming) if present\n if (typeof responseMessage.reasoning === 'string' && responseMessage.reasoning.length > 0) {\n const thinkingType = callContext === 'AGENT_THOUGHT'\n ? 'AGENT_THOUGHT_LLM_THINKING'\n : 'FINAL_SYNTHESIS_LLM_THINKING';\n yield { type: 'TOKEN', data: responseMessage.reasoning, threadId: tid, traceId: trid, sessionId: sid, tokenType: thinkingType };\n }\n if (Array.isArray(responseMessage.reasoning_details)) {\n for (const rd of responseMessage.reasoning_details) {\n if (rd?.type === 'reasoning.text' && typeof rd.text === 'string' && rd.text.length > 0) {\n const thinkingType = callContext === 'AGENT_THOUGHT'\n ? 'AGENT_THOUGHT_LLM_THINKING'\n : 'FINAL_SYNTHESIS_LLM_THINKING';\n yield { type: 'TOKEN', data: rd.text, threadId: tid, traceId: trid, sessionId: sid, tokenType: thinkingType };\n } else if (rd?.type === 'reasoning.summary' && typeof rd.summary === 'string' && rd.summary.length > 0) {\n const thinkingType = callContext === 'AGENT_THOUGHT'\n ? 'AGENT_THOUGHT_LLM_THINKING'\n : 'FINAL_SYNTHESIS_LLM_THINKING';\n yield { type: 'TOKEN', data: rd.summary, threadId: tid, traceId: trid, sessionId: sid, tokenType: thinkingType };\n }\n }\n }\n\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n\n const toolData =\n (responseMessage.tool_calls as any[] | undefined)?.map((tc) => ({\n type: 'tool_use',\n id: String(tc?.id ?? ''),\n name: String(tc?.function?.name ?? ''),\n input: JSON.parse((tc?.function?.arguments as string | undefined) ?? '{}'),\n })) || [];\n\n const responseContent = (responseMessage.content as string | null) ?? '';\n const tokenPayload: any[] = [];\n if (responseContent.trim()) {\n tokenPayload.push({ type: 'text', text: responseContent.trim() });\n }\n tokenPayload.push(...toolData);\n\n if (tokenPayload.length > 0) {\n yield {\n type: 'TOKEN',\n data: tokenPayload.length === 1 && tokenPayload[0].type === 'text' ? tokenPayload[0].text : tokenPayload,\n threadId: tid,\n traceId: trid,\n sessionId: sid,\n tokenType,\n };\n }\n\n const usage = data.usage;\n const metadata: LLMMetadata = {\n stopReason: firstChoice.finish_reason,\n inputTokens: usage?.prompt_tokens,\n outputTokens: usage?.completion_tokens,\n thinkingTokens: usage?.completion_tokens_details?.reasoning_tokens,\n providerRawUsage: { ...usage, finish_reason: firstChoice.finish_reason },\n traceId: trid,\n };\n yield { type: 'METADATA', data: metadata, threadId: tid, traceId: trid, sessionId: sid };\n yield { type: 'END', data: null, threadId: tid, traceId: trid, sessionId: sid };\n }\n\n private translateArtToolsToOpenAI(artTools: ToolSchema[]): OpenRouterTool[] {\n return artTools.map((artTool) => ({\n type: 'function',\n function: {\n name: artTool.name,\n description: artTool.description,\n parameters: artTool.inputSchema,\n },\n }));\n }\n\n private translateToOpenAI(artPrompt: ArtStandardPrompt): OpenRouterMessage[] {\n return artPrompt.map((message: ArtStandardMessage): OpenRouterMessage => {\n switch (message.role) {\n case 'system':\n return { role: 'system', content: String(message.content) };\n case 'user':\n return { role: 'user', content: String(message.content) };\n case 'assistant': {\n const assistantMsg: OpenRouterMessage = {\n role: 'assistant',\n content: typeof message.content === 'string' ? message.content : null,\n };\n if (message.tool_calls && message.tool_calls.length > 0) {\n assistantMsg.tool_calls = message.tool_calls.map((tc) => {\n if (tc.type !== 'function' || !tc.function?.name || typeof tc.function?.arguments !== 'string') {\n throw new ARTError(\n `OpenRouterAdapter: Invalid tool_call structure in assistant message. ID: ${tc.id}`,\n ErrorCode.PROMPT_TRANSLATION_FAILED,\n );\n }\n return {\n id: tc.id,\n type: tc.type,\n function: {\n name: tc.function.name,\n arguments: tc.function.arguments,\n },\n };\n });\n }\n if (assistantMsg.content === '' && assistantMsg.tool_calls) {\n assistantMsg.content = null;\n }\n return assistantMsg;\n }\n case 'tool_result': {\n if (!message.tool_call_id) {\n throw new ARTError(\n `OpenRouterAdapter: 'tool_result' message missing required 'tool_call_id'.`,\n ErrorCode.PROMPT_TRANSLATION_FAILED,\n );\n }\n return {\n role: 'tool',\n tool_call_id: message.tool_call_id,\n content: String(message.content),\n };\n }\n case 'tool_request': {\n throw new ARTError(\n `OpenRouterAdapter: Unexpected 'tool_request' role. This should be handled by 'tool_calls' in an assistant message.`,\n ErrorCode.PROMPT_TRANSLATION_FAILED,\n );\n }\n default: {\n throw new ARTError(\n `OpenRouterAdapter: Unknown message role '${message.role}' encountered.`,\n ErrorCode.PROMPT_TRANSLATION_FAILED,\n );\n }\n }\n });\n }\n}","// src/adapters/reasoning/deepseek.ts\nimport { ProviderAdapter } from '@/core/interfaces';\nimport {\n ArtStandardPrompt, // Use the new standard type\n ArtStandardMessage, // Keep for translation function type hint\n CallOptions,\n StreamEvent,\n LLMMetadata,\n} from '@/types';\nimport { Logger } from '@/utils/logger';\nimport { ARTError, ErrorCode } from '@/errors'; // Import ARTError and ErrorCode\n\n// TODO: Implement streaming support for DeepSeek.\n// TODO: Implement support for 'tools' and 'tool_choice'.\n\n/**\n * Configuration options required for the `DeepSeekAdapter`.\n */\nexport interface DeepSeekAdapterOptions {\n /** Your DeepSeek API key. Handle securely. */\n apiKey: string;\n /** The default DeepSeek model ID to use (e.g., 'deepseek-chat', 'deepseek-coder'). Defaults to 'deepseek-chat' if not provided. */\n model?: string;\n /** Optional: Override the base URL for the DeepSeek API. Defaults to 'https://api.deepseek.com/v1'. */\n apiBaseUrl?: string;\n}\n\n// Use OpenAI-compatible structures\n// Based on https://platform.deepseek.com/api-docs/api/create-chat-completion/index.html\ninterface OpenAIMessage {\n role: 'system' | 'user' | 'assistant' | 'tool';\n content: string | null;\n name?: string;\n tool_calls?: OpenAIToolCall[];\n tool_call_id?: string;\n}\n\ninterface OpenAIToolCall {\n id: string;\n type: 'function';\n function: {\n name: string;\n arguments: string; // Stringified JSON\n };\n}\n\ninterface OpenAIChatCompletionPayload {\n model: string;\n messages: OpenAIMessage[];\n temperature?: number;\n max_tokens?: number;\n top_p?: number;\n frequency_penalty?: number;\n presence_penalty?: number;\n stop?: string | string[];\n stream?: boolean; // DeepSeek supports streaming\n // TODO: Add support for 'tools' and 'tool_choice' if needed later\n}\n\ninterface OpenAIChatCompletionResponse {\n id: string;\n object: string;\n created: number;\n model: string;\n choices: {\n index: number;\n message: OpenAIMessage; // Use the defined OpenAIMessage type\n finish_reason: string; // e.g., 'stop', 'length', 'tool_calls'\n }[];\n usage: { // Note: DeepSeek usage structure matches OpenAI\n prompt_tokens: number;\n completion_tokens: number;\n total_tokens: number;\n };\n}\n\n/**\n * This adapter provides a consistent interface for ART agents to use DeepSeek models,\n * handling the conversion of standard ART prompts to the DeepSeek API format and\n * parsing the responses into the ART `StreamEvent` format.\n *\n * @see {@link ProviderAdapter} for the interface it implements.\n */\nexport class DeepSeekAdapter implements ProviderAdapter {\n readonly providerName = 'deepseek';\n private apiKey: string;\n private model: string;\n private apiBaseUrl: string;\n\n /**\n * Creates an instance of the DeepSeekAdapter.\n * @param {DeepSeekAdapterOptions} options - Configuration options including the API key and optional model/baseURL overrides.\n * @throws {Error} If the API key is missing.\n * @see https://platform.deepseek.com/api-docs\n */\n constructor(options: DeepSeekAdapterOptions) {\n if (!options.apiKey) {\n throw new Error('DeepSeekAdapter requires an apiKey in options.');\n }\n this.apiKey = options.apiKey;\n this.model = options.model || 'deepseek-chat'; // Default model\n this.apiBaseUrl = options.apiBaseUrl || 'https://api.deepseek.com/v1';\n Logger.debug(`DeepSeekAdapter initialized with model: ${this.model}`);\n }\n\n /**\n * Sends a request to the DeepSeek Chat Completions API endpoint.\n * Translates `ArtStandardPrompt` to the OpenAI-compatible format.\n *\n * **Note:** Streaming is **not yet implemented**.\n *\n * @param {ArtStandardPrompt} prompt - The standardized prompt messages.\n * @param {CallOptions} options - Call options, including `threadId`, `traceId`, `stream`, and any OpenAI-compatible generation parameters.\n * @returns {Promise<AsyncIterable<StreamEvent>>} A promise resolving to an AsyncIterable of StreamEvent objects. If streaming is requested, it yields an error event and ends.\n * @see https://platform.deepseek.com/api-docs/api/create-chat-completion/index.html\n */\n async call(prompt: ArtStandardPrompt, options: CallOptions): Promise<AsyncIterable<StreamEvent>> {\n const { threadId, traceId = `deepseek-trace-${Date.now()}`, sessionId, stream, callContext, model: modelOverride } = options;\n const modelToUse = modelOverride || this.model;\n\n // --- Placeholder for Streaming ---\n // TODO: Implement streaming for DeepSeek\n if (stream) {\n Logger.warn(`DeepSeekAdapter: Streaming requested but not implemented. Returning error stream.`, { threadId, traceId });\n const errorGenerator = async function*(): AsyncIterable<StreamEvent> {\n const err = new ARTError(\"Streaming is not yet implemented for the DeepSeekAdapter.\", ErrorCode.LLM_PROVIDER_ERROR);\n yield { type: 'ERROR', data: err, threadId: threadId ?? '', traceId: traceId ?? '', sessionId };\n yield { type: 'END', data: null, threadId: threadId ?? '', traceId: traceId ?? '', sessionId };\n };\n return errorGenerator();\n }\n\n // --- Non-Streaming Logic ---\n\n // --- Translate Prompt ---\n let openAiMessages: OpenAIMessage[];\n try {\n // Reuse the same translation logic as OpenAI adapter\n openAiMessages = this.translateToOpenAI(prompt);\n } catch (error: any) {\n Logger.error(`Error translating ArtStandardPrompt to DeepSeek/OpenAI format: ${error.message}`, { error, threadId, traceId });\n const generator = async function*(): AsyncIterable<StreamEvent> {\n const err = error instanceof ARTError ? error : new ARTError(`Prompt translation failed: ${error.message}`, ErrorCode.PROMPT_TRANSLATION_FAILED, error);\n yield { type: 'ERROR', data: err, threadId, traceId, sessionId };\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n }\n return generator();\n }\n // --- End Translate Prompt ---\n\n const apiUrl = `${this.apiBaseUrl}/chat/completions`;\n const stopSequences = options.stop || options.stop_sequences || options.stopSequences;\n\n const payload: OpenAIChatCompletionPayload = {\n model: modelToUse,\n messages: openAiMessages,\n temperature: options.temperature,\n max_tokens: options.max_tokens || options.maxOutputTokens,\n top_p: options.top_p || options.topP,\n stop: stopSequences,\n stream: false, // Explicitly false for non-streaming\n // TODO: Add tools/tool_choice if needed\n };\n\n Object.keys(payload).forEach(key => payload[key as keyof OpenAIChatCompletionPayload] === undefined && delete payload[key as keyof OpenAIChatCompletionPayload]);\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.apiKey}`,\n };\n \n Logger.debug(`Calling DeepSeek API (non-streaming): ${apiUrl} with model ${this.model}`, { threadId, traceId });\n \n // Use an async generator for non-streaming case too\n const generator = async function*(): AsyncIterable<StreamEvent> {\n try {\n const response = await fetch(apiUrl, {\n method: 'POST',\n headers: headers,\n body: JSON.stringify(payload),\n });\n \n if (!response.ok) {\n const errorBody = await response.text();\n let errorMessage = errorBody;\n try {\n const parsedError = JSON.parse(errorBody);\n if (parsedError?.error?.message) errorMessage = parsedError.error.message;\n } catch (e) { /* Ignore */ }\n const err = new ARTError(\n `DeepSeek API request failed: ${response.status} ${response.statusText} - ${errorMessage}`,\n ErrorCode.LLM_PROVIDER_ERROR,\n new Error(errorBody) // Pass underlying error context\n );\n yield { type: 'ERROR', data: err, threadId, traceId, sessionId };\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n return; // Stop the generator on error\n }\n\n const data = await response.json() as OpenAIChatCompletionResponse;\n const firstChoice = data.choices?.[0];\n\n if (!firstChoice?.message) {\n const err = new ARTError('Invalid response structure from DeepSeek API: No message found.', ErrorCode.LLM_PROVIDER_ERROR, new Error(JSON.stringify(data)));\n yield { type: 'ERROR', data: err, threadId, traceId, sessionId };\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n return; // Stop the generator\n }\n\n const responseMessage = firstChoice.message;\n // TODO: Handle tool_calls in non-streaming response if needed by agent logic\n if (responseMessage.tool_calls) {\n Logger.debug(\"DeepSeek response included tool calls (non-streaming)\", { toolCalls: responseMessage.tool_calls, threadId, traceId });\n }\n Logger.debug(`DeepSeek API call successful. Finish reason: ${firstChoice.finish_reason}`, { threadId, traceId });\n\n // Yield TOKEN\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n const responseContent = responseMessage.content ?? '';\n yield { type: 'TOKEN', data: responseContent.trim(), threadId, traceId, sessionId, tokenType };\n\n // Yield METADATA\n const metadata: LLMMetadata = {\n inputTokens: data.usage?.prompt_tokens,\n outputTokens: data.usage?.completion_tokens,\n stopReason: firstChoice.finish_reason,\n providerRawUsage: { usage: data.usage, finish_reason: firstChoice.finish_reason },\n traceId: traceId,\n };\n yield { type: 'METADATA', data: metadata, threadId, traceId, sessionId };\n\n // Yield END\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n\n } catch (error: any) {\n Logger.error(`Error during DeepSeek API call: ${error.message}`, { error, threadId, traceId });\n const artError = error instanceof ARTError ? error : new ARTError(error.message, ErrorCode.LLM_PROVIDER_ERROR, error);\n yield { type: 'ERROR', data: artError, threadId, traceId, sessionId };\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n }\n }; // No need for .bind(this)\n\n return generator();\n }\n\n /**\n * Translates the provider-agnostic `ArtStandardPrompt` into the OpenAI API's `OpenAIMessage[]` format.\n * (Copied from OpenAIAdapter - assumes DeepSeek compatibility)\n *\n * @private\n * @param {ArtStandardPrompt} artPrompt - The input `ArtStandardPrompt` array.\n * @returns {OpenAIMessage[]} The `OpenAIMessage[]` array formatted for the OpenAI API.\n * @throws {ARTError} If translation encounters an issue (ErrorCode.PROMPT_TRANSLATION_FAILED).\n */\n private translateToOpenAI(artPrompt: ArtStandardPrompt): OpenAIMessage[] {\n // Identical implementation to OpenAIAdapter's translateToOpenAI\n return artPrompt.map((message: ArtStandardMessage): OpenAIMessage => {\n switch (message.role) {\n case 'system': {\n if (typeof message.content !== 'string') {\n Logger.warn(`DeepSeekAdapter: System message content is not a string. Stringifying.`, { content: message.content });\n return { role: 'system', content: String(message.content) };\n }\n return { role: 'system', content: message.content };\n }\n case 'user': {\n if (typeof message.content !== 'string') {\n Logger.warn(`DeepSeekAdapter: User message content is not a string. Stringifying.`, { content: message.content });\n return { role: 'user', content: String(message.content) };\n }\n return { role: 'user', content: message.content };\n }\n case 'assistant': {\n const assistantMsg: OpenAIMessage = {\n role: 'assistant',\n content: typeof message.content === 'string' ? message.content : null,\n };\n if (message.tool_calls && message.tool_calls.length > 0) {\n assistantMsg.tool_calls = message.tool_calls.map(tc => {\n if (tc.type !== 'function' || !tc.function?.name || typeof tc.function?.arguments !== 'string') {\n throw new ARTError(\n `DeepSeekAdapter: Invalid tool_call structure in assistant message. ID: ${tc.id}`,\n ErrorCode.PROMPT_TRANSLATION_FAILED\n );\n }\n return {\n id: tc.id,\n type: tc.type,\n function: {\n name: tc.function.name,\n arguments: tc.function.arguments,\n }\n };\n });\n }\n if (assistantMsg.content === '' && !assistantMsg.tool_calls) {\n assistantMsg.content = null;\n }\n if (assistantMsg.content === '' && assistantMsg.tool_calls) {\n assistantMsg.content = null;\n }\n if (typeof assistantMsg.content !== 'string' && assistantMsg.content !== null) {\n assistantMsg.content = null;\n }\n return assistantMsg;\n }\n case 'tool_result': {\n if (!message.tool_call_id) {\n throw new ARTError(\n `DeepSeekAdapter: 'tool_result' message missing required 'tool_call_id'.`,\n ErrorCode.PROMPT_TRANSLATION_FAILED\n );\n }\n if (typeof message.content !== 'string') {\n Logger.warn(`DeepSeekAdapter: Tool result content is not a string. Stringifying.`, { content: message.content });\n }\n return {\n role: 'tool',\n tool_call_id: message.tool_call_id,\n content: String(message.content),\n };\n }\n case 'tool_request': {\n throw new ARTError(\n `DeepSeekAdapter: Unexpected 'tool_request' role encountered during translation.`,\n ErrorCode.PROMPT_TRANSLATION_FAILED\n );\n }\n default: {\n throw new ARTError(\n `DeepSeekAdapter: Unknown message role '${message.role}' encountered during translation.`,\n ErrorCode.PROMPT_TRANSLATION_FAILED\n );\n }\n }\n });\n }\n }","// src/adapters/reasoning/ollama.ts\nimport OpenAI from \"openai\";\n\nimport { ProviderAdapter } from '@/core/interfaces';\nimport {\n ArtStandardPrompt,\n ArtStandardMessage,\n CallOptions,\n StreamEvent,\n LLMMetadata,\n ToolSchema, // Added for tool support\n} from '@/types';\nimport { Logger } from '@/utils/logger';\nimport { ARTError, ErrorCode } from '@/errors';\n// XmlMatcher removed, parsing of embedded XML is responsibility of OutputParser\n\n// Define expected options for the Ollama adapter constructor\n/**\n * Configuration options required for the `OllamaAdapter`.\n */\nexport interface OllamaAdapterOptions {\n /**\n * The base URL for the Ollama API. Defaults to 'http://localhost:11434'.\n * The '/v1' suffix for OpenAI compatibility will be added automatically.\n */\n ollamaBaseUrl?: string;\n /**\n * The default Ollama model ID to use (e.g., 'llama3', 'mistral').\n * This can be overridden by `RuntimeProviderConfig.modelId` or `CallOptions.model`.\n * It's recommended to set this if you primarily use one model with Ollama.\n */\n defaultModel?: string;\n /**\n * API key for Ollama (if secured). Defaults to \"ollama\" as commonly used.\n */\n apiKey?: string;\n}\n\n// OpenAI-compatible structures (can be shared or adapted from openai.ts)\ninterface OpenAIMessage {\n role: 'system' | 'user' | 'assistant' | 'tool';\n content: string | null;\n name?: string;\n tool_calls?: OpenAIToolCall[];\n tool_call_id?: string;\n}\n\ninterface OpenAIToolCall {\n id: string;\n type: 'function';\n function: {\n name: string;\n arguments: string; // Stringified JSON\n };\n}\n\n// Note: Payload and Response types are from 'openai' package directly.\n\n/**\n * Implements the `ProviderAdapter` interface for interacting with Ollama's\n * OpenAI-compatible API endpoint.\n *\n * Handles formatting requests, parsing responses, streaming, and tool use.\n *\n * @see {@link ProviderAdapter} for the interface definition.\n * @see {@link OllamaAdapterOptions} for configuration options.\n */\nexport class OllamaAdapter implements ProviderAdapter {\n readonly providerName = 'ollama';\n private client: OpenAI;\n private defaultModel?: string;\n private ollamaBaseUrl: string;\n\n /**\n * Creates an instance of the OllamaAdapter.\n * @param options - Configuration options.\n */\n constructor(options: OllamaAdapterOptions) {\n this.ollamaBaseUrl = options.ollamaBaseUrl || 'http://localhost:11434';\n this.defaultModel = options.defaultModel;\n\n // Ensure ollamaBaseUrl doesn't end with /v1 or /\n const cleanBaseUrl = this.ollamaBaseUrl.replace(/\\/v1$/, \"\").replace(/\\/$/, \"\");\n\n this.client = new OpenAI({\n baseURL: `${cleanBaseUrl}/v1`,\n apiKey: options.apiKey || \"ollama\", // Default API key for local Ollama\n dangerouslyAllowBrowser: true, // Necessary if running in a browser-like environment for local calls\n });\n\n Logger.debug(`OllamaAdapter initialized. Base URL: ${cleanBaseUrl}/v1, Default Model: ${this.defaultModel || 'Not set'}`);\n }\n\n /**\n * Sends a request to the Ollama API.\n * Translates `ArtStandardPrompt` to the OpenAI format and handles streaming and tool use.\n *\n * @param {ArtStandardPrompt} prompt - The standardized prompt messages.\n * @param {CallOptions} options - Call options.\n * @returns {Promise<AsyncIterable<StreamEvent>>} A promise resolving to an AsyncIterable of StreamEvent objects.\n */\n async call(prompt: ArtStandardPrompt, options: CallOptions): Promise<AsyncIterable<StreamEvent>> {\n const {\n threadId,\n traceId = `ollama-trace-${Date.now()}`,\n sessionId,\n stream = false,\n callContext,\n model: modelOverride,\n tools: availableArtTools,\n providerConfig,\n } = options;\n\n const modelToUse = providerConfig?.modelId || modelOverride || this.defaultModel;\n\n if (!modelToUse) {\n const err = new ARTError(\n \"Ollama model ID is not specified. Provide it in adapter options, runtime config, or call options.\",\n ErrorCode.INVALID_CONFIG\n );\n const errorGenerator = async function* (): AsyncIterable<StreamEvent> {\n yield { type: 'ERROR', data: err, threadId, traceId, sessionId };\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n };\n return errorGenerator();\n }\n\n let openAiMessages: OpenAIMessage[];\n try {\n openAiMessages = this.translateToOpenAI(prompt, modelToUse); // Pass modelToUse here\n } catch (error: any) {\n Logger.error(`Error translating ArtStandardPrompt to OpenAI format for Ollama: ${error.message}`, { error, threadId, traceId });\n const artError = error instanceof ARTError ? error : new ARTError(`Prompt translation failed: ${error.message}`, ErrorCode.PROMPT_TRANSLATION_FAILED, error);\n const errorGenerator = async function* (): AsyncIterable<StreamEvent> {\n yield { type: 'ERROR', data: artError, threadId, traceId, sessionId };\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n };\n return errorGenerator();\n }\n\n const openAiTools: OpenAI.Chat.Completions.ChatCompletionTool[] | undefined = availableArtTools\n ? this.translateArtToolsToOpenAI(availableArtTools)\n : undefined;\n\n const requestBody: OpenAI.Chat.Completions.ChatCompletionCreateParams = {\n model: modelToUse,\n messages: openAiMessages as OpenAI.Chat.ChatCompletionMessageParam[], // Cast needed\n temperature: options.temperature ?? providerConfig?.adapterOptions?.temperature,\n max_tokens: options.max_tokens ?? options.maxOutputTokens ?? providerConfig?.adapterOptions?.max_tokens,\n top_p: options.top_p ?? options.topP ?? providerConfig?.adapterOptions?.top_p,\n stop: (options.stop || options.stop_sequences || options.stopSequences) ?? providerConfig?.adapterOptions?.stop,\n stream: stream,\n tools: openAiTools,\n tool_choice: options.tool_choice ?? providerConfig?.adapterOptions?.tool_choice,\n };\n\n // Remove undefined keys from the request body\n Object.keys(requestBody).forEach(key => {\n const K = key as keyof OpenAI.Chat.Completions.ChatCompletionCreateParams;\n if (requestBody[K] === undefined) {\n delete requestBody[K];\n }\n });\n\n Logger.debug(`Calling Ollama API (via OpenAI client) with model ${modelToUse}`, { stream, tools: !!openAiTools, threadId, traceId });\n\n const generator = async function* (this: OllamaAdapter): AsyncIterable<StreamEvent> {\n const startTime = Date.now();\n let timeToFirstTokenMs: number | undefined;\n let accumulatedOutputTokens = 0;\n let finalApiResponseUsage: OpenAI.CompletionUsage | undefined;\n let finalStopReason: string | undefined;\n\n try {\n if (stream) {\n const streamInstance = await this.client.chat.completions.create(\n requestBody as OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming\n );\n \n // let accumulatedText = \"\"; // Not strictly needed here as text is yielded token by token\n const accumulatedToolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] = [];\n\n for await (const chunk of streamInstance) {\n if (!timeToFirstTokenMs) {\n timeToFirstTokenMs = Date.now() - startTime;\n }\n\n const delta = chunk.choices[0]?.delta;\n finalStopReason = chunk.choices[0]?.finish_reason ?? finalStopReason;\n\n if (delta?.content) {\n accumulatedOutputTokens++; // Approximation: count each content chunk as one token\n // If XML parsing is needed for <think> tags, it should be done by OutputParser\n // Adapter streams raw content.\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n yield { type: 'TOKEN', data: delta.content, threadId, traceId, sessionId, tokenType };\n }\n\n if (delta?.tool_calls) {\n delta.tool_calls.forEach((tcDelta: OpenAI.Chat.Completions.ChatCompletionChunk.Choice.Delta.ToolCall) => {\n if (tcDelta.index === undefined) return;\n\n if (!accumulatedToolCalls[tcDelta.index]) {\n accumulatedToolCalls[tcDelta.index] = {\n id: tcDelta.id || '',\n type: 'function', // Type is always 'function' for OpenAI tools\n function: {\n name: tcDelta.function?.name || '',\n arguments: tcDelta.function?.arguments || ''\n }\n };\n } else {\n if (tcDelta.id) accumulatedToolCalls[tcDelta.index].id = tcDelta.id;\n if (tcDelta.function?.name) accumulatedToolCalls[tcDelta.index].function.name = tcDelta.function.name;\n if (tcDelta.function?.arguments) {\n // Ensure function object exists if not initialized by name first\n if (!accumulatedToolCalls[tcDelta.index].function) {\n accumulatedToolCalls[tcDelta.index].function = { name: '', arguments: ''};\n }\n accumulatedToolCalls[tcDelta.index].function.arguments += tcDelta.function.arguments;\n }\n }\n });\n }\n // Ollama's OpenAI compatible stream might not include usage per chunk.\n // We'll rely on the final non-streaming call for accurate usage if possible,\n // or estimate for streaming.\n if (chunk.usage) { // Check if usage is present in the chunk\n finalApiResponseUsage = chunk.usage;\n }\n }\n \n // If streaming and stop reason is tool_calls, yield the accumulated tool calls.\n // Text content would have been yielded incrementally.\n if (finalStopReason === 'tool_calls' && accumulatedToolCalls.length > 0) {\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n const toolData = accumulatedToolCalls.map(tc => ({\n type: 'tool_use', // ART specific marker\n id: tc.id,\n name: tc.function.name,\n input: JSON.parse(tc.function.arguments || '{}'),\n }));\n yield { type: 'TOKEN', data: toolData, threadId, traceId, sessionId, tokenType };\n }\n // Note: accumulatedText is not explicitly yielded here as all text content from delta.content\n // was already yielded token by token. If there's a scenario where text needs to be combined\n // with tool_calls in a single final stream TOKEN event, this logic would need adjustment,\n // but typically stream consumers aggregate individual TOKENs.\n\n } else { // Non-streaming\n const response = await this.client.chat.completions.create(\n requestBody as OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming\n );\n\n const firstChoice = response.choices[0];\n if (!firstChoice || !firstChoice.message) {\n throw new ARTError('Invalid response structure from Ollama API: No message found.', ErrorCode.LLM_PROVIDER_ERROR, new Error(JSON.stringify(response)));\n }\n\n finalStopReason = firstChoice.finish_reason ?? undefined;\n finalApiResponseUsage = response.usage;\n const responseMessage = firstChoice.message;\n\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n\n if (responseMessage.tool_calls && responseMessage.tool_calls.length > 0) {\n const toolData = responseMessage.tool_calls.map((tc: OpenAI.Chat.Completions.ChatCompletionMessageToolCall) => ({\n type: 'tool_use',\n id: tc.id,\n name: tc.function.name,\n input: JSON.parse(tc.function.arguments || '{}'),\n }));\n if (responseMessage.content) {\n yield { type: 'TOKEN', data: [{type: 'text', text: responseMessage.content.trim()}, ...toolData], threadId, traceId, sessionId, tokenType };\n } else {\n yield { type: 'TOKEN', data: toolData, threadId, traceId, sessionId, tokenType };\n }\n } else if (responseMessage.content) {\n yield { type: 'TOKEN', data: responseMessage.content.trim(), threadId, traceId, sessionId, tokenType };\n }\n }\n\n const totalGenerationTimeMs = Date.now() - startTime;\n const metadata: LLMMetadata = {\n stopReason: finalStopReason,\n inputTokens: finalApiResponseUsage?.prompt_tokens,\n outputTokens: finalApiResponseUsage?.completion_tokens ?? (stream ? accumulatedOutputTokens : undefined),\n timeToFirstTokenMs: stream ? timeToFirstTokenMs : undefined, // TTFT only for stream\n totalGenerationTimeMs: totalGenerationTimeMs,\n providerRawUsage: { usage: finalApiResponseUsage, finish_reason: finalStopReason },\n traceId: traceId,\n };\n yield { type: 'METADATA', data: metadata, threadId, traceId, sessionId };\n\n } catch (error: any) {\n Logger.error(`Error during Ollama API call: ${error.message}`, { error, threadId, traceId });\n const artError = error instanceof ARTError ? error :\n (error.constructor.name === 'APIError' ? new ARTError(`Ollama API Error (${(error as any).status}): ${(error as any).message}`, ErrorCode.LLM_PROVIDER_ERROR, error) :\n new ARTError(error.message || 'Unknown Ollama adapter error', ErrorCode.LLM_PROVIDER_ERROR, error));\n yield { type: 'ERROR', data: artError, threadId, traceId, sessionId };\n } finally {\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n }\n }.bind(this);\n\n return generator();\n }\n\n /**\n * Translates the provider-agnostic `ArtStandardPrompt` into the OpenAI API's `OpenAIMessage[]` format.\n * This method can handle model-specific formatting, such as merging consecutive messages for certain models.\n * @private\n * @param {ArtStandardPrompt} artPrompt - The input `ArtStandardPrompt` array.\n * @param {string} [modelIdForTransform] - The model ID, used to determine if special formatting is needed.\n * @returns {OpenAIMessage[]} The `OpenAIMessage[]` array formatted for the OpenAI API.\n */\n private translateToOpenAI(artPrompt: ArtStandardPrompt, modelIdForTransform?: string): OpenAIMessage[] {\n const messagesToProcess = [...artPrompt];\n const translatedMessages: OpenAIMessage[] = [];\n\n // Determine if R1-style merging is needed (e.g., for deepseek-r1)\n const useR1Format = modelIdForTransform?.toLowerCase().includes(\"deepseek-r1\");\n\n if (useR1Format) {\n Logger.debug(`OllamaAdapter: Applying R1-style message merging for model: ${modelIdForTransform}`);\n let lastMessage: OpenAIMessage | null = null;\n for (const artMsg of messagesToProcess) {\n // Map current ArtStandardMessage to a basic OpenAIMessage structure first\n // This mapping needs to be careful about roles, as 'tool_result' becomes 'tool'\n let currentRoleForCompare: 'system' | 'user' | 'assistant' | 'tool' = 'user'; // default\n if (artMsg.role === 'system') currentRoleForCompare = 'system';\n else if (artMsg.role === 'user') currentRoleForCompare = 'user';\n else if (artMsg.role === 'assistant') currentRoleForCompare = 'assistant';\n else if (artMsg.role === 'tool_result') currentRoleForCompare = 'tool';\n // 'tool_request' is an error case handled by mapArtMessageToOpenAIMessage\n\n const currentOpenAIMsgPart = this.mapArtMessageToOpenAIMessage(artMsg);\n\n\n if (lastMessage && lastMessage.role === currentRoleForCompare && currentRoleForCompare !== 'system' && currentRoleForCompare !== 'tool') {\n // Merge content for 'user' or 'assistant' roles\n // Note: OpenAI API generally allows consecutive 'tool' messages if they have different tool_call_ids.\n // And 'system' messages are usually single or handled specially.\n // The primary concern for merging is consecutive 'user' or 'assistant' messages for models like DeepSeek R1.\n\n let mergedContent = \"\";\n if (typeof lastMessage.content === 'string' && typeof currentOpenAIMsgPart.content === 'string') {\n mergedContent = `${lastMessage.content}\\n${currentOpenAIMsgPart.content}`;\n } else if (typeof lastMessage.content === 'string') {\n mergedContent = `${lastMessage.content}\\n${currentOpenAIMsgPart.content === null ? '' : String(currentOpenAIMsgPart.content)}`;\n } else if (typeof currentOpenAIMsgPart.content === 'string') {\n mergedContent = `${lastMessage.content === null ? '' : String(lastMessage.content)}\\n${currentOpenAIMsgPart.content}`;\n } else { // both might be null or non-string\n mergedContent = `${lastMessage.content === null ? '' : String(lastMessage.content)}\\n${currentOpenAIMsgPart.content === null ? '' : String(currentOpenAIMsgPart.content)}`;\n }\n lastMessage.content = mergedContent.trim() || null;\n\n // Merge tool_calls for assistant messages\n if (lastMessage.role === 'assistant' && currentOpenAIMsgPart.role === 'assistant' && currentOpenAIMsgPart.tool_calls) {\n lastMessage.tool_calls = [...(lastMessage.tool_calls || []), ...currentOpenAIMsgPart.tool_calls];\n }\n // Ensure content is null if only tool_calls are present after merge\n if (lastMessage.role === 'assistant' && !lastMessage.content && lastMessage.tool_calls && lastMessage.tool_calls.length > 0) {\n lastMessage.content = null;\n }\n\n } else {\n // If roles are different, or it's a system/tool message not needing merge, or it's the first message\n lastMessage = currentOpenAIMsgPart;\n translatedMessages.push(lastMessage);\n }\n }\n } else {\n // Standard mapping without R1-specific merging\n for (const artMsg of messagesToProcess) {\n translatedMessages.push(this.mapArtMessageToOpenAIMessage(artMsg));\n }\n }\n return translatedMessages;\n }\n\n // Helper function to map a single ArtStandardMessage to an OpenAIMessage\n // This is called by translateToOpenAI\n /**\n * Maps a single `ArtStandardMessage` to an `OpenAIMessage`.\n * @private\n * @param {ArtStandardMessage} message - The message to map.\n * @returns {OpenAIMessage} The mapped message.\n * @throws {ARTError} If an unsupported or invalid message role is encountered.\n */\n private mapArtMessageToOpenAIMessage(message: ArtStandardMessage): OpenAIMessage {\n switch (message.role) {\n case 'system':\n return { role: 'system', content: typeof message.content === 'string' ? message.content : String(message.content) };\n case 'user':\n // User content can be complex (e.g. multipart with images for some providers, but OpenAI expects string or array of content parts)\n // For Ollama with OpenAI client, we assume string content for user messages for now.\n // If ArtStandardMessage.content for user can be an array of parts, this needs adjustment.\n return { role: 'user', content: typeof message.content === 'string' ? message.content : JSON.stringify(message.content) };\n case 'assistant': {\n const assistantMsg: OpenAIMessage = {\n role: 'assistant',\n content: typeof message.content === 'string' ? message.content : null,\n };\n if (message.tool_calls && message.tool_calls.length > 0) {\n assistantMsg.tool_calls = message.tool_calls.map(tc => {\n if (tc.type !== 'function' || !tc.function?.name || typeof tc.function?.arguments !== 'string') {\n throw new ARTError(`OllamaAdapter: Invalid tool_call structure in assistant message. ID: ${tc.id}`, ErrorCode.PROMPT_TRANSLATION_FAILED);\n }\n return {\n id: tc.id,\n type: tc.type,\n function: { name: tc.function.name, arguments: tc.function.arguments },\n };\n });\n }\n // OpenAI API: content is required unless tool_calls is present.\n // If content is an empty string and tool_calls are present, set content to null.\n if (assistantMsg.content === '' && assistantMsg.tool_calls && assistantMsg.tool_calls.length > 0) {\n assistantMsg.content = null;\n } else if (assistantMsg.content === '' && (!assistantMsg.tool_calls || assistantMsg.tool_calls.length === 0)) {\n // If content is empty string and no tool_calls, it might be an issue for some models.\n // However, OpenAI allows empty string content. For safety, can be null.\n // Let's stick to null if it was not a string initially or became empty.\n if (typeof message.content !== 'string') assistantMsg.content = null;\n }\n // Ensure content is explicitly null if it's not a string and not empty (e.g. if it was an object that didn't become a string)\n if (typeof assistantMsg.content !== 'string' && assistantMsg.content !== null) {\n assistantMsg.content = null;\n }\n return assistantMsg;\n }\n case 'tool_result': {\n if (!message.tool_call_id) {\n throw new ARTError(\"OllamaAdapter: 'tool_result' message missing required 'tool_call_id'.\", ErrorCode.PROMPT_TRANSLATION_FAILED);\n }\n return {\n role: 'tool',\n tool_call_id: message.tool_call_id,\n content: String(message.content), // Content is the stringified result/error\n };\n }\n case 'tool_request': // This role should not be directly translated as it's part of assistant's tool_calls\n throw new ARTError(\"OllamaAdapter: Unexpected 'tool_request' role during mapping. This should be handled via assistant's tool_calls.\", ErrorCode.PROMPT_TRANSLATION_FAILED);\n default:\n // This should ideally not be reached if ArtStandardMessageRole is comprehensive\n throw new ARTError(`OllamaAdapter: Unknown message role '${(message as ArtStandardMessage).role}' encountered during mapping.`, ErrorCode.PROMPT_TRANSLATION_FAILED);\n }\n }\n\n /**\n * Translates an array of `ToolSchema` from the ART framework format to OpenAI's specific tool format.\n * @private\n * @param {ToolSchema[]} artTools - An array of ART tool schemas.\n * @returns {OpenAI.Chat.Completions.ChatCompletionTool[]} An array of tools formatted for the OpenAI API.\n * @throws {ARTError} If a tool's schema is invalid.\n */\n private translateArtToolsToOpenAI(artTools: ToolSchema[]): OpenAI.Chat.Completions.ChatCompletionTool[] {\n return artTools.map(artTool => {\n // ART's ToolSchema directly provides name, description, and inputSchema.\n // OpenAI tools are always of type 'function'.\n if (!artTool.name || !artTool.inputSchema) {\n throw new ARTError(`Invalid ART ToolSchema for tool '${artTool.name || 'unknown'}'. Must include name and inputSchema.`, ErrorCode.INVALID_CONFIG);\n }\n return {\n type: 'function', // OpenAI tool type is always 'function'\n function: {\n name: artTool.name,\n description: artTool.description,\n parameters: artTool.inputSchema as OpenAI.FunctionParameters, // artTool.inputSchema is the JSON schema\n },\n };\n });\n }\n\n /**\n * Optional method for graceful shutdown. For Ollama, which is typically a separate\n * local server, this adapter doesn't manage persistent connections that need explicit closing.\n * @returns {Promise<void>} A promise that resolves when the shutdown is complete.\n */\n async shutdown(): Promise<void> {\n Logger.debug(`OllamaAdapter shutdown called. No specific resources to release for model ${this.defaultModel || 'not set'}.`);\n // No explicit resources to release for a typical Ollama HTTP API client.\n return Promise.resolve();\n }\n}\n// TODO: Management Features as below\n{/*\n Model Management (List, Pull, Delete):\n\nThese are administrative tasks. In a complex application, these might be handled by a separate \"Ollama Management Service\" or utility functions within the application that interact directly with these Ollama API endpoints.\nThey don't fit naturally into the ProviderAdapter.call() flow, which is about sending a prompt and receiving a response.\nExposing these directly on the OllamaAdapter instance might be possible but could blur its primary responsibility.\n\n\nAborting a Stream:\n\nThe AsyncIterable<StreamEvent> returned by ProviderAdapter.call() can be aborted by the consumer of the stream. When the consumer stops iterating (e.g., breaks from a for await...of loop or the underlying mechanism like an AbortController signals an abort to the fetch call within the adapter), the adapter's fetch request should be cancelled. This, in turn, should close the connection to the Ollama server, effectively aborting the stream from Ollama's perspective.\nThe openai SDK (which my OllamaAdapter uses) supports passing an AbortSignal to its methods. This is the standard way to handle cancellation. The OllamaAdapter.call method could accept an AbortSignal in its CallOptions if ART's ReasoningEngine and AgentCore were designed to propagate such a signal.\nCurrently, CallOptions in ART does not have a standard abortSignal property. Adding this would be a framework-level change.\nWithout a framework-level abort signal, the adapter itself cannot easily expose an \"abort\" method for a stream initiated by call(), because the stream consumption is managed externally by the AgentCore.\n */}","// src/tools/CalculatorTool.ts\nimport { IToolExecutor } from '@/core/interfaces';\nimport { ToolSchema, ExecutionContext, ToolResult } from '@/types';\nimport { Logger } from '@/utils/logger';\n// Import necessary parts from mathjs\nimport { evaluate, type Complex } from 'mathjs'; // Removed unused MathJsStatic, MathNode\nimport * as math from 'mathjs'; // Import the full math object to access functions\n\n/**\n * A restricted set of safe functions allowed from the mathjs library.\n * Prevents access to potentially unsafe functions like `import`, `evaluate`, etc.\n * @internal\n */\nconst allowedFunctions: Record<string, any> = {\n // Basic arithmetic & roots\n sqrt: math.sqrt,\n cbrt: math.cbrt,\n abs: math.abs,\n pow: math.pow, // Note: ^ operator also works\n exp: math.exp,\n log: math.log,\n log10: math.log10,\n log2: math.log2,\n // Trigonometry\n sin: math.sin,\n cos: math.cos,\n tan: math.tan,\n asin: math.asin,\n acos: math.acos,\n atan: math.atan,\n atan2: math.atan2,\n // Rounding & Modulo\n round: math.round,\n floor: math.floor,\n ceil: math.ceil,\n mod: math.mod, // Note: % operator also works\n // Statistical functions\n mean: math.mean,\n median: math.median,\n std: math.std,\n variance: math.variance,\n max: math.max,\n min: math.min,\n // Additional mathematical functions\n factorial: math.factorial,\n gamma: math.gamma,\n combinations: math.combinations,\n permutations: math.permutations,\n // Number formatting\n format: math.format,\n // Constants (implicitly allowed via evaluate, but good to be aware)\n // pi: math.pi,\n // e: math.e,\n};\n\n/**\n * An ART Framework tool that safely evaluates mathematical expressions using the mathjs library.\n * It supports basic arithmetic, variables via a scope, complex numbers, and a predefined list of safe functions.\n *\n * This tool is designed to be used within the ART framework's `ToolSystem`.\n * It provides a safe way to perform mathematical calculations by leveraging\n * the `mathjs` library. The tool validates the input expression to ensure it's a\n * single, valid mathematical expression before evaluation.\n *\n * @see {@link IToolExecutor} for the interface it implements.\n * @see {@link ToolSystem} for the system that manages and executes tools.\n */\nexport class CalculatorTool implements IToolExecutor {\n /** The unique name identifier for this tool. */\n public static readonly toolName = \"calculator\";\n \n /** Store for previous calculation results by threadId */\n private resultStore: Map<string, any> = new Map();\n\n /**\n * The schema definition for the CalculatorTool, conforming to the `ToolSchema` interface.\n * It defines the tool's name, description, input parameters (expression and optional scope),\n * and provides examples for the LLM.\n */\n // TODO: Consider renaming this property to `getSchema()` for better idiomatic consistency? (See sample-app feedback)\n readonly schema: ToolSchema = {\n name: CalculatorTool.toolName,\n description: `Evaluates mathematical expressions using a sandboxed mathjs environment.\nYou can reference previous calculation results using the 'ans' variable.\nSupports standard operators (+, -, *, /, %, ^), variables via 'scope', complex numbers, and the following allowed functions:\nsqrt, cbrt, abs, pow, exp, log, log10, log2, sin, cos, tan, asin, acos, atan, atan2, round, floor, ceil, mod, \nmean, median, std, variance, max, min, factorial, gamma, combinations, permutations, format.`,\n inputSchema: {\n type: 'object',\n properties: {\n expression: {\n type: 'string',\n description: 'The mathematical expression to evaluate (e.g., \"2 + 2\", \"sqrt(a)\", \"a * b\", \"sqrt(-4)\", \"factorial(5)\", \"ans + 10\").',\n },\n scope: {\n type: 'object',\n description: 'An optional object containing variables and their values (numbers only) to be used in the expression (e.g., {\"a\": 16, \"b\": 3}).',\n additionalProperties: { type: 'number' },\n default: {},\n },\n },\n required: ['expression'],\n },\n // Note: outputSchema is omitted as the result can be number or string (for complex numbers).\n // A more complex schema using 'oneOf' could be defined if strict output validation is needed.\n examples: [\n { input: { expression: \"2 + 2\" }, output: { result: 4 }, description: \"Simple addition\" },\n { input: { expression: \"12 % 5\" }, output: { result: 2 }, description: \"Modulo operation\" },\n { input: { expression: \"sqrt(16)\" }, output: { result: 4 }, description: \"Square root function\" },\n { input: { expression: \"a + b\", scope: { a: 7, b: 3 } }, output: { result: 10 }, description: \"Expression with variables\" },\n { input: { expression: \"result % 13\", scope: { result: 347 } }, output: { result: 9 }, description: \"Modulo with variable\" },\n { input: { expression: \"sqrt(-4)\" }, output: { result: \"2i\" }, description: \"Square root of negative (complex result)\" },\n { input: { expression: \"pow(i, 2)\" }, output: { result: -1 }, description: \"Complex number calculation (i^2)\" },\n { input: { expression: \"log(10)\" }, output: { result: 2.302585092994046 }, description: \"Natural logarithm\" },\n { input: { expression: \"factorial(5)\" }, output: { result: 120 }, description: \"Factorial function\" },\n { input: { expression: \"ans + 10\" }, output: { result: 130 }, description: \"Using previous result with 'ans'\" },\n { input: { expression: \"mean([1, 2, 3, 4, 5])\" }, output: { result: 3 }, description: \"Statistical function\" },\n // Example of how an error might be represented if a disallowed function were used:\n // { input: { expression: \"factorial(5)\" }, error: \"Failed to evaluate expression: Function factorial is not allowed\" },\n ],\n };\n\n /**\n * Executes the calculator tool by evaluating the provided mathematical expression.\n * It uses a restricted scope including only allowed mathjs functions and any variables\n * passed in the `input.scope`. Handles basic number and complex number results.\n *\n * @param input - An object containing the `expression` (string) and optional `scope` (object). Must match `inputSchema`.\n * @param context - The execution context containing `threadId`, `traceId`, etc.\n * @returns A promise resolving to a `ToolResult` object.\n * On success, `status` is 'success' and `output` is `{ result: number | string }`.\n * On failure, `status` is 'error' and `error` contains the error message.\n */\n async execute(input: any, context: ExecutionContext): Promise<ToolResult> {\n const expression = input.expression as string;\n const threadId = context.threadId || 'default-thread';\n \n // Get previous result for this thread if available\n const previousResult = this.resultStore.get(threadId);\n \n // Combine user scope with allowed functions and previous result. User scope takes precedence if names clash.\n const executionScope = { \n ...allowedFunctions, \n ...(input.scope || {}),\n // Add 'ans' variable referencing the previous result\n ...(previousResult !== undefined ? { ans: previousResult } : {})\n };\n \n const callId = context.traceId || 'calculator-call';\n\n Logger.debug(`CalculatorTool executing with expression: \"${expression}\" and combined scope keys: ${Object.keys(executionScope).join(', ')}`, { callId, context });\n\n try {\n // Use mathjs.evaluate with the restricted scope\n const resultValue = evaluate(expression, executionScope);\n\n let outputResult: number | string;\n\n // Check if the result is a finite number\n if (typeof resultValue === 'number' && Number.isFinite(resultValue)) {\n outputResult = resultValue;\n }\n // Check if the result is a Complex number\n else if (math.isComplex(resultValue)) {\n // Convert complex number to string representation (e.g., \"2 + 3i\")\n outputResult = (resultValue as Complex).toString();\n }\n // Handle other types (like matrices, units, functions returned) as errors for now\n else {\n throw new Error(`Evaluation resulted in an unsupported type: ${math.typeOf(resultValue)}`);\n }\n\n // Store the result for future reference\n this.resultStore.set(threadId, resultValue);\n\n Logger.info(`CalculatorTool evaluated \"${expression}\" to ${outputResult}`, { callId });\n\n return {\n callId: callId,\n toolName: this.schema.name,\n status: 'success',\n output: { result: outputResult }, // Use the processed result\n };\n } catch (error: any) {\n Logger.error(`CalculatorTool failed to evaluate expression \"${expression}\": ${error.message}`, { callId, error });\n // Return the specific error message from mathjs or our validation\n return {\n callId: callId,\n toolName: this.schema.name,\n status: 'error',\n error: `Failed to evaluate expression: ${error.message}`, // More specific error\n };\n }\n }\n}","import { IAuthStrategy } from '@/core/interfaces';\nimport { ARTError, ErrorCode } from '@/errors';\nimport { Logger } from '@/utils/logger';\n\n/**\n * Configuration for the PKCE OAuth 2.0 authentication strategy.\n */\nexport interface PKCEOAuthConfig {\n /** The OAuth 2.0 authorization endpoint URL. */\n authorizationEndpoint: string;\n /** The OAuth 2.0 token endpoint URL. */\n tokenEndpoint: string;\n /** The client ID for the application. */\n clientId: string;\n /** The redirect URI for the application. */\n redirectUri: string;\n /** The scopes to request (space-separated). */\n scopes: string;\n /** Optional: The resource parameter to specify the target audience (for MCP servers). */\n resource?: string;\n /** Open login in a new tab (default true for ART MCP flows). */\n openInNewTab?: boolean;\n /** BroadcastChannel name used to receive auth codes from callback tab (default 'art-auth'). */\n channelName?: string;\n}\n\ninterface CachedToken {\n accessToken: string;\n refreshToken?: string;\n expiresAt: number;\n}\n\n/**\n * Implements the OAuth 2.0 Authorization Code Flow with PKCE (Proof Key for Code Exchange).\n * This is the recommended, most secure method for authenticating users in browser-based applications.\n */\nexport class PKCEOAuthStrategy implements IAuthStrategy {\n private config: PKCEOAuthConfig;\n private cachedToken: CachedToken | null = null;\n private codeVerifierForPendingLogin: string | null = null;\n private loginWaiter: { resolve: () => void; reject: (e: any) => void } | null = null;\n private channel?: BroadcastChannel;\n\n /**\n * Creates an instance of PKCEOAuthStrategy.\n * @param {PKCEOAuthConfig} config - The configuration for the PKCE OAuth 2.0 strategy.\n */\n constructor(config: PKCEOAuthConfig) {\n if (!config.authorizationEndpoint || !config.tokenEndpoint || !config.clientId || !config.redirectUri || !config.scopes) {\n throw new ARTError(\n 'PKCEOAuthStrategy requires authorizationEndpoint, tokenEndpoint, clientId, redirectUri, and scopes.',\n ErrorCode.INVALID_CONFIG,\n );\n }\n this.config = { openInNewTab: true, channelName: 'art-auth', ...config };\n\n // Setup BroadcastChannel to receive auth codes from the callback tab (new-tab flow)\n try {\n this.channel = new BroadcastChannel(this.config.channelName!);\n this.channel.onmessage = async (evt: MessageEvent) => {\n const msg = evt.data || {};\n if (msg?.type === 'art-auth-code' && typeof msg?.code === 'string') {\n try {\n await this.exchangeCodeForToken(msg.code);\n if (this.loginWaiter) this.loginWaiter.resolve();\n } catch (e) {\n if (this.loginWaiter) this.loginWaiter.reject(e);\n } finally {\n this.loginWaiter = null;\n }\n }\n };\n } catch {\n // BroadcastChannel not available; new-tab flow will not work in this environment\n }\n }\n\n /**\n * Initiates the PKCE login flow by redirecting the user to the authorization endpoint.\n * @returns {Promise<void>} A promise that resolves when the login process is complete.\n */\n public async login(): Promise<void> {\n const codeVerifier = this.generateCodeVerifier();\n const codeChallenge = await this.generateCodeChallenge(codeVerifier);\n\n // Store verifier for same-tab fallback and keep in-memory for new-tab token exchange\n sessionStorage.setItem('pkce_code_verifier', codeVerifier);\n this.codeVerifierForPendingLogin = codeVerifier;\n\n const params = new URLSearchParams({\n client_id: this.config.clientId,\n redirect_uri: this.config.redirectUri,\n scope: this.config.scopes,\n response_type: 'code',\n code_challenge: codeChallenge,\n code_challenge_method: 'S256',\n });\n\n if (this.config.resource) {\n params.append('resource', this.config.resource);\n }\n\n // Include a minimal state that carries the BroadcastChannel name for the callback tab\n try {\n const statePayload = { ch: this.config.channelName };\n const state = btoa(unescape(encodeURIComponent(JSON.stringify(statePayload)))).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n params.append('state', state);\n } catch {/* ignore */}\n\n const authorizationUrl = `${this.config.authorizationEndpoint}?${params.toString()}`;\n Logger.info('Starting PKCE login at authorization endpoint.');\n\n if (this.config.openInNewTab) {\n const popup = window.open(authorizationUrl, '_blank', 'noopener,noreferrer');\n if (!popup) {\n throw new ARTError('Popup blocked. Please allow popups to continue login.', ErrorCode.INVALID_CONFIG);\n }\n // Wait for token acquisition via BroadcastChannel\n await new Promise<void>((resolve, reject) => {\n this.loginWaiter = { resolve, reject };\n setTimeout(() => {\n if (this.loginWaiter) {\n this.loginWaiter = null;\n reject(new ARTError('Login timed out. Please try again.', ErrorCode.TIMEOUT));\n }\n }, 180000); // 3 minutes\n });\n return;\n }\n\n // Same-tab redirect fallback (not preferred for ART MCP flows)\n window.location.assign(authorizationUrl);\n }\n\n /**\n * Handles the redirect from the authorization server.\n * This method should be called on the redirect URI page.\n * It exchanges the authorization code for an access token.\n * @returns {Promise<void>} A promise that resolves when the redirect has been handled.\n */\n public async handleRedirect(): Promise<void> {\n const params = new URLSearchParams(window.location.search);\n const code = params.get('code');\n\n if (!code) {\n const error = params.get('error');\n const errorDescription = params.get('error_description');\n throw new ARTError(\n `OAuth error on redirect: ${error} - ${errorDescription || 'No description provided.'}`,\n ErrorCode.EXTERNAL_SERVICE_ERROR,\n );\n }\n\n const codeVerifier = sessionStorage.getItem('pkce_code_verifier');\n if (!codeVerifier) {\n throw new ARTError('No PKCE code verifier found in session storage. Please initiate login again.', ErrorCode.INVALID_CONFIG);\n }\n\n try {\n const tokenResponse = await fetch(this.config.tokenEndpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n grant_type: 'authorization_code',\n client_id: this.config.clientId,\n redirect_uri: this.config.redirectUri,\n code: code,\n code_verifier: codeVerifier,\n }),\n });\n\n if (!tokenResponse.ok) {\n const errorText = await tokenResponse.text();\n throw new ARTError(`Failed to exchange authorization code for token: ${errorText}`, ErrorCode.NETWORK_ERROR);\n }\n\n const tokenData = await tokenResponse.json();\n this.cachedToken = {\n accessToken: tokenData.access_token,\n refreshToken: tokenData.refresh_token,\n expiresAt: Date.now() + (tokenData.expires_in || 3600) * 1000,\n };\n\n Logger.info('Successfully obtained access token.');\n } catch (error) {\n Logger.error('Error during token exchange:', error);\n throw new ARTError('An unexpected error occurred during the token exchange process.', ErrorCode.UNKNOWN_ERROR, error as Error);\n } finally {\n sessionStorage.removeItem('pkce_code_verifier');\n }\n }\n\n /**\n * Gets the authentication headers, automatically handling token refresh if needed.\n * @returns {Promise<Record<string, string>>} A promise that resolves to the authentication headers.\n */\n public async getAuthHeaders(): Promise<Record<string, string>> {\n if (!this.cachedToken) {\n throw new ARTError('No cached token available. Please login first.', ErrorCode.INVALID_CONFIG);\n }\n\n if (Date.now() >= this.cachedToken.expiresAt) {\n Logger.info('Access token expired, attempting to refresh.');\n await this.refreshToken();\n }\n\n return {\n Authorization: `Bearer ${this.cachedToken!.accessToken}`,\n };\n }\n\n /**\n * Clears the cached token.\n */\n public logout(): void {\n this.cachedToken = null;\n sessionStorage.removeItem('pkce_code_verifier');\n Logger.info('Cached token and PKCE code verifier cleared.');\n }\n\n /**\n * Checks if there is a valid, non-expired token.\n * @returns {Promise<boolean>} A promise that resolves to true if the token is valid, false otherwise.\n */\n public async isAuthenticated(): Promise<boolean> {\n if (!this.cachedToken) {\n return false;\n }\n\n if (Date.now() >= this.cachedToken.expiresAt) {\n try {\n await this.refreshToken();\n return true;\n } catch (error) {\n return false;\n }\n }\n\n return true;\n }\n\n // --- Private Helper Methods ---\n\n /**\n * Generates a random string for the code verifier.\n * @returns {string} The generated code verifier.\n */\n private generateCodeVerifier(): string {\n const randomBytes = new Uint8Array(32);\n window.crypto.getRandomValues(randomBytes);\n return this.base64UrlEncode(randomBytes);\n }\n\n /**\n * Generates a code challenge from a code verifier.\n * @param {string} verifier - The code verifier.\n * @returns {Promise<string>} A promise that resolves to the code challenge.\n */\n private async generateCodeChallenge(verifier: string): Promise<string> {\n const encoder = new TextEncoder();\n const data = encoder.encode(verifier);\n const hashBuffer = await window.crypto.subtle.digest('SHA-256', data);\n return this.base64UrlEncode(new Uint8Array(hashBuffer));\n }\n\n /**\n * Encodes a byte array into a base64 URL-safe string.\n * @param {Uint8Array} bytes - The byte array to encode.\n * @returns {string} The base64 URL-safe encoded string.\n */\n private base64UrlEncode(bytes: Uint8Array): string {\n return btoa(String.fromCharCode.apply(null, Array.from(bytes)))\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n }\n\n /**\n * Refreshes the access token using the refresh token.\n * @returns {Promise<void>} A promise that resolves when the token has been refreshed.\n */\n private async refreshToken(): Promise<void> {\n if (!this.cachedToken?.refreshToken) {\n this.logout(); // Clear expired token\n throw new ARTError('No refresh token available. User must re-authenticate.', ErrorCode.INVALID_CONFIG);\n }\n\n try {\n const tokenResponse = await fetch(this.config.tokenEndpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: this.config.clientId,\n refresh_token: this.cachedToken.refreshToken,\n }),\n });\n\n if (!tokenResponse.ok) {\n const errorText = await tokenResponse.text();\n this.logout(); // Clear tokens on failure\n throw new ARTError(`Failed to refresh token: ${errorText}`, ErrorCode.NETWORK_ERROR);\n }\n\n const tokenData = await tokenResponse.json();\n this.cachedToken = {\n accessToken: tokenData.access_token,\n // Keep the same refresh token if a new one isn't provided\n refreshToken: tokenData.refresh_token || this.cachedToken.refreshToken,\n expiresAt: Date.now() + (tokenData.expires_in || 3600) * 1000,\n };\n\n Logger.info('Successfully refreshed access token.');\n } catch (error) {\n this.logout();\n Logger.error('Error during token refresh:', error);\n throw new ARTError('An unexpected error occurred during the token refresh process.', ErrorCode.UNKNOWN_ERROR, error as Error);\n }\n }\n\n // --- Private: Exchange code to token using stored verifier (new-tab flow) ---\n /**\n * Exchanges an authorization code for an access token.\n * @param {string} code - The authorization code.\n * @returns {Promise<void>} A promise that resolves when the token exchange is complete.\n */\n private async exchangeCodeForToken(code: string): Promise<void> {\n if (!this.codeVerifierForPendingLogin) {\n throw new ARTError('Missing code verifier for PKCE exchange.', ErrorCode.INVALID_CONFIG);\n }\n\n const tokenResponse = await fetch(this.config.tokenEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'authorization_code',\n client_id: this.config.clientId,\n redirect_uri: this.config.redirectUri,\n code,\n code_verifier: this.codeVerifierForPendingLogin,\n }),\n });\n\n if (!tokenResponse.ok) {\n const errorText = await tokenResponse.text();\n throw new ARTError(`Failed to exchange authorization code for token: ${errorText}`, ErrorCode.NETWORK_ERROR);\n }\n\n const tokenData = await tokenResponse.json();\n this.cachedToken = {\n accessToken: tokenData.access_token,\n refreshToken: tokenData.refresh_token,\n expiresAt: Date.now() + (tokenData.expires_in || 3600) * 1000,\n };\n\n // Clear pending verifier\n this.codeVerifierForPendingLogin = null;\n sessionStorage.removeItem('pkce_code_verifier');\n }\n}","import { IAuthStrategy } from '@/core/interfaces';\n\n/**\n * Simple API key authentication strategy.\n * Supports configurable header names for different service requirements.\n */\nexport class ApiKeyStrategy implements IAuthStrategy {\n /**\n * Creates a new API key authentication strategy.\n * @param apiKey - The API key to use for authentication\n * @param headerName - The header name to use (defaults to 'Authorization')\n */\n constructor(\n private readonly apiKey: string,\n private readonly headerName: string = 'Authorization'\n ) {\n if (!apiKey || apiKey.trim() === '') {\n throw new Error('API key cannot be empty or null');\n }\n if (!headerName || headerName.trim() === '') {\n throw new Error('Header name cannot be empty or null');\n }\n }\n\n /**\n * Generates authentication headers for API key-based authentication.\n * Uses Bearer token format for Authorization header, plain key for custom headers.\n * @returns Promise resolving to authentication headers\n */\n async getAuthHeaders(): Promise<Record<string, string>> {\n // Use Bearer token format for Authorization header, plain key for custom headers\n const value = this.headerName === 'Authorization' \n ? `Bearer ${this.apiKey}` \n : this.apiKey;\n \n return { [this.headerName]: value };\n }\n\n /**\n * Gets the configured header name for this strategy.\n * @returns The header name that will be used\n */\n public getHeaderName(): string {\n return this.headerName;\n }\n\n /**\n * Checks if this strategy uses the standard Authorization header.\n * @returns True if using Authorization header, false for custom headers\n */\n public isUsingAuthorizationHeader(): boolean {\n return this.headerName === 'Authorization';\n }\n} ","import { IAuthStrategy } from '@/core/interfaces';\nimport { ARTError, ErrorCode } from '@/errors';\nimport { Logger } from '@/utils/logger';\n\n/**\n * Configuration for OAuth 2.0 authentication strategy\n */\nexport interface OAuthConfig {\n /** Client ID for OAuth authentication */\n clientId: string;\n /** Client secret for OAuth authentication */\n clientSecret: string;\n /** OAuth token endpoint URL */\n tokenEndpoint: string;\n /** OAuth scopes to request (space-separated) */\n scopes?: string;\n /** Grant type to use (defaults to 'client_credentials') */\n grantType?: 'client_credentials' | 'authorization_code' | 'refresh_token';\n /** Additional headers to send with token requests */\n tokenRequestHeaders?: Record<string, string>;\n /** Custom timeout for token requests in milliseconds (default: 30000) */\n tokenTimeoutMs?: number;\n /** Buffer time before token expiry to trigger refresh (default: 300000 = 5 minutes) */\n tokenRefreshBufferMs?: number;\n}\n\n/**\n * OAuth token response structure\n */\ninterface TokenResponse {\n access_token: string;\n token_type: string;\n expires_in?: number;\n refresh_token?: string;\n scope?: string;\n}\n\n/**\n * Cached token with expiry information\n */\ninterface CachedToken {\n accessToken: string;\n tokenType: string;\n expiresAt: number; // Unix timestamp\n refreshToken?: string;\n scope?: string;\n}\n\n/**\n * Generic OAuth 2.0 authentication strategy with token caching and refresh capabilities.\n * Supports client credentials flow and authorization code flow with automatic token refresh.\n * @deprecated This strategy is not recommended for browser-based applications as it uses the insecure client_credentials grant type. Please use PKCEOAuthStrategy instead.\n */\nexport class GenericOAuthStrategy implements IAuthStrategy {\n private config: OAuthConfig;\n private cachedToken: CachedToken | null = null;\n private refreshPromise: Promise<CachedToken> | null = null;\n\n /**\n * Creates a new OAuth authentication strategy.\n * @param {OAuthConfig} config - OAuth configuration including endpoints, credentials, and options\n */\n constructor(config: OAuthConfig) {\n this.validateConfig(config);\n this.config = {\n grantType: 'client_credentials',\n tokenTimeoutMs: 30000,\n tokenRefreshBufferMs: 300000, // 5 minutes\n ...config\n };\n \n Logger.debug(`GenericOAuthStrategy: Initialized with endpoint ${config.tokenEndpoint} and grant type ${this.config.grantType}`);\n }\n\n /**\n * Validates the OAuth configuration to ensure required fields are present.\n * @param {OAuthConfig} config - The OAuth configuration to validate.\n * @throws {ARTError} If the configuration is invalid.\n */\n private validateConfig(config: OAuthConfig): void {\n if (!config.clientId || config.clientId.trim() === '') {\n throw new ARTError('OAuth client ID cannot be empty', ErrorCode.VALIDATION_ERROR);\n }\n if (!config.clientSecret || config.clientSecret.trim() === '') {\n throw new ARTError('OAuth client secret cannot be empty', ErrorCode.VALIDATION_ERROR);\n }\n if (!config.tokenEndpoint || config.tokenEndpoint.trim() === '') {\n throw new ARTError('OAuth token endpoint cannot be empty', ErrorCode.VALIDATION_ERROR);\n }\n \n // Validate URL format\n try {\n new URL(config.tokenEndpoint);\n } catch (error) {\n throw new ARTError('Invalid OAuth token endpoint URL', ErrorCode.VALIDATION_ERROR, error instanceof Error ? error : new Error(String(error)));\n }\n }\n\n /**\n * Gets authentication headers, automatically handling token refresh if needed.\n * @returns {Promise<Record<string, string>>} A promise that resolves to the authentication headers.\n */\n async getAuthHeaders(): Promise<Record<string, string>> {\n try {\n const token = await this.getValidToken();\n return {\n 'Authorization': `${token.tokenType} ${token.accessToken}`\n };\n } catch (error) {\n const message = 'Failed to get OAuth authentication headers';\n Logger.error(message, error);\n throw new ARTError(message, ErrorCode.LLM_PROVIDER_ERROR, error instanceof Error ? error : new Error(String(error)));\n }\n }\n\n /**\n * Gets a valid access token, refreshing if necessary.\n * @returns {Promise<CachedToken>} A promise that resolves to a valid cached token.\n */\n private async getValidToken(): Promise<CachedToken> {\n // Check if we have a valid cached token\n if (this.cachedToken && this.isTokenValid(this.cachedToken)) {\n Logger.debug('GenericOAuthStrategy: Using cached token');\n return this.cachedToken;\n }\n\n // If a refresh is already in progress, wait for it\n if (this.refreshPromise) {\n Logger.debug('GenericOAuthStrategy: Waiting for ongoing token refresh');\n return await this.refreshPromise;\n }\n\n // Start new token acquisition\n this.refreshPromise = this.acquireNewToken();\n \n try {\n const token = await this.refreshPromise;\n this.cachedToken = token;\n return token;\n } finally {\n this.refreshPromise = null;\n }\n }\n\n /**\n * Checks if a token is still valid (not expired with buffer).\n * @param {CachedToken} token - The token to validate.\n * @returns {boolean} True if the token is valid, false otherwise.\n */\n private isTokenValid(token: CachedToken): boolean {\n const now = Date.now();\n const buffer = this.config.tokenRefreshBufferMs!;\n return token.expiresAt > (now + buffer);\n }\n\n /**\n * Acquires a new token from the OAuth provider.\n * @returns {Promise<CachedToken>} A promise that resolves to a new cached token.\n */\n private async acquireNewToken(): Promise<CachedToken> {\n Logger.debug(`GenericOAuthStrategy: Acquiring new token from ${this.config.tokenEndpoint}`);\n\n const tokenRequest = this.buildTokenRequest();\n \n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.config.tokenTimeoutMs!);\n\n const response = await fetch(this.config.tokenEndpoint, {\n ...tokenRequest,\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => 'Unknown error');\n throw new ARTError(\n `OAuth token request failed: ${response.status} ${response.statusText}: ${errorText}`,\n ErrorCode.EXTERNAL_SERVICE_ERROR\n );\n }\n\n const tokenResponse: TokenResponse = await response.json();\n return this.processTokenResponse(tokenResponse);\n\n } catch (error) {\n if (error instanceof ARTError) {\n throw error;\n }\n \n const message = `Failed to acquire OAuth token: ${error instanceof Error ? error.message : String(error)}`;\n Logger.error(message, error);\n throw new ARTError(message, ErrorCode.EXTERNAL_SERVICE_ERROR, error instanceof Error ? error : new Error(String(error)));\n }\n }\n\n /**\n * Builds the token request configuration based on grant type.\n * @returns {RequestInit} The request initialization object for the token request.\n */\n private buildTokenRequest(): RequestInit {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Accept': 'application/json',\n ...this.config.tokenRequestHeaders\n };\n\n let body: string;\n \n if (this.config.grantType === 'client_credentials') {\n const params = new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: this.config.clientId,\n client_secret: this.config.clientSecret\n });\n \n if (this.config.scopes) {\n params.append('scope', this.config.scopes);\n }\n \n body = params.toString();\n } else if (this.config.grantType === 'refresh_token' && this.cachedToken?.refreshToken) {\n const params = new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: this.cachedToken.refreshToken,\n client_id: this.config.clientId,\n client_secret: this.config.clientSecret\n });\n \n body = params.toString();\n } else {\n throw new ARTError(`Unsupported grant type: ${this.config.grantType}`, ErrorCode.NOT_IMPLEMENTED);\n }\n\n return {\n method: 'POST',\n headers,\n body\n };\n }\n\n /**\n * Processes the token response and creates a cached token object.\n * @param {TokenResponse} response - The token response from the provider.\n * @returns {CachedToken} The processed and cached token.\n */\n private processTokenResponse(response: TokenResponse): CachedToken {\n if (!response.access_token) {\n throw new ARTError('OAuth token response missing access_token', ErrorCode.EXTERNAL_SERVICE_ERROR);\n }\n\n const now = Date.now();\n const expiresIn = response.expires_in || 3600; // Default to 1 hour if not specified\n const expiresAt = now + (expiresIn * 1000);\n\n const cachedToken: CachedToken = {\n accessToken: response.access_token,\n tokenType: response.token_type || 'Bearer',\n expiresAt,\n refreshToken: response.refresh_token,\n scope: response.scope\n };\n\n Logger.debug(`GenericOAuthStrategy: Token acquired, expires at ${new Date(expiresAt).toISOString()}`);\n return cachedToken;\n }\n\n /**\n * Manually refreshes the cached token.\n * @returns {Promise<Record<string, string>>} A promise that resolves to new authentication headers.\n */\n public async refreshToken(): Promise<Record<string, string>> {\n Logger.debug('GenericOAuthStrategy: Manual token refresh requested');\n this.cachedToken = null; // Force refresh\n this.refreshPromise = null;\n return await this.getAuthHeaders();\n }\n\n /**\n * Clears the cached token, forcing a new token request on next use.\n */\n public clearTokenCache(): void {\n Logger.debug('GenericOAuthStrategy: Clearing token cache');\n this.cachedToken = null;\n this.refreshPromise = null;\n }\n\n /**\n * Gets information about the current cached token.\n * @returns {{ expiresAt: Date; scope?: string; hasRefreshToken: boolean } | null} Token information or null if no token is cached.\n */\n public getTokenInfo(): { expiresAt: Date; scope?: string; hasRefreshToken: boolean } | null {\n if (!this.cachedToken) {\n return null;\n }\n\n return {\n expiresAt: new Date(this.cachedToken.expiresAt),\n scope: this.cachedToken.scope,\n hasRefreshToken: !!this.cachedToken.refreshToken\n };\n }\n\n /**\n * Gets the configured OAuth endpoints and settings.\n * @returns {Omit<OAuthConfig, 'clientSecret'>} Configuration information (excluding sensitive data).\n */\n public getConfig(): Omit<OAuthConfig, 'clientSecret'> {\n return {\n clientId: this.config.clientId,\n tokenEndpoint: this.config.tokenEndpoint,\n scopes: this.config.scopes,\n grantType: this.config.grantType,\n tokenRequestHeaders: this.config.tokenRequestHeaders,\n tokenTimeoutMs: this.config.tokenTimeoutMs,\n tokenRefreshBufferMs: this.config.tokenRefreshBufferMs\n };\n }\n} ","import { GenericOAuthStrategy, type OAuthConfig } from '@/auth/GenericOAuthStrategy';\nimport { Logger } from '@/utils/logger';\n\n/**\n * Configuration specific to Zyntopia OAuth strategy\n */\nexport interface ZyntopiaOAuthConfig {\n /** Client ID for Zyntopia OAuth authentication */\n clientId: string;\n /** Client secret for Zyntopia OAuth authentication */\n clientSecret: string;\n /** Optional custom token endpoint (defaults to Zyntopia's standard endpoint) */\n tokenEndpoint?: string;\n /** Optional custom scopes (defaults to Zyntopia's standard scopes) */\n scopes?: string;\n /** Optional environment ('production' | 'staging' | 'development') */\n environment?: 'production' | 'staging' | 'development';\n /** Optional custom timeout for token requests in milliseconds */\n tokenTimeoutMs?: number;\n /** Optional custom buffer time before token expiry to trigger refresh */\n tokenRefreshBufferMs?: number;\n /** Additional custom headers for Zyntopia API requirements */\n customHeaders?: Record<string, string>;\n}\n\n/**\n * Zyntopia-specific OAuth 2.0 authentication strategy.\n * Pre-configured for Zyntopia services with standard endpoints, scopes, and authentication flows.\n * Extends GenericOAuthStrategy with Zyntopia-specific defaults and configurations.\n */\nexport class ZyntopiaOAuthStrategy extends GenericOAuthStrategy {\n private static readonly ZYNTOPIA_ENDPOINTS = {\n production: 'https://auth.zyntopia.com/oauth/token',\n staging: 'https://staging-auth.zyntopia.com/oauth/token',\n development: 'https://dev-auth.zyntopia.com/oauth/token'\n };\n\n private static readonly ZYNTOPIA_DEFAULT_SCOPES = {\n production: 'zyntopia:read zyntopia:write zyntopia:admin',\n staging: 'zyntopia:read zyntopia:write zyntopia:admin zyntopia:debug',\n development: 'zyntopia:read zyntopia:write zyntopia:admin zyntopia:debug zyntopia:test'\n };\n\n private zyntopiaConfig: Required<ZyntopiaOAuthConfig>;\n\n /**\n * Creates a new Zyntopia OAuth authentication strategy.\n * @param {ZyntopiaOAuthConfig} config - Zyntopia-specific OAuth configuration\n */\n constructor(config: ZyntopiaOAuthConfig) {\n // Set defaults for Zyntopia\n const environment = config.environment || 'production';\n const defaultTokenEndpoint = ZyntopiaOAuthStrategy.ZYNTOPIA_ENDPOINTS[environment];\n const defaultScopes = ZyntopiaOAuthStrategy.ZYNTOPIA_DEFAULT_SCOPES[environment];\n\n // Build the complete configuration with Zyntopia defaults\n const zyntopiaConfig: Required<ZyntopiaOAuthConfig> = {\n clientId: config.clientId,\n clientSecret: config.clientSecret,\n tokenEndpoint: config.tokenEndpoint || defaultTokenEndpoint,\n scopes: config.scopes || defaultScopes,\n environment,\n tokenTimeoutMs: config.tokenTimeoutMs || 30000,\n tokenRefreshBufferMs: config.tokenRefreshBufferMs || 300000, // 5 minutes\n customHeaders: config.customHeaders || {}\n };\n\n // Create the generic OAuth config with Zyntopia-specific settings\n const genericConfig: OAuthConfig = {\n clientId: zyntopiaConfig.clientId,\n clientSecret: zyntopiaConfig.clientSecret,\n tokenEndpoint: zyntopiaConfig.tokenEndpoint,\n scopes: zyntopiaConfig.scopes,\n grantType: 'client_credentials', // Zyntopia uses client credentials flow\n tokenTimeoutMs: zyntopiaConfig.tokenTimeoutMs,\n tokenRefreshBufferMs: zyntopiaConfig.tokenRefreshBufferMs,\n tokenRequestHeaders: {\n 'User-Agent': 'ART-Framework-Zyntopia/1.0',\n 'X-Zyntopia-Client': 'art-framework',\n 'X-Zyntopia-Environment': environment,\n ...zyntopiaConfig.customHeaders\n }\n };\n\n // Initialize the parent GenericOAuthStrategy\n super(genericConfig);\n\n this.zyntopiaConfig = zyntopiaConfig;\n\n Logger.debug(`ZyntopiaOAuthStrategy: Initialized for ${environment} environment with endpoint ${zyntopiaConfig.tokenEndpoint}`);\n }\n\n /**\n * Gets the Zyntopia-specific configuration.\n * @returns {Omit<ZyntopiaOAuthConfig, 'clientSecret'>} Zyntopia configuration (excluding sensitive data).\n */\n public getZyntopiaConfig(): Omit<ZyntopiaOAuthConfig, 'clientSecret'> {\n return {\n clientId: this.zyntopiaConfig.clientId,\n tokenEndpoint: this.zyntopiaConfig.tokenEndpoint,\n scopes: this.zyntopiaConfig.scopes,\n environment: this.zyntopiaConfig.environment,\n tokenTimeoutMs: this.zyntopiaConfig.tokenTimeoutMs,\n tokenRefreshBufferMs: this.zyntopiaConfig.tokenRefreshBufferMs,\n customHeaders: this.zyntopiaConfig.customHeaders\n };\n }\n\n /**\n * Gets the current environment this strategy is configured for.\n * @returns {'production' | 'staging' | 'development'} The environment ('production', 'staging', or 'development').\n */\n public getEnvironment(): 'production' | 'staging' | 'development' {\n return this.zyntopiaConfig.environment;\n }\n\n /**\n * Checks if this strategy is configured for production environment.\n * @returns {boolean} True if configured for production, false otherwise.\n */\n public isProduction(): boolean {\n return this.zyntopiaConfig.environment === 'production';\n }\n\n /**\n * Checks if this strategy is configured for development/testing.\n * @returns {boolean} True if configured for development or staging, false for production.\n */\n public isDevelopment(): boolean {\n return this.zyntopiaConfig.environment !== 'production';\n }\n\n /**\n * Creates a ZyntopiaOAuthStrategy instance pre-configured for production.\n * @param {string} clientId - Zyntopia client ID\n * @param {string} clientSecret - Zyntopia client secret\n * @param {string} [customScopes] - Optional custom scopes (defaults to production scopes)\n * @returns {ZyntopiaOAuthStrategy} Configured ZyntopiaOAuthStrategy for production.\n */\n public static forProduction(\n clientId: string, \n clientSecret: string, \n customScopes?: string\n ): ZyntopiaOAuthStrategy {\n return new ZyntopiaOAuthStrategy({\n clientId,\n clientSecret,\n environment: 'production',\n scopes: customScopes\n });\n }\n\n /**\n * Creates a ZyntopiaOAuthStrategy instance pre-configured for staging.\n * @param {string} clientId - Zyntopia client ID\n * @param {string} clientSecret - Zyntopia client secret\n * @param {string} [customScopes] - Optional custom scopes (defaults to staging scopes)\n * @returns {ZyntopiaOAuthStrategy} Configured ZyntopiaOAuthStrategy for staging.\n */\n public static forStaging(\n clientId: string, \n clientSecret: string, \n customScopes?: string\n ): ZyntopiaOAuthStrategy {\n return new ZyntopiaOAuthStrategy({\n clientId,\n clientSecret,\n environment: 'staging',\n scopes: customScopes\n });\n }\n\n /**\n * Creates a ZyntopiaOAuthStrategy instance pre-configured for development.\n * @param {string} clientId - Zyntopia client ID\n * @param {string} clientSecret - Zyntopia client secret\n * @param {string} [customScopes] - Optional custom scopes (defaults to development scopes)\n * @returns {ZyntopiaOAuthStrategy} Configured ZyntopiaOAuthStrategy for development.\n */\n public static forDevelopment(\n clientId: string, \n clientSecret: string, \n customScopes?: string\n ): ZyntopiaOAuthStrategy {\n return new ZyntopiaOAuthStrategy({\n clientId,\n clientSecret,\n environment: 'development',\n scopes: customScopes\n });\n }\n\n /**\n * Gets the default scopes for a specific environment.\n * @param {'production' | 'staging' | 'development'} environment - The environment to get scopes for\n * @returns {string} Default scopes for the specified environment.\n */\n public static getDefaultScopes(environment: 'production' | 'staging' | 'development'): string {\n return ZyntopiaOAuthStrategy.ZYNTOPIA_DEFAULT_SCOPES[environment];\n }\n\n /**\n * Gets the token endpoint for a specific environment.\n * @param {'production' | 'staging' | 'development'} environment - The environment to get endpoint for\n * @returns {string} Token endpoint URL for the specified environment.\n */\n public static getTokenEndpoint(environment: 'production' | 'staging' | 'development'): string {\n return ZyntopiaOAuthStrategy.ZYNTOPIA_ENDPOINTS[environment];\n }\n\n /**\n * Validates Zyntopia-specific configuration requirements.\n * @param {ZyntopiaOAuthConfig} config - Configuration to validate\n * @throws {Error} If configuration is invalid.\n */\n public static validateZyntopiaConfig(config: ZyntopiaOAuthConfig): void {\n if (!config.clientId || config.clientId.trim() === '') {\n throw new Error('Zyntopia client ID is required');\n }\n if (!config.clientSecret || config.clientSecret.trim() === '') {\n throw new Error('Zyntopia client secret is required');\n }\n if (config.environment && !['production', 'staging', 'development'].includes(config.environment)) {\n throw new Error('Zyntopia environment must be one of: production, staging, development');\n }\n if (config.tokenTimeoutMs && (config.tokenTimeoutMs < 1000 || config.tokenTimeoutMs > 60000)) {\n throw new Error('Zyntopia token timeout must be between 1000ms and 60000ms');\n }\n if (config.tokenRefreshBufferMs && (config.tokenRefreshBufferMs < 30000 || config.tokenRefreshBufferMs > 600000)) {\n throw new Error('Zyntopia token refresh buffer must be between 30000ms and 600000ms');\n }\n }\n} ","/**\n * ART (Agentic Reasoning & Tool-use) Framework - Main Entry Point\n * -----------------------------------------------------------------\n *\n * Welcome to the ART framework! This file is the primary public API surface for the library.\n * It's structured to provide a clear and intuitive experience for developers,\n * whether you're just getting started or building advanced, custom agentic systems.\n *\n * --- Quick Start ---\n * For most use cases, you'll only need `createArtInstance` and the associated types.\n *\n * Example:\n * ```ts\n * import { createArtInstance } from 'art-framework';\n * import type { ArtInstanceConfig } from 'art-framework';\n *\n * const config: ArtInstanceConfig = {\n * storage: { type: 'memory' },\n * providers: {\n * openai: { adapter: 'openai', apiKey: '...' }\n * },\n * tools: [new CalculatorTool()],\n * persona: {\n * name: 'MyAgent',\n * prompts: {\n * synthesis: 'You are MyAgent. Always answer in rhyme.'\n * }\n * }\n * };\n *\n * const art = await createArtInstance(config);\n * const response = await art.process({ query: \"Hello, world!\" });\n * ```\n *\n * --- API Structure ---\n * 1. **Core Factory**: The main function to create an ART instance.\n * 2. **Primary Interfaces & Types**: Essential types for configuration and interaction.\n * 3. **Built-in Components**: Concrete implementations of adapters, tools, and agents.\n * 4. **Advanced Systems & Managers**: Lower-level components for building custom logic.\n * 5. **Utilities**: Helper functions and classes.\n *\n * @module ART\n */\n\n// --- 1. Core Factory ---\n\n/**\n * The main factory function to create and initialize a complete ART framework instance.\n * This is the recommended starting point for all users. It simplifies setup by\n * assembling all necessary components based on the provided configuration.\n * @param {ArtInstanceConfig} config - The configuration object for the ART instance.\n * @returns {Promise<ArtInstance>} A promise that resolves to a ready-to-use ART instance.\n * @see {@link ArtInstanceConfig} for configuration options.\n */\nexport { createArtInstance } from '@/core/agent-factory';\n\n// --- 2. Primary Interfaces & Types ---\n\n/**\n * Core interfaces that define the contracts for key components of the ART framework.\n * Use these to build your own custom components (e.g., agents, tools, storage adapters).\n */\nexport * from '@/core/interfaces';\n\n/**\n * Core data structures, enums, and type definitions used throughout the framework.\n * This includes types for messages, observations, agent state, and more.\n */\nexport * from '@/types';\n\n/**\n * The main configuration object for creating an ART instance.\n * Explicitly exported for clarity and ease of use.\n */\nexport type { ArtInstanceConfig, AgentPersona } from '@/types';\n\n/**\n * Types related to LLM Provider management.\n * Useful for advanced scenarios, such as dynamically configuring providers at runtime.\n */\nexport type {\n ProviderManagerConfig,\n AvailableProviderEntry,\n RuntimeProviderConfig,\n ManagedAdapterAccessor,\n IProviderManager,\n} from '@/types/providers';\n\n// --- 3. Built-in Components ---\n\n// --- Agent Implementations ---\n\n/**\n * The default agent core implementation based on the Plan-Execute-Synthesize model.\n * It's suitable for a wide range of general-purpose tasks.\n * When to use: As the default reasoning engine unless you have a specific need for a different agent architecture.\n */\nexport { PESAgent } from '@/core/agents/pes-agent';\n\n// --- Storage Adapters ---\n\n/**\n * A non-persistent storage adapter that keeps all data in memory.\n * When to use: Ideal for testing, short-lived scripts, or scenarios\n * where data persistence across sessions is not required.\n */\nexport { InMemoryStorageAdapter } from '@/integrations/storage/inMemory';\n\n/**\n * A persistent storage adapter that uses the browser's IndexedDB.\n * When to use: The recommended choice for web-based applications to persist\n * conversation history and agent state on the client-side.\n */\nexport { IndexedDBStorageAdapter } from '@/integrations/storage/indexedDB';\n\n/**\n * A persistent storage adapter for connecting to a Supabase (Postgres) database.\n * When to use: Suitable for server-side environments, or for applications\n * requiring data to be shared or persisted in the cloud.\n */\nexport { SupabaseStorageAdapter } from '@/integrations/storage/supabase';\n\n// --- Reasoning Provider Adapters ---\n\n/**\n * Adapter for Google's Gemini models.\n */\nexport { GeminiAdapter } from '@/integrations/reasoning/gemini';\nexport type { GeminiAdapterOptions } from '@/integrations/reasoning/gemini';\n\n/**\n * Adapter for OpenAI's models (e.g., GPT-3.5, GPT-4).\n */\nexport { OpenAIAdapter } from '@/integrations/reasoning/openai';\nexport type { OpenAIAdapterOptions } from '@/integrations/reasoning/openai';\n\n/**\n * Adapter for Anthropic's Claude models.\n */\nexport { AnthropicAdapter } from '@/integrations/reasoning/anthropic';\nexport type { AnthropicAdapterOptions } from '@/integrations/reasoning/anthropic';\n\n/**\n * Adapter for OpenRouter, which acts as a proxy to a wide variety of models.\n */\nexport { OpenRouterAdapter } from '@/integrations/reasoning/openrouter';\nexport type { OpenRouterAdapterOptions } from '@/integrations/reasoning/openrouter';\n\n/**\n * Adapter for DeepSeek models.\n */\nexport { DeepSeekAdapter } from '@/integrations/reasoning/deepseek';\nexport type { DeepSeekAdapterOptions } from '@/integrations/reasoning/deepseek';\n\n/**\n * Adapter for running local LLMs through the Ollama service.\n */\nexport { OllamaAdapter } from '@/integrations/reasoning/ollama';\nexport type { OllamaAdapterOptions } from '@/integrations/reasoning/ollama';\n\n// --- Built-in Tools ---\n\n/**\n * A basic tool that allows the agent to evaluate mathematical expressions.\n */\nexport { CalculatorTool } from '@/tools/CalculatorTool';\n\n// --- 4. Advanced Systems & Managers ---\n// For developers who need to directly interact with or extend ART's internal systems.\n\n// --- UI & Sockets ---\n/**\n * Provides a real-time connection to an agent's conversation history.\n * When to use: For building custom UI components that display the back-and-forth\n * interaction between a user and the agent.\n */\nexport { ConversationSocket } from '@/systems/ui/conversation-socket';\n\n/**\n * Provides a real-time stream of agent observations (e.g., tool calls, state changes).\n * When to use: For building developer tools, debug panels, or UIs that visualize\n * the agent's internal thought process.\n */\nexport { ObservationSocket } from '@/systems/ui/observation-socket';\nexport type { StreamEventTypeFilter } from '@/systems/ui/llm-stream-socket';\n/**\n * Provides a real-time stream of raw token output from the LLM as it's generated.\n * When to use: For building UIs with a typewriter effect and fine-grained stream control.\n */\nexport { LLMStreamSocket } from '@/systems/ui/llm-stream-socket';\n/**\n * Provides real-time updates for A2A task lifecycle events.\n * When to use: For dashboards/monitors tracking delegated task progress.\n */\nexport { A2ATaskSocket } from '@/systems/ui/a2a-task-socket';\n/**\n * Facade providing access to all UI sockets.\n */\nexport { UISystem } from '@/systems/ui/ui-system';\n\n// --- Authentication ---\n/**\n * Manages authentication strategies and token lifecycle for external services.\n * When to use: When your tools or providers require secure authentication (e.g., OAuth2).\n * You can register different strategies with this manager.\n */\nexport { AuthManager } from '@/systems/auth/AuthManager';\n\n/**\n * An implementation of the PKCE (Proof Key for Code Exchange) OAuth2 flow.\n * When to use: As a strategy in the `AuthManager` for services that support\n * the PKCE flow, common in public clients and SPAs.\n */\nexport { PKCEOAuthStrategy } from '@/auth/PKCEOAuthStrategy';\nexport type { PKCEOAuthConfig } from '@/auth/PKCEOAuthStrategy';\n/**\n * Simple API key authentication strategy and generic OAuth strategy variants.\n */\nexport { ApiKeyStrategy } from '@/auth/ApiKeyStrategy';\nexport { GenericOAuthStrategy } from '@/auth/GenericOAuthStrategy';\nexport type { OAuthConfig } from '@/auth/GenericOAuthStrategy';\nexport { ZyntopiaOAuthStrategy } from '@/auth/ZyntopiaOAuthStrategy';\nexport type { ZyntopiaOAuthConfig } from '@/auth/ZyntopiaOAuthStrategy';\n\n// --- MCP (Model Context Protocol) ---\n/**\n * The core manager for handling connections to MCP servers.\n * When to use: When integrating ART with an MCP server to dynamically load tools and resources.\n */\nexport { McpManager } from '@/systems/mcp';\nexport type { McpManagerConfig } from '@/systems/mcp/types';\n\n/**\n * A special tool that acts as a proxy for all tools provided by an MCP server.\n * When to use: This is typically registered automatically when MCP is configured,\n * but can be used manually for advanced MCP integrations.\n */\nexport { McpProxyTool } from '@/systems/mcp';\n\n/**\n * Client controller for making direct requests to an MCP server.\n * When to use: If you need to interact with an MCP server's resources outside\n * of the standard agent tool-use loop.\n */\nexport { McpClientController } from '@/systems/mcp';\nexport type {\n McpServerConfig,\n McpToolDefinition,\n McpResource,\n McpResourceTemplate,\n McpServerStatus,\n} from '@/systems/mcp/types';\n\n// --- A2A (Agent-to-Agent Communication) ---\n/**\n * Service for discovering other agents available on an A2A network.\n * When to use: When building collaborative agent systems where one agent\n * needs to find and delegate tasks to another.\n */\nexport { AgentDiscoveryService } from '@/systems/a2a/AgentDiscoveryService';\nexport type { AgentDiscoveryConfig } from '@/systems/a2a/AgentDiscoveryService';\n\n/**\n * Service for delegating tasks to other agents and monitoring their status.\n * When to use: After discovering an agent, use this service to assign it a task\n * and receive updates on its progress.\n */\nexport { TaskDelegationService } from '@/systems/a2a/TaskDelegationService';\nexport type { TaskDelegationConfig, TaskStatusResponse } from '@/systems/a2a/TaskDelegationService';\nexport type { A2ATaskEvent, A2ATaskFilter } from '@/systems/ui/a2a-task-socket';\n\n\n// --- 5. Utilities ---\n\n// --- Managers & Registries (advanced) ---\n/**\n * State manager for thread config/state with explicit/implicit save strategies.\n */\nexport { StateManager } from '@/systems/context/managers/StateManager';\n/**\n * In-memory tool registry for registering and querying tool executors.\n */\nexport { ToolRegistry } from '@/systems/tool/ToolRegistry';\n/**\n * Provider manager implementation controlling adapter lifecycles and concurrency.\n */\nexport { ProviderManagerImpl } from '@/systems/reasoning/ProviderManagerImpl';\n\n/**\n * A simple logging utility with configurable levels.\n * When to use: For adding consistent logging throughout your custom components.\n * An instance is available on `ArtInstance.logger`.\n */\nexport { Logger, LogLevel } from '@/utils/logger';\nexport type { LoggerConfig } from '@/utils/logger';\n\n/**\n * A function to generate RFC4122 v4 compliant UUIDs.\n * When to use: For creating unique identifiers for threads, messages, or other entities.\n */\nexport { generateUUID } from '@/utils/uuid';\n\n// --- Framework Version ---\n/**\n * The current version of the ART Framework package.\n */\nexport const VERSION = '0.3.8';"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/systems/reasoning/ProviderManagerImpl.ts","../src/utils/logger.ts","../src/systems/ui/typed-socket.ts","../src/systems/ui/llm-stream-socket.ts","../src/systems/ui/a2a-task-socket.ts","../src/types/pes-types.ts","../src/types/schemas.ts","../src/types/index.ts","../src/utils/uuid.ts","../src/core/agents/pes-agent.ts","../src/integrations/storage/inMemory.ts","../src/integrations/storage/indexedDB.ts","../src/systems/context/repositories/ConversationRepository.ts","../src/systems/context/repositories/ObservationRepository.ts","../src/systems/context/repositories/StateRepository.ts","../src/systems/context/repositories/TaskStatusRepository.ts","../src/systems/context/managers/ConversationManager.ts","../src/systems/context/managers/StateManager.ts","../src/systems/observation/observation-manager.ts","../src/systems/tool/ToolRegistry.ts","../src/utils/validation.ts","../src/systems/tool/ToolSystem.ts","../src/systems/reasoning/SystemPromptResolver.ts","../src/systems/reasoning/ReasoningEngine.ts","../src/utils/xml-matcher.ts","../src/systems/reasoning/OutputParser.ts","../src/systems/ui/observation-socket.ts","../src/systems/ui/conversation-socket.ts","../src/systems/ui/ui-system.ts","../src/systems/auth/AuthManager.ts","../src/systems/mcp/McpProxyTool.ts","../src/systems/mcp/ConfigManager.ts","../src/systems/mcp/McpClient.ts","../src/systems/mcp/McpManager.ts","../src/systems/a2a/AgentDiscoveryService.ts","../src/systems/a2a/TaskDelegationService.ts","../src/core/agent-factory.ts","../src/integrations/storage/supabase.ts","../src/integrations/reasoning/gemini.ts","../src/integrations/reasoning/openai.ts","../src/integrations/reasoning/anthropic.ts","../src/integrations/reasoning/openrouter.ts","../src/integrations/reasoning/deepseek.ts","../src/integrations/reasoning/ollama.ts","../src/tools/CalculatorTool.ts","../src/auth/PKCEOAuthStrategy.ts","../src/auth/ApiKeyStrategy.ts","../src/auth/GenericOAuthStrategy.ts","../src/auth/ZyntopiaOAuthStrategy.ts","../src/index.ts"],"names":["ErrorCode","ARTError","_ARTError","message","code","originalError","details","str","UnknownProviderError","providerName","LocalProviderConflictError","requestedProvider","activeProvider","LocalInstanceBusyError","modelId","ApiQueueTimeoutError","AdapterInstantiationError","ProviderManagerImpl","config","p","sortedAdapterOptions","obj","key","configSignature","existingInstance","release","providerEntry","idleLocalProviderDifferentSignature","sig","instance","entry","resolve","reject","adapterInstance","adapterOptions","error","newManagedInstance","nextRequest","LogLevel","_Logger","args","Logger","TypedSocket","callback","filter","options","id","uuidv4","subscription","data","filterCheck","socketType","sub","_filter","_options","LLMStreamSocket","event","A2ATaskSocket","taskRepository","task","metadata","previousStatus","eventType","tasks","events","a","b","TodoItemStatus","ArtStandardMessageSchema","z","val","ArtStandardPromptSchema","MessageRole","ObservationType","ModelCapability","A2ATaskStatus","A2ATaskPriority","generateUUID","DEFAULT_PERSONA","PESAgent","dependencies","props","startTime","traceId","status","errorMessage","llmCalls","toolCallsCount","finalAiMessage","aggregatedLlmMetadata","phase","threadContext","planningSystemPrompt","synthesisSystemPrompt","runtimeProviderConfig","finalPersona","history","availableTools","pesState","refinementResult","planningResult","executionResult","finalResponseContent","synthesisMetadata","uiMetadata","artError","saveError","endTime","threadId","planningOutput","rawText","systemPrompt","formattedHistory","toolsJson","t","planningPrompt","currentState","prompt","planningOptions","outputText","streamError","stream","err","toolCalls","accumulatedMetadata","loopContinue","MAX_LOOPS","loopCount","pendingItem","item","depId","depItem","i","itemResult","state","delegationToolSchema","executionTools","completedItemsContext","messages","MAX_ITEM_ITERATIONS","iteration","itemDone","finalOutput","finalStatus","currentMetadata","parsed","a2aCalls","tc","localCalls","a2aTasks","toolResults","res","completedItems","failedItems","summary","synthesisPrompt","synthesisOptions","mainContent","metadataBlockRegex","match","callPersona","threadPersona","instancePersona","historyOptions","rawHistory","delegationCalls","call","delegatedTasks","agentId","taskType","input","instructions","targetAgent","now","a2aTask","delegatedTask","maxWaitTimeMs","pollIntervalMs","updatedTasks","incompleteTasks","latestTask","finalTimestamp","msg","role","InMemoryStorageAdapter","_config","collection","collectionMap","filterOptions","results","DEFAULT_DB_NAME","DEFAULT_DB_VERSION","IndexedDBStorageAdapter","request","existingStores","missingStores","store","errorEvent","existingStoreNames","storeName","mode","sName","dataAsAny","dataToStore","transaction","sortKey","sortDir","valA","valB","skip","limit","storeNames","clearCount","totalStores","ConversationRepository","storageAdapter","setPromises","messageToStore","filteredMessages","m","_id","rest","ObservationRepository","observation","filteredObservations","typeSet","obs","StateRepository","storedContext","context","contextToStore","currentContext","newContext","TaskStatusRepository","taskToStore","taskId","storedTask","updates","existingTask","updatedTask","filteredTasks","statusArray","queryResults","offset","cleanTask","ConversationManager","conversationRepository","conversationSocket","deepClone","clonedObj","StateManager","stateRepository","strategy","_userId","contextFromRepo","cachedContext","originalStateSnapshot","toolName","cachedData","currentStateSnapshot","toolNames","currentEnabledTools","newEnabledTools","updatedConfig","tool","ObservationManager","observationRepository","observationSocket","observationData","ToolRegistry","stateManager","executor","allExecutors","allSchemas","enabledToolNames","enabledSchemas","predicate","removed","name","exec","ajv","Ajv","compiledValidators","validateJsonSchema","schema","schemaKey","validate","ToolSystem","toolRegistry","observationManager","result","callId","validationResult","errorMessages","e","executionContext","applyStrategy","base","addition","normalizeOverride","SystemPromptResolver","registry","finalPrompt","levels","lvl","ov","rendered","spec","variables","template","_m","v","ReasoningEngine","providerManager","providerConfig","accessor","streamResult","XmlMatcher","tagName","transform","position","newMatchStatus","statusToUse","lastChunk","chunksToYield","chunk","char","parsedToolCallSchema","toolCallsSchema","todoItemSchema","todoListSchema","OutputParser","output","processedOutput","thoughtsList","chunks","nonThinkingContent","raw","s","first","last","validation","titleMatch","intentMatch","planMatch","jsonBlockMatch","jsonContent","ObservationSocket","observationFilter","ConversationSocket","messageOptions","UISystem","a2aTaskRepository","AuthManager","strategyId","count","McpProxyTool","card","toolDefinition","mcpManager","client","response","duration","validatedResponse","CallToolResultSchema","ConfigManager","storedConfig","rawConfig","validatedConfig","defaultConfig","cleanConfig","serverId","serverConfig","fixedConfig","base64UrlEncode","buffer","sha256Base64Url","digest","generateRandomString","length","array","TokenManager","oauthConfig","exp","token","body","McpClientController","_McpClientController","baseUrl","scopes","asMetadataUrl","asMetadataRes","existing","randomId","clientId","codeVerifier","codeChallenge","authUrl","url","discoveryDoc","customFetch","headers","newOptions","sessionIdHeader","StreamableHTTPClientTransport","Client","McpManager","_stateManager","authManager","mcpConfig","localServerConfigs","discoveredServerConfigs","allServerConfigs","discoveredConfig","registeredToolCount","toolsToRegister","toolDef","proxyTool","disconnectionPromises","existingClient","conn","targetUrl","hasInstall","install","getInstallUrl","hostname","info","getAllowedInfo","requestHosts","discoveryEndpoint","mcpCards","service","mcpCard","server","normalized","updated","fallback","timeoutMs","start","r","prefix","AgentDiscoveryService","cacheKey","cached","controller","timeoutId","a2aServices","agents","topK","topMatches","agent","capabilities","totalScore","matchedCapabilities","capability","capLower","taskLower","capabilityScore","semanticPairs","word1","word2","getWordRoot","word","capWords","taskWords","capWord","taskWord","matchingAgents","requiredCap","agentCap","TaskDelegationService","submissionResponse","persistError","taskSubmissionUrl","submissionPayload","lastError","attempt","responseData","delay","statusUrl","statusData","statusResponse","updatedMetadata","cancelUrl","AgentFactory","storageConfig","AgentCoreImplementation","createArtInstance","factory","agentCore","uiSystem","conversationManager","SupabaseStorageAdapter","createClient","table","row","query","value","tables","DEFAULT_MAX_RETRIES","DEFAULT_INITIAL_DELAY_MS","DEFAULT_MAX_DELAY_MS","RETRYABLE_STATUS_CODES","isRetryableError","statusCode","withRetry","fn","maxRetries","initialDelayMs","maxDelayMs","baseDelay","jitter","delayMs","GeminiAdapter","GoogleGenAI","sessionId","callContext","modelOverride","modelToUse","contents","generationConfig","includeThoughts","thinkingBudget","requestConfig","genAIInstance","timeToFirstTokenMs","streamUsageMetadata","streamFinishReason","parts","part","partText","isThought","textPart","totalGenerationTimeMs","finalUsage","firstCandidate","responseText","finishReason","usageMetadata","nonStreamParts","tokenType","artPrompt","geminiContents","systemPromptContent","userContent","toolCall","OPENAI_DEFAULT_MODEL_ID","OPENAI_DEFAULT_MAX_TOKENS","OPENAI_DEFAULT_TEMPERATURE","OpenAIAdapter","OpenAI","availableArtTools","openaiApiParams","maxTokens","temperature","openaiOptions","reasoningEffort","reasoningSummary","responsesInput","translationResult","openaiTools","requestBody","K","streamInstance","accumulatedText","accumulatedReasoning","finalStopReason","accumulatedToolCalls","content","reasoningText","toolUseBlocks","outputItem","tu","artMsg","systemText","translatedContent","toolResultText","userText","toolCallsText","artTools","artTool","ANTHROPIC_DEFAULT_MODEL_ID","ANTHROPIC_DEFAULT_MAX_TOKENS","AnthropicAdapter","Anthropic","anthropicApiParams","topP","stopSequences","thinking","anthropicMessages","anthropicTools","accumulatedToolUses","toolUseAcc","thinkingBlockIndexes","currentInputTokens","currentOutputTokens","initialMetadata","deltaMetadata","thinkingText","block","textDelta","thinkingDelta","partial","joined","idx","toolData","betas","currentRoleInternal","messageRoleToPush","lastMessage","currentLastMessageContentArray","contentToMergeArray","mergedContent","lastArtMsg","blocks","toolResultBlock","c","OpenRouterAdapter","openAiMessages","openAiTools","openRouterOptions","includeReasoning","payload","apiUrl","errorBody","_a","tid","trid","sid","aggregatedToolCalls","reader","decoder","done","lines","line","dataContent","choice","delta","reasoningDetails","rd","tcDelta","dst","firstChoice","responseMessage","thinkingType","responseContent","tokenPayload","usage","assistantMsg","DeepSeekAdapter","parsedError","OllamaAdapter","cleanBaseUrl","accumulatedOutputTokens","finalApiResponseUsage","modelIdForTransform","messagesToProcess","translatedMessages","currentRoleForCompare","currentOpenAIMsgPart","allowedFunctions","_CalculatorTool","expression","previousResult","executionScope","resultValue","evaluate","outputResult","CalculatorTool","PKCEOAuthStrategy","evt","params","statePayload","authorizationUrl","errorDescription","tokenResponse","errorText","tokenData","randomBytes","verifier","hashBuffer","bytes","ApiKeyStrategy","apiKey","headerName","GenericOAuthStrategy","tokenRequest","expiresIn","expiresAt","cachedToken","_ZyntopiaOAuthStrategy","environment","defaultTokenEndpoint","defaultScopes","zyntopiaConfig","genericConfig","clientSecret","customScopes","ZyntopiaOAuthStrategy","VERSION"],"mappings":"8jBAMO,IAAKA,CAAAA,CAAAA,CAAAA,CAAAA,GAGRA,EAAA,cAAA,CAAiB,gBAAA,CAEjBA,EAAA,eAAA,CAAkB,iBAAA,CAElBA,CAAAA,CAAA,mBAAA,CAAsB,qBAAA,CAItBA,CAAAA,CAAA,cAAgB,eAAA,CAEhBA,CAAAA,CAAA,iBAAmB,kBAAA,CAEnBA,CAAAA,CAAA,YAAc,aAAA,CAIdA,CAAAA,CAAA,kBAAA,CAAqB,oBAAA,CAErBA,CAAAA,CAAA,wBAAA,CAA2B,2BAE3BA,CAAAA,CAAA,qBAAA,CAAwB,wBAExBA,CAAAA,CAAA,sBAAA,CAAyB,yBAEzBA,CAAAA,CAAA,yBAAA,CAA4B,2BAAA,CAE5BA,CAAAA,CAAA,wBAAA,CAA2B,0BAAA,CAE3BA,EAAA,yBAAA,CAA4B,2BAAA,CAI5BA,CAAAA,CAAA,cAAA,CAAiB,gBAAA,CAEjBA,CAAAA,CAAA,8BAAgC,+BAAA,CAEhCA,CAAAA,CAAA,oBAAA,CAAuB,sBAAA,CAEvBA,CAAAA,CAAA,aAAA,CAAgB,gBAIhBA,CAAAA,CAAA,eAAA,CAAkB,kBAElBA,CAAAA,CAAA,qBAAA,CAAwB,wBAExBA,CAAAA,CAAA,gBAAA,CAAmB,kBAAA,CAEnBA,CAAAA,CAAA,sBAAA,CAAyB,wBAAA,CAEzBA,EAAA,iBAAA,CAAoB,mBAAA,CAIpBA,EAAA,aAAA,CAAgB,eAAA,CAEhBA,EAAA,aAAA,CAAgB,eAAA,CAEhBA,CAAAA,CAAA,OAAA,CAAU,SAAA,CAEVA,CAAAA,CAAA,uBAAyB,wBAAA,CAEzBA,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CAAAA,CAAO,cAAA,CAAiB,KACpF,MAAM,IAAI,KAAA,CAAM,2DAA2D,CAAA,CAE7E,GAAIA,CAAAA,CAAO,oBAAA,GAAyBA,EAAO,oBAAA,CAAuB,GAAA,EAASA,CAAAA,CAAO,oBAAA,CAAuB,GAAA,CAAA,CACvG,MAAM,IAAI,KAAA,CAAM,oEAAoE,CAExF,CACF,CAAA,CA1MagqB,CAAAA,CACa,kBAAA,CAAqB,CAC3C,UAAA,CAAY,uCAAA,CACZ,QAAS,+CAAA,CACT,WAAA,CAAa,2CACf,CAAA,CALWA,CAAAA,CAOa,uBAAA,CAA0B,CAChD,UAAA,CAAY,8CACZ,OAAA,CAAS,4DAAA,CACT,WAAA,CAAa,0EACf,CAAA,CAXK,IAAMQ,EAAAA,CAANR,MCoRMS,EAAAA,CAAU","file":"index.js","sourcesContent":["// src/errors.ts\n\n/**\n * Defines standard error codes for the ART framework.\n * These codes categorize errors originating from different subsystems.\n */\nexport enum ErrorCode {\n // Configuration Errors\n /** Invalid or malformed configuration provided. */\n INVALID_CONFIG = 'INVALID_CONFIG',\n /** A required API key was not provided. */\n MISSING_API_key = 'MISSING_API_KEY',\n /** General configuration-related error. */\n CONFIGURATION_ERROR = 'CONFIGURATION_ERROR',\n\n // Storage Errors\n /** A generic error occurred in the storage layer. */\n STORAGE_ERROR = 'STORAGE_ERROR',\n /** The requested thread could not be found in storage. */\n THREAD_NOT_FOUND = 'THREAD_NOT_FOUND',\n /** Failed to save data to the storage layer. */\n SAVE_FAILED = 'SAVE_FAILED',\n\n // Reasoning Errors\n /** An error occurred while communicating with the LLM provider. */\n LLM_PROVIDER_ERROR = 'LLM_PROVIDER_ERROR',\n /** Failed to generate a prompt. */\n PROMPT_GENERATION_FAILED = 'PROMPT_GENERATION_FAILED',\n /** Failed to parse the output from the LLM. */\n OUTPUT_PARSING_FAILED = 'OUTPUT_PARSING_FAILED',\n /** Error during prompt template rendering or initial structure creation. */\n PROMPT_ASSEMBLY_FAILED = 'PROMPT_ASSEMBLY_FAILED',\n /** The requested prompt fragment does not exist. */\n PROMPT_FRAGMENT_NOT_FOUND = 'PROMPT_FRAGMENT_NOT_FOUND',\n /** The constructed prompt object failed schema validation. */\n PROMPT_VALIDATION_FAILED = 'PROMPT_VALIDATION_FAILED',\n /** Failed to translate the ART standard prompt to a provider-specific format. */\n PROMPT_TRANSLATION_FAILED = 'PROMPT_TRANSLATION_FAILED',\n\n // Tool Errors\n /** The requested tool could not be found in the registry. */\n TOOL_NOT_FOUND = 'TOOL_NOT_FOUND',\n /** The provided tool schema failed validation. */\n TOOL_SCHEMA_VALIDATION_FAILED = 'TOOL_SCHEMA_VALIDATION_FAILED',\n /** A generic error occurred during tool execution. */\n TOOL_EXECUTION_ERROR = 'TOOL_EXECUTION_ERROR',\n /** The requested tool is disabled for the current thread. */\n TOOL_DISABLED = 'TOOL_DISABLED',\n\n // Agent Core / Orchestration Errors\n /** The planning phase of the agent failed. */\n PLANNING_FAILED = 'PLANNING_FAILED',\n /** An error occurred within the ToolSystem execution loop. */\n TOOL_EXECUTION_FAILED = 'TOOL_EXECUTION_FAILED',\n /** The synthesis phase of the agent failed. */\n SYNTHESIS_FAILED = 'SYNTHESIS_FAILED',\n /** A general error occurred during the agent's process method. */\n AGENT_PROCESSING_ERROR = 'AGENT_PROCESSING_ERROR',\n /** An A2A (Agent-to-Agent) task delegation failed. */\n DELEGATION_FAILED = 'DELEGATION_FAILED',\n\n // General Errors\n /** A network error occurred. */\n NETWORK_ERROR = 'NETWORK_ERROR',\n /** An operation timed out. */\n TIMEOUT_ERROR = 'TIMEOUT_ERROR',\n /** An operation timed out (duplicate of TIMEOUT_ERROR). */\n TIMEOUT = 'TIMEOUT',\n /** An error occurred with an external service. */\n EXTERNAL_SERVICE_ERROR = 'EXTERNAL_SERVICE_ERROR',\n /** The requested task was not found. */\n TASK_NOT_FOUND = 'TASK_NOT_FOUND',\n /** Input data failed validation. */\n VALIDATION_ERROR = 'VALIDATION_ERROR',\n /** The request was invalid or malformed. */\n INVALID_REQUEST = 'INVALID_REQUEST',\n /** A task with the same ID already exists. */\n DUPLICATE_TASK_ID = 'DUPLICATE_TASK_ID',\n /** A generic error occurred in a repository. */\n REPOSITORY_ERROR = 'REPOSITORY_ERROR',\n /** A connection is already established. */\n ALREADY_CONNECTED = 'ALREADY_CONNECTED',\n /** A required configuration is missing. */\n MISSING_CONFIG = 'MISSING_CONFIG',\n /** The requested feature is not implemented. */\n NOT_IMPLEMENTED = 'NOT_IMPLEMENTED',\n /** No active connection is available. */\n NOT_CONNECTED = 'NOT_CONNECTED',\n /** The request timed out. */\n REQUEST_TIMEOUT = 'REQUEST_TIMEOUT',\n /** Standard input is not available. */\n NO_STDIN = 'NO_STDIN',\n /** The provided URL is not an HTTP/HTTPS URL. */\n NO_HTTP_URL = 'NO_HTTP_URL',\n /** An HTTP error occurred. */\n HTTP_ERROR = 'HTTP_ERROR',\n /** The requested server was not found. */\n SERVER_NOT_FOUND = 'SERVER_NOT_FOUND',\n /** A health check for a service failed. */\n HEALTH_CHECK_FAILED = 'HEALTH_CHECK_FAILED',\n /** Failed to discover tools from a remote source. */\n TOOL_DISCOVERY_FAILED = 'TOOL_DISCOVERY_FAILED',\n /** The requested transport protocol is not supported. */\n UNSUPPORTED_TRANSPORT = 'UNSUPPORTed_TRANSPORT',\n /** A CORS browser extension is required to proceed. */\n CORS_EXTENSION_REQUIRED = 'CORS_EXTENSION_REQUIRED',\n /** CORS permissions are required but have not been granted. */\n CORS_PERMISSION_REQUIRED = 'CORS_PERMISSION_REQUIRED',\n /** An unknown or unexpected error occurred. */\n UNKNOWN_ERROR = 'UNKNOWN_ERROR',\n\n // Provider Manager Errors\n /** The requested LLM provider is not known or configured. */\n UNKNOWN_PROVIDER = 'UNKNOWN_PROVIDER',\n /** Attempted to activate a local provider when another is already active. */\n LOCAL_PROVIDER_CONFLICT = 'LOCAL_PROVIDER_CONFLICT',\n /** The requested local LLM instance is currently busy. */\n LOCAL_INSTANCE_BUSY = 'LOCAL_INSTANCE_BUSY',\n /** Timeout waiting for an available instance of an API provider. */\n API_QUEUE_TIMEOUT = 'API_QUEUE_TIMEOUT',\n /** Failed to instantiate an adapter for a provider. */\n ADAPTER_INSTANTIATION_ERROR = 'ADAPTER_INSTANTIATION_ERROR',\n}\n\n/**\n * Custom error class for ART framework specific errors.\n * It includes an error code, an optional original error for chaining,\n * and a details object for additional context.\n */\nexport class ARTError extends Error {\n /** The specific error code from the ErrorCode enum. */\n public readonly code: ErrorCode;\n /** The original error that caused this error, if any. */\n public readonly originalError?: Error;\n /** A record of additional details about the error. */\n public details: Record<string, any>;\n\n /**\n * Creates an instance of ARTError.\n * @param {string} message - The error message.\n * @param {ErrorCode} code - The error code.\n * @param {Error} [originalError] - The original error, if any.\n * @param {Record<string, any>} [details={}] - Additional details about the error.\n */\n constructor(message: string, code: ErrorCode, originalError?: Error, details: Record<string, any> = {}) {\n super(message);\n this.name = 'ARTError';\n this.code = code;\n this.originalError = originalError;\n this.details = details;\n\n // Maintains proper stack trace in V8 environments (Node, Chrome)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, ARTError);\n }\n }\n\n /**\n * Returns a string representation of the error, including the original error if present.\n * @returns {string} The string representation of the error.\n */\n toString(): string {\n let str = `${this.name} [${this.code}]: ${this.message}`;\n if (this.originalError) {\n str += `\\nCaused by: ${this.originalError.stack || this.originalError.toString()}`;\n }\n return str;\n }\n}\n\n/**\n * Error thrown when a requested LLM provider is not known or configured.\n */\nexport class UnknownProviderError extends ARTError {\n constructor(providerName: string) {\n super(`Unknown provider requested: ${providerName}`, ErrorCode.UNKNOWN_PROVIDER);\n this.name = 'UnknownProviderError';\n }\n}\n\n/**\n * Error thrown when attempting to activate a local provider while another is already active.\n */\nexport class LocalProviderConflictError extends ARTError {\n constructor(requestedProvider: string, activeProvider: string) {\n super(`Cannot activate local provider '${requestedProvider}'. Local provider '${activeProvider}' is already active.`, ErrorCode.LOCAL_PROVIDER_CONFLICT);\n this.name = 'LocalProviderConflictError';\n }\n}\n\n/**\n * Error thrown when a requested local LLM instance is currently busy.\n */\nexport class LocalInstanceBusyError extends ARTError {\n constructor(providerName: string, modelId: string) {\n super(`Local provider instance '${providerName}:${modelId}' is currently busy.`, ErrorCode.LOCAL_INSTANCE_BUSY);\n this.name = 'LocalInstanceBusyError';\n }\n}\n\n/**\n * Error thrown when a timeout occurs while waiting for an available instance of an API provider.\n */\nexport class ApiQueueTimeoutError extends ARTError {\n constructor(providerName: string) {\n super(`Timeout waiting for an available instance of API provider '${providerName}'.`, ErrorCode.API_QUEUE_TIMEOUT);\n this.name = 'ApiQueueTimeoutError';\n }\n}\n\n/**\n * Error thrown when an adapter for a provider fails to instantiate.\n */\nexport class AdapterInstantiationError extends ARTError {\n constructor(providerName: string, originalError: Error) {\n super(`Failed to instantiate adapter for provider '${providerName}'.`, ErrorCode.ADAPTER_INSTANTIATION_ERROR, originalError);\n this.name = 'AdapterInstantiationError';\n }\n}","import {\n IProviderManager,\n ProviderManagerConfig,\n RuntimeProviderConfig,\n ManagedAdapterAccessor,\n AvailableProviderEntry,\n} from '@/types/providers';\nimport { ProviderAdapter } from '@/core/interfaces';\nimport {\n UnknownProviderError,\n LocalProviderConflictError,\n LocalInstanceBusyError,\n AdapterInstantiationError, // Will need this later\n} from '@/errors';\n\n/** Internal type to track managed adapter instances */\ninterface ManagedInstance {\n adapter: ProviderAdapter;\n configSignature: string;\n state: 'idle' | 'active';\n lastUsedTimestamp?: number; // For API instance idle eviction\n idleTimer?: NodeJS.Timeout; // Timer reference for idle timeout\n}\n\n/** Internal type for queued requests */\ninterface QueuedRequest {\n config: RuntimeProviderConfig;\n resolve: (value: ManagedAdapterAccessor | PromiseLike<ManagedAdapterAccessor>) => void;\n reject: (reason?: any) => void;\n}\n\n/**\n * Manages the lifecycle and access to multiple ProviderAdapter implementations.\n */\nexport class ProviderManagerImpl implements IProviderManager {\n private availableProviders: Map<string, AvailableProviderEntry>;\n private maxParallelApiInstancesPerProvider: number;\n private apiInstanceIdleTimeoutMs: number;\n private managedInstances: Map<string, ManagedInstance>;\n private requestQueue: QueuedRequest[]; // Use the refined queue item type\n\n constructor(config: ProviderManagerConfig) {\n this.availableProviders = new Map(config.availableProviders.map(p => [p.name, p]));\n this.maxParallelApiInstancesPerProvider = config.maxParallelApiInstancesPerProvider ?? 5;\n this.apiInstanceIdleTimeoutMs = (config.apiInstanceIdleTimeoutSeconds ?? 300) * 1000;\n this.managedInstances = new Map();\n this.requestQueue = [];\n }\n\n /**\n * Generates a stable configuration signature for caching.\n * @param config The runtime provider configuration.\n * @returns A string signature.\n */\n private _getConfigSignature(config: RuntimeProviderConfig): string {\n const sortedAdapterOptions = config.adapterOptions\n ? Object.keys(config.adapterOptions).sort().reduce((obj: any, key) => {\n // Never include secrets in signature logs; signature remains internal only\n obj[key] = key.toLowerCase().includes('key') ? '***' : config.adapterOptions[key];\n return obj;\n }, {})\n : {};\n return JSON.stringify({\n providerName: config.providerName,\n modelId: config.modelId,\n adapterOptions: sortedAdapterOptions,\n });\n }\n\n getAvailableProviders(): string[] {\n return Array.from(this.availableProviders.keys());\n }\n\n async getAdapter(config: RuntimeProviderConfig): Promise<ManagedAdapterAccessor> {\n const configSignature = this._getConfigSignature(config);\n\n // 1. Check cache for existing instance\n const existingInstance = this.managedInstances.get(configSignature);\n\n if (existingInstance && existingInstance.state === 'idle') {\n // Reuse idle instance\n existingInstance.state = 'active';\n // Clear idle timer when reusing\n if (existingInstance.idleTimer) {\n clearTimeout(existingInstance.idleTimer);\n existingInstance.idleTimer = undefined;\n }\n\n const release = () => this._releaseAdapter(configSignature);\n return { adapter: existingInstance.adapter, release };\n }\n\n // 2. Check local provider constraints\n const providerEntry = this.availableProviders.get(config.providerName);\n if (!providerEntry) {\n throw new UnknownProviderError(config.providerName);\n }\n\n if (providerEntry.isLocal) {\n let idleLocalProviderDifferentSignature: ManagedInstance | undefined = undefined;\n\n for (const [sig, instance] of this.managedInstances.entries()) {\n const entry = this.availableProviders.get(instance.configSignature.split('\"providerName\":\"')[1].split('\"')[0]);\n if (entry?.isLocal) {\n if (instance.state === 'active') {\n if (sig !== configSignature) {\n throw new LocalProviderConflictError(config.providerName, entry.name);\n } else {\n throw new LocalInstanceBusyError(config.providerName, config.modelId);\n }\n } else if (instance.state === 'idle' && sig !== configSignature) {\n idleLocalProviderDifferentSignature = instance;\n }\n }\n }\n\n if (idleLocalProviderDifferentSignature) {\n await this._evictInstance(idleLocalProviderDifferentSignature.configSignature);\n }\n }\n\n // 3. Check API provider concurrency limits\n if (!providerEntry.isLocal) {\n const activeApiInstancesCount = Array.from(this.managedInstances.values()).filter(\n instance => {\n const entry = this.availableProviders.get(instance.configSignature.split('\"providerName\":\"')[1].split('\"')[0]);\n return entry && !entry.isLocal && instance.state === 'active' && entry.name === config.providerName;\n }\n ).length;\n\n if (activeApiInstancesCount >= this.maxParallelApiInstancesPerProvider) {\n return new Promise<ManagedAdapterAccessor>((resolve, reject) => {\n this.requestQueue.push({ config, resolve, reject });\n });\n }\n }\n\n // 4. Create new instance\n let adapterInstance: ProviderAdapter;\n try {\n // Merge baseOptions from provider entry with runtime adapterOptions\n const adapterOptions = {\n ...providerEntry.baseOptions,\n ...config.adapterOptions,\n providerName: config.providerName\n };\n adapterInstance = new providerEntry.adapter(adapterOptions);\n } catch (error: any) {\n throw new AdapterInstantiationError(config.providerName, error);\n }\n\n // 5. Store new instance\n const newManagedInstance: ManagedInstance = {\n adapter: adapterInstance,\n configSignature: configSignature,\n state: 'active',\n };\n this.managedInstances.set(configSignature, newManagedInstance);\n\n // 6. Return accessor\n const release = () => this._releaseAdapter(configSignature);\n return { adapter: newManagedInstance.adapter, release };\n }\n\n /**\n * Internal method to release an adapter instance back to the manager.\n * @param configSignature The signature of the instance to release.\n */\n private _releaseAdapter(configSignature: string): void {\n const instance = this.managedInstances.get(configSignature);\n if (!instance) {\n return;\n }\n\n instance.state = 'idle';\n instance.lastUsedTimestamp = Date.now();\n\n const providerEntry = this.availableProviders.get(instance.configSignature.split('\"providerName\":\"')[1].split('\"')[0]);\n\n // Start idle timer for API instances\n if (providerEntry && !providerEntry.isLocal) {\n if (instance.idleTimer) {\n clearTimeout(instance.idleTimer);\n }\n instance.idleTimer = setTimeout(() => {\n this._evictInstance(configSignature);\n }, this.apiInstanceIdleTimeoutMs);\n }\n\n // Check request queue\n if (this.requestQueue.length > 0) {\n const nextRequest = this.requestQueue.shift();\n if (nextRequest) {\n this.getAdapter(nextRequest.config)\n .then(nextRequest.resolve)\n .catch(nextRequest.reject);\n }\n }\n }\n\n /**\n * Internal method to evict an instance from the manager.\n * @param configSignature The signature of the instance to evict.\n */\n private async _evictInstance(configSignature: string): Promise<void> {\n const instance = this.managedInstances.get(configSignature);\n\n if (instance && instance.state === 'idle') {\n if (instance.adapter.shutdown) {\n try {\n await instance.adapter.shutdown();\n } catch (_error) {\n // swallow adapter shutdown errors\n }\n }\n\n this.managedInstances.delete(configSignature);\n if (instance.idleTimer) {\n clearTimeout(instance.idleTimer);\n instance.idleTimer = undefined;\n }\n }\n }\n}","/**\n * @module utils/logger\n * Provides a simple, static, and configurable logger for the ART framework.\n * It supports different log levels and can be enabled or disabled globally.\n */\n\n/**\n * Defines the available logging levels, ordered from most verbose to least verbose.\n *\n * @enum {number}\n */\nexport enum LogLevel {\n /** Detailed debugging information, useful for development. */\n DEBUG = 0,\n /** General informational messages about application flow. */\n INFO = 1,\n /** Potential issues or unexpected situations that don't prevent execution. */\n WARN = 2,\n /** Errors that indicate a failure or problem. */\n ERROR = 3,\n}\n\n/**\n * Configuration options for the static Logger class.\n *\n * @interface LoggerConfig\n */\nexport interface LoggerConfig {\n /**\n * The minimum log level to output messages for. Messages below this level will be ignored.\n * @property {LogLevel} level\n */\n level: LogLevel;\n /**\n * An optional prefix string to prepend to all log messages (e.g., '[MyApp]'). Defaults to '[ART]'.\n * @property {string} [prefix]\n */\n prefix?: string;\n}\n\n/**\n * A simple static logger class for outputting messages to the console at different levels.\n *\n * @remarks\n * Configuration is global via the static `configure` method.\n *\n * @class Logger\n */\nexport class Logger {\n private static config: LoggerConfig = {\n level: LogLevel.INFO,\n };\n\n /**\n * Configures the static logger settings.\n *\n * @param config A partial `LoggerConfig` object. Provided settings will override defaults.\n */\n static configure(config: Partial<LoggerConfig>): void {\n Logger.config = { ...Logger.config, ...config };\n }\n\n /**\n * Logs a message at the DEBUG level.\n *\n * @remarks\n * Only outputs if the configured log level is DEBUG.\n *\n * @param message The main log message string.\n * @param args Additional arguments to include in the console output (e.g., objects, arrays).\n */\n static debug(message: string, ...args: any[]): void {\n if (Logger.config.level <= LogLevel.DEBUG) {\n // eslint-disable-next-line no-console\n console.debug(`${Logger.config.prefix || '[ART]'} ${message}`, ...args);\n }\n }\n\n /**\n * Logs a message at the INFO level.\n *\n * @remarks\n * Outputs if the configured log level is INFO or DEBUG.\n *\n * @param message The main log message string.\n * @param args Additional arguments to include in the console output.\n */\n static info(message: string, ...args: any[]): void {\n if (Logger.config.level <= LogLevel.INFO) {\n // eslint-disable-next-line no-console\n console.info(`${Logger.config.prefix || '[ART]'} ${message}`, ...args);\n }\n }\n\n /**\n * Logs a message at the WARN level.\n *\n * @remarks\n * Outputs if the configured log level is WARN, INFO, or DEBUG.\n *\n * @param message The main log message string.\n * @param args Additional arguments to include in the console output.\n */\n static warn(message: string, ...args: any[]): void {\n if (Logger.config.level <= LogLevel.WARN) {\n // eslint-disable-next-line no-console\n console.warn(`${Logger.config.prefix || '[ART]'} ${message}`, ...args);\n }\n }\n\n /**\n * Logs a message at the ERROR level.\n *\n * @remarks\n * Outputs if the configured log level is ERROR, WARN, INFO, or DEBUG.\n *\n * @param message The main log message string.\n * @param args Additional arguments to include in the console output (often an error object).\n */\n static error(message: string, ...args: any[]): void {\n if (Logger.config.level <= LogLevel.ERROR) {\n // eslint-disable-next-line no-console\n console.error(`${Logger.config.prefix || '[ART]'} ${message}`, ...args);\n }\n }\n}","// src/systems/ui/typed-socket.ts\nimport { v4 as uuidv4 } from 'uuid';\nimport { Logger } from '@/utils/logger'; // Assuming logger exists\n\nexport type UnsubscribeFunction = () => void;\n\nexport interface Subscription<DataType, FilterType> {\n id: string;\n callback: (data: DataType) => void;\n filter?: FilterType;\n options?: { threadId?: string };\n}\n\n/**\n * A generic class for implementing a publish/subscribe pattern with filtering capabilities.\n * Designed for decoupling components, particularly UI updates from backend events.\n */\nexport class TypedSocket<DataType, FilterType = any> {\n protected subscriptions: Map<string, Subscription<DataType, FilterType>> = new Map();\n // Removed logger instance property\n\n constructor() {\n // No logger instantiation needed\n }\n\n /**\n * Subscribes a callback function to receive notifications.\n * @param callback - The function to call when new data is notified.\n * @param filter - An optional filter to only receive specific types of data.\n * @param options - Optional configuration, like a threadId for filtering.\n * @returns An unsubscribe function.\n */\n subscribe(\n callback: (data: DataType) => void,\n filter?: FilterType,\n options?: { threadId?: string }\n ): UnsubscribeFunction {\n const id = uuidv4();\n const subscription: Subscription<DataType, FilterType> = { id, callback, filter, options };\n this.subscriptions.set(id, subscription);\n Logger.debug(`New subscription added: ${id}, Filter: ${JSON.stringify(filter)}, Options: ${JSON.stringify(options)}`); // Use static Logger\n\n return () => {\n this.subscriptions.delete(id);\n Logger.debug(`Subscription removed: ${id}`); // Use static Logger\n };\n }\n\n /**\n * Notifies all relevant subscribers with new data.\n * @param data - The data payload to send to subscribers.\n * @param options - Optional targeting options (e.g., targetThreadId).\n * @param filterCheck - A function to check if a subscription's filter matches the data.\n */\n notify(\n data: DataType,\n options?: { targetThreadId?: string; targetSessionId?: string }, // targetSessionId might be useful later\n filterCheck?: (data: DataType, filter?: FilterType) => boolean\n ): void {\n // ADD THIS LOG: Identify the socket instance being notified\n const socketType = this.constructor.name; // Get class name (e.g., 'LLMStreamSocket', 'ObservationSocket')\n Logger.debug(`[${socketType}] notify() called. Data type: ${typeof data}, Sub count: ${this.subscriptions.size}, Options: ${JSON.stringify(options)}`);\n\n Logger.debug(`Notifying ${this.subscriptions.size} subscribers. Data: ${JSON.stringify(data).substring(0, 100)}..., Options: ${JSON.stringify(options)}`); // Use static Logger\n this.subscriptions.forEach((sub) => {\n try {\n // 1. Check threadId if provided in both subscription options and notification options\n if (sub.options?.threadId && options?.targetThreadId && sub.options.threadId !== options.targetThreadId) {\n return; // Skip if thread IDs don't match\n }\n\n // 2. Check filter if provided and a filterCheck function exists\n if (filterCheck && sub.filter !== undefined && !filterCheck(data, sub.filter)) {\n return; // Skip if filter doesn't match\n }\n\n // If checks pass, invoke the callback\n Logger.debug(`Checks passed for sub ${sub.id}. Invoking callback.`); // Add log before callback\n sub.callback(data);\n } catch (error) {\n Logger.error(`Error executing subscription callback ${sub.id}:`, error); // Use static Logger\n // Decide if we should remove the faulty subscription? For now, just log.\n }\n });\n }\n\n /**\n * Optional: Retrieves historical data. This base implementation is empty.\n * Subclasses might implement this by interacting with repositories.\n */\n async getHistory?(_filter?: FilterType, _options?: { threadId?: string; limit?: number }): Promise<DataType[]> { // Prefix unused vars\n Logger.warn('getHistory is not implemented in the base TypedSocket.'); // Use static Logger\n return [];\n }\n\n /**\n * Clears all subscriptions. Useful for cleanup.\n */\n clearAllSubscriptions(): void {\n this.subscriptions.clear();\n Logger.debug('All subscriptions cleared.'); // Use static Logger\n }\n}","// src/systems/ui/llm-stream-socket.ts\nimport { TypedSocket } from './typed-socket';\nimport { StreamEvent } from '@/types';\nimport { Logger } from '@/utils/logger';\n\n// Define the type for the filter used in this specific socket\nexport type StreamEventTypeFilter = StreamEvent['type'] | Array<StreamEvent['type']>;\n\n/**\n * A dedicated socket for broadcasting LLM stream events (`StreamEvent`) to UI subscribers.\n * Extends the generic TypedSocket and implements filtering based on `StreamEvent.type`.\n */\nexport class LLMStreamSocket extends TypedSocket<StreamEvent, StreamEventTypeFilter> {\n\n constructor() {\n super(); // Call base constructor\n Logger.debug('LLMStreamSocket initialized.');\n }\n\n /**\n * Notifies subscribers about a new LLM stream event.\n * Filters based on event type if a filter is provided during subscription.\n * @param event - The StreamEvent data.\n */\n notifyStreamEvent(event: StreamEvent): void {\n Logger.debug(`Notifying LLMStreamEvent: ${event.type} for thread ${event.threadId}, trace ${event.traceId}`);\n super.notify(\n event,\n { targetThreadId: event.threadId, targetSessionId: event.sessionId },\n // Filter check function: Matches if no filter or if event type matches filter\n (data, filter) => {\n if (!filter) return true; // No filter, always notify\n if (Array.isArray(filter)) {\n return filter.includes(data.type); // Check if type is in the array\n }\n return data.type === filter; // Check for single type match\n }\n );\n }\n\n // getHistory is not applicable for transient stream events, so we don't implement it.\n // The base class provides an empty implementation with a warning if called.\n}","import { TypedSocket } from './typed-socket';\nimport { A2ATask, A2ATaskStatus, A2ATaskPriority } from '@/types';\nimport { Logger } from '@/utils/logger';\nimport { IA2ATaskRepository } from '@/core/interfaces';\n\n/**\n * Filter type for A2A task notifications.\n * Allows filtering by task status, task type, agent, or priority.\n */\nexport interface A2ATaskFilter {\n /** Filter by task status (single status or array of statuses) */\n status?: A2ATaskStatus | A2ATaskStatus[];\n /** Filter by task type (e.g., 'analyze', 'synthesize', 'transform') */\n taskType?: string | string[];\n /** Filter by source agent ID */\n sourceAgentId?: string;\n /** Filter by target agent ID */\n targetAgentId?: string;\n /** Filter by task priority */\n priority?: A2ATaskPriority | string;\n /** Filter by thread ID */\n threadId?: string;\n}\n\n/**\n * Event data structure for A2A task updates.\n * Contains the updated task and metadata about the change.\n */\nexport interface A2ATaskEvent {\n /** The A2A task that was updated */\n task: A2ATask;\n /** The type of event that occurred */\n eventType: 'created' | 'updated' | 'completed' | 'failed' | 'cancelled' | 'status_changed' | 'delegated';\n /** Timestamp when the event occurred */\n timestamp: number;\n /** Previous status (if applicable) for status change events */\n previousStatus?: A2ATaskStatus;\n /** Additional metadata about the event */\n metadata?: {\n /** Whether this was an automatic update or manual */\n automatic?: boolean;\n /** The component that triggered the update */\n source?: string;\n /** Any additional context */\n context?: Record<string, any>;\n };\n}\n\n/**\n * A specialized TypedSocket for handling A2A task status updates and events.\n * Allows filtering by task status, type, agent, and other criteria.\n * Can optionally fetch historical task data from a repository.\n */\nexport class A2ATaskSocket extends TypedSocket<A2ATaskEvent, A2ATaskFilter> {\n private taskRepository?: IA2ATaskRepository;\n\n constructor(taskRepository?: IA2ATaskRepository) {\n super();\n this.taskRepository = taskRepository;\n Logger.debug('A2ATaskSocket initialized.');\n }\n\n /**\n * Notifies subscribers about a new A2A task event.\n * @param event - The A2A task event data.\n */\n notifyTaskEvent(event: A2ATaskEvent): void {\n Logger.debug(`Notifying A2A Task Event: ${event.task.taskId} (${event.eventType}) status: ${event.task.status}`);\n \n super.notify(\n event,\n { \n targetThreadId: event.task.metadata.correlationId, // Use correlationId as threadId if available\n targetSessionId: event.task.sourceAgent.agentId \n },\n (data, filter) => this.matchesFilter(data, filter)\n );\n }\n\n /**\n * Convenience method to notify about a task creation.\n * @param task - The newly created A2A task.\n * @param metadata - Optional additional metadata about the creation.\n */\n notifyTaskCreated(task: A2ATask, metadata?: A2ATaskEvent['metadata']): void {\n this.notifyTaskEvent({\n task,\n eventType: 'created',\n timestamp: Date.now(),\n metadata\n });\n }\n\n /**\n * Convenience method to notify about a task update.\n * @param task - The updated A2A task.\n * @param previousStatus - The previous status of the task (if status changed).\n * @param metadata - Optional additional metadata about the update.\n */\n notifyTaskUpdated(task: A2ATask, previousStatus?: A2ATaskStatus, metadata?: A2ATaskEvent['metadata']): void {\n // Determine the specific event type based on the status\n let eventType: A2ATaskEvent['eventType'] = 'updated';\n \n if (previousStatus && previousStatus !== task.status) {\n eventType = 'status_changed';\n if (task.status === A2ATaskStatus.COMPLETED) {\n eventType = 'completed';\n } else if (task.status === A2ATaskStatus.FAILED) {\n eventType = 'failed';\n } else if (task.status === A2ATaskStatus.CANCELLED) {\n eventType = 'cancelled';\n } else if (task.targetAgent && previousStatus === A2ATaskStatus.PENDING) {\n eventType = 'delegated';\n }\n }\n\n this.notifyTaskEvent({\n task,\n eventType,\n timestamp: Date.now(),\n previousStatus,\n metadata\n });\n }\n\n /**\n * Convenience method to notify about task delegation.\n * @param task - The delegated A2A task.\n * @param metadata - Optional additional metadata about the delegation.\n */\n notifyTaskDelegated(task: A2ATask, metadata?: A2ATaskEvent['metadata']): void {\n this.notifyTaskEvent({\n task,\n eventType: 'delegated',\n timestamp: Date.now(),\n metadata\n });\n }\n\n /**\n * Convenience method to notify about task completion.\n * @param task - The completed A2A task.\n * @param metadata - Optional additional metadata about the completion.\n */\n notifyTaskCompleted(task: A2ATask, metadata?: A2ATaskEvent['metadata']): void {\n this.notifyTaskEvent({\n task,\n eventType: 'completed',\n timestamp: Date.now(),\n metadata\n });\n }\n\n /**\n * Convenience method to notify about task failure.\n * @param task - The failed A2A task.\n * @param metadata - Optional additional metadata about the failure.\n */\n notifyTaskFailed(task: A2ATask, metadata?: A2ATaskEvent['metadata']): void {\n this.notifyTaskEvent({\n task,\n eventType: 'failed',\n timestamp: Date.now(),\n metadata\n });\n }\n\n /**\n * Retrieves historical A2A task events, optionally filtered by criteria.\n * Note: This method constructs events from stored tasks, not from a dedicated event log.\n * @param filter - Optional A2ATaskFilter to filter the tasks.\n * @param options - Optional threadId and limit.\n * @returns A promise resolving to an array of A2A task events.\n */\n async getHistory(\n filter?: A2ATaskFilter,\n options?: { threadId?: string; limit?: number }\n ): Promise<A2ATaskEvent[]> {\n if (!this.taskRepository) {\n Logger.warn('Cannot getHistory for A2ATaskSocket: IA2ATaskRepository not configured.');\n return [];\n }\n\n Logger.debug(`Getting history for A2ATaskSocket: Thread ${options?.threadId}, Filter: ${JSON.stringify(filter)}, Limit: ${options?.limit}`);\n\n try {\n let tasks: A2ATask[] = [];\n\n // Fetch tasks based on available filters\n if (options?.threadId) {\n // If threadId is specified, get tasks by thread (assuming threadId maps to correlationId)\n tasks = await this.taskRepository.getTasksByThread(options.threadId);\n } else if (filter?.status) {\n // If status filter is specified, get tasks by status\n tasks = await this.taskRepository.getTasksByStatus(filter.status, {\n limit: options?.limit\n });\n } else {\n // Fallback: get tasks by status (all non-cancelled tasks)\n tasks = await this.taskRepository.getTasksByStatus([\n A2ATaskStatus.PENDING,\n A2ATaskStatus.IN_PROGRESS,\n A2ATaskStatus.COMPLETED,\n A2ATaskStatus.FAILED,\n A2ATaskStatus.WAITING,\n A2ATaskStatus.REVIEW\n ], { limit: options?.limit });\n }\n\n // Convert tasks to events and apply client-side filtering\n let events: A2ATaskEvent[] = tasks\n .map(task => this.taskToEvent(task))\n .filter(event => this.matchesFilter(event, filter));\n\n // Sort by timestamp (newest first)\n events.sort((a, b) => b.timestamp - a.timestamp);\n\n // Apply limit if specified and not already applied at repository level\n if (options?.limit && (!filter?.status || options.threadId)) {\n events = events.slice(0, options.limit);\n }\n\n return events;\n } catch (error) {\n Logger.error(`Error fetching A2A task history:`, error);\n return [];\n }\n }\n\n /**\n * Converts an A2ATask to an A2ATaskEvent for historical data.\n * @param task - The A2ATask to convert.\n * @returns An A2ATaskEvent representing the current state of the task.\n */\n private taskToEvent(task: A2ATask): A2ATaskEvent {\n // Determine event type based on current task status\n let eventType: A2ATaskEvent['eventType'] = 'updated';\n \n if (task.status === A2ATaskStatus.COMPLETED) {\n eventType = 'completed';\n } else if (task.status === A2ATaskStatus.FAILED) {\n eventType = 'failed';\n } else if (task.status === A2ATaskStatus.CANCELLED) {\n eventType = 'cancelled';\n } else if (task.targetAgent) {\n eventType = 'delegated';\n } else if (task.metadata.createdAt === task.metadata.updatedAt) {\n eventType = 'created';\n }\n\n return {\n task,\n eventType,\n timestamp: task.metadata.updatedAt || task.metadata.createdAt,\n metadata: {\n automatic: true,\n source: 'history',\n context: {\n taskType: task.payload.taskType,\n priority: task.priority,\n hasTargetAgent: !!task.targetAgent\n }\n }\n };\n }\n\n /**\n * Checks if an A2A task event matches the specified filter criteria.\n * @param event - The A2A task event to check.\n * @param filter - The filter criteria (optional).\n * @returns True if the event matches the filter, false otherwise.\n */\n private matchesFilter(event: A2ATaskEvent, filter?: A2ATaskFilter): boolean {\n if (!filter) return true;\n\n const task = event.task;\n\n // Filter by status\n if (filter.status) {\n const statusArray = Array.isArray(filter.status) ? filter.status : [filter.status];\n if (!statusArray.includes(task.status)) {\n return false;\n }\n }\n\n // Filter by task type\n if (filter.taskType) {\n const taskTypeArray = Array.isArray(filter.taskType) ? filter.taskType : [filter.taskType];\n if (!taskTypeArray.includes(task.payload.taskType)) {\n return false;\n }\n }\n\n // Filter by source agent ID\n if (filter.sourceAgentId && task.sourceAgent.agentId !== filter.sourceAgentId) {\n return false;\n }\n\n // Filter by target agent ID\n if (filter.targetAgentId) {\n if (!task.targetAgent || task.targetAgent.agentId !== filter.targetAgentId) {\n return false;\n }\n }\n\n // Filter by priority\n if (filter.priority && task.priority !== filter.priority) {\n return false;\n }\n\n // Filter by thread ID (using correlationId as threadId)\n if (filter.threadId && task.metadata.correlationId !== filter.threadId) {\n return false;\n }\n\n return true;\n }\n} ","// src/types/pes-types.ts\n\nimport { ParsedToolCall, ToolResult } from './index';\n\nexport enum TodoItemStatus {\n PENDING = 'pending',\n IN_PROGRESS = 'in_progress',\n COMPLETED = 'completed',\n FAILED = 'failed',\n CANCELLED = 'cancelled',\n WAITING = 'waiting' // For A2A tasks\n}\n\nexport interface TodoItem {\n id: string;\n description: string;\n status: TodoItemStatus;\n dependencies?: string[]; // IDs of tasks that must be finished first\n\n // Execution history for this item\n result?: any;\n thoughts?: string[];\n toolCalls?: ParsedToolCall[];\n toolResults?: ToolResult[];\n\n // Metadata\n createdTimestamp: number;\n updatedTimestamp: number;\n}\n\nexport interface PESAgentStateData {\n threadId: string;\n intent: string;\n title: string;\n plan: string; // High level description\n todoList: TodoItem[];\n currentStepId: string | null;\n isPaused: boolean;\n // Keep track of iterations for the overall process or per item?\n // The legacy executionHistory was per process call.\n // We might want to persist some history.\n}\n\nexport interface ExecutionOutput {\n thoughts?: string;\n content?: string; // The response text\n toolCalls?: ParsedToolCall[];\n nextStepDecision?: 'continue' | 'wait' | 'complete_item' | 'update_plan';\n updatedPlan?: {\n intent?: string;\n plan?: string;\n todoList?: TodoItem[]; // If the agent decides to modify the list\n };\n}\n","/**\n * @module types/schemas\n * This module defines Zod schemas for validating the core data structures of the ART framework,\n * ensuring type safety and data integrity at runtime.\n */\nimport { z } from 'zod';\nimport { ArtStandardMessageRole } from '@/types'; // Import role type from main types\n\n/**\n * Zod schema for validating a single {@link ArtStandardMessage} object.\n *\n * @remarks\n * This schema enforces the structural and type requirements for each message, including:\n * - A valid `role` from the {@link ArtStandardMessageRole} enum.\n * - `content` that matches the expected type for a given role (e.g., string for 'user', string or null for 'assistant').\n * - The presence of `tool_call_id` for 'tool' or 'tool_result' roles.\n * - The structure of `tool_calls` when present in an 'assistant' message.\n *\n * It uses a `.refine()` method to implement context-aware validation based on the message's `role`.\n */\nexport const ArtStandardMessageSchema = z.object({\n role: z.custom<ArtStandardMessageRole>((val) => {\n // Basic check, refine if needed based on actual ArtStandardMessageRole definition\n // Ensure all roles from ArtStandardMessageRole are included here\n return typeof val === 'string' && ['system', 'user', 'assistant', 'tool', 'tool_request', 'tool_result'].includes(val);\n }, { message: \"Invalid message role\" }),\n // Define content explicitly matching 'string | object | null' from interface\n content: z.union([z.string(), z.record(z.any()), z.null()]),\n name: z.string().optional(),\n tool_calls: z.array(z.object({\n id: z.string(),\n type: z.literal('function'),\n function: z.object({\n name: z.string(),\n arguments: z.string(), // Arguments are expected to be a stringified JSON\n }),\n })).optional(),\n tool_call_id: z.string().optional(),\n}).strict().refine(data => {\n // Role-specific validation logic:\n if (data.role === 'tool' || data.role === 'tool_result') { // 'tool' is the standard, 'tool_result' might be used internally\n if (!data.tool_call_id) return false; // tool_call_id is required for tool role\n // Content for tool role should ideally be a string (stringified result)\n // if (typeof data.content !== 'string') return false; // Uncomment for stricter validation\n }\n if (data.role === 'assistant') {\n // Assistant content should be string or null (if only making tool calls)\n if (data.content !== null && typeof data.content !== 'string') return false;\n // If content is null/empty, tool_calls should ideally exist (though not strictly enforced here)\n }\n if (data.role === 'user' || data.role === 'system') {\n // User/System content must be a string\n if (typeof data.content !== 'string') return false;\n }\n // 'tool_request' role might not be used directly, validation TBD if needed.\n\n return true;\n}, {\n message: \"Invalid message structure based on role (e.g., tool_call_id missing for tool role, invalid content type for user/system, assistant content not string/null)\",\n // path: ['role', 'content', 'tool_call_id'], // Optional: Specify path for better error reporting\n});\n\n\n/**\n * Zod schema for validating an entire {@link ArtStandardPrompt} (an array of messages).\n *\n * @remarks\n * This is a straightforward array schema that applies the {@link ArtStandardMessageSchema} to each element,\n * ensuring that every message in the prompt conforms to the required structure.\n */\nexport const ArtStandardPromptSchema = z.array(ArtStandardMessageSchema);","// src/types/index.ts\nimport type { RuntimeProviderConfig } from './providers'; // Import for use within this file\nimport type { IToolExecutor, IAgentCore } from '@/core/interfaces'; // For ArtInstanceConfig\nimport type { LogLevel } from '@/utils/logger'; // For ArtInstanceConfig\nimport type { StorageAdapter } from '@/core/interfaces'; // For ArtInstanceConfig (storage property)\n// --- ART Error Types ---\nexport {\n ErrorCode,\n ARTError,\n UnknownProviderError,\n LocalProviderConflictError,\n LocalInstanceBusyError,\n ApiQueueTimeoutError,\n AdapterInstantiationError\n} from '@/errors';\n\n/**\n * @module types\n *\n * This module aggregates and exports the core data structures, enums, and type definitions\n * used throughout the ART framework. It serves as the single source of truth for\n * a majority of the framework's types.\n *\n * Key exports include:\n * - {@link AgentProps}: Input properties for agent execution.\n * - {@link AgentFinalResponse}: Standardized output from an agent.\n * - {@link ConversationMessage}: Structure for a single message in a conversation.\n * - {@link ToolSchema}: Definition for a tool's capabilities.\n * - {@link A2ATask}: Structure for Agent-to-Agent tasks.\n * - Various enums like {@link MessageRole}, {@link ModelCapability}, etc.\n */\n\n// --- UI Socket Related Types ---\nexport { LLMStreamSocket } from '@/systems/ui/llm-stream-socket';\nexport { TypedSocket } from '@/systems/ui/typed-socket';\nexport { A2ATaskSocket } from '@/systems/ui/a2a-task-socket';\nexport type { UnsubscribeFunction } from '@/systems/ui/typed-socket';\n\n// --- PES Types ---\nexport { TodoItemStatus, TodoItem, PESAgentStateData, ExecutionOutput } from './pes-types';\n\n// --- Zod Schemas for Validation ---\nexport { ArtStandardPromptSchema, ArtStandardMessageSchema } from './schemas';\n\n\n// Re-export necessary types from submodules\nexport type {\n ProviderManagerConfig,\n AvailableProviderEntry,\n RuntimeProviderConfig,\n ManagedAdapterAccessor,\n IProviderManager\n} from './providers';\n\n/**\n * Represents the role of a message sender in a conversation.\n *\n * @enum {string}\n */\nexport enum MessageRole {\n /** The end-user interacting with the agent. */\n USER = 'USER',\n /** The AI agent. */\n AI = 'AI',\n /** A system-level message providing context or instructions. */\n SYSTEM = 'SYSTEM',\n /** A message containing the result of a tool execution. */\n TOOL = 'TOOL',\n}\n\n/**\n * Represents a single message within a conversation thread.\n *\n * @interface ConversationMessage\n */\nexport interface ConversationMessage {\n /**\n * A unique identifier for this specific message.\n * @property {string} messageId\n */\n messageId: string;\n /**\n * The identifier of the conversation thread this message belongs to.\n * @property {string} threadId\n */\n threadId: string;\n /**\n * The role of the sender (User, AI, System, or Tool).\n * @property {MessageRole} role\n */\n role: MessageRole;\n /**\n * The textual content of the message.\n * @property {string} content\n */\n content: string;\n /**\n * A Unix timestamp (in milliseconds) indicating when the message was created.\n * @property {number} timestamp\n */\n timestamp: number;\n /**\n * Optional metadata associated with the message (e.g., related observation IDs, tool call info, UI state).\n * @property {Record<string, any>} [metadata]\n */\n metadata?: Record<string, any>;\n}\n\n/**\n * Represents the type of an observation record, capturing significant events during agent execution.\n *\n * @enum {string}\n */\nexport enum ObservationType {\n /** The user's inferred intent. */\n INTENT = 'INTENT',\n /** The generated concise thread title. */\n TITLE = 'TITLE',\n /** The agent's step-by-step plan to address the intent. */\n PLAN = 'PLAN',\n /** The agent's internal monologue or reasoning process. */\n THOUGHTS = 'THOUGHTS',\n /** Records the LLM's decision to call one or more tools (part of the plan). */\n TOOL_CALL = 'TOOL_CALL',\n /** Records the actual execution attempt and result of a specific tool call. */\n TOOL_EXECUTION = 'TOOL_EXECUTION',\n /** Records events specifically related to the synthesis phase (e.g., the LLM call). */\n SYNTHESIS = 'SYNTHESIS',\n /** Records an error encountered during any phase of execution. */\n ERROR = 'ERROR',\n /** Records the final AI response message generated by the agent. */\n FINAL_RESPONSE = 'FINAL_RESPONSE',\n /** Records changes made to the agent's persistent state. */\n STATE_UPDATE = 'STATE_UPDATE',\n /** Records updates to the plan structure (intent, title, or list changes). */\n PLAN_UPDATE = 'PLAN_UPDATE',\n /** Records status changes of a specific todo item. */\n ITEM_STATUS_CHANGE = 'ITEM_STATUS_CHANGE',\n\n // New types for streaming events\n /** Logged by Agent Core when LLM stream consumption begins. */\n LLM_STREAM_START = 'LLM_STREAM_START',\n /** Logged by Agent Core upon receiving a METADATA stream event. Content should be LLMMetadata. */\n LLM_STREAM_METADATA = 'LLM_STREAM_METADATA',\n /** Logged by Agent Core upon receiving an END stream event. */\n LLM_STREAM_END = 'LLM_STREAM_END',\n /** Logged by Agent Core upon receiving an ERROR stream event. Content should be Error object or message. */\n LLM_STREAM_ERROR = 'LLM_STREAM_ERROR',\n}\n\n// --- NEW ENUM DEFINITION ---\n/**\n * Represents the different capabilities a model might possess.\n * Used for model selection and validation.\n *\n * @enum {string}\n */\nexport enum ModelCapability {\n /** Basic text generation/understanding. */\n TEXT = 'text',\n /** Ability to process and understand images. */\n VISION = 'vision',\n /** Supports streaming responses chunk by chunk. */\n STREAMING = 'streaming',\n /** Capable of using tools/function calling. */\n TOOL_USE = 'tool_use',\n /** Built-in or optimized for Retrieval-Augmented Generation. */\n RAG = 'rag',\n /** Specialized in understanding or generating code. */\n CODE = 'code',\n /** Advanced reasoning, planning, complex instruction following. */\n REASONING = 'reasoning'\n}\n// --- END NEW ENUM DEFINITION ---\n\n\n/**\n * Represents a recorded event during the agent's execution.\n *\n * @interface Observation\n */\nexport interface Observation {\n /**\n * A unique identifier for this specific observation record.\n * @property {string} id\n */\n id: string;\n /**\n * The identifier of the conversation thread this observation relates to.\n * @property {string} threadId\n */\n threadId: string;\n /**\n * An optional identifier for the parent object (e.g., a TodoItem ID) to which this observation belongs.\n * This allows differentiation between primary (user query) and secondary (sub-task) observations.\n * @property {string} [parentId]\n */\n parentId?: string;\n /**\n * An optional identifier for tracing a request across multiple systems or components.\n * @property {string} [traceId]\n */\n traceId?: string;\n /**\n * A Unix timestamp (in milliseconds) indicating when the observation was recorded.\n * @property {number} timestamp\n */\n timestamp: number;\n /**\n * The category of the event being observed (e.g., PLAN, THOUGHTS, TOOL_EXECUTION).\n * @property {ObservationType} type\n */\n type: ObservationType;\n /**\n * A concise, human-readable title summarizing the observation (often generated based on type/metadata).\n * @property {string} title\n */\n title: string;\n /**\n * The main data payload of the observation, structure depends on the `type`.\n *\n * @remarks\n * Common content shapes by `type`:\n * - `TITLE`: `{ title: string }` — a concise thread title (<= 10 words)\n * - `INTENT`: `{ intent: string }`\n * - `PLAN`: `{ plan: string; rawOutput?: string }`\n * - `TOOL_CALL`: `{ toolCalls: ParsedToolCall[] }`\n * - `TOOL_EXECUTION`: `{ callId: string; toolName: string; status: 'success' | 'error'; output?: any; error?: string }`\n * - `FINAL_RESPONSE`: `{ message: ConversationMessage; uiMetadata?: object }`\n * @property {any} content\n */\n content: any;\n /**\n * Optional metadata providing additional context (e.g., source phase, related IDs, status).\n * @property {Record<string, any>} [metadata]\n */\n metadata?: Record<string, any>;\n}\n\n/**\n * Represents a single event emitted from an asynchronous LLM stream (`ReasoningEngine.call`).\n *\n * @remarks\n * Allows for real-time delivery of tokens, metadata, errors, and lifecycle signals.\n * Adapters are responsible for translating provider-specific stream chunks into these standard events.\n *\n * @interface StreamEvent\n */\nexport interface StreamEvent {\n /**\n * The type of the stream event.\n * - `TOKEN`: A chunk of text generated by the LLM.\n * - `METADATA`: Information about the LLM call (e.g., token counts, stop reason), typically sent once at the end.\n * - `ERROR`: An error occurred during the LLM call or stream processing. `data` will contain the Error object.\n * - `END`: Signals the successful completion of the stream. `data` is typically null.\n * @property {'TOKEN' | 'METADATA' | 'ERROR' | 'END'} type\n */\n type: 'TOKEN' | 'METADATA' | 'ERROR' | 'END';\n /**\n * The actual content of the event.\n * - For `TOKEN`: string (the text chunk).\n * - For `METADATA`: `LLMMetadata` object.\n * - For `ERROR`: `Error` object or error details.\n * - For `END`: null.\n * @property {any} data\n */\n data: any;\n /**\n * Optional: Provides a more specific classification for `TOKEN` events,\n * combining LLM-level detection (thinking/response, if available from adapter)\n * and agent-level context (`callContext` from `CallOptions`).\n * Used by consumers (like UI) to differentiate between intermediate thoughts and the final response.\n *\n * - `LLM_THINKING`: Token identified by the adapter as part of the LLM's internal reasoning/thought process.\n * - `LLM_RESPONSE`: Token identified by the adapter as part of the LLM's final response content.\n * - `AGENT_THOUGHT_LLM_THINKING`: Token from an LLM call made in the 'AGENT_THOUGHT' context, identified as thinking.\n * - `AGENT_THOUGHT_LLM_RESPONSE`: Token from an LLM call made in the 'AGENT_THOUGHT' context, identified as response (e.g., the raw planning output).\n * - `FINAL_SYNTHESIS_LLM_THINKING`: Token from an LLM call made in the 'FINAL_SYNTHESIS' context, identified as thinking.\n * - `FINAL_SYNTHESIS_LLM_RESPONSE`: Token from an LLM call made in the 'FINAL_SYNTHESIS' context, identified as response (part of the final answer to the user).\n *\n * @remarks\n * Not all adapters can reliably distinguish 'LLM_THINKING' vs 'LLM_RESPONSE'.\n * Adapters should prioritize setting the agent context part (`AGENT_THOUGHT_...` or `FINAL_SYNTHESIS_...`) based on `CallOptions.callContext`.\n * If thinking detection is unavailable, adapters should default to `AGENT_THOUGHT_LLM_RESPONSE` or `FINAL_SYNTHESIS_LLM_RESPONSE`.\n * @property {'LLM_THINKING' | 'LLM_RESPONSE' | 'AGENT_THOUGHT_LLM_THINKING' | 'AGENT_THOUGHT_LLM_RESPONSE' | 'FINAL_SYNTHESIS_LLM_THINKING' | 'FINAL_SYNTHESIS_LLM_RESPONSE'} [tokenType]\n */\n tokenType?: 'LLM_THINKING' | 'LLM_RESPONSE' | 'AGENT_THOUGHT_LLM_THINKING' | 'AGENT_THOUGHT_LLM_RESPONSE' | 'FINAL_SYNTHESIS_LLM_THINKING' | 'FINAL_SYNTHESIS_LLM_RESPONSE';\n /**\n * The identifier of the conversation thread this event belongs to.\n * @property {string} threadId\n */\n threadId: string;\n /**\n * The identifier tracing the specific agent execution cycle this event is part of.\n * @property {string} traceId\n */\n traceId: string;\n /**\n * Optional identifier linking the event to a specific UI tab/window.\n * @property {string} [sessionId]\n */\n sessionId?: string;\n}\n\n/**\n * Represents a basic JSON Schema definition, focusing on object types commonly used for tool inputs/outputs.\n * This is a simplified representation and doesn't cover all JSON Schema features.\n *\n * @interface JsonObjectSchema\n */\nexport interface JsonObjectSchema {\n /**\n * @property {'object'} type\n */\n type: 'object';\n /**\n * @property {object} properties\n */\n properties: {\n [key: string]: {\n type: string; // e.g., 'string', 'number', 'boolean', 'object', 'array'\n description?: string;\n default?: any;\n items?: JsonObjectSchema | { type: string }; // For array type\n properties?: JsonObjectSchema['properties']; // For nested object type\n required?: string[]; // For nested object type\n additionalProperties?: boolean | { type: string };\n [key: string]: any; // Allow other JSON schema properties\n };\n };\n required?: string[];\n additionalProperties?: boolean;\n}\n\n// Allow for other schema types (string, number, etc.) although object is most common for tools\nexport type JsonSchema = JsonObjectSchema | { type: 'string' | 'number' | 'boolean' | 'array', [key: string]: any };\n\n/**\n * Structure for holding metadata about an LLM call, typically received via a `METADATA` `StreamEvent`\n * or parsed from a non-streaming response. Fields are optional as availability varies by provider and stream state.\n *\n * @interface LLMMetadata\n */\nexport interface LLMMetadata {\n /**\n * The number of tokens in the input prompt, if available.\n * @property {number} [inputTokens]\n */\n inputTokens?: number;\n /**\n * The number of tokens generated in the output response, if available.\n * @property {number} [outputTokens]\n */\n outputTokens?: number;\n /**\n * The number of tokens identified as part of the LLM's internal thinking process (if available from provider).\n * @property {number} [thinkingTokens]\n */\n thinkingTokens?: number;\n /**\n * The time elapsed (in milliseconds) until the first token was generated in a streaming response, if applicable and available.\n * @property {number} [timeToFirstTokenMs]\n */\n timeToFirstTokenMs?: number;\n /**\n * The total time elapsed (in milliseconds) for the entire generation process, if available.\n * @property {number} [totalGenerationTimeMs]\n */\n totalGenerationTimeMs?: number;\n /**\n * The reason the LLM stopped generating tokens (e.g., 'stop_sequence', 'max_tokens', 'tool_calls'), if available.\n * @property {string} [stopReason]\n */\n stopReason?: string;\n /**\n * Optional raw usage data provided directly by the LLM provider for extensibility (structure depends on provider).\n * @property {any} [providerRawUsage]\n */\n providerRawUsage?: any;\n /**\n * The trace ID associated with the LLM call, useful for correlating metadata with the specific request.\n * @property {string} [traceId]\n */\n traceId?: string; // Include traceId if this object might be stored or passed independently.\n}\n\n/**\n * Defines the schema for a tool, including its input parameters.\n * Uses JSON Schema format for inputSchema.\n *\n * @interface ToolSchema\n */\nexport interface ToolSchema {\n /**\n * A unique name identifying the tool (used in LLM prompts and registry lookups). Must be unique.\n * @property {string} name\n */\n name: string;\n /**\n * A clear description of what the tool does, intended for the LLM to understand its purpose and usage.\n * @property {string} description\n */\n description: string;\n /**\n * A JSON Schema object defining the structure, types, and requirements of the input arguments the tool expects.\n * @property {JsonSchema} inputSchema\n */\n inputSchema: JsonSchema;\n /**\n * An optional JSON Schema object defining the expected structure of the data returned in the `output` field of a successful `ToolResult`.\n * @property {JsonSchema} [outputSchema]\n */\n outputSchema?: JsonSchema;\n /**\n * Optional array of examples demonstrating how to use the tool, useful for few-shot prompting of the LLM.\n * @property {Array<{ input: any; output?: any; description?: string }>} [examples]\n */\n examples?: Array<{ input: any; output?: any; description?: string }>;\n}\n/**\n * Represents the structured result of a tool execution.\n *\n * @interface ToolResult\n */\nexport interface ToolResult {\n /**\n * The unique identifier of the corresponding `ParsedToolCall` that initiated this execution attempt.\n * @property {string} callId\n */\n callId: string;\n /**\n * The name of the tool that was executed.\n * @property {string} toolName\n */\n toolName: string;\n /**\n * Indicates whether the tool execution succeeded or failed.\n * @property {'success' | 'error'} status\n */\n status: 'success' | 'error';\n /**\n * The data returned by the tool upon successful execution. Structure may be validated against `outputSchema`.\n * @property {any} [output]\n */\n output?: any;\n /**\n * A descriptive error message if the execution failed (`status` is 'error').\n * @property {string} [error]\n */\n error?: string;\n /**\n * Optional metadata about the execution (e.g., duration, cost, logs).\n * @property {object} [metadata]\n */\n metadata?: {\n sources?: Array<{\n sourceName: string;\n url?: string;\n [key: string]: any;\n }>;\n [key: string]: any;\n };\n}\n\n// --- SYSTEM PROMPT STANDARDIZATION TYPES ---\n/**\n * Strategy for combining custom system prompt content across precedence levels.\n *\n * @typedef {'append' | 'prepend'} SystemPromptMergeStrategy\n */\nexport type SystemPromptMergeStrategy = 'append' | 'prepend';\n\n/**\n * Named preset for system prompts, supporting variables and a default merge strategy.\n *\n * @interface SystemPromptSpec\n */\nexport interface SystemPromptSpec {\n /**\n * Optional explicit ID; when in a registry map, the key is typically the tag.\n * @property {string} [id]\n */\n id?: string;\n /**\n * Template string. Supports simple {{variable}} placeholders and {{fragment:name}} for PromptManager fragments.\n * @property {string} template\n */\n template: string;\n /**\n * Default variables applied if not provided at use time.\n * @property {Record<string, any>} [defaultVariables]\n */\n defaultVariables?: Record<string, any>;\n /**\n * Default strategy to combine this spec with lower levels. Defaults to 'append'.\n * @property {SystemPromptMergeStrategy} [mergeStrategy]\n */\n mergeStrategy?: SystemPromptMergeStrategy;\n}\n\n/**\n * Registry of available system prompt presets (tags) at the instance level.\n *\n * @interface SystemPromptsRegistry\n */\nexport interface SystemPromptsRegistry {\n /**\n * Tag to use when no other tag is specified.\n * @property {string} [defaultTag]\n */\n defaultTag?: string;\n /**\n * Mapping of tag -> spec.\n * @property {Record<string, SystemPromptSpec>} specs\n */\n specs: Record<string, SystemPromptSpec>;\n}\n\n/**\n * Override provided at instance/thread/call level to select a tag and/or provide variables,\n * or to provide freeform content and a merge strategy.\n *\n * @interface SystemPromptOverride\n */\nexport interface SystemPromptOverride {\n /**\n * Preset tag from the registry (e.g., 'default', 'legal_advisor').\n * @property {string} [tag]\n */\n tag?: string;\n /**\n * Variables to substitute in the selected template.\n * @property {Record<string, any>} [variables]\n */\n variables?: Record<string, any>;\n /**\n * Freeform content to apply directly (escape hatch).\n * @property {string} [content]\n */\n content?: string;\n /**\n * Merge behavior against previous level: append | prepend.\n * @property {SystemPromptMergeStrategy} [strategy]\n */\n strategy?: SystemPromptMergeStrategy;\n}\n\n/**\n * Represents a parsed request from the LLM to call a specific tool.\n *\n * @interface ParsedToolCall\n */\nexport interface ParsedToolCall {\n /**\n * A unique identifier generated by the OutputParser for this specific tool call request within a plan.\n * @property {string} callId\n */\n callId: string;\n /**\n * The name of the tool the LLM intends to call. Must match a registered tool's schema name.\n * @property {string} toolName\n */\n toolName: string;\n /**\n * The arguments object, parsed from the LLM response, intended to be passed to the tool's `execute` method after validation.\n * @property {any} arguments\n */\n arguments: any;\n}\n\n/**\n * Configuration specific to a conversation thread.\n *\n * @interface ThreadConfig\n */\n export interface ThreadConfig {\n /**\n * Default provider configuration for this thread.\n * @property {RuntimeProviderConfig} providerConfig\n */\n providerConfig: RuntimeProviderConfig;\n /**\n * An array of tool names (matching `ToolSchema.name`) that are permitted for use within this thread.\n * @property {string[]} enabledTools\n */\n enabledTools: string[];\n /**\n * The maximum number of past messages (`ConversationMessage` objects) to retrieve for context.\n * @property {number} historyLimit\n */\n historyLimit: number;\n /**\n * Optional system prompt override to be used for this thread, overriding instance or agent defaults.\n * @property {string | SystemPromptOverride} [systemPrompt]\n */\n systemPrompt?: string | SystemPromptOverride;\n /**\n * Optional: Defines the identity and high-level guidance for the agent for this specific thread.\n * This overrides the instance-level persona.\n * @property {Partial<AgentPersona>} [persona]\n */\n persona?: Partial<AgentPersona>;\n // TODO: Add other potential thread-specific settings (e.g., RAG configuration, default timeouts)\n }\n\n/**\n * Represents non-configuration state associated with an agent or thread.\n * Could include user preferences, accumulated knowledge, etc. (Less defined for v1.0)\n *\n * @interface AgentState\n */\nexport interface AgentState {\n /**\n * The primary data payload of the agent's state. Structure is application-defined.\n * @property {any} data\n */\n data: any;\n /**\n * An optional version number for the agent's state, useful for migrations or tracking changes.\n * @property {number} [version]\n */\n version?: number;\n /**\n * Allows for other arbitrary properties to be stored in the agent's state.\n * @property {any} [key: string]\n */\n [key: string]: any;\n}\n\n/**\n * Encapsulates the configuration and state for a specific thread.\n *\n * @interface ThreadContext\n */\nexport interface ThreadContext {\n /**\n * The configuration settings (`ThreadConfig`) currently active for the thread.\n * @property {ThreadConfig} config\n */\n config: ThreadConfig;\n /**\n * The persistent state (`AgentState`) associated with the thread, or `null` if no state exists.\n * @property {AgentState | null} state\n */\n state: AgentState | null;\n}\n\n/**\n * Properties required to initiate an agent processing cycle.\n *\n * @interface AgentProps\n */\nexport interface AgentProps {\n /**\n * The user's input query or request to the agent.\n * @property {string} query\n */\n query: string;\n /**\n * The mandatory identifier for the conversation thread. All context is scoped to this ID.\n * @property {string} threadId\n */\n threadId: string;\n /**\n * An optional identifier for the specific UI session, useful for targeting UI updates.\n * @property {string} [sessionId]\n */\n sessionId?: string;\n /**\n * An optional identifier for the user interacting with the agent.\n * @property {string} [userId]\n */\n userId?: string;\n /**\n * An optional identifier used for tracing a request across multiple systems or services.\n * @property {string} [traceId]\n */\n traceId?: string;\n /**\n * Optional runtime options that can override default behaviors for this specific `process` call.\n * @property {AgentOptions} [options]\n */\n options?: AgentOptions;\n // Note: Core dependencies (StateManager, ConversationManager, etc.) are typically injected\n // during `createArtInstance` and are accessed internally by the Agent Core, not passed in AgentProps.\n}\n\n/**\n * Options to override agent behavior at runtime.\n *\n * @interface AgentOptions\n */\n export interface AgentOptions {\n /**\n * Override specific LLM parameters (e.g., temperature, max_tokens) for this call only.\n * @property {Record<string, any>} [llmParams]\n */\n llmParams?: Record<string, any>;\n /**\n * Override provider configuration for this specific call.\n * @property {RuntimeProviderConfig} [providerConfig]\n */\n providerConfig?: RuntimeProviderConfig; // Add this line\n /**\n * Force the use of specific tools, potentially overriding the thread's `enabledTools` for this call (use with caution).\n * @property {string[]} [forceTools]\n */\n forceTools?: string[];\n /**\n * Specify a particular reasoning model to use for this call, overriding the thread's default.\n * @property {{ provider: string; model: string }} [overrideModel]\n */\n overrideModel?: { provider: string; model: string };\n /**\n * Request a streaming response for this specific agent process call.\n * @property {boolean} [stream]\n */\n stream?: boolean;\n /**\n * Override the prompt template used for this specific call.\n * @property {string} [promptTemplateId]\n */\n promptTemplateId?: string;\n /**\n * Optional system prompt override/tag to override thread, instance, or agent defaults for this specific call.\n * @property {string | SystemPromptOverride} [systemPrompt]\n */\n systemPrompt?: string | SystemPromptOverride;\n /**\n * Optional: Defines the identity and high-level guidance for the agent for this specific call.\n * This overrides both the instance-level and thread-level persona.\n * @property {Partial<AgentPersona>} [persona]\n */\n persona?: Partial<AgentPersona>;\n // TODO: Add other potential runtime overrides (e.g., history length).\n }\n\n/**\n * The final structured response returned by the agent core after processing.\n *\n * @interface AgentFinalResponse\n */\nexport interface AgentFinalResponse {\n /**\n * The final `ConversationMessage` generated by the AI, which has also been persisted.\n * @property {ConversationMessage} response\n */\n response: ConversationMessage;\n /**\n * Metadata summarizing the execution cycle that produced this response.\n * @property {ExecutionMetadata} metadata\n */\n metadata: ExecutionMetadata;\n}\n\n/**\n * Metadata summarizing an agent execution cycle, including performance metrics and outcomes.\n *\n * @interface ExecutionMetadata\n */\nexport interface ExecutionMetadata {\n /**\n * The thread ID associated with this execution cycle.\n * @property {string} threadId\n */\n threadId: string;\n /**\n * The trace ID used during this execution, if provided.\n * @property {string} [traceId]\n */\n traceId?: string;\n /**\n * The user ID associated with the execution, if provided.\n * @property {string} [userId]\n */\n userId?: string;\n /**\n * The overall status of the execution ('success', 'error', or 'partial' if some steps failed but a response was generated).\n * @property {'success' | 'error' | 'partial'} status\n */\n status: 'success' | 'error' | 'partial';\n /**\n * The total duration of the `agent.process()` call in milliseconds.\n * @property {number} totalDurationMs\n */\n totalDurationMs: number;\n /**\n * The number of calls made to the `ReasoningEngine`.\n * @property {number} llmCalls\n */\n llmCalls: number;\n /**\n * The number of tool execution attempts made by the `ToolSystem`.\n * @property {number} toolCalls\n */\n toolCalls: number;\n /**\n * An optional estimated cost for the LLM calls made during this execution.\n * @property {number} [llmCost]\n */\n llmCost?: number;\n /**\n * A top-level error message if the overall status is 'error' or 'partial'.\n * @property {string} [error]\n */\n error?: string;\n /**\n * Aggregated metadata from LLM calls made during the execution.\n * @property {LLMMetadata} [llmMetadata]\n */\n llmMetadata?: LLMMetadata;\n}\n\n/**\n * Context provided to a tool during its execution.\n *\n * @interface ExecutionContext\n */\nexport interface ExecutionContext {\n /**\n * The ID of the thread in which the tool is being executed.\n * @property {string} threadId\n */\n threadId: string;\n /**\n * The trace ID for this execution cycle, if available.\n * @property {string} [traceId]\n */\n traceId?: string;\n /**\n * The user ID associated with the execution, if available.\n * @property {string} [userId]\n */\n userId?: string;\n // TODO: Potentially include access tokens or credentials scoped to this execution, if needed securely.\n // TODO: Consider providing limited access to StateManager or other relevant context if required by complex tools.\n}\n\n/**\n * Options for configuring an LLM call, including streaming and context information.\n *\n * @interface CallOptions\n */\nexport interface CallOptions {\n /**\n * The mandatory thread ID, used by the ReasoningEngine to fetch thread-specific configuration (e.g., model, params) via StateManager.\n * @property {string} threadId\n */\n threadId: string;\n /**\n * Optional trace ID for correlation.\n * @property {string} [traceId]\n */\n traceId?: string;\n /**\n * Optional user ID.\n * @property {string} [userId]\n */\n userId?: string;\n /**\n * Optional session ID.\n * @property {string} [sessionId]\n */\n sessionId?: string; // Added sessionId\n /**\n * Request a streaming response from the LLM provider.\n * Adapters MUST check this flag.\n * @property {boolean} [stream]\n */\n stream?: boolean;\n /**\n * Provides context for the LLM call, allowing adapters to differentiate\n * between agent-level thoughts and final synthesis calls for token typing.\n * Agent Core MUST provide this.\n * @property {'AGENT_THOUGHT' | 'FINAL_SYNTHESIS' | string} [callContext]\n */\n callContext?: 'AGENT_THOUGHT' | 'FINAL_SYNTHESIS' | string;\n /**\n * An optional callback function invoked when the LLM streams intermediate 'thoughts' or reasoning steps.\n * @deprecated Prefer using StreamEvent with appropriate tokenType for thoughts. Kept for potential transitional compatibility.\n */\n // onThought?: (thought: string) => void; // Commented out as per implementation plan decision (Ref: 7.2, Checklist Phase 1)\n /**\n * Carries the specific target provider and configuration for this call.\n * @property {RuntimeProviderConfig} providerConfig\n */\n providerConfig: RuntimeProviderConfig;\n /**\n * Additional key-value pairs representing provider-specific parameters (e.g., `temperature`, `max_tokens`, `top_p`). These often override defaults set in `ThreadConfig`.\n * @property {any} [key: string]\n */\n [key: string]: any;\n}\n\n// --- ART STANDARD PROMPT TYPES (Refactor Phase 1) ---\n\n/**\n * Defines the standard roles for messages within the `ArtStandardPrompt` format.\n *\n * @remarks\n * These roles are chosen for broad compatibility across major LLM providers (like OpenAI, Anthropic, Gemini).\n * Provider Adapters are responsible for translating these standard roles into the specific formats\n * required by their respective APIs (e.g., 'assistant' might become 'model' for Gemini).\n *\n * - `system`: Instructions or context provided to the AI, typically at the beginning.\n * - `user`: Input or queries from the end-user. Also used to wrap `tool_result` content for some providers (e.g., Gemini).\n * - `assistant`: Responses generated by the AI model. Can contain text content and/or `tool_calls`.\n * - `tool_request`: Represents the LLM's request to use tools (often implicitly part of an `assistant` message with `tool_calls`). Included for potential future explicit use.\n * - `tool_result`: The outcome (output or error) of executing a requested tool call.\n *\n * @typedef {'system' | 'user' | 'assistant' | 'tool_request' | 'tool_result' | 'tool'} ArtStandardMessageRole\n */\n export type ArtStandardMessageRole = 'system' | 'user' | 'assistant' | 'tool_request' | 'tool_result' | 'tool'; // Added 'tool' role\n\n/**\n * Represents a single message in the standardized, provider-agnostic `ArtStandardPrompt` format.\n *\n * @remarks\n * This structure aims to capture common message elements used by various LLM APIs.\n *\n * @interface ArtStandardMessage\n */\nexport interface ArtStandardMessage {\n /**\n * The role indicating the source or type of the message.\n * @property {ArtStandardMessageRole} role\n */\n role: ArtStandardMessageRole;\n /**\n * The primary content of the message. The type and interpretation depend on the `role`:\n * - `system`: string (The system instruction).\n * - `user`: string (The user's text input).\n * - `assistant`: string | null (The AI's text response, or null/empty if only making `tool_calls`).\n * - `tool_request`: object | null (Structured representation of the tool call, often implicitly handled via `assistant` message's `tool_calls`).\n * - `tool_result`: string (Stringified JSON output or error message from the tool execution).\n * @property {string | object | null} content\n */\n content: string | object | null;\n /**\n * Optional name associated with the message. Primarily used for `tool_result` role to specify the name of the tool that was executed.\n * @property {string} [name]\n */\n name?: string;\n /**\n * Optional array of tool calls requested by the assistant.\n *\n * @remarks\n * Only relevant for 'assistant' role messages that trigger tool usage.\n * Structure mirrors common provider formats (e.g., OpenAI).\n *\n * @property {Array<{ id: string; type: 'function'; function: { name: string; arguments: string; }; }>} [tool_calls]\n */\n tool_calls?: Array<{\n /** A unique identifier for this specific tool call request. */\n id: string;\n /** The type of the tool call, typically 'function'. */\n type: 'function'; // Assuming 'function' is the standard type\n /** Details of the function to be called. */\n function: {\n /** The name of the function/tool to call. */\n name: string;\n /** A stringified JSON object representing the arguments for the function. */\n arguments: string;\n };\n }>;\n /**\n * Optional identifier linking a 'tool_result' message back to the specific 'tool_calls' entry\n * in the preceding 'assistant' message that requested it.\n * Required for 'tool_result' role.\n * @property {string} [tool_call_id]\n */\n tool_call_id?: string;\n}\n\n/**\n * Represents the entire prompt as an array of standardized messages (`ArtStandardMessage`).\n *\n * @remarks\n * Constructed by agent logic (e.g., `PESAgent`) and optionally validated via\n * `PromptManager.validatePrompt` before being sent to the `ReasoningEngine` and\n * translated by a `ProviderAdapter` for provider-specific API formats.\n *\n * @typedef {ArtStandardMessage[]} ArtStandardPrompt\n */\nexport type ArtStandardPrompt = ArtStandardMessage[];\n\n/**\n * Represents the contextual data gathered by Agent Logic (e.g., `PESAgent`) to be injected\n * into a Mustache blueprint/template by the `PromptManager.assemblePrompt` method.\n *\n * @remarks\n * Contains standard fields commonly needed for prompts, plus allows for arbitrary\n * additional properties required by specific agent blueprints. Agent logic is responsible\n * for populating this context appropriately before calling `assemblePrompt`.\n *\n * @interface PromptContext\n */\nexport interface PromptContext {\n /**\n * The user's current query or input relevant to this prompt generation step.\n * @property {string} [query]\n */\n query?: string;\n /**\n * The conversation history, typically formatted as an array suitable for the blueprint\n * (e.g., array of objects with `role` and `content`). Agent logic should pre-format this.\n *\n * @remarks\n * While `ArtStandardPrompt` could be used, simpler structures might be preferred for blueprints.\n *\n * @property {Array<{ role: string; content: string; [key: string]: any }>} [history]\n */\n history?: Array<{ role: string; content: string; [key: string]: any }>; // Flexible history format for blueprints\n /**\n * The schemas of the tools available for use, potentially pre-formatted for the blueprint\n * (e.g., with `inputSchemaJson` pre-stringified).\n * @property {Array<ToolSchema & { inputSchemaJson?: string }>} [availableTools]\n */\n availableTools?: Array<ToolSchema & { inputSchemaJson?: string }>;\n /**\n * The results from any tools executed in a previous step, potentially pre-formatted for the blueprint\n * (e.g., with `outputJson` pre-stringified).\n * @property {Array<ToolResult & { outputJson?: string }>} [toolResults]\n */\n toolResults?: Array<ToolResult & { outputJson?: string }>;\n /**\n * The system prompt string to be used (resolved by agent logic from config or defaults).\n * @property {string} [systemPrompt]\n */\n systemPrompt?: string;\n /**\n * Allows agent patterns (like PES) to pass any other custom data needed by their specific blueprints (e.g., `intent`, `plan`).\n * @property {any} [key: string]\n */\n [key: string]: any;\n}\n\n/**\n * Represents a Mustache template that can be rendered with a PromptContext to produce an ArtStandardPrompt.\n * Used by the PromptManager.assemblePrompt method.\n *\n * @interface PromptBlueprint\n */\nexport interface PromptBlueprint {\n /**\n * The Mustache template string that will be rendered with context data to produce a JSON string representing an ArtStandardPrompt\n * @property {string} template\n */\n template: string;\n}\n\n// --- END ART STANDARD PROMPT TYPES ---\n\n\n/**\n * Represents the prompt data formatted for a specific LLM provider.\n * Can be a simple string or a complex object (e.g., for OpenAI Chat Completion API).\n *\n * @deprecated Use `ArtStandardPrompt` as the standard intermediate format. ProviderAdapters handle final formatting.\n * @typedef {ArtStandardPrompt} FormattedPrompt\n */\nexport type FormattedPrompt = ArtStandardPrompt; // Point deprecated type to the new standard\n\n/**\n * Options for filtering data retrieved from storage.\n * Structure depends heavily on the underlying adapter's capabilities.\n *\n * @interface FilterOptions\n */\nexport interface FilterOptions {\n /**\n * An object defining filter criteria (e.g., `{ threadId: 'abc', type: 'TOOL_EXECUTION' }`). Structure may depend on adapter capabilities.\n * @property {Record<string, any>} [filter]\n */\n filter?: Record<string, any>;\n /**\n * An object defining sorting criteria (e.g., `{ timestamp: 'desc' }`).\n * @property {Record<string, 'asc' | 'desc'>} [sort]\n */\n sort?: Record<string, 'asc' | 'desc'>;\n /**\n * The maximum number of records to return.\n * @property {number} [limit]\n */\n limit?: number;\n /**\n * The number of records to skip (for pagination).\n * @property {number} [skip]\n */\n skip?: number;\n // TODO: Consider adding projection options to retrieve only specific fields.\n}\n\n/**\n * Options for retrieving conversation messages.\n *\n * @interface MessageOptions\n */\nexport interface MessageOptions {\n /**\n * The maximum number of messages to retrieve.\n * @property {number} [limit]\n */\n limit?: number;\n /**\n * Retrieve messages created before this Unix timestamp (milliseconds).\n * @property {number} [beforeTimestamp]\n */\n beforeTimestamp?: number;\n /**\n * Retrieve messages created after this Unix timestamp (milliseconds).\n * @property {number} [afterTimestamp]\n */\n afterTimestamp?: number;\n /**\n * Optionally filter messages by role (e.g., retrieve only 'AI' messages).\n * @property {MessageRole[]} [roles]\n */\n roles?: MessageRole[];\n}\n\n/**\n * Options for filtering observations.\n *\n * @interface ObservationFilter\n */\nexport interface ObservationFilter {\n /**\n * An array of `ObservationType` enums to filter by. If provided, only observations matching these types are returned.\n * @property {ObservationType[]} [types]\n */\n types?: ObservationType[];\n /**\n * Retrieve observations recorded before this Unix timestamp (milliseconds).\n * @property {number} [beforeTimestamp]\n */\n beforeTimestamp?: number;\n /**\n * Retrieve observations recorded after this Unix timestamp (milliseconds).\n * @property {number} [afterTimestamp]\n */\n afterTimestamp?: number;\n // TODO: Add other potential criteria like filtering by metadata content if needed.\n}\n\n// Removed duplicate TypedSocket interface definition.\n// The primary definition is in src/core/interfaces.ts\n\n/**\n * Defines the strategy for saving AgentState.\n *\n * @remarks\n * - 'explicit': AgentState is only saved when `StateManager.setAgentState()` is explicitly called by the agent.\n * `StateManager.saveStateIfModified()` will be a no-op for AgentState persistence.\n * - 'implicit': AgentState is loaded by `StateManager.loadThreadContext()`, and if modified by the agent,\n * `StateManager.saveStateIfModified()` will attempt to automatically persist these changes\n * by comparing the current state with a snapshot taken at load time.\n * `StateManager.setAgentState()` will still work for explicit saves.\n *\n * @typedef {'explicit' | 'implicit'} StateSavingStrategy\n */\nexport type StateSavingStrategy = 'explicit' | 'implicit';\n\n// Explicitly import ProviderManagerConfig here for ArtInstanceConfig\nimport type { ProviderManagerConfig as PMConfig } from './providers';\n// Import McpManagerConfig for ArtInstanceConfig\nimport type { McpManagerConfig } from '../systems/mcp/types';\n\n/**\n * Configuration for creating an ART instance.\n *\n * @interface ArtInstanceConfig\n */\nexport interface ArtInstanceConfig {\n /**\n * Configuration for the storage adapter.\n * Can be a pre-configured `StorageAdapter` instance,\n * or an object specifying the type and options for a built-in adapter.\n *\n * @example { type: 'indexedDB', dbName: 'MyArtDB' }\n *\n * @property {StorageAdapter | { type: 'memory' | 'indexedDB', dbName?: string, version?: number, objectStores?: any[] }} storage\n */\n storage: StorageAdapter | { type: 'memory' | 'indexedDB', dbName?: string, version?: number, objectStores?: any[] };\n /**\n * Configuration for the ProviderManager, defining available LLM provider adapters.\n * @property {PMConfig} providers\n */\n providers: PMConfig; // Use the aliased import\n /**\n * The agent core implementation class to use.\n * Defaults to `PESAgent` if not provided.\n *\n * @example MyCustomAgentClass\n *\n * @property {new (dependencies: any) => IAgentCore} [agentCore]\n */\n agentCore?: new (dependencies: any) => IAgentCore; // Constructor type for an IAgentCore implementation\n /**\n * An optional array of tool executor instances to register at initialization.\n * @property {IToolExecutor[]} [tools]\n */\n tools?: IToolExecutor[];\n /**\n * Defines the strategy for saving `AgentState`. Defaults to 'explicit'.\n *\n * @remarks\n * - 'explicit': `AgentState` is only saved when `StateManager.setAgentState()` is explicitly called by the agent.\n * `StateManager.saveStateIfModified()` will be a no-op for `AgentState` persistence.\n * - 'implicit': `AgentState` is loaded by `StateManager.loadThreadContext()`. If modified by the agent,\n * `StateManager.saveStateIfModified()` will attempt to automatically persist these changes.\n * `StateManager.setAgentState()` will still work for explicit saves in this mode.\n *\n * @property {StateSavingStrategy} [stateSavingStrategy]\n */\n stateSavingStrategy?: StateSavingStrategy;\n /**\n * Optional configuration for the framework's logger.\n * @property {{ level?: LogLevel }} [logger]\n */\n logger?: {\n /** Minimum log level to output. Defaults to 'info'. */\n level?: LogLevel;\n };\n /**\n * Optional: Defines the default identity and high-level guidance for the agent.\n * This can be overridden at the thread or call level.\n * @property {AgentPersona} [persona]\n */\n persona?: AgentPersona;\n /**\n * Optional configuration for MCP (Model Context Protocol) manager.\n * Enables connection to external MCP servers for dynamic tool loading.\n * @property {McpManagerConfig} [mcpConfig]\n */\n mcpConfig?: McpManagerConfig;\n /**\n * Optional configuration for authentication strategies.\n * Used for secure connections to external services and MCP servers.\n * @property {object} [authConfig]\n */\n authConfig?: {\n /**\n * Whether to enable authentication manager. Defaults to false.\n * @property {boolean} [enabled]\n */\n enabled?: boolean;\n /**\n * Pre-configured authentication strategies to register at startup.\n * @property {Array<{ id: string; strategy: any }>} [strategies]\n */\n strategies?: Array<{ id: string; strategy: any }>;\n };\n /**\n * Optional: Configuration for A2A services.\n * @property {object} [a2aConfig]\n */\n a2aConfig?: {\n /**\n * The endpoint for discovering A2A agents.\n * @property {string} [discoveryEndpoint]\n */\n discoveryEndpoint?: string;\n /**\n * The callback URL for receiving A2A task updates.\n * @property {string} [callbackUrl]\n */\n callbackUrl?: string;\n };\n // Add other top-level configuration properties as needed, e.g.:\n // defaultThreadConfig?: Partial<ThreadConfig>;\n}\n\n/**\n * Represents the possible states of an A2A (Agent-to-Agent) task.\n *\n * @enum {string}\n */\nexport enum A2ATaskStatus {\n /** Task has been created but not yet assigned to an agent. */\n PENDING = 'PENDING',\n /** Task has been assigned to an agent and is being processed. */\n IN_PROGRESS = 'IN_PROGRESS',\n /** Task has been completed successfully. */\n COMPLETED = 'COMPLETED',\n /** Task has failed during execution. */\n FAILED = 'FAILED',\n /** Task has been cancelled before completion. */\n CANCELLED = 'CANCELLED',\n /** Task is waiting for external dependencies or manual intervention. */\n WAITING = 'WAITING',\n /** Task is being reviewed for quality assurance. */\n REVIEW = 'REVIEW'\n}\n\n/**\n * Represents the priority level of an A2A task.\n *\n * @enum {string}\n */\nexport enum A2ATaskPriority {\n /** Low priority. */\n LOW = 'LOW',\n /** Medium priority. */\n MEDIUM = 'MEDIUM',\n /** High priority. */\n HIGH = 'HIGH',\n /** Urgent priority. */\n URGENT = 'URGENT'\n}\n\n/**\n * Represents agent information for A2A task assignment.\n *\n * @interface A2AAgentInfo\n */\nexport interface A2AAgentInfo {\n /**\n * Unique identifier for the agent.\n * @property {string} agentId\n */\n agentId: string;\n /**\n * Human-readable name for the agent.\n * @property {string} agentName\n */\n agentName: string;\n /**\n * The type or role of the agent (e.g., 'reasoning', 'data-processing', 'synthesis').\n * @property {string} agentType\n */\n agentType: string;\n /**\n * Base URL or endpoint for communicating with the agent.\n * @property {string} [endpoint]\n */\n endpoint?: string;\n /**\n * Agent capabilities or specializations.\n * @property {string[]} [capabilities]\n */\n capabilities?: string[];\n /**\n * Current load or availability status of the agent.\n * @property {'available' | 'busy' | 'offline'} [status]\n */\n status?: 'available' | 'busy' | 'offline';\n /**\n * Authentication configuration for communicating with the agent.\n * @property {object} [authentication]\n */\n authentication?: {\n /**\n * Type of authentication required.\n * @property {'bearer' | 'api_key' | 'none'} type\n */\n type: 'bearer' | 'api_key' | 'none';\n /**\n * Bearer token for authorization (if type is 'bearer').\n * @property {string} [token]\n */\n token?: string;\n /**\n * API key for authorization (if type is 'api_key').\n * @property {string} [apiKey]\n */\n apiKey?: string;\n };\n}\n\n/**\n * Represents metadata about A2A task execution.\n *\n * @interface A2ATaskMetadata\n */\nexport interface A2ATaskMetadata {\n /**\n * Timestamp when the task was created (Unix timestamp in milliseconds).\n * @property {number} createdAt\n */\n createdAt: number;\n /**\n * Timestamp when the task was last updated (Unix timestamp in milliseconds).\n * @property {number} updatedAt\n */\n updatedAt: number;\n /**\n * Timestamp when the task was started (if applicable).\n * @property {number} [startedAt]\n */\n startedAt?: number;\n /**\n * Timestamp when the task was completed/failed (if applicable).\n * @property {number} [completedAt]\n */\n completedAt?: number;\n /**\n * Timestamp when the task was delegated to a remote agent (if applicable).\n * @property {number} [delegatedAt]\n */\n delegatedAt?: number;\n /**\n * Timestamp when the task was last updated (for compatibility).\n * @property {number} [lastUpdated]\n */\n lastUpdated?: number;\n /**\n * The user or system that initiated this task.\n * @property {string} [initiatedBy]\n */\n initiatedBy?: string;\n /**\n * Correlation ID for tracking related tasks across the system.\n * @property {string} [correlationId]\n */\n correlationId?: string;\n /**\n * Number of retry attempts made for this task.\n * @property {number} [retryCount]\n */\n retryCount?: number;\n /**\n * Maximum number of retry attempts allowed.\n * @property {number} [maxRetries]\n */\n maxRetries?: number;\n /**\n * Timeout duration in milliseconds.\n * @property {number} [timeoutMs]\n */\n timeoutMs?: number;\n /**\n * Estimated completion time in milliseconds (if provided by remote agent).\n * @property {number} [estimatedCompletionMs]\n */\n estimatedCompletionMs?: number;\n /**\n * Tags or labels for categorizing tasks.\n * @property {string[]} [tags]\n */\n tags?: string[];\n}\n\n/**\n * Represents the result of an A2A task execution.\n *\n * @interface A2ATaskResult\n */\nexport interface A2ATaskResult {\n /**\n * Whether the task execution was successful.\n * @property {boolean} success\n */\n success: boolean;\n /**\n * The data returned by the task execution.\n * @property {any} [data]\n */\n data?: any;\n /**\n * Error message if the task failed.\n * @property {string} [error]\n */\n error?: string;\n /**\n * Additional metadata about the execution.\n * @property {object} [metadata]\n */\n metadata?: {\n sources?: Array<{\n sourceName: string;\n url?: string;\n [key: string]: any;\n }>;\n [key: string]: any;\n };\n /**\n * Execution duration in milliseconds.\n * @property {number} [durationMs]\n */\n durationMs?: number;\n}\n\n/**\n * Represents a task for Agent-to-Agent (A2A) communication and delegation.\n * Used for asynchronous task delegation between AI agents in distributed systems.\n *\n * @interface A2ATask\n */\nexport interface A2ATask {\n /**\n * Unique identifier for the task.\n * @property {string} taskId\n */\n taskId: string;\n /**\n * The thread this task belongs to (top-level for efficient filtering).\n * @property {string} threadId\n */\n threadId: string;\n \n /**\n * Current status of the task.\n * @property {A2ATaskStatus} status\n */\n status: A2ATaskStatus;\n \n /**\n * The data payload containing task parameters and context.\n * @property {object} payload\n */\n payload: {\n /**\n * The type of task to be executed (e.g., 'analyze', 'synthesize', 'transform').\n * @property {string} taskType\n */\n taskType: string;\n /**\n * Input data required for task execution.\n * @property {any} input\n */\n input: any;\n /**\n * Instructions or configuration for the task.\n * @property {string} [instructions]\n */\n instructions?: string;\n /**\n * Additional parameters specific to the task type.\n * @property {Record<string, any>} [parameters]\n */\n parameters?: Record<string, any>;\n };\n \n /**\n * Information about the agent that created/requested this task.\n * @property {A2AAgentInfo} sourceAgent\n */\n sourceAgent: A2AAgentInfo;\n \n /**\n * Information about the agent assigned to execute this task (if assigned).\n * @property {A2AAgentInfo} [targetAgent]\n */\n targetAgent?: A2AAgentInfo;\n \n /**\n * Task priority level.\n * @property {A2ATaskPriority} priority\n */\n priority: A2ATaskPriority;\n \n /**\n * Task execution metadata.\n * @property {A2ATaskMetadata} metadata\n */\n metadata: A2ATaskMetadata;\n \n /**\n * The result of task execution (if completed).\n * @property {A2ATaskResult} [result]\n */\n result?: A2ATaskResult;\n \n /**\n * Callback URL or identifier for task completion notifications.\n * @property {string} [callbackUrl]\n */\n callbackUrl?: string;\n \n /**\n * Dependencies that must be completed before this task can start.\n * @property {string[]} [dependencies]\n */\n dependencies?: string[];\n}\n\n/**\n * Represents a request to create a new A2A task.\n *\n * @interface CreateA2ATaskRequest\n */\nexport interface CreateA2ATaskRequest {\n /**\n * The type of task to be executed.\n * @property {string} taskType\n */\n taskType: string;\n /**\n * Input data for the task.\n * @property {any} input\n */\n input: any;\n /**\n * Instructions for task execution.\n * @property {string} [instructions]\n */\n instructions?: string;\n /**\n * Task parameters.\n * @property {Record<string, any>} [parameters]\n */\n parameters?: Record<string, any>;\n /**\n * Task priority.\n * @property {A2ATaskPriority} [priority]\n */\n priority?: A2ATaskPriority;\n /**\n * Source agent information.\n * @property {A2AAgentInfo} sourceAgent\n */\n sourceAgent: A2AAgentInfo;\n /**\n * Preferred target agent (if any).\n * @property {A2AAgentInfo} [preferredTargetAgent]\n */\n preferredTargetAgent?: A2AAgentInfo;\n /**\n * Task dependencies.\n * @property {string[]} [dependencies]\n */\n dependencies?: string[];\n /**\n * Callback URL for notifications.\n * @property {string} [callbackUrl]\n */\n callbackUrl?: string;\n /**\n * Task timeout in milliseconds.\n * @property {number} [timeoutMs]\n */\n timeoutMs?: number;\n /**\n * Maximum retry attempts.\n * @property {number} [maxRetries]\n */\n maxRetries?: number;\n /**\n * Task tags.\n * @property {string[]} [tags]\n */\n tags?: string[];\n}\n\n/**\n * Represents an update to an existing A2A task.\n *\n * @interface UpdateA2ATaskRequest\n */\nexport interface UpdateA2ATaskRequest {\n /**\n * Task ID to update.\n * @property {string} taskId\n */\n taskId: string;\n /**\n * New task status (if changing).\n * @property {A2ATaskStatus} [status]\n */\n status?: A2ATaskStatus;\n /**\n * Target agent assignment (if assigning/reassigning).\n * @property {A2AAgentInfo} [targetAgent]\n */\n targetAgent?: A2AAgentInfo;\n /**\n * Task result (if completing).\n * @property {A2ATaskResult} [result]\n */\n result?: A2ATaskResult;\n /**\n * Additional metadata updates.\n * @property {Partial<A2ATaskMetadata>} [metadata]\n */\n metadata?: Partial<A2ATaskMetadata>;\n}\n\n/**\n * Defines the default identity and high-level guidance for an agent.\n * This is provided at the instance level and can be overridden by thread or call-specific prompts.\n *\n * @interface AgentPersona\n */\nexport interface AgentPersona {\n /**\n * The name or identity of the agent (e.g., \"Zoi\").\n * This will be used in the synthesis prompt.\n * @property {string} name\n */\n name: string;\n\n /**\n * The default system prompt that provides high-level guidance.\n * This serves as the base layer in the system prompt resolution hierarchy.\n * @property {string} defaultSystemPrompt\n */\n prompts: StageSpecificPrompts;\n}\n\n/**\n * Defines stage-specific system prompts for planning and synthesis.\n *\n * @interface StageSpecificPrompts\n */\nexport interface StageSpecificPrompts {\n /**\n * System prompt to guide the planning phase.\n * Focuses on reasoning, expertise, and tool selection.\n * @property {string} [planning]\n */\n planning?: string;\n\n /**\n * System prompt to guide the synthesis phase.\n * Focuses on tone, formatting, and final response structure.\n * @property {string} [synthesis]\n */\n synthesis?: string;\n}","/**\n * @module utils/uuid\n * Provides a utility function for generating Version 4 UUIDs.\n */\nimport { v4 as uuidv4 } from 'uuid';\n\n/**\n * Generates a unique Version 4 UUID (Universally Unique Identifier) string.\n *\n * @remarks\n * Uses the underlying 'uuid' library's v4 implementation.\n *\n * @returns A randomly generated UUID string (e.g., \"f47ac10b-58cc-4372-a567-0e02b2c3d479\").\n *\n * @see {@link https://www.npmjs.com/package/uuid | uuid npm package}\n */\nexport const generateUUID = (): string => {\n return uuidv4();\n};","// src/core/agents/pes-agent.ts\nimport {\n IAgentCore,\n StateManager,\n ConversationManager,\n ToolRegistry,\n ReasoningEngine,\n OutputParser,\n ObservationManager,\n ToolSystem,\n UISystem,\n IA2ATaskRepository\n} from '@/core/interfaces';\nimport {\n AgentProps,\n AgentFinalResponse,\n ConversationMessage,\n ParsedToolCall,\n ToolResult,\n ObservationType,\n ExecutionMetadata,\n MessageRole,\n CallOptions,\n ModelCapability,\n LLMMetadata,\n ArtStandardPrompt,\n ArtStandardMessageRole,\n A2ATask,\n A2ATaskStatus,\n A2ATaskPriority,\n A2AAgentInfo,\n AgentPersona,\n TodoItem,\n TodoItemStatus,\n PESAgentStateData,\n ExecutionOutput\n} from '@/types';\nimport { RuntimeProviderConfig } from '@/types/providers';\nimport { generateUUID } from '@/utils/uuid';\nimport { ARTError, ErrorCode } from '@/errors';\nimport { Logger } from '@/utils/logger';\n\nimport { AgentDiscoveryService } from '@/systems/a2a/AgentDiscoveryService';\nimport { TaskDelegationService } from '@/systems/a2a/TaskDelegationService';\n\nexport interface PESAgentDependencies {\n /** Manages thread configuration and state. */\n stateManager: StateManager;\n /** Manages conversation history. */\n conversationManager: ConversationManager;\n /** Registry for available tools. */\n toolRegistry: ToolRegistry;\n /** Handles interaction with the LLM provider. */\n reasoningEngine: ReasoningEngine;\n /** Parses LLM responses. */\n outputParser: OutputParser;\n /** Records agent execution observations. */\n observationManager: ObservationManager;\n /** Orchestrates tool execution. */\n toolSystem: ToolSystem;\n /** Provides access to UI communication sockets. */\n uiSystem: UISystem;\n /** Repository for A2A tasks. */\n a2aTaskRepository: IA2ATaskRepository;\n /** Service for discovering A2A agents. */\n agentDiscoveryService?: AgentDiscoveryService | null;\n /** Service for delegating A2A tasks. */\n taskDelegationService?: TaskDelegationService | null;\n /** Resolver for standardized system prompt composition. */\n systemPromptResolver: import('@/core/interfaces').SystemPromptResolver;\n /** Optional: Defines the default identity and high-level guidance for the agent. */\n persona?: AgentPersona;\n}\n\nconst DEFAULT_PERSONA: AgentPersona = {\n name: 'Zoi',\n prompts: {\n planning: 'You are a helpful AI assistant. Your primary goal is to understand a user\\'s query, determine the intent, and create a clear plan to provide an accurate and helpful response. You can use tools to gather information if necessary.',\n synthesis: 'You are a helpful AI assistant named Art. Your primary goal is to synthesize the information gathered from tools, outcomes of each todo list task and planning into a final, user-friendly response. Be clear, concise, and helpful. If any ui components are defined, you should use those to display your outputs.'\n }\n};\n\n/**\n * Implements the Plan-Execute-Synthesize (PES) agent orchestration logic.\n * Refactored to support persistent TodoList execution and iterative refinement.\n */\nexport class PESAgent implements IAgentCore {\n private readonly deps: PESAgentDependencies;\n private readonly persona: AgentPersona;\n\n constructor(dependencies: PESAgentDependencies) {\n this.deps = dependencies;\n this.persona = {\n ...DEFAULT_PERSONA,\n ...dependencies.persona,\n prompts: {\n ...DEFAULT_PERSONA.prompts,\n ...dependencies.persona?.prompts,\n },\n };\n }\n\n async process(props: AgentProps): Promise<AgentFinalResponse> {\n const startTime = Date.now();\n const traceId = props.traceId ?? generateUUID();\n let status: ExecutionMetadata['status'] = 'success';\n let errorMessage: string | undefined;\n let llmCalls = 0;\n let toolCallsCount = 0;\n let finalAiMessage: ConversationMessage | undefined;\n let aggregatedLlmMetadata: LLMMetadata | undefined = undefined;\n\n let phase = 'initialization';\n try {\n // Stage 1: Load configuration and resolve system prompt\n phase = 'configuration';\n const { threadContext, planningSystemPrompt, synthesisSystemPrompt, runtimeProviderConfig, finalPersona } = await this._loadConfiguration(props, traceId);\n\n // Stage 2: Gather context data\n phase = 'context_gathering';\n const history = await this._gatherHistory(props.threadId, threadContext);\n const availableTools = await this._gatherTools(props.threadId);\n\n // Stage 3: State Loading & Plan Determination\n phase = 'state_loading';\n\n // Cast the opaque state data to our specific type\n let pesState = (threadContext.state?.data) as PESAgentStateData | undefined;\n const isFollowUp = !!pesState && pesState.todoList && pesState.todoList.length > 0;\n\n if (!isFollowUp) {\n // Initial Planning Phase\n Logger.debug(`[${traceId}] No existing plan found. Initiating Planning Phase.`);\n phase = 'planning';\n const planningResult = await this._performPlanning(\n props, planningSystemPrompt, history, availableTools, runtimeProviderConfig, traceId\n );\n llmCalls++;\n if (planningResult.metadata) aggregatedLlmMetadata = { ...(aggregatedLlmMetadata ?? {}), ...planningResult.metadata };\n\n // Initialize State\n pesState = {\n threadId: props.threadId,\n intent: planningResult.output.intent || 'Unknown Intent',\n title: planningResult.output.title || 'New Conversation',\n plan: planningResult.output.plan || '',\n todoList: planningResult.output.todoList || [],\n currentStepId: null,\n isPaused: false\n };\n\n // Persist Initial State\n await this._saveState(props.threadId, pesState);\n await this._recordPlanObservations(props.threadId, traceId, planningResult.output, planningResult.rawText);\n\n } else {\n // Follow-up / Refinement Phase\n Logger.debug(`[${traceId}] Existing plan found. Processing follow-up/refinement.`);\n phase = 'planning_refinement';\n\n if (props.query && props.query.trim().length > 0) {\n // We know pesState is defined here because isFollowUp is true\n const refinementResult = await this._performPlanRefinement(\n props, planningSystemPrompt, history, pesState!, availableTools, runtimeProviderConfig, traceId\n );\n llmCalls++;\n if (refinementResult.metadata) aggregatedLlmMetadata = { ...(aggregatedLlmMetadata ?? {}), ...refinementResult.metadata };\n\n if (refinementResult.output.todoList) {\n pesState!.intent = refinementResult.output.intent || pesState!.intent;\n pesState!.plan = refinementResult.output.plan || pesState!.plan;\n pesState!.todoList = refinementResult.output.todoList;\n\n await this._saveState(props.threadId, pesState!);\n await this._recordPlanObservations(props.threadId, traceId, refinementResult.output, refinementResult.rawText);\n }\n }\n }\n\n // Stage 4: Execution Loop\n phase = 'execution_loop';\n const executionResult = await this._executeTodoList(\n props, pesState!, availableTools, runtimeProviderConfig, traceId\n );\n\n llmCalls += executionResult.llmCalls;\n toolCallsCount += executionResult.toolCalls;\n if (executionResult.llmMetadata) aggregatedLlmMetadata = { ...(aggregatedLlmMetadata ?? {}), ...executionResult.llmMetadata };\n\n // Stage 5: Synthesis\n phase = 'synthesis';\n // Only synthesize if we have completed items or if we paused/stopped\n const { finalResponseContent, synthesisMetadata, uiMetadata } = await this._performSynthesis(\n props, synthesisSystemPrompt, history, pesState!, runtimeProviderConfig, traceId, finalPersona\n );\n llmCalls++;\n if (synthesisMetadata) aggregatedLlmMetadata = { ...(aggregatedLlmMetadata ?? {}), ...synthesisMetadata };\n\n // Stage 6: Finalization\n phase = 'finalization';\n finalAiMessage = await this._finalize(props, finalResponseContent, traceId, uiMetadata);\n\n } catch (error: any) {\n const artError = (error instanceof ARTError)\n ? error\n : new ARTError(`An unexpected error occurred during agent processing: ${error.message}`, ErrorCode.UNKNOWN_ERROR, error);\n\n artError.details = artError.details || {};\n artError.details.phase = phase;\n Logger.error(`[${traceId}] PESAgent process error in phase '${phase}':`, artError);\n\n status = 'error';\n errorMessage = artError.message;\n\n await this.deps.observationManager.record({\n threadId: props.threadId, traceId, type: ObservationType.ERROR,\n content: { phase, error: artError.message, stack: artError.stack },\n metadata: { timestamp: Date.now() }\n });\n } finally {\n try {\n await this.deps.stateManager.saveStateIfModified(props.threadId);\n } catch (saveError: any) {\n Logger.error(`[${traceId}] Failed to save state during finalization:`, saveError);\n }\n }\n\n const endTime = Date.now();\n const metadata: ExecutionMetadata = {\n threadId: props.threadId,\n traceId: traceId,\n userId: props.userId,\n status: status,\n totalDurationMs: endTime - startTime,\n llmCalls: llmCalls,\n toolCalls: toolCallsCount,\n error: errorMessage,\n llmMetadata: aggregatedLlmMetadata,\n };\n\n if (!finalAiMessage && status !== 'success') {\n finalAiMessage = {\n messageId: generateUUID(),\n threadId: props.threadId,\n role: MessageRole.AI,\n content: errorMessage ?? \"Agent execution failed.\",\n timestamp: Date.now(),\n metadata: { traceId, error: true }\n };\n }\n\n return {\n response: finalAiMessage!,\n metadata: metadata,\n };\n }\n\n // --- Helper Methods ---\n\n private async _saveState(threadId: string, pesState: PESAgentStateData) {\n await this.deps.stateManager.setAgentState(threadId, {\n data: pesState,\n version: 1,\n modified: Date.now()\n });\n }\n\n private async _recordPlanObservations(threadId: string, traceId: string, planningOutput: any, rawText: string) {\n await this.deps.observationManager.record({\n threadId, traceId, type: ObservationType.INTENT,\n content: { intent: planningOutput.intent }, metadata: { timestamp: Date.now() }\n });\n if (planningOutput.title) {\n await this.deps.observationManager.record({\n threadId, traceId, type: ObservationType.TITLE,\n content: { title: planningOutput.title }, metadata: { timestamp: Date.now() }\n });\n }\n await this.deps.observationManager.record({\n threadId, traceId, type: ObservationType.PLAN,\n content: {\n plan: planningOutput.plan,\n todoList: planningOutput.todoList,\n rawOutput: rawText\n },\n metadata: { timestamp: Date.now() }\n });\n // Also emit initial plan update\n await this.deps.observationManager.record({\n threadId, traceId, type: ObservationType.PLAN_UPDATE,\n content: { todoList: planningOutput.todoList },\n metadata: { timestamp: Date.now() }\n });\n }\n\n private async _performPlanning(\n props: AgentProps,\n systemPrompt: string,\n formattedHistory: ArtStandardPrompt,\n availableTools: any[],\n runtimeProviderConfig: RuntimeProviderConfig,\n traceId: string\n ) {\n Logger.debug(`[${traceId}] Stage 3: Planning`);\n\n const toolsJson = availableTools.map(t => ({\n name: t.name, description: t.description, inputSchema: t.inputSchema\n }));\n\n const wrappedSystemPrompt = `You are a planning assistant.\n[BEGIN_CUSTOM_GUIDANCE]\n${systemPrompt}\n[END_CUSTOM_GUIDANCE]\n\nYour goal is to understand the user's query and create a structured plan (Todo List) to answer it.\nThe todo list should be a logical, methodical, sensible list of steps that the agent should take to answer the user's query. Each step should progress gradually towards delivering a cmoprehensive, accurate, evidence driven, validated response.\nYou MUST output a JSON object with the following structure:\n{\n \"title\": \"Short title\",\n \"intent\": \"User intent summary\",\n \"plan\": \"High level description of the plan with and overview and bullet points\",\n \"todoList\": [\n { \"id\": \"step_1\", \"description\": \"Description of step 1\", \"dependencies\": [] },\n { \"id\": \"step_2\", \"description\": \"Description of step 2\", \"dependencies\": [\"step_1\"] }\n ]\n}\n`;\n const planningPrompt: ArtStandardPrompt = [\n { role: 'system', content: wrappedSystemPrompt },\n ...formattedHistory,\n { role: 'user', content: `User Query: ${props.query}\\n\\nAvailable Tools:\\n${JSON.stringify(toolsJson, null, 2)}` }\n ];\n\n return this._callPlanningLLM(planningPrompt, props, runtimeProviderConfig, traceId);\n }\n\n private async _performPlanRefinement(\n props: AgentProps,\n systemPrompt: string,\n formattedHistory: ArtStandardPrompt,\n currentState: PESAgentStateData,\n availableTools: any[],\n runtimeProviderConfig: RuntimeProviderConfig,\n traceId: string\n ) {\n Logger.debug(`[${traceId}] Stage 3: Plan Refinement`);\n\n const toolsJson = availableTools.map(t => ({\n name: t.name, description: t.description, inputSchema: t.inputSchema\n }));\n\n const wrappedSystemPrompt = `You are a planning assistant.\n[BEGIN_CUSTOM_GUIDANCE]\n${systemPrompt}\n[END_CUSTOM_GUIDANCE]\n\nThe user has provided a follow-up query. You must update the existing plan and todo list to accommodate this request.\nCurrent Plan:\nIntent: ${currentState.intent}\nTodo List:\n${JSON.stringify(currentState.todoList, null, 2)}\n\nOutput the updated JSON object (title, intent, plan, todoList). Ensure you preserve completed items and logically append or insert new items.\n`;\n const planningPrompt: ArtStandardPrompt = [\n { role: 'system', content: wrappedSystemPrompt },\n ...formattedHistory,\n { role: 'user', content: `User Query: ${props.query}\\n\\nAvailable Tools:\\n${JSON.stringify(toolsJson, null, 2)}` }\n ];\n\n return this._callPlanningLLM(planningPrompt, props, runtimeProviderConfig, traceId);\n }\n\n private async _callPlanningLLM(\n prompt: ArtStandardPrompt,\n props: AgentProps,\n runtimeProviderConfig: RuntimeProviderConfig,\n traceId: string\n ) {\n const planningOptions: CallOptions = {\n threadId: props.threadId, traceId, userId: props.userId, sessionId: props.sessionId,\n stream: true, callContext: 'AGENT_THOUGHT',\n requiredCapabilities: [ModelCapability.REASONING],\n providerConfig: runtimeProviderConfig,\n ...(props.options?.llmParams ?? {}),\n };\n\n let outputText = '';\n let metadata: LLMMetadata | undefined;\n let streamError: Error | null = null;\n\n try {\n await this.deps.observationManager.record({\n threadId: props.threadId, traceId, type: ObservationType.PLAN,\n content: { message: \"Generating/Refining Plan...\" }, metadata: { timestamp: Date.now() }\n });\n\n const stream = await this.deps.reasoningEngine.call(prompt, planningOptions);\n\n await this.deps.observationManager.record({\n threadId: props.threadId, traceId, type: ObservationType.LLM_STREAM_START,\n content: { phase: 'planning' }, metadata: { timestamp: Date.now() }\n });\n\n for await (const event of stream) {\n this.deps.uiSystem.getLLMStreamSocket().notify(event, {\n targetThreadId: event.threadId, targetSessionId: event.sessionId\n });\n\n if (event.type === 'TOKEN') {\n outputText += event.data;\n } else if (event.type === 'METADATA') {\n metadata = event.data;\n } else if (event.type === 'ERROR') {\n streamError = event.data;\n }\n }\n\n if (streamError) throw streamError;\n\n const parsed = await this.deps.outputParser.parsePlanningOutput(outputText);\n return { output: parsed, metadata, rawText: outputText };\n\n } catch (err: any) {\n throw new ARTError(`Planning failed: ${err.message}`, ErrorCode.PLANNING_FAILED, err);\n }\n }\n\n private async _executeTodoList(\n props: AgentProps,\n pesState: PESAgentStateData,\n availableTools: any[],\n runtimeProviderConfig: RuntimeProviderConfig,\n traceId: string\n ) {\n Logger.debug(`[${traceId}] Starting Execution Loop`);\n\n let llmCalls = 0;\n let toolCalls = 0;\n let accumulatedMetadata: LLMMetadata = {};\n\n // Loop until all items are completed or we hit a break condition\n let loopContinue = true;\n const MAX_LOOPS = 20;\n let loopCount = 0;\n\n while (loopContinue && loopCount < MAX_LOOPS) {\n loopCount++;\n\n // Find next pending item whose dependencies are met\n const pendingItem = pesState.todoList.find(item => {\n if (item.status !== TodoItemStatus.PENDING) return false;\n if (!item.dependencies || item.dependencies.length === 0) return true;\n return item.dependencies.every(depId => {\n const depItem = pesState.todoList.find(i => i.id === depId);\n return depItem && depItem.status === TodoItemStatus.COMPLETED;\n });\n });\n\n if (!pendingItem) {\n Logger.debug(`[${traceId}] No runnable pending items found.`);\n loopContinue = false;\n break;\n }\n\n Logger.debug(`[${traceId}] Executing Item: ${pendingItem.id}`);\n pesState.currentStepId = pendingItem.id;\n pendingItem.status = TodoItemStatus.IN_PROGRESS;\n pendingItem.updatedTimestamp = Date.now();\n\n // Persist status change\n await this._saveState(props.threadId, pesState);\n await this.deps.observationManager.record({\n threadId: props.threadId, traceId, type: ObservationType.ITEM_STATUS_CHANGE,\n content: { itemId: pendingItem.id, status: TodoItemStatus.IN_PROGRESS },\n parentId: pendingItem.id,\n metadata: { timestamp: Date.now() }\n });\n\n // Execute the item\n try {\n const itemResult = await this._processTodoItem(\n props, pendingItem, pesState, availableTools, runtimeProviderConfig, traceId\n );\n\n llmCalls += itemResult.llmCalls;\n toolCalls += itemResult.toolCalls;\n if (itemResult.metadata) {\n accumulatedMetadata = { ...accumulatedMetadata, ...itemResult.metadata };\n }\n\n if (itemResult.status === 'success') {\n pendingItem.status = TodoItemStatus.COMPLETED;\n pendingItem.result = itemResult.output;\n } else if (itemResult.status === 'wait') {\n pendingItem.status = TodoItemStatus.WAITING;\n } else {\n pendingItem.status = TodoItemStatus.FAILED;\n loopContinue = false;\n }\n\n } catch (err: any) {\n Logger.error(`[${traceId}] Error executing item ${pendingItem.id}:`, err);\n pendingItem.status = TodoItemStatus.FAILED;\n loopContinue = false;\n }\n\n pendingItem.updatedTimestamp = Date.now();\n await this._saveState(props.threadId, pesState);\n await this.deps.observationManager.record({\n threadId: props.threadId, traceId, type: ObservationType.ITEM_STATUS_CHANGE,\n content: { itemId: pendingItem.id, status: pendingItem.status },\n parentId: pendingItem.id,\n metadata: { timestamp: Date.now() }\n });\n }\n\n return { llmCalls, toolCalls, llmMetadata: accumulatedMetadata };\n }\n\n private async _processTodoItem(\n props: AgentProps,\n item: TodoItem,\n state: PESAgentStateData,\n availableTools: any[],\n runtimeProviderConfig: RuntimeProviderConfig,\n traceId: string\n ): Promise<{ status: 'success' | 'fail' | 'wait', output?: any, llmCalls: number, toolCalls: number, metadata?: LLMMetadata }> {\n\n let llmCalls = 0;\n let toolCallsCount = 0;\n let accumulatedMetadata: LLMMetadata = {};\n\n const toolsJson = availableTools.map(t => ({\n name: t.name, description: t.description, inputSchema: t.inputSchema\n }));\n\n // Add A2A delegation tool to execution context\n const delegationToolSchema = {\n name: 'delegate_to_agent',\n description: 'Delegates a specific task to another agent.',\n inputSchema: {\n type: 'object',\n properties: {\n agentId: { type: 'string' },\n taskType: { type: 'string' },\n input: { type: 'object' },\n instructions: { type: 'string' }\n },\n required: ['agentId', 'taskType', 'input', 'instructions']\n }\n };\n const executionTools = [...toolsJson, delegationToolSchema];\n\n const completedItemsContext = state.todoList\n .filter(i => i.status === TodoItemStatus.COMPLETED)\n .map(i => `Item ${i.id}: ${i.description}\\nResult: ${JSON.stringify(i.result)}`)\n .join('\\n\\n');\n\n const systemPromptText = `You are executing a step in a larger plan.\nCurrent Task: ${item.description}\nContext: ${props.query}\nPrevious Steps Results:\n${completedItemsContext}\nInstructions:\n1. Use tools if necessary.\n2. If you need to delegate to another agent, use 'delegate_to_agent'.\n3. If you learn new information that changes the plan, include 'updatedPlan' in your JSON output.\n4. Output Format: JSON response with 'content', 'toolCalls', 'updatedPlan', 'nextStepDecision'.\n`;\n\n const messages: ArtStandardPrompt = [\n { role: 'system', content: systemPromptText },\n { role: 'user', content: `Execute the task: ${item.description}\\n\\nAvailable Tools:\\n${JSON.stringify(executionTools)}` }\n ];\n\n const MAX_ITEM_ITERATIONS = 5;\n let iteration = 0;\n let itemDone = false;\n let finalOutput: string | undefined;\n let finalStatus: 'success' | 'fail' | 'wait' = 'success';\n\n while (!itemDone && iteration < MAX_ITEM_ITERATIONS) {\n iteration++;\n\n const options: CallOptions = {\n threadId: props.threadId, traceId, userId: props.userId, sessionId: props.sessionId,\n stream: true, callContext: 'AGENT_THOUGHT',\n requiredCapabilities: [ModelCapability.REASONING],\n providerConfig: runtimeProviderConfig,\n ...(props.options?.llmParams ?? {}),\n };\n\n let outputText = '';\n let streamError: Error | null = null;\n let currentMetadata: LLMMetadata | undefined;\n\n await this.deps.observationManager.record({\n threadId: props.threadId, traceId, type: ObservationType.LLM_STREAM_START,\n content: { phase: `execution_item_${item.id}_iter_${iteration}` },\n parentId: item.id,\n metadata: { timestamp: Date.now() }\n });\n\n const stream = await this.deps.reasoningEngine.call(messages, options);\n llmCalls++;\n\n for await (const event of stream) {\n this.deps.uiSystem.getLLMStreamSocket().notify(event, {\n targetThreadId: event.threadId, targetSessionId: event.sessionId\n });\n\n if (event.type === 'TOKEN') {\n outputText += event.data;\n if (event.tokenType && String(event.tokenType).includes('THINKING')) {\n await this.deps.observationManager.record({\n threadId: props.threadId,\n traceId,\n type: ObservationType.THOUGHTS,\n content: { text: event.data },\n parentId: item.id,\n metadata: { phase: 'execution', tokenType: event.tokenType, timestamp: Date.now() }\n }).catch(err => Logger.error(`[${traceId}] Failed to record THOUGHTS observation:`, err));\n }\n } else if (event.type === 'METADATA') {\n currentMetadata = event.data;\n } else if (event.type === 'ERROR') {\n streamError = event.data;\n }\n }\n\n if (streamError) throw streamError;\n if (currentMetadata) accumulatedMetadata = { ...accumulatedMetadata, ...currentMetadata };\n\n const parsed = await this.deps.outputParser.parseExecutionOutput(outputText);\n messages.push({ role: 'assistant', content: outputText });\n\n // Check for Plan Updates\n if (parsed.updatedPlan && parsed.updatedPlan.todoList) {\n Logger.info(`[${traceId}] Plan update received from execution step.`);\n state.todoList = parsed.updatedPlan.todoList;\n if (parsed.updatedPlan.intent) state.intent = parsed.updatedPlan.intent;\n if (parsed.updatedPlan.plan) state.plan = parsed.updatedPlan.plan;\n\n await this._saveState(props.threadId, state);\n await this.deps.observationManager.record({\n threadId: props.threadId, traceId, type: ObservationType.PLAN_UPDATE,\n content: { todoList: state.todoList },\n metadata: { timestamp: Date.now() }\n });\n }\n\n if (parsed.toolCalls && parsed.toolCalls.length > 0) {\n // Check for A2A delegation\n const a2aCalls = parsed.toolCalls.filter(tc => tc.toolName === 'delegate_to_agent');\n const localCalls = parsed.toolCalls.filter(tc => tc.toolName !== 'delegate_to_agent');\n\n let a2aTasks: A2ATask[] = [];\n\n if (a2aCalls.length > 0) {\n a2aTasks = await this._delegateA2ATasks({ toolCalls: a2aCalls }, props.threadId, traceId);\n // Wait for completion (blocking this item step)\n const completedTasks = await this._waitForA2ACompletion(a2aTasks, props.threadId, traceId);\n\n // Add results to messages\n completedTasks.forEach(task => {\n messages.push({\n role: 'tool_result',\n content: JSON.stringify(task.result || { error: 'Task failed' }),\n name: 'delegate_to_agent',\n tool_call_id: task.taskId // Assuming task ID maps to call ID\n });\n });\n }\n\n if (localCalls.length > 0) {\n const toolResults = await this.deps.toolSystem.executeTools(localCalls, props.threadId, traceId);\n toolCallsCount += toolResults.length;\n\n await this.deps.observationManager.record({\n threadId: props.threadId, traceId, type: ObservationType.TOOL_EXECUTION,\n content: { toolResults },\n parentId: item.id,\n metadata: { timestamp: Date.now() }\n });\n\n toolResults.forEach(res => {\n messages.push({\n role: 'tool_result',\n content: JSON.stringify(res.output || res.error),\n name: res.toolName,\n tool_call_id: res.callId\n });\n });\n }\n } else {\n itemDone = true;\n finalOutput = parsed.content;\n }\n }\n\n return {\n status: finalStatus,\n output: finalOutput,\n llmCalls,\n toolCalls: toolCallsCount,\n metadata: accumulatedMetadata\n };\n }\n\n private async _performSynthesis(\n props: AgentProps,\n systemPrompt: string,\n formattedHistory: ArtStandardPrompt,\n state: PESAgentStateData,\n runtimeProviderConfig: RuntimeProviderConfig,\n traceId: string,\n finalPersona: AgentPersona\n ) {\n Logger.debug(`[${traceId}] Stage 6: Synthesis`);\n\n const completedItems = state.todoList.filter(i => i.status === TodoItemStatus.COMPLETED);\n const failedItems = state.todoList.filter(i => i.status === TodoItemStatus.FAILED);\n\n const summary = `\nCompleted Tasks:\n${completedItems.map(i => `- ${i.description}: ${JSON.stringify(i.result).substring(0, 200)}...`).join('\\n')}\n\nFailed Tasks:\n${failedItems.map(i => `- ${i.description}`).join('\\n')}\n`;\n\n const wrappedSynthesisSystemPrompt = `You are ${finalPersona.name}.\n[BEGIN_CUSTOM_GUIDANCE]\n${systemPrompt}\n[END_CUSTOM_GUIDANCE]\n\nSynthesize the final answer based on the completed tasks.\nFormat your response with <mainContent>...</mainContent> for the user message and <uiMetadata>...</uiMetadata> for metadata (JSON).\n`;\n const synthesisPrompt: ArtStandardPrompt = [\n { role: 'system', content: wrappedSynthesisSystemPrompt },\n ...formattedHistory,\n { role: 'user', content: `User Query: ${props.query}\\n\\nWork Summary:\\n${summary}` }\n ];\n\n const synthesisOptions: CallOptions = {\n threadId: props.threadId,\n traceId: traceId,\n userId: props.userId,\n sessionId: props.sessionId,\n stream: true,\n callContext: 'FINAL_SYNTHESIS',\n requiredCapabilities: [ModelCapability.TEXT],\n providerConfig: runtimeProviderConfig,\n ...(props.options?.llmParams ?? {}),\n };\n\n let finalResponseContent: string = '';\n let synthesisMetadata: LLMMetadata | undefined = undefined;\n\n // ... Stream handling same as before ...\n // Re-using stream logic for synthesis\n const stream = await this.deps.reasoningEngine.call(synthesisPrompt, synthesisOptions);\n\n await this.deps.observationManager.record({\n threadId: props.threadId, traceId, type: ObservationType.LLM_STREAM_START,\n content: { phase: 'synthesis' }, metadata: { timestamp: Date.now() }\n });\n\n for await (const event of stream) {\n this.deps.uiSystem.getLLMStreamSocket().notify(event, {\n targetThreadId: event.threadId, targetSessionId: event.sessionId\n });\n if (event.type === 'TOKEN') {\n if (event.tokenType === 'FINAL_SYNTHESIS_LLM_RESPONSE' || event.tokenType === 'LLM_RESPONSE') {\n finalResponseContent += event.data;\n }\n } else if (event.type === 'METADATA') {\n synthesisMetadata = event.data;\n }\n }\n\n // Parse metadata block (same as before)\n let mainContent = finalResponseContent;\n let uiMetadata: object | undefined = undefined;\n const metadataBlockRegex = /```json\\s*([\\s\\S]*?)\\s*```$/;\n const match = finalResponseContent.match(metadataBlockRegex);\n if (match && match[1]) {\n mainContent = finalResponseContent.replace(metadataBlockRegex, '').trim();\n try { uiMetadata = JSON.parse(match[1]); } catch { }\n }\n\n return { finalResponseContent: mainContent, synthesisMetadata, uiMetadata };\n }\n\n private async _loadConfiguration(props: AgentProps, traceId: string) {\n // ... (Same as original implementation) ...\n // To save tokens/lines in this overwite, assuming I keep the exact same logic.\n // For brevity in this tool call, I'll copy-paste the logic from the original file I read.\n Logger.debug(`[${traceId}] Stage 1: Initiation & Config`);\n\n const threadContext = await this.deps.stateManager.loadThreadContext(props.threadId, props.userId);\n if (!threadContext) {\n throw new ARTError(`Thread context not found for threadId: ${props.threadId}`, ErrorCode.THREAD_NOT_FOUND);\n }\n\n const callPersona = props.options?.persona;\n const threadPersona = await this.deps.stateManager.getThreadConfigValue<Partial<AgentPersona>>(props.threadId, 'persona');\n const instancePersona = this.persona;\n\n const finalPersona: AgentPersona = {\n name: callPersona?.name || threadPersona?.name || instancePersona.name,\n prompts: {\n planning: callPersona?.prompts?.planning || threadPersona?.prompts?.planning || instancePersona.prompts.planning,\n synthesis: callPersona?.prompts?.synthesis || threadPersona?.prompts?.synthesis || instancePersona.prompts.synthesis,\n },\n };\n\n const planningSystemPrompt = await this.deps.systemPromptResolver.resolve({\n base: finalPersona.prompts.planning || '',\n thread: await this.deps.stateManager.getThreadConfigValue<any>(props.threadId, 'systemPrompt'),\n call: props.options?.systemPrompt\n }, traceId);\n\n const synthesisSystemPrompt = await this.deps.systemPromptResolver.resolve({\n base: finalPersona.prompts.synthesis || '',\n thread: await this.deps.stateManager.getThreadConfigValue<any>(props.threadId, 'systemPrompt'),\n call: props.options?.systemPrompt\n }, traceId);\n\n const runtimeProviderConfig: RuntimeProviderConfig | undefined =\n props.options?.providerConfig || threadContext.config.providerConfig;\n\n if (!runtimeProviderConfig) {\n throw new ARTError(`RuntimeProviderConfig is missing in AgentProps.options or ThreadConfig for threadId: ${props.threadId}`, ErrorCode.INVALID_CONFIG);\n }\n\n return {\n threadContext,\n planningSystemPrompt,\n synthesisSystemPrompt,\n runtimeProviderConfig,\n finalPersona\n };\n }\n\n private async _gatherHistory(threadId: string, threadContext: any) {\n // Same as original\n Logger.debug(`[${threadContext.threadId || threadId}] Stage 2: Gathering History`);\n const historyOptions = { limit: threadContext.config.historyLimit };\n const rawHistory = await this.deps.conversationManager.getMessages(threadId, historyOptions);\n return this.formatHistoryForPrompt(rawHistory);\n }\n\n private async _gatherTools(threadId: string) {\n // Same as original\n Logger.debug(`[${threadId}] Stage 2: Gathering Tools`);\n return await this.deps.toolRegistry.getAvailableTools({ enabledForThreadId: threadId });\n }\n\n // --- Restored A2A Logic ---\n private async _delegateA2ATasks(\n planningOutput: { toolCalls?: ParsedToolCall[] },\n threadId: string,\n traceId: string\n ): Promise<A2ATask[]> {\n Logger.debug(`[${traceId}] Stage 4: A2A Task Delegation`);\n\n const delegationCalls = planningOutput.toolCalls?.filter(\n call => call.toolName === 'delegate_to_agent'\n ) ?? [];\n\n if (delegationCalls.length === 0) {\n Logger.debug(`[${traceId}] No A2A delegation calls in the plan.`);\n return [];\n }\n\n if (!this.deps.taskDelegationService || !this.deps.agentDiscoveryService) {\n Logger.warn(`[${traceId}] A2A services not available. Skipping delegation.`);\n return [];\n }\n\n const delegatedTasks: A2ATask[] = [];\n for (const call of delegationCalls) {\n try {\n const args = call.arguments;\n const { agentId, taskType, input, instructions } = args;\n\n const allAgents = await this.deps.agentDiscoveryService.discoverAgents(traceId);\n const targetAgent = allAgents.find(a => a.agentId === agentId);\n\n if (!targetAgent) {\n throw new Error(`Agent with ID \"${agentId}\" not found during delegation.`);\n }\n\n const now = Date.now();\n const a2aTask: A2ATask = {\n taskId: call.callId,\n threadId: threadId,\n status: A2ATaskStatus.PENDING,\n payload: { taskType, input, instructions, parameters: { threadId, traceId } },\n sourceAgent: { agentId: 'pes-agent', agentName: 'PES Agent', agentType: 'orchestrator' },\n targetAgent: targetAgent,\n priority: A2ATaskPriority.MEDIUM,\n metadata: {\n createdAt: now, updatedAt: now, initiatedBy: threadId, correlationId: traceId,\n retryCount: 0, maxRetries: 3, timeoutMs: 60000, tags: ['delegated', taskType]\n }\n };\n\n await this.deps.a2aTaskRepository.createTask(a2aTask);\n\n const delegatedTask = await this.deps.taskDelegationService.delegateTask(a2aTask, traceId);\n if (delegatedTask) {\n delegatedTasks.push(delegatedTask);\n }\n } catch (err: any) {\n Logger.error(`[${traceId}] Failed to process and delegate A2A task for call ${call.callId}:`, err);\n await this.deps.observationManager.record({\n threadId, traceId, type: ObservationType.ERROR,\n content: { phase: 'a2a_delegation', error: `Delegation for call ${call.callId} failed: ${err.message}` },\n metadata: { timestamp: Date.now() }\n });\n }\n }\n\n Logger.info(`[${traceId}] Successfully initiated delegation for ${delegatedTasks.length}/${delegationCalls.length} A2A task(s).`);\n return delegatedTasks;\n }\n\n private async _waitForA2ACompletion(\n a2aTasks: A2ATask[],\n threadId: string,\n traceId: string,\n maxWaitTimeMs: number = 30000,\n pollIntervalMs: number = 2000\n ): Promise<A2ATask[]> {\n if (a2aTasks.length === 0) {\n return a2aTasks;\n }\n\n Logger.debug(`[${traceId}] Waiting for ${a2aTasks.length} A2A task(s) to complete (timeout: ${maxWaitTimeMs}ms)`);\n\n const startTime = Date.now();\n const updatedTasks: A2ATask[] = [...a2aTasks];\n\n try {\n while ((Date.now() - startTime) < maxWaitTimeMs) {\n const incompleteTasks = updatedTasks.filter(task =>\n task.status !== A2ATaskStatus.COMPLETED &&\n task.status !== A2ATaskStatus.FAILED &&\n task.status !== A2ATaskStatus.CANCELLED\n );\n\n if (incompleteTasks.length === 0) {\n Logger.info(`[${traceId}] All A2A tasks completed successfully`);\n break;\n }\n\n Logger.debug(`[${traceId}] Waiting for ${incompleteTasks.length} A2A task(s) to complete...`);\n\n for (let i = 0; i < updatedTasks.length; i++) {\n const task = updatedTasks[i];\n\n if (task.status === A2ATaskStatus.COMPLETED ||\n task.status === A2ATaskStatus.FAILED ||\n task.status === A2ATaskStatus.CANCELLED) {\n continue;\n }\n\n try {\n const latestTask = await this.deps.a2aTaskRepository.getTask(task.taskId);\n if (latestTask) {\n updatedTasks[i] = latestTask;\n }\n } catch (error: any) {\n Logger.warn(`[${traceId}] Failed to get updated status for task ${task.taskId}:`, error);\n }\n }\n\n await new Promise(resolve => setTimeout(resolve, pollIntervalMs));\n }\n\n return updatedTasks;\n\n } catch (error: any) {\n Logger.error(`[${traceId}] Error during A2A task waiting:`, error);\n return updatedTasks;\n }\n }\n\n\n private async _finalize(props: AgentProps, finalResponseContent: string, traceId: string, uiMetadata?: object): Promise<ConversationMessage> {\n // Same as original\n Logger.debug(`[${traceId}] Stage 7: Finalization`);\n const finalTimestamp = Date.now();\n const finalAiMessage: ConversationMessage = {\n messageId: generateUUID(),\n threadId: props.threadId,\n role: MessageRole.AI,\n content: finalResponseContent,\n timestamp: finalTimestamp,\n metadata: { traceId },\n };\n await this.deps.conversationManager.addMessages(props.threadId, [finalAiMessage]);\n await this.deps.observationManager.record({\n threadId: props.threadId,\n traceId,\n type: ObservationType.FINAL_RESPONSE,\n content: { message: finalAiMessage, uiMetadata: uiMetadata },\n metadata: { timestamp: finalTimestamp }\n });\n return finalAiMessage;\n }\n\n private formatHistoryForPrompt(history: ConversationMessage[]): ArtStandardPrompt {\n // Same as original\n return history.map((msg) => {\n let role: ArtStandardMessageRole;\n switch (msg.role) {\n case MessageRole.USER: role = 'user'; break;\n case MessageRole.AI: role = 'assistant'; break;\n case MessageRole.SYSTEM: role = 'system'; break;\n case MessageRole.TOOL: role = 'tool'; break;\n default: role = 'user';\n }\n return { role: role, content: msg.content };\n }).filter(msg => msg.content);\n }\n}\n","import { StorageAdapter } from '@/core/interfaces';\nimport { FilterOptions } from '@/types';\n\n/**\n * An in-memory implementation of the `StorageAdapter` interface.\n * Stores all data in JavaScript Maps within the current process memory.\n * Data is **not persisted** and will be lost when the application session ends.\n *\n * Useful for:\n * - Unit and integration testing (fast, no external dependencies).\n * - Simple demos or examples where persistence isn't needed.\n * - Ephemeral agents that don't require long-term memory.\n *\n * It provides a simple key-value store for various data types used within the\n * ART framework, such as conversation history, agent state, and observations.\n *\n * @see {@link StorageAdapter} for the interface definition.\n */\nexport class InMemoryStorageAdapter implements StorageAdapter {\n private storage: Map<string, Map<string, any>> = new Map();\n\n /**\n * Creates an instance of InMemoryStorageAdapter.\n * @see StorageAdapter\n */\n constructor() {\n // No-op\n }\n\n /**\n * Initializes the adapter. This is a no-op for the in-memory adapter\n * and is provided for interface compatibility.\n * @param _config - Optional configuration (ignored by this adapter).\n * @returns A promise that resolves immediately.\n */\n async init(_config?: any): Promise<void> { // Renamed config to _config\n // No initialization needed for in-memory storage\n return Promise.resolve();\n }\n\n /**\n * Retrieves a single item (as a deep copy) from a specified collection by its ID.\n * @template T - The expected type of the retrieved item.\n * @param collection - The name of the data collection (e.g., 'messages', 'observations').\n * @param id - The unique ID of the item within the collection.\n * @returns A promise resolving to a deep copy of the item if found, or `null` otherwise.\n */\n async get<T>(collection: string, id: string): Promise<T | null> {\n const collectionMap = this.storage.get(collection);\n if (!collectionMap) {\n return null;\n }\n const item = collectionMap.get(id);\n // Return a deep copy to prevent accidental modification of the stored object\n return item ? JSON.parse(JSON.stringify(item)) : null;\n }\n\n /**\n * Saves (creates or updates) an item in a specified collection.\n * Stores a deep copy of the provided data to prevent external mutations.\n * @template T - The type of the data being saved.\n * @param collection - The name of the collection.\n * @param id - The unique ID for the item.\n * @param data - The data object to save.\n * @returns A promise that resolves when the data is saved in memory.\n */\n async set<T>(collection: string, id: string, data: T): Promise<void> {\n if (!this.storage.has(collection)) {\n this.storage.set(collection, new Map());\n }\n const collectionMap = this.storage.get(collection)!;\n // Store a deep copy to prevent external modifications affecting the store\n collectionMap.set(id, JSON.parse(JSON.stringify(data)));\n return Promise.resolve();\n }\n\n /**\n * Deletes an item from a specified collection using its ID.\n * If the collection or item does not exist, the operation completes silently.\n * @param collection - The name of the collection.\n * @param id - The unique ID of the item to delete.\n * @returns A promise that resolves when the deletion attempt is complete.\n */\n async delete(collection: string, id: string): Promise<void> {\n const collectionMap = this.storage.get(collection);\n if (collectionMap) {\n collectionMap.delete(id);\n }\n return Promise.resolve();\n }\n\n /**\n * Queries items within a collection based on provided filter options.\n * **Note:** This in-memory implementation provides basic filtering capabilities:\n * - Supports exact matches on top-level properties specified in `filterOptions.filter`.\n * - Supports limiting results via `filterOptions.limit`.\n * - **Does not** support sorting (`filterOptions.sort`), skipping (`filterOptions.skip`), complex operators (like $gt, $in), or nested property filtering.\n * @template T - The expected type of the items in the collection.\n * @param collection - The name of the collection to query.\n * @param filterOptions - Options for filtering and limiting the results.\n * @returns A promise resolving to an array of deep copies of the matching items.\n */\n async query<T>(collection: string, filterOptions: FilterOptions): Promise<T[]> {\n const collectionMap = this.storage.get(collection);\n if (!collectionMap) {\n return [];\n }\n\n let results = Array.from(collectionMap.values());\n\n // Basic filtering (exact match on top-level properties)\n if (filterOptions.filter) {\n results = results.filter(item => {\n for (const key in filterOptions.filter) {\n // eslint-disable-next-line no-prototype-builtins\n if (filterOptions.filter.hasOwnProperty(key)) {\n // Use type assertion carefully or add more robust checks\n if ((item as any)[key] !== (filterOptions.filter as any)[key]) {\n return false;\n }\n }\n }\n return true;\n });\n }\n\n // Basic limit\n if (typeof filterOptions.limit === 'number' && filterOptions.limit >= 0) {\n results = results.slice(0, filterOptions.limit);\n }\n\n // Return deep copies\n return JSON.parse(JSON.stringify(results));\n }\n\n /**\n * Removes all items from a specific collection within the in-memory store.\n * @param collection - The name of the collection to clear.\n * @returns A promise that resolves when the collection is cleared.\n */\n async clearCollection(collection: string): Promise<void> {\n this.storage.delete(collection);\n return Promise.resolve();\n }\n\n /**\n * Removes all collections and all data stored within the adapter instance.\n * Use with caution, especially during testing.\n * @returns A promise that resolves when all data is cleared.\n */\n async clearAll(): Promise<void> {\n this.storage.clear();\n return Promise.resolve();\n }\n}","import { StorageAdapter } from '@/core/interfaces';\nimport { FilterOptions } from '@/types';\nimport { Logger } from '@/utils/logger'; // Import Logger at top level\n\n// Default configuration\nconst DEFAULT_DB_NAME = 'ART_Framework_DB';\nconst DEFAULT_DB_VERSION = 1; // Increment this when object stores change\n\n/**\n * Configuration options for initializing the `IndexedDBStorageAdapter`.\n */\nexport interface IndexedDBConfig {\n /** The name of the IndexedDB database to use. Defaults to 'ART_Framework_DB'. */\n dbName?: string;\n /** The version of the database schema. Increment this when changing `objectStores` or indexes to trigger an upgrade. Defaults to 1. */\n dbVersion?: number;\n /** An array of strings specifying the names of the object stores (collections) required by the application. Core stores like 'conversations', 'observations', 'state' are usually added automatically. */\n objectStores: string[];\n}\n\n/**\n * An implementation of the `StorageAdapter` interface that uses the browser's\n * IndexedDB API for persistent, client-side storage.\n *\n * This adapter is suitable for web applications where conversation history,\n * agent state, and observations need to persist across sessions.\n *\n * **Important:** The `init()` method *must* be called and awaited before performing\n * any other database operations (get, set, delete, query).\n *\n * @see {@link StorageAdapter} for the interface it implements.\n * @see {@link IndexedDBConfig} for configuration options.\n */\nexport class IndexedDBStorageAdapter implements StorageAdapter {\n private db: IDBDatabase | null = null;\n private dbName: string;\n private dbVersion: number;\n private requiredObjectStores: Set<string>;\n private initPromise: Promise<void> | null = null;\n\n /**\n * Creates an instance of IndexedDBStorageAdapter.\n * Note: The database connection is not opened until `init()` is called.\n * @param {module:integrations/storage/indexedDB.IndexedDBConfig} config - Configuration options including database name, version, and required object stores.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API\n */\n constructor(config: IndexedDBConfig) {\n this.dbName = config.dbName || DEFAULT_DB_NAME;\n this.dbVersion = config.dbVersion || DEFAULT_DB_VERSION;\n // Ensure core stores used by default repositories are included\n this.requiredObjectStores = new Set([\n 'conversations', // Used by ConversationRepository\n 'observations', // Used by ObservationRepository\n 'state', // Used by StateRepository\n 'a2a_tasks', // Used by TaskStatusRepository\n ...(config.objectStores || []) // Add any user-defined stores\n ]);\n }\n\n /**\n * Opens the IndexedDB database connection and ensures the required object stores\n * are created or updated based on the configured `dbVersion`.\n * This method MUST be called and awaited successfully before using other adapter methods.\n * It handles the `onupgradeneeded` event to create stores.\n * @returns A promise that resolves when the database is successfully opened and ready, or rejects on error.\n */\n async init(): Promise<void> {\n // Prevent multiple initializations\n if (this.initPromise) {\n return this.initPromise;\n }\n\n this.initPromise = new Promise((resolve, reject) => {\n if (!('indexedDB' in window)) {\n Logger.error(\"IndexedDBStorageAdapter: IndexedDB not supported in this browser.\"); // Use Logger\n return reject(new Error(\"IndexedDB not supported\"));\n }\n\n const request = indexedDB.open(this.dbName, this.dbVersion);\n\n request.onerror = (event) => {\n Logger.error(`IndexedDBStorageAdapter: Database error: ${request.error}`, event); // Use Logger\n reject(new Error(`IndexedDB error: ${request.error?.message}`));\n };\n\n request.onsuccess = (event) => {\n this.db = (event.target as IDBOpenDBRequest).result;\n Logger.info(`IndexedDBStorageAdapter: Database '${this.dbName}' opened successfully (Version: ${this.db.version}).`); // Use Logger\n\n // Optional: Check if all required stores actually exist after opening\n const existingStores = new Set(Array.from(this.db.objectStoreNames));\n const missingStores = [...this.requiredObjectStores].filter(store => !existingStores.has(store));\n if (missingStores.length > 0) {\n Logger.warn(`IndexedDBStorageAdapter: The following required object stores were not found after opening DB version ${this.db.version}: ${missingStores.join(', ')}. This might happen if the DB version wasn't incremented after adding stores.`); // Use Logger\n // Depending on strictness, you might reject here\n }\n\n this.db.onerror = (errorEvent) => {\n // Generic error handler for the database connection\n Logger.error(`IndexedDBStorageAdapter: Generic database error:`, errorEvent); // Use Logger\n };\n resolve();\n };\n\n request.onupgradeneeded = (event) => {\n Logger.info(`IndexedDBStorageAdapter: Upgrading database '${this.dbName}' from version ${event.oldVersion} to ${event.newVersion}...`); // Use Logger\n this.db = (event.target as IDBOpenDBRequest).result;\n const transaction = (event.target as IDBOpenDBRequest).transaction; // Get transaction for upgrade\n\n if (!transaction) {\n Logger.error(\"IndexedDBStorageAdapter: Upgrade transaction is null!\"); // Use Logger\n reject(new Error(\"Upgrade transaction failed\"));\n return;\n }\n\n const existingStoreNames = new Set(Array.from(this.db.objectStoreNames));\n\n this.requiredObjectStores.forEach(storeName => {\n if (!existingStoreNames.has(storeName)) {\n Logger.info(`IndexedDBStorageAdapter: Creating object store '${storeName}'...`); // Use Logger\n // Use 'id' as the key path, assuming all stored objects will have an 'id' property.\n // If not, a different key strategy or autoIncrement might be needed.\n // For flexibility, we might need a config per store, but 'id' is common.\n this.db?.createObjectStore(storeName, { keyPath: 'id' });\n // TODO: Consider adding indexes here if needed for query performance based on FilterOptions\n // Example: store.createIndex('by_type', 'type', { unique: false });\n }\n // Handle index creation/updates or data migration if necessary for existing stores\n });\n\n // Example: Removing old stores if needed (use with caution)\n // existingStoreNames.forEach(storeName => {\n // if (!this.requiredObjectStores.has(storeName)) {\n // Logger.info(`IndexedDBStorageAdapter: Deleting old object store '${storeName}'...`); // Use Logger\n // this.db?.deleteObjectStore(storeName);\n // }\n // });\n\n Logger.info(`IndexedDBStorageAdapter: Database upgrade complete.`); // Use Logger\n // Note: onsuccess will be called automatically after onupgradeneeded completes.\n };\n\n request.onblocked = (event) => {\n // This event fires if the database is open in another tab/window with an older version\n Logger.warn(`IndexedDBStorageAdapter: Database open request blocked for '${this.dbName}'. Please close other tabs/connections using an older version of this database.`, event); // Use Logger\n reject(new Error(`IndexedDB open blocked for ${this.dbName}. Close other connections.`));\n };\n\n });\n\n return this.initPromise;\n }\n\n // --- Helper Method to get a transaction ---\n /**\n * Helper method to create and return an IndexedDB transaction.\n * Ensures the database is initialized and the requested store(s) exist.\n * @param storeName - The name of the object store or an array of store names for the transaction.\n * @param mode - The transaction mode ('readonly' or 'readwrite').\n * @returns The initiated IDBTransaction.\n * @throws {Error} If the database is not initialized or if a requested store does not exist.\n */\n private getTransaction(storeName: string | string[], mode: IDBTransactionMode): IDBTransaction {\n if (!this.db) {\n // It's crucial init() was awaited, but add runtime check.\n throw new Error(\"IndexedDBStorageAdapter: Database not initialized. Ensure init() was called and awaited.\");\n }\n // Check if the requested store exists\n const storesToCheck = Array.isArray(storeName) ? storeName : [storeName];\n storesToCheck.forEach(sName => {\n if (!this.db?.objectStoreNames.contains(sName)) {\n throw new Error(`IndexedDBStorageAdapter: Object store \"${sName}\" does not exist in the database.`);\n }\n });\n\n return this.db.transaction(storeName, mode);\n }\n\n // --- CRUD Methods ---\n\n /**\n * Retrieves a single item by its ID from the specified object store (collection).\n * @template T - The expected type of the retrieved item.\n * @param collection - The name of the object store.\n * @param id - The ID (key) of the item to retrieve.\n * @returns A promise resolving to a copy of the item if found, or `null` otherwise.\n * @throws {Error} If the database is not initialized, the store doesn't exist, or a database error occurs.\n */\n async get<T>(collection: string, id: string): Promise<T | null> {\n await this.init(); // Ensure DB is ready (init is idempotent)\n return new Promise((resolve, reject) => {\n try {\n const transaction = this.getTransaction(collection, 'readonly');\n const store = transaction.objectStore(collection);\n const request = store.get(id);\n\n request.onsuccess = () => {\n // Return a copy? IndexedDB usually returns structured clones already,\n // but explicit copy might be safer depending on usage.\n resolve(request.result ? { ...request.result } : null);\n };\n\n request.onerror = () => {\n Logger.error(`IndexedDBStorageAdapter: Error getting item '${id}' from '${collection}':`, request.error); // Use Logger\n reject(new Error(`Failed to get item: ${request.error?.message}`));\n };\n } catch (error) {\n reject(error); // Catch errors from getTransaction (e.g., store not found)\n }\n });\n }\n\n // Removed the 'extends { id: string }' constraint to match the interface\n /**\n * Saves (creates or updates) an item in the specified object store (collection).\n * Assumes the object store uses 'id' as its keyPath. The `id` parameter provided\n * should match the `id` property within the `data` object.\n * Uses `structuredClone` to store a deep copy.\n * @template T - The type of the data being saved. Must have an 'id' property.\n * @param collection - The name of the object store.\n * @param id - The unique ID of the item (should match `data.id`).\n * @param data - The data object to save. Must contain an `id` property matching the `id` parameter.\n * @returns A promise that resolves when the data is successfully saved.\n * @throws {Error} If the database is not initialized, the store doesn't exist, data is missing the 'id' property, or a database error occurs.\n */\n async set<T>(collection: string, id: string, data: T): Promise<void> {\n // Runtime check: Ensure data has the 'id' property matching the keyPath\n // We cast to 'any' here because T doesn't guarantee 'id' exists at compile time anymore.\n const dataAsAny = data as any;\n if (typeof dataAsAny.id === 'undefined') {\n return Promise.reject(new Error(`IndexedDBStorageAdapter: Data for collection '${collection}' must have an 'id' property matching the keyPath.`));\n }\n if (dataAsAny.id !== id) {\n Logger.warn(`IndexedDBStorageAdapter: Provided id ('${id}') and data.id ('${dataAsAny.id}') mismatch for collection '${collection}'. Using data.id as the key.`); // Use Logger\n // Optionally throw an error or enforce consistency based on project needs.\n // For now, we proceed using data.id as the key for the put operation.\n }\n\n\n await this.init(); // Ensure DB is ready\n return new Promise((resolve, reject) => {\n try {\n // Use structuredClone for a robust deep copy before storing\n const dataToStore = structuredClone(data);\n const transaction = this.getTransaction(collection, 'readwrite');\n const store = transaction.objectStore(collection);\n // Use the id from the data object itself, as it's the keyPath\n const request = store.put(dataToStore); // put = insert or update\n\n request.onsuccess = () => {\n resolve();\n };\n\n request.onerror = () => {\n // Use dataAsAny.id in the error message as it's the actual key used\n Logger.error(`IndexedDBStorageAdapter: Error setting item with id '${dataAsAny.id}' in '${collection}':`, request.error); // Use Logger\n reject(new Error(`Failed to set item: ${request.error?.message}`));\n };\n\n transaction.oncomplete = () => {\n // Transaction completed successfully (optional logging)\n };\n\n transaction.onerror = (event) => {\n // Use dataAsAny.id in the error message\n Logger.error(`IndexedDBStorageAdapter: Transaction error setting item with id '${dataAsAny.id}' in '${collection}':`, transaction.error, event); // Use Logger\n reject(new Error(`Transaction failed: ${transaction.error?.message}`));\n };\n } catch (error) {\n reject(error);\n }\n });\n }\n\n /**\n * Deletes an item from the specified object store (collection) by its ID.\n * @param collection - The name of the object store.\n * @param id - The ID (key) of the item to delete.\n * @returns A promise that resolves when the deletion is successful.\n * @throws {Error} If the database is not initialized, the store doesn't exist, or a database error occurs.\n */\n async delete(collection: string, id: string): Promise<void> {\n await this.init(); // Ensure DB is ready\n return new Promise((resolve, reject) => {\n try {\n const transaction = this.getTransaction(collection, 'readwrite');\n const store = transaction.objectStore(collection);\n const request = store.delete(id);\n\n request.onsuccess = () => {\n resolve();\n };\n\n request.onerror = () => {\n Logger.error(`IndexedDBStorageAdapter: Error deleting item '${id}' from '${collection}':`, request.error); // Use Logger\n reject(new Error(`Failed to delete item: ${request.error?.message}`));\n };\n\n transaction.onerror = (event) => {\n Logger.error(`IndexedDBStorageAdapter: Transaction error deleting item '${id}' from '${collection}':`, transaction.error, event); // Use Logger\n reject(new Error(`Transaction failed: ${transaction.error?.message}`));\n };\n } catch (error) {\n reject(error);\n }\n });\n }\n\n /**\n * Queries items within a collection based on provided filter options.\n * **Note:** This implementation uses `getAll()` and performs filtering, sorting,\n * and limiting **client-side**. For large datasets, performance may be suboptimal.\n * A more advanced version would leverage IndexedDB indexes and cursors for\n * efficient querying directly within the database.\n * Supports basic exact-match filtering and single-key sorting.\n * @template T - The expected type of the items in the collection.\n * @param collection - The name of the object store to query.\n * @param filterOptions - Options for filtering, sorting, skipping, and limiting results.\n * @returns A promise resolving to an array of deep copies of the matching items.\n * @throws {Error} If the database is not initialized, the store doesn't exist, or a database error occurs.\n * @remarks TODO: Implement more advanced querying using IndexedDB indexes and cursors.\n * This will improve performance for large datasets.\n */\n async query<T>(collection: string, filterOptions: FilterOptions): Promise<T[]> {\n await this.init(); // Ensure DB is ready\n return new Promise((resolve, reject) => {\n try {\n const transaction = this.getTransaction(collection, 'readonly');\n const store = transaction.objectStore(collection);\n const request = store.getAll(); // Get all records\n\n request.onsuccess = () => {\n let results: T[] = request.result || [];\n\n // Client-side filtering (basic exact match)\n if (filterOptions.filter) {\n results = results.filter(item => {\n for (const key in filterOptions.filter) {\n // eslint-disable-next-line no-prototype-builtins\n if (filterOptions.filter.hasOwnProperty(key)) {\n if ((item as any)[key] !== (filterOptions.filter as any)[key]) {\n return false;\n }\n }\n }\n return true;\n });\n }\n\n // Client-side sorting (basic single key)\n if (filterOptions.sort) {\n const sortKey = Object.keys(filterOptions.sort)[0];\n const sortDir = filterOptions.sort[sortKey];\n if (sortKey) {\n results.sort((a, b) => {\n const valA = (a as any)[sortKey];\n const valB = (b as any)[sortKey];\n if (valA < valB) return sortDir === 'asc' ? -1 : 1;\n if (valA > valB) return sortDir === 'asc' ? 1 : -1;\n return 0;\n });\n }\n }\n\n // Client-side skip/limit\n const skip = filterOptions.skip || 0;\n const limit = filterOptions.limit ?? Infinity; // Default to no limit if undefined\n results = results.slice(skip, skip + limit);\n\n\n // Return copies\n resolve(results.map(item => ({ ...item })));\n };\n\n request.onerror = () => {\n Logger.error(`IndexedDBStorageAdapter: Error querying collection '${collection}':`, request.error); // Use Logger\n reject(new Error(`Failed to query collection: ${request.error?.message}`));\n };\n } catch (error) {\n reject(error);\n }\n });\n }\n\n /**\n * Removes all items from a specific object store (collection).\n * @param collection - The name of the object store to clear.\n * @returns A promise that resolves when the collection is successfully cleared.\n * @throws {Error} If the database is not initialized, the store doesn't exist, or a database error occurs.\n */\n async clearCollection(collection: string): Promise<void> {\n await this.init(); // Ensure DB is ready\n return new Promise((resolve, reject) => {\n try {\n const transaction = this.getTransaction(collection, 'readwrite');\n const store = transaction.objectStore(collection);\n const request = store.clear();\n\n request.onsuccess = () => {\n resolve();\n };\n\n request.onerror = () => {\n Logger.error(`IndexedDBStorageAdapter: Error clearing collection '${collection}':`, request.error); // Use Logger\n reject(new Error(`Failed to clear collection: ${request.error?.message}`));\n };\n\n transaction.onerror = (event) => {\n Logger.error(`IndexedDBStorageAdapter: Transaction error clearing collection '${collection}':`, transaction.error, event); // Use Logger\n reject(new Error(`Transaction failed: ${transaction.error?.message}`));\n };\n } catch (error) {\n reject(error);\n }\n });\n }\n\n /**\n * Removes all data from all object stores managed by this adapter instance within the database.\n * Use with caution as this is destructive.\n * @returns A promise that resolves when all specified object stores have been cleared.\n * @throws {Error} If the database is not initialized or a transaction error occurs.\n */\n async clearAll(): Promise<void> {\n await this.init(); // Ensure DB is ready\n if (!this.db) {\n throw new Error(\"Database not initialized.\");\n }\n\n const storeNames = Array.from(this.db.objectStoreNames);\n if (storeNames.length === 0) {\n return Promise.resolve(); // Nothing to clear\n }\n\n return new Promise((resolve, reject) => {\n try {\n // Need a transaction covering all stores to clear\n const transaction = this.getTransaction(storeNames, 'readwrite');\n\n let clearCount = 0;\n const totalStores = storeNames.length;\n\n storeNames.forEach(storeName => {\n const request = transaction.objectStore(storeName).clear();\n request.onsuccess = () => {\n clearCount++;\n if (clearCount === totalStores) {\n // This might resolve before transaction.oncomplete\n }\n };\n request.onerror = () => {\n // Error on individual clear, transaction might still complete or abort\n Logger.error(`IndexedDBStorageAdapter: Error clearing object store '${storeName}':`, request.error); // Use Logger\n // Don't reject immediately, let transaction handle overall status\n };\n });\n\n transaction.oncomplete = () => {\n Logger.info(`IndexedDBStorageAdapter: All object stores cleared successfully.`); // Use Logger\n resolve();\n };\n\n transaction.onerror = (event) => {\n Logger.error(`IndexedDBStorageAdapter: Transaction error during clearAll:`, transaction.error, event); // Use Logger\n reject(new Error(`Failed to clear all stores: ${transaction.error?.message}`));\n };\n } catch (error) {\n reject(error);\n }\n });\n }\n}","import { IConversationRepository, StorageAdapter } from '@/core/interfaces';\nimport { ConversationMessage, MessageOptions } from '@/types';\n\n// Define the structure of the data as stored, including the 'id' field\ntype StoredConversationMessage = ConversationMessage & { id: string };\n\n/**\n * Implements the `IConversationRepository` interface, providing methods to\n * manage `ConversationMessage` objects using an underlying `StorageAdapter`.\n * Handles adding and retrieving conversation history for specific threads.\n *\n * It abstracts the underlying storage mechanism through the `StorageAdapter` interface,\n * allowing for different storage backends (e.g., in-memory, IndexedDB, Supabase)\n * to be used interchangeably.\n *\n * @see {@link IConversationRepository} for the interface it implements.\n * @see {@link StorageAdapter} for the storage backend interface.\n */\nexport class ConversationRepository implements IConversationRepository {\n private adapter: StorageAdapter;\n private readonly collectionName = 'conversations'; // Define the collection name\n\n /**\n * Creates an instance of ConversationRepository.\n * @param {StorageAdapter} storageAdapter - The configured `StorageAdapter` instance that will be used for persistence.\n */\n constructor(storageAdapter: StorageAdapter) {\n if (!storageAdapter) {\n throw new Error(\"ConversationRepository requires a valid StorageAdapter instance.\");\n }\n this.adapter = storageAdapter;\n // Note: Initialization of the adapter (adapter.init()) should be handled\n // at the application setup level (e.g., within AgentFactory or createArtInstance)\n // before the repository is used.\n }\n\n /**\n * Adds one or more `ConversationMessage` objects to the storage for a specific thread.\n * It uses the `messageId` as the primary key for storage, assuming the adapter's collection uses 'id' as keyPath.\n * @param {string} threadId - The ID of the thread these messages belong to. Used for potential filtering/querying and validation.\n * @param {ConversationMessage[]} messages - An array of `ConversationMessage` objects to add. Each message should have a unique `messageId`.\n * @returns {Promise<void>} A promise that resolves when all messages have been attempted to be saved.\n * @throws {Error} Propagates errors from the storage adapter's `set` method.\n */\n async addMessages(threadId: string, messages: ConversationMessage[]): Promise<void> {\n if (!messages || messages.length === 0) {\n return Promise.resolve();\n }\n\n // Use Promise.all to handle multiple async set operations concurrently\n const setPromises = messages.map(message => {\n if (message.threadId !== threadId) {\n console.warn(`ConversationRepository: Message ${message.messageId} has mismatching threadId (${message.threadId}) for repository operation on thread ${threadId}.`);\n // Decide on handling: throw error, skip message, or proceed? For now, proceed but log.\n }\n // Add the 'id' field mirroring 'messageId' for compatibility with keyPath='id' adapters\n const messageToStore: StoredConversationMessage = {\n ...message,\n id: message.messageId\n };\n return this.adapter.set<StoredConversationMessage>(this.collectionName, messageToStore.id, messageToStore);\n });\n\n await Promise.all(setPromises);\n }\n\n /**\n * Retrieves messages for a specific thread from the storage adapter.\n * This implementation fetches all messages for the thread and then applies\n * sorting, filtering (by timestamp), and limiting client-side.\n * For performance with very large histories, adapter-level querying/indexing would be preferable.\n * @param {string} threadId - The ID of the thread whose messages are to be retrieved.\n * @param {MessageOptions} [options] - Optional `MessageOptions` to control retrieval (limit, timestamp filters).\n * @returns {Promise<ConversationMessage[]>} A promise resolving to an array of `ConversationMessage` objects, sorted chronologically (ascending timestamp).\n * @throws {Error} Propagates errors from the storage adapter's `query` method.\n */\n async getMessages(threadId: string, options?: MessageOptions): Promise<ConversationMessage[]> {\n // Query the adapter for all messages matching the threadId\n const queryResults = await this.adapter.query<StoredConversationMessage>(this.collectionName, {\n filter: { threadId: threadId },\n // Add sorting at the adapter level if supported and efficient, otherwise sort client-side\n // sort: { timestamp: 'asc' } // Example if adapter supported it well\n });\n\n // Client-side filtering and sorting\n let filteredMessages = queryResults;\n\n // Sort by timestamp (ascending) - essential for correct history order\n filteredMessages.sort((a, b) => a.timestamp - b.timestamp);\n\n // Apply timestamp filters client-side\n if (options?.beforeTimestamp !== undefined) {\n filteredMessages = filteredMessages.filter(m => m.timestamp < options.beforeTimestamp!);\n }\n if (options?.afterTimestamp !== undefined) {\n filteredMessages = filteredMessages.filter(m => m.timestamp > options.afterTimestamp!);\n }\n\n // Apply limit client-side (usually applied last, after sorting/filtering)\n // If sorting descending, limit needs care. Assuming ascending sort for history.\n if (options?.limit !== undefined && options.limit > 0) {\n // Get the last 'limit' messages after sorting ascending\n filteredMessages = filteredMessages.slice(-options.limit);\n }\n\n // Remove the 'id' field before returning to match the ConversationMessage interface\n // Prefix 'id' with '_' because it's unused in the destructuring assignment.\n const finalMessages: ConversationMessage[] = filteredMessages.map(({ id: _id, ...rest }) => rest);\n\n return finalMessages;\n }\n}","import { IObservationRepository, StorageAdapter } from '@/core/interfaces';\nimport { Observation, ObservationFilter } from '@/types';\n\n// Observation already has an 'id' field, so no need for a separate Stored type usually.\n// However, ensure the StorageAdapter expects 'id' as the keyPath for the 'observations' store.\n\n/**\n * Implements the `IObservationRepository` interface, providing methods to\n * manage `Observation` objects using an underlying `StorageAdapter`.\n * Handles adding and retrieving observations for specific threads.\n *\n * It relies on a `StorageAdapter` to abstract the actual storage mechanism,\n * making it compatible with different backends like IndexedDB, Supabase, or\n * in-memory storage.\n *\n * @see {@link IObservationRepository} for the interface it implements.\n * @see {@link StorageAdapter} for the storage backend interface.\n */\nexport class ObservationRepository implements IObservationRepository {\n private adapter: StorageAdapter;\n private readonly collectionName = 'observations'; // Define the collection name\n\n /**\n * Creates an instance of ObservationRepository.\n * @param {StorageAdapter} storageAdapter - The configured `StorageAdapter` instance that will be used for persistence.\n */\n constructor(storageAdapter: StorageAdapter) {\n if (!storageAdapter) {\n throw new Error(\"ObservationRepository requires a valid StorageAdapter instance.\");\n }\n this.adapter = storageAdapter;\n // Note: Initialization of the adapter (adapter.init()) should be handled\n // at the application setup level (e.g., within AgentFactory or createArtInstance)\n // before the repository is used.\n }\n\n /**\n * Adds a single `Observation` object to the storage using its `id` as the key.\n * @param {Observation} observation - The `Observation` object to add. Must have a valid `id`.\n * @returns {Promise<void>} A promise that resolves when the observation has been saved.\n * @throws {Error} If the observation is missing an `id` or if the storage adapter fails.\n */\n async addObservation(observation: Observation): Promise<void> {\n // The observation object already has an 'id' property, which should match the keyPath.\n if (typeof observation.id === 'undefined') {\n return Promise.reject(new Error(`ObservationRepository: Observation must have an 'id' property.`));\n }\n await this.adapter.set<Observation>(this.collectionName, observation.id, observation);\n }\n\n /**\n * Retrieves observations for a specific thread from the storage adapter.\n * This implementation fetches all observations for the thread and then applies\n * client-side filtering (by type, timestamp) and sorting (by timestamp).\n * For performance with many observations, adapter-level querying/indexing would be preferable.\n * @param {string} threadId - The ID of the thread whose observations are to be retrieved.\n * @param {ObservationFilter} [filter] - Optional `ObservationFilter` criteria (e.g., `types`, `beforeTimestamp`, `afterTimestamp`).\n * @returns {Promise<Observation[]>} A promise resolving to an array of `Observation` objects matching the criteria, sorted chronologically (ascending timestamp).\n * @throws {Error} Propagates errors from the storage adapter's `query` method.\n */\n async getObservations(threadId: string, filter?: ObservationFilter): Promise<Observation[]> {\n // Query the adapter for all observations matching the threadId\n const queryResults = await this.adapter.query<Observation>(this.collectionName, {\n filter: { threadId: threadId },\n // Add sorting by timestamp at the adapter level if supported, otherwise sort client-side\n // sort: { timestamp: 'asc' }\n });\n\n // Client-side filtering and sorting\n let filteredObservations = queryResults;\n\n // Sort by timestamp (ascending) - useful for chronological view\n filteredObservations.sort((a, b) => a.timestamp - b.timestamp);\n\n // Apply type filter client-side\n if (filter?.types && filter.types.length > 0) {\n const typeSet = new Set(filter.types);\n filteredObservations = filteredObservations.filter(obs => typeSet.has(obs.type));\n }\n\n // Apply timestamp filters client-side\n if (filter?.beforeTimestamp !== undefined) {\n filteredObservations = filteredObservations.filter(obs => obs.timestamp < filter.beforeTimestamp!);\n }\n if (filter?.afterTimestamp !== undefined) {\n filteredObservations = filteredObservations.filter(obs => obs.timestamp > filter.afterTimestamp!);\n }\n\n // Note: Limit/Skip are not part of ObservationFilter in the current types,\n // but could be added if needed and handled here similarly to ConversationRepository.\n\n // Observations retrieved from storage should already match the Observation interface.\n // No need to remove 'id' like in ConversationRepository.\n return filteredObservations;\n }\n}","import { IStateRepository, StorageAdapter } from '@/core/interfaces';\nimport { ThreadContext, ThreadConfig, AgentState } from '@/types';\n\n// Define the structure of the data as stored, including the 'id' field (threadId)\ntype StoredThreadContext = ThreadContext & { id: string };\n\n/**\n * Implements the `IStateRepository` interface, providing methods to manage\n * `ThreadContext` (which includes `ThreadConfig` and `AgentState`) using an\n * underlying `StorageAdapter`. It stores the entire context object for each thread\n * under a key equal to the `threadId` within a designated collection (default: 'state').\n *\n * It uses a `StorageAdapter` to abstract the underlying storage, allowing for\n * flexibility in choosing storage backends (e.g., in-memory, IndexedDB, Supabase).\n * This repository is responsible for CRUD operations on thread state and configuration.\n *\n * @see {@link IStateRepository} for the interface it implements.\n * @see {@link StorageAdapter} for the storage backend interface.\n */\nexport class StateRepository implements IStateRepository {\n private adapter: StorageAdapter;\n private readonly collectionName = 'state'; // Define the collection name\n\n /**\n * Creates an instance of StateRepository.\n * @param {StorageAdapter} storageAdapter - The configured `StorageAdapter` instance used for persistence.\n */\n constructor(storageAdapter: StorageAdapter) {\n if (!storageAdapter) {\n throw new Error(\"StateRepository requires a valid StorageAdapter instance.\");\n }\n this.adapter = storageAdapter;\n // Note: Adapter initialization (adapter.init()) should be handled externally.\n }\n\n /**\n * Retrieves the complete `ThreadContext` (config and state) for a specific thread ID.\n * @param {string} threadId - The unique identifier of the thread.\n * @returns {Promise<ThreadContext | null>} A promise resolving to the `ThreadContext` object if found, or `null` otherwise.\n * @throws {Error} Propagates errors from the storage adapter's `get` method.\n */\n async getThreadContext(threadId: string): Promise<ThreadContext | null> {\n const storedContext = await this.adapter.get<StoredThreadContext>(this.collectionName, threadId);\n if (!storedContext) {\n return null;\n }\n // Remove the internal 'id' field before returning\n // Create a copy and delete the 'id' property to avoid ESLint unused var rule\n const context = { ...storedContext };\n delete (context as Partial<StoredThreadContext>).id; // Cast to allow deletion\n return context as ThreadContext; // Cast back to the expected return type\n }\n\n /**\n * Saves (or overwrites) the complete `ThreadContext` for a specific thread ID.\n * Ensures the context object includes the `threadId` as the `id` property for storage.\n * @param {string} threadId - The unique identifier of the thread.\n * @param {ThreadContext} context - The `ThreadContext` object to save. Must contain at least the `config` property.\n * @returns {Promise<void>} A promise that resolves when the context is successfully saved.\n * @throws {Error} If the context is missing the required `config` property or if the storage adapter fails.\n */\n async setThreadContext(threadId: string, context: ThreadContext): Promise<void> {\n if (!context || typeof context.config === 'undefined') {\n // Enforce that context must have at least a config part.\n return Promise.reject(new Error(\"StateRepository: ThreadContext must contain a 'config' property.\"));\n }\n const contextToStore: StoredThreadContext = {\n ...context,\n id: threadId, // Use threadId as the 'id' for storage keyPath\n };\n await this.adapter.set<StoredThreadContext>(this.collectionName, threadId, contextToStore);\n }\n\n /**\n * Retrieves only the `ThreadConfig` part of the context for a specific thread ID.\n * @param {string} threadId - The unique identifier of the thread.\n * @returns {Promise<ThreadConfig | null>} A promise resolving to the `ThreadConfig` object if found, or `null` otherwise.\n * @throws {Error} Propagates errors from the underlying `getThreadContext` call.\n */\n async getThreadConfig(threadId: string): Promise<ThreadConfig | null> {\n const context = await this.getThreadContext(threadId);\n return context?.config ?? null;\n }\n\n /**\n * Sets or updates only the `ThreadConfig` part of the context for a specific thread ID.\n * It fetches the existing context, replaces the `config` field, preserves the existing `state` (or sets it to null if none existed),\n * and then saves the entire updated `ThreadContext` back to storage.\n * @param {string} threadId - The unique identifier of the thread.\n * @param {ThreadConfig} config - The `ThreadConfig` object to save.\n * @returns {Promise<void>} A promise that resolves when the updated context is saved.\n * @throws {Error} Propagates errors from the underlying `getThreadContext` or `setThreadContext` calls.\n */\n async setThreadConfig(threadId: string, config: ThreadConfig): Promise<void> {\n const currentContext = await this.getThreadContext(threadId);\n const newContext: ThreadContext = {\n config: config,\n state: currentContext?.state ?? null, // Preserve existing state or set to null\n };\n await this.setThreadContext(threadId, newContext);\n }\n\n /**\n * Retrieves only the `AgentState` part of the context for a specific thread ID.\n * @param {string} threadId - The unique identifier of the thread.\n * @returns {Promise<AgentState | null>} A promise resolving to the `AgentState` object if found and not null, or `null` otherwise.\n * @throws {Error} Propagates errors from the underlying `getThreadContext` call.\n */\n async getAgentState(threadId: string): Promise<AgentState | null> {\n const context = await this.getThreadContext(threadId);\n return context?.state ?? null;\n }\n\n /**\n * Sets or updates only the `AgentState` part of the context for a specific thread ID.\n * It fetches the existing context, replaces the `state` field, preserves the existing `config`,\n * and then saves the entire updated `ThreadContext` back to storage.\n * **Important:** This method requires that a `ThreadConfig` already exists for the thread.\n * Attempting to set state for a thread without prior configuration will result in an error.\n * @param {string} threadId - The unique identifier of the thread.\n * @param {AgentState} state - The `AgentState` object to save.\n * @returns {Promise<void>} A promise that resolves when the updated context is saved.\n * @throws {Error} If no `ThreadConfig` exists for the `threadId`, or if errors occur during context retrieval or saving.\n */\n async setAgentState(threadId: string, state: AgentState): Promise<void> {\n const currentContext = await this.getThreadContext(threadId);\n if (!currentContext || !currentContext.config) {\n // Require config to exist before setting state.\n return Promise.reject(new Error(`StateRepository: Cannot set AgentState for thread '${threadId}' because no ThreadConfig exists. Set config first.`));\n }\n const newContext: ThreadContext = {\n config: currentContext.config, // Preserve existing config\n state: state,\n };\n await this.setThreadContext(threadId, newContext);\n }\n}","import { IA2ATaskRepository, StorageAdapter } from '@/core/interfaces';\nimport { A2ATask, A2ATaskStatus, A2ATaskPriority, ARTError, ErrorCode } from '@/types';\n\n// Define the structure of the data as stored, including the 'id' field (taskId)\ntype StoredA2ATask = A2ATask & { id: string };\n\n/**\n * Implements the `IA2ATaskRepository` interface, providing methods to manage\n * `A2ATask` objects using an underlying `StorageAdapter`. Handles creating,\n * retrieving, updating, and deleting A2A (Agent-to-Agent) tasks, as well as\n * filtering tasks by various criteria such as thread, agent, and status.\n *\n * @see {@link IA2ATaskRepository} for the interface it implements.\n * @see {@link StorageAdapter} for the storage backend interface.\n */\nexport class TaskStatusRepository implements IA2ATaskRepository {\n private adapter: StorageAdapter;\n private readonly collectionName = 'a2a_tasks'; // Define the collection name\n\n /**\n * Creates an instance of TaskStatusRepository.\n * @param {StorageAdapter} storageAdapter - The configured `StorageAdapter` instance used for persistence.\n */\n constructor(storageAdapter: StorageAdapter) {\n if (!storageAdapter) {\n throw new Error(\"TaskStatusRepository requires a valid StorageAdapter instance.\");\n }\n this.adapter = storageAdapter;\n // Note: Adapter initialization (adapter.init()) should be handled externally.\n }\n\n /**\n * Creates a new A2A task in the repository.\n * @param {A2ATask} task - The A2ATask object to create.\n * @returns {Promise<void>} A promise that resolves when the task is successfully stored.\n * @throws {ARTError} If the task cannot be created (e.g., duplicate taskId, validation errors).\n */\n async createTask(task: A2ATask): Promise<void> {\n if (!task || !task.taskId) {\n throw new ARTError('Task must have a valid taskId', ErrorCode.VALIDATION_ERROR);\n }\n\n // Check if task already exists\n const existingTask = await this.adapter.get<StoredA2ATask>(this.collectionName, task.taskId);\n if (existingTask) {\n throw new ARTError(`Task with ID '${task.taskId}' already exists`, ErrorCode.DUPLICATE_TASK_ID);\n }\n\n // Add the 'id' field mirroring 'taskId' for compatibility with keyPath='id' adapters\n const taskToStore: StoredA2ATask = {\n ...task,\n id: task.taskId\n };\n\n await this.adapter.set<StoredA2ATask>(this.collectionName, task.taskId, taskToStore);\n }\n\n /**\n * Retrieves an A2A task by its unique identifier.\n * @param {string} taskId - The unique identifier of the task.\n * @returns {Promise<A2ATask | null>} A promise resolving to the A2ATask object if found, or null if not found.\n * @throws {ARTError} If an error occurs during retrieval.\n */\n async getTask(taskId: string): Promise<A2ATask | null> {\n if (!taskId) {\n throw new ARTError('TaskId is required', ErrorCode.VALIDATION_ERROR);\n }\n\n try {\n const storedTask = await this.adapter.get<StoredA2ATask>(this.collectionName, taskId);\n if (!storedTask) {\n return null;\n }\n\n // Remove the internal 'id' field before returning\n const task = { ...storedTask };\n delete (task as Partial<StoredA2ATask>).id;\n return task as A2ATask;\n } catch (error) {\n throw new ARTError(`Failed to retrieve task '${taskId}': ${error}`, ErrorCode.REPOSITORY_ERROR);\n }\n }\n\n /**\n * Updates an existing A2A task with new information.\n * @param {string} taskId - The unique identifier of the task to update.\n * @param {Partial<A2ATask>} updates - Partial A2ATask object containing the fields to update.\n * @returns {Promise<void>} A promise that resolves when the task is successfully updated.\n * @throws {ARTError} If the task is not found or cannot be updated.\n */\n async updateTask(taskId: string, updates: Partial<A2ATask>): Promise<void> {\n if (!taskId) {\n throw new ARTError('TaskId is required', ErrorCode.VALIDATION_ERROR);\n }\n\n if (!updates || Object.keys(updates).length === 0) {\n throw new ARTError('Updates object cannot be empty', ErrorCode.VALIDATION_ERROR);\n }\n\n try {\n // Get the existing task\n const existingTask = await this.adapter.get<StoredA2ATask>(this.collectionName, taskId);\n if (!existingTask) {\n throw new ARTError(`Task with ID '${taskId}' not found`, ErrorCode.TASK_NOT_FOUND);\n }\n\n // Merge updates with existing task\n const updatedTask: StoredA2ATask = {\n ...existingTask,\n ...updates,\n taskId, // Ensure taskId cannot be changed\n id: taskId // Ensure consistency\n };\n\n // Update metadata if provided\n if (updates.metadata) {\n updatedTask.metadata = {\n ...existingTask.metadata,\n ...updates.metadata,\n lastUpdated: Date.now() // Always update timestamp\n };\n }\n\n await this.adapter.set<StoredA2ATask>(this.collectionName, taskId, updatedTask);\n } catch (error) {\n if (error instanceof ARTError) {\n throw error;\n }\n throw new ARTError(`Failed to update task '${taskId}': ${error}`, ErrorCode.REPOSITORY_ERROR);\n }\n }\n\n /**\n * Removes an A2A task from the repository.\n * @param {string} taskId - The unique identifier of the task to delete.\n * @returns {Promise<void>} A promise that resolves when the task is successfully deleted.\n * @throws {ARTError} If the task is not found or cannot be deleted.\n */\n async deleteTask(taskId: string): Promise<void> {\n if (!taskId) {\n throw new ARTError('TaskId is required', ErrorCode.VALIDATION_ERROR);\n }\n\n try {\n // Check if task exists\n const existingTask = await this.adapter.get<StoredA2ATask>(this.collectionName, taskId);\n if (!existingTask) {\n throw new ARTError(`Task with ID '${taskId}' not found`, ErrorCode.TASK_NOT_FOUND);\n }\n\n await this.adapter.delete(this.collectionName, taskId);\n } catch (error) {\n if (error instanceof ARTError) {\n throw error;\n }\n throw new ARTError(`Failed to delete task '${taskId}': ${error}`, ErrorCode.REPOSITORY_ERROR);\n }\n }\n\n /**\n * Retrieves tasks associated with a specific thread.\n * @param {string} threadId - The thread identifier to filter tasks.\n * @param {object} [filter] - Optional filter criteria for task status, priority, or assigned agent.\n * @returns {Promise<A2ATask[]>} A promise resolving to an array of A2ATask objects matching the criteria.\n */\n async getTasksByThread(\n threadId: string,\n filter?: {\n status?: A2ATaskStatus | A2ATaskStatus[];\n priority?: A2ATaskPriority;\n assignedAgentId?: string;\n }\n ): Promise<A2ATask[]> {\n if (!threadId) {\n throw new ARTError('ThreadId is required', ErrorCode.VALIDATION_ERROR);\n }\n\n try {\n // Query tasks for the specific thread\n const queryResults = await this.adapter.query<StoredA2ATask>(this.collectionName, {\n filter: { threadId: threadId }\n });\n\n // Apply additional client-side filtering\n let filteredTasks = queryResults;\n\n if (filter) {\n if (filter.status) {\n const statusArray = Array.isArray(filter.status) ? filter.status : [filter.status];\n filteredTasks = filteredTasks.filter(task => statusArray.includes(task.status));\n }\n\n if (filter.priority) {\n filteredTasks = filteredTasks.filter(task => task.priority === filter.priority);\n }\n\n if (filter.assignedAgentId) {\n filteredTasks = filteredTasks.filter(task => \n task.targetAgent?.agentId === filter.assignedAgentId\n );\n }\n }\n\n // Sort by creation timestamp (newest first)\n filteredTasks.sort((a, b) => (b.metadata?.createdAt || 0) - (a.metadata?.createdAt || 0));\n\n // Remove the 'id' field from results\n return this._removeIdField(filteredTasks);\n } catch (error) {\n throw new ARTError(`Failed to get tasks for thread '${threadId}': ${error}`, ErrorCode.REPOSITORY_ERROR);\n }\n }\n\n /**\n * Retrieves tasks assigned to a specific agent.\n * @param {string} agentId - The agent identifier to filter tasks.\n * @param {object} [filter] - Optional filter criteria for task status or priority.\n * @returns {Promise<A2ATask[]>} A promise resolving to an array of A2ATask objects assigned to the agent.\n */\n async getTasksByAgent(\n agentId: string,\n filter?: {\n status?: A2ATaskStatus | A2ATaskStatus[];\n priority?: A2ATaskPriority;\n }\n ): Promise<A2ATask[]> {\n if (!agentId) {\n throw new ARTError('AgentId is required', ErrorCode.VALIDATION_ERROR);\n }\n\n try {\n // Query all tasks and filter client-side (storage adapters may not support nested filtering)\n const queryResults = await this.adapter.query<StoredA2ATask>(this.collectionName, {\n filter: {} // Get all tasks, then filter client-side\n });\n\n // Filter by assigned agent\n let filteredTasks = queryResults.filter(task => \n task.targetAgent?.agentId === agentId\n );\n\n // Apply additional filters\n if (filter) {\n if (filter.status) {\n const statusArray = Array.isArray(filter.status) ? filter.status : [filter.status];\n filteredTasks = filteredTasks.filter(task => statusArray.includes(task.status));\n }\n\n if (filter.priority) {\n filteredTasks = filteredTasks.filter(task => task.priority === filter.priority);\n }\n }\n\n // Sort by creation timestamp (newest first)\n filteredTasks.sort((a, b) => (b.metadata?.createdAt || 0) - (a.metadata?.createdAt || 0));\n\n // Remove the 'id' field from results\n return this._removeIdField(filteredTasks);\n } catch (error) {\n throw new ARTError(`Failed to get tasks for agent '${agentId}': ${error}`, ErrorCode.REPOSITORY_ERROR);\n }\n }\n\n /**\n * Retrieves tasks based on their current status.\n * @param {A2ATaskStatus | A2ATaskStatus[]} status - The task status(es) to filter by.\n * @param {object} [options] - Optional query parameters like limit and pagination.\n * @returns {Promise<A2ATask[]>} A promise resolving to an array of A2ATask objects with the specified status.\n */\n async getTasksByStatus(\n status: A2ATaskStatus | A2ATaskStatus[],\n options?: { limit?: number; offset?: number }\n ): Promise<A2ATask[]> {\n if (!status) {\n throw new ARTError('Status is required', ErrorCode.VALIDATION_ERROR);\n }\n\n try {\n // Query all tasks (since we need to filter by status client-side)\n const queryResults = await this.adapter.query<StoredA2ATask>(this.collectionName, {\n filter: {} // Get all, then filter client-side\n });\n\n // Filter by status\n const statusArray = Array.isArray(status) ? status : [status];\n let filteredTasks = queryResults.filter(task => statusArray.includes(task.status));\n\n // Sort by creation timestamp (newest first)\n filteredTasks.sort((a, b) => (b.metadata?.createdAt || 0) - (a.metadata?.createdAt || 0));\n\n // Apply pagination\n if (options) {\n const offset = options.offset || 0;\n const limit = options.limit;\n \n if (offset > 0) {\n filteredTasks = filteredTasks.slice(offset);\n }\n \n if (limit && limit > 0) {\n filteredTasks = filteredTasks.slice(0, limit);\n }\n }\n\n // Remove the 'id' field from results\n return this._removeIdField(filteredTasks);\n } catch (error) {\n throw new ARTError(`Failed to get tasks by status: ${error}`, ErrorCode.REPOSITORY_ERROR);\n }\n }\n\n /**\n * Utility method to remove the internal 'id' field from stored tasks before returning them.\n * @private\n * @param {StoredA2ATask[]} tasks - Array of StoredA2ATask objects.\n * @returns {A2ATask[]} Array of A2ATask objects with 'id' field removed.\n */\n private _removeIdField(tasks: StoredA2ATask[]): A2ATask[] {\n return tasks.map(task => {\n const cleanTask = { ...task };\n delete (cleanTask as Partial<StoredA2ATask>).id;\n return cleanTask as A2ATask;\n });\n }\n} ","import { ConversationManager as IConversationManager, IConversationRepository } from '@/core/interfaces';\nimport { ConversationSocket } from '@/systems/ui/conversation-socket'; // Import the class\nimport { ConversationMessage, MessageOptions } from '@/types';\n\n/**\n * Manages the retrieval and addition of `ConversationMessage` objects for different threads,\n * interacting with an underlying `IConversationRepository` for persistence and notifying\n * the `ConversationSocket` of new messages.\n */\nexport class ConversationManager implements IConversationManager {\n private repository: IConversationRepository;\n private conversationSocket: ConversationSocket; // Add socket property\n\n /**\n * Creates an instance of ConversationManager.\n * @param {IConversationRepository} conversationRepository - The repository responsible for persisting conversation messages.\n * @param {ConversationSocket} conversationSocket - The socket instance used to notify the UI of new messages.\n */\n constructor(\n conversationRepository: IConversationRepository,\n conversationSocket: ConversationSocket\n ) {\n this.repository = conversationRepository;\n this.conversationSocket = conversationSocket;\n }\n\n /**\n * Adds one or more messages to a specific thread's history using the repository\n * and notifies the `ConversationSocket` for each added message.\n * @param {string} threadId - The ID of the thread to add messages to. Must not be empty.\n * @param {ConversationMessage[]} messages - An array of `ConversationMessage` objects to add.\n * @returns {Promise<void>} A promise that resolves when messages are saved and notifications are sent (or attempted).\n * @throws {Error} If `threadId` is empty. Repository errors might also propagate.\n */\n async addMessages(threadId: string, messages: ConversationMessage[]): Promise<void> {\n // Basic validation or preprocessing could happen here if needed.\n if (!threadId) {\n return Promise.reject(new Error(\"ConversationManager: threadId cannot be empty.\"));\n }\n if (!messages || messages.length === 0) {\n return Promise.resolve(); // Nothing to add\n }\n // Delegate to the repository\n await this.repository.addMessages(threadId, messages);\n\n // Notify socket for each added message\n messages.forEach(message => {\n // Assuming ConversationSocket has a method like notifyMessage or just notify\n // Use notify as per the TypedSocket interface\n try {\n this.conversationSocket.notify(message, { targetThreadId: threadId });\n } catch (error) {\n // Log error but don't let notification failure stop the flow\n console.error(`ConversationManager: Failed to notify message ${message.messageId} via socket for thread ${threadId}`, error);\n }\n });\n }\n\n /**\n * Retrieves messages from a specific thread's history using the repository.\n * @param {string} threadId - The ID of the thread whose history is needed. Must not be empty.\n * @param {MessageOptions} [options] - Optional parameters (`MessageOptions`) to control retrieval (e.g., limit, timestamp filters).\n * @returns {Promise<ConversationMessage[]>} A promise resolving to an array of `ConversationMessage` objects, typically ordered newest first by the repository.\n * @throws {Error} If `threadId` is empty. Repository errors might also propagate.\n */\n async getMessages(threadId: string, options?: MessageOptions): Promise<ConversationMessage[]> {\n if (!threadId) {\n return Promise.reject(new Error(\"ConversationManager: threadId cannot be empty.\"));\n }\n // Delegate to the repository\n const messages = await this.repository.getMessages(threadId, options);\n return messages;\n }\n\n // Optional future methods:\n // async clearHistory(threadId: string): Promise<void> { ... }\n // async deleteMessage(threadId: string, messageId: string): Promise<void> { ... }\n}","import { StateManager as IStateManager, IStateRepository } from '@/core/interfaces';\nimport { ThreadContext, ThreadConfig, AgentState, StateSavingStrategy } from '@/types';\n\n// Helper for deep cloning, as structuredClone might not be available in all environments\n// or might not handle all types perfectly (e.g., functions, though not expected in AgentState).\n// For simple JSON-like objects, JSON.parse(JSON.stringify(obj)) is a common approach.\nfunction deepClone<T>(obj: T): T {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n // For Date objects\n if (obj instanceof Date) {\n return new Date(obj.getTime()) as any;\n }\n // For Arrays\n if (Array.isArray(obj)) {\n return obj.map(item => deepClone(item)) as any;\n }\n // For Objects\n const clonedObj = {} as T;\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n clonedObj[key] = deepClone(obj[key]);\n }\n }\n return clonedObj;\n}\n\n\n/**\n * Manages thread-specific configuration (ThreadConfig) and state (AgentState)\n * using an underlying StateRepository. Supports explicit and implicit state saving strategies.\n */\nexport class StateManager implements IStateManager {\n private repository: IStateRepository;\n private strategy: StateSavingStrategy;\n private contextCache: Map<string, { originalStateSnapshot: string | null, context: ThreadContext }>;\n\n /**\n * Creates an instance of StateManager.\n * @param {IStateRepository} stateRepository - The repository for persisting state.\n * @param {StateSavingStrategy} [strategy='explicit'] - The state saving strategy to use.\n */\n constructor(\n stateRepository: IStateRepository,\n strategy: StateSavingStrategy = 'explicit' // Default to explicit\n ) {\n this.repository = stateRepository;\n this.strategy = strategy;\n this.contextCache = new Map();\n }\n\n /**\n * Loads the complete context (`ThreadConfig` and `AgentState`) for a specific thread.\n * If in 'implicit' state saving strategy, it caches the loaded context and a snapshot\n * of its AgentState for later comparison in `saveStateIfModified`.\n * @param {string} threadId - The unique identifier for the thread.\n * @param {string} [_userId] - Optional user identifier (currently unused).\n * @returns {Promise<ThreadContext>} A promise resolving to the `ThreadContext` object.\n * @throws {Error} If `threadId` is empty or if the repository fails to find the context.\n */\n async loadThreadContext(threadId: string, _userId?: string): Promise<ThreadContext> {\n if (!threadId) {\n throw new Error(\"StateManager: threadId cannot be empty for loadThreadContext.\");\n }\n\n // If in implicit mode and context is already cached for this cycle, return cached version.\n // This ensures the agent operates on the same object instance that will be checked for modifications.\n if (this.strategy === 'implicit' && this.contextCache.has(threadId)) {\n // console.debug(`StateManager (implicit): Returning cached context for ${threadId}`);\n return this.contextCache.get(threadId)!.context;\n }\n \n const contextFromRepo = await this.repository.getThreadContext(threadId);\n if (!contextFromRepo) {\n throw new Error(`StateManager: Thread context not found for threadId '${threadId}'. Application should call setThreadConfig first for new threads.`);\n }\n\n if (this.strategy === 'implicit') {\n // console.debug(`StateManager (implicit): Caching context for ${threadId}`);\n // Deep clone the context to prevent modifications to the repository's object if it's not already a clone.\n // The agent will modify this cloned object.\n const cachedContext = deepClone(contextFromRepo);\n const originalStateSnapshot = cachedContext.state ? JSON.stringify(cachedContext.state) : null;\n this.contextCache.set(threadId, { originalStateSnapshot, context: cachedContext });\n return cachedContext;\n } else {\n // In explicit mode, return the context directly. Agent is responsible for all saves.\n return contextFromRepo;\n }\n }\n\n /**\n * Checks if a specific tool is permitted for use within a given thread.\n * It loads the thread's context and checks the `enabledTools` array in the configuration.\n * @param {string} threadId - The ID of the thread.\n * @param {string} toolName - The name of the tool to check.\n * @returns {Promise<boolean>} A promise resolving to `true` if the tool is listed in the thread's `enabledTools` config, `false` otherwise or if the context/config cannot be loaded.\n */\n async isToolEnabled(threadId: string, toolName: string): Promise<boolean> {\n try {\n const context = await this.loadThreadContext(threadId); // Will use cache if implicit\n return context.config?.enabledTools?.includes(toolName) ?? false;\n } catch (error) {\n console.warn(`StateManager: Could not check if tool '${toolName}' is enabled for thread '${threadId}' because context failed to load: ${error}`);\n return false;\n }\n }\n\n /**\n * Retrieves a specific value from the thread's configuration (`ThreadConfig`).\n * Loads the context first (which might come from cache in implicit mode).\n * @template T - The expected type of the configuration value.\n * @param {string} threadId - The ID of the thread.\n * @param {string} key - The top-level configuration key.\n * @returns {Promise<T | undefined>} A promise resolving to the configuration value, or `undefined`.\n */\n async getThreadConfigValue<T>(threadId: string, key: string): Promise<T | undefined> {\n const context = await this.loadThreadContext(threadId); // Will use cache if implicit\n\n if (!context.config) {\n return undefined;\n }\n if (key in context.config) {\n return (context.config as any)[key] as T | undefined;\n } else {\n return undefined;\n }\n }\n\n /**\n * Persists the thread's `AgentState` if it has been modified.\n * Behavior depends on the `stateSavingStrategy`:\n * - 'explicit': This method is a no-op for `AgentState` persistence and logs a warning.\n * - 'implicit': Compares the current `AgentState` (from the cached `ThreadContext` modified by the agent)\n * with the snapshot taken during `loadThreadContext`. If different, saves the state\n * to the repository and updates the snapshot.\n * @param {string} threadId - The ID of the thread whose state might need saving.\n * @returns {Promise<void>} A promise that resolves when the state is saved or the operation is skipped.\n */\n async saveStateIfModified(threadId: string): Promise<void> {\n if (!threadId) {\n throw new Error(\"StateManager: threadId cannot be empty for saveStateIfModified.\");\n }\n\n if (this.strategy === 'explicit') {\n console.warn(`StateManager (explicit): saveStateIfModified called for thread ${threadId}. AgentState must be saved explicitly using setAgentState(). This method is a no-op for AgentState in explicit mode.`);\n return Promise.resolve();\n }\n\n // Implicit strategy\n const cachedData = this.contextCache.get(threadId);\n if (!cachedData) {\n console.warn(`StateManager (implicit): saveStateIfModified called for thread ${threadId}, but context was not loaded or cached in this StateManager instance for this cycle. State will not be saved implicitly.`);\n return Promise.resolve();\n }\n\n const currentState = cachedData.context.state; // This is the potentially modified state\n const currentStateSnapshot = currentState ? JSON.stringify(currentState) : null;\n\n if (currentStateSnapshot !== cachedData.originalStateSnapshot) {\n // console.debug(`StateManager (implicit): AgentState for thread ${threadId} has changed. Saving...`);\n if (currentState === null) {\n // This case should ideally be handled by setAgentState(threadId, null) if we want to allow nulling out state.\n // For now, if it becomes null and was not null, we treat it as a change.\n // The repository's setAgentState should handle null appropriately if it's allowed.\n // However, our setAgentState currently throws if state is null.\n // This implies that if an agent wants to clear state, it should set it to an empty object or similar.\n // For implicit, if it becomes null, we might need to decide if repository.deleteAgentState is a thing.\n // For now, we'll assume if it's null, it means \"remove it\" or \"set to null\".\n // Let's assume repository.setAgentState can handle null to clear.\n console.warn(`StateManager (implicit): AgentState for thread ${threadId} became null. Attempting to save null state.`);\n }\n if (currentState !== null) { // Only save if not null, as our setAgentState doesn't allow null\n await this.repository.setAgentState(threadId, currentState);\n cachedData.originalStateSnapshot = currentStateSnapshot; // Update snapshot after successful save\n // console.debug(`StateManager (implicit): AgentState for thread ${threadId} saved and snapshot updated.`);\n } else {\n // If current state is null, and original was not, this is a change.\n // However, our current setAgentState throws on null.\n // This indicates a design consideration: how should \"clearing\" state be handled implicitly?\n // For now, we won't call repository.setAgentState with null to avoid the error.\n // This means if an agent sets context.state = null in implicit mode, it won't be persisted by saveStateIfModified.\n // They would need to use setAgentState with a non-null value (e.g., { data: null, version: ... }).\n console.warn(`StateManager (implicit): AgentState for thread ${threadId} is null. Implicit save will not persist null state due to setAgentState constraints. Use setAgentState with a valid object to clear or update.`);\n }\n } else {\n // console.debug(`StateManager (implicit): No changes detected in AgentState for thread ${threadId}.`);\n }\n return Promise.resolve();\n }\n \n /**\n * Sets or completely replaces the configuration (`ThreadConfig`) for a specific thread\n * by calling the underlying state repository. This also clears any cached context for the thread.\n * @param {string} threadId - The ID of the thread.\n * @param {ThreadConfig} config - The complete `ThreadConfig` object.\n * @returns {Promise<void>} A promise that resolves when the configuration is saved.\n */\n async setThreadConfig(threadId: string, config: ThreadConfig): Promise<void> {\n if (!threadId || !config) {\n throw new Error(\"StateManager: threadId and config are required for setThreadConfig.\");\n }\n await this.repository.setThreadConfig(threadId, config);\n // If context was cached, it's now potentially stale regarding config.\n // And its originalStateSnapshot might be based on a context that no longer fully matches repo.\n // For simplicity, clear it. Next loadThreadContext will re-fetch and re-cache if implicit.\n if (this.contextCache.has(threadId)) {\n this.contextCache.delete(threadId);\n // console.debug(`StateManager: Cleared cached context for ${threadId} after setThreadConfig.`);\n }\n }\n\n /**\n * Explicitly sets or updates the AgentState for a specific thread by calling the underlying state repository.\n * If in 'implicit' mode, this also updates the cached snapshot to prevent `saveStateIfModified`\n * from re-saving the same state immediately.\n * @param {string} threadId - The unique identifier of the thread.\n * @param {AgentState} state - The AgentState object to save. Must not be undefined or null.\n * @returns {Promise<void>} A promise that resolves when the state is saved.\n * @throws {Error} If threadId or state is undefined/null, or if the repository fails.\n */\n async setAgentState(threadId: string, state: AgentState): Promise<void> {\n if (!threadId) {\n throw new Error(\"StateManager: threadId cannot be empty for setAgentState.\");\n }\n if (typeof state === 'undefined' || state === null) {\n throw new Error(\"StateManager: state cannot be undefined or null for setAgentState.\");\n }\n \n await this.repository.setAgentState(threadId, state);\n // console.debug(`StateManager: Explicitly set agent state for ${threadId} in repository.`);\n\n if (this.strategy === 'implicit') {\n const cachedData = this.contextCache.get(threadId);\n if (cachedData) {\n // Update the cached context's state and its snapshot\n cachedData.context.state = deepClone(state); // Ensure cache has a clone\n cachedData.originalStateSnapshot = JSON.stringify(state);\n // console.debug(`StateManager (implicit): Updated cached context and snapshot for ${threadId} after explicit setAgentState.`);\n } else {\n // If not in cache, it means loadThreadContext wasn't called for this thread in this cycle,\n // or it's explicit mode. For implicit, if setAgentState is called without prior load,\n // there's no \"original\" snapshot to compare against for saveStateIfModified later in this cycle.\n // However, the state *is* saved in the repo. Next loadThreadContext will pick it up.\n // console.debug(`StateManager (implicit): setAgentState called for ${threadId} which was not in cache. State saved to repo.`);\n }\n }\n }\n \n /**\n * Enables specific tools for a conversation thread by adding them to the thread's enabled tools list.\n * This method loads the current thread configuration, updates the enabledTools array,\n * and persists the changes. Cache is invalidated to ensure fresh data on next load.\n * @param {string} threadId - The unique identifier of the thread.\n * @param {string[]} toolNames - Array of tool names to enable for this thread.\n * @returns {Promise<void>} A promise that resolves when the tools are enabled.\n * @throws {Error} If threadId is empty, toolNames is empty, or if the repository fails.\n */\n async enableToolsForThread(threadId: string, toolNames: string[]): Promise<void> {\n if (!threadId) {\n throw new Error(\"StateManager: threadId cannot be empty for enableToolsForThread.\");\n }\n if (!toolNames || toolNames.length === 0) {\n throw new Error(\"StateManager: toolNames cannot be empty for enableToolsForThread.\");\n }\n\n // Load current context to get existing config\n const context = await this.loadThreadContext(threadId);\n if (!context.config) {\n throw new Error(`StateManager: No ThreadConfig found for threadId '${threadId}'. Cannot enable tools without existing configuration.`);\n }\n\n // Create updated config with additional enabled tools\n const currentEnabledTools = context.config.enabledTools || [];\n const newEnabledTools = [...new Set([...currentEnabledTools, ...toolNames])]; // Remove duplicates\n\n const updatedConfig: ThreadConfig = {\n ...context.config,\n enabledTools: newEnabledTools\n };\n\n // Save updated config and clear cache\n await this.setThreadConfig(threadId, updatedConfig);\n // console.debug(`StateManager: Enabled tools [${toolNames.join(', ')}] for thread ${threadId}.`);\n }\n\n /**\n * Disables specific tools for a conversation thread by removing them from the thread's enabled tools list.\n * This method loads the current thread configuration, updates the enabledTools array,\n * and persists the changes. Cache is invalidated to ensure fresh data on next load.\n * @param {string} threadId - The unique identifier of the thread.\n * @param {string[]} toolNames - Array of tool names to disable for this thread.\n * @returns {Promise<void>} A promise that resolves when the tools are disabled.\n * @throws {Error} If threadId is empty, toolNames is empty, or if the repository fails.\n */\n async disableToolsForThread(threadId: string, toolNames: string[]): Promise<void> {\n if (!threadId) {\n throw new Error(\"StateManager: threadId cannot be empty for disableToolsForThread.\");\n }\n if (!toolNames || toolNames.length === 0) {\n throw new Error(\"StateManager: toolNames cannot be empty for disableToolsForThread.\");\n }\n\n // Load current context to get existing config\n const context = await this.loadThreadContext(threadId);\n if (!context.config) {\n throw new Error(`StateManager: No ThreadConfig found for threadId '${threadId}'. Cannot disable tools without existing configuration.`);\n }\n\n // Create updated config with tools removed\n const currentEnabledTools = context.config.enabledTools || [];\n const newEnabledTools = currentEnabledTools.filter(tool => !toolNames.includes(tool));\n\n const updatedConfig: ThreadConfig = {\n ...context.config,\n enabledTools: newEnabledTools\n };\n\n // Save updated config and clear cache\n await this.setThreadConfig(threadId, updatedConfig);\n // console.debug(`StateManager: Disabled tools [${toolNames.join(', ')}] for thread ${threadId}.`);\n }\n\n /**\n * Gets the list of currently enabled tools for a specific thread.\n * This is a convenience method that loads the thread context and returns the enabledTools array.\n * @param {string} threadId - The unique identifier of the thread.\n * @returns {Promise<string[]>} A promise that resolves to an array of enabled tool names, or empty array if no tools are enabled.\n * @throws {Error} If the thread context cannot be loaded.\n */\n async getEnabledToolsForThread(threadId: string): Promise<string[]> {\n if (!threadId) {\n throw new Error(\"StateManager: threadId cannot be empty for getEnabledToolsForThread.\");\n }\n\n const context = await this.loadThreadContext(threadId);\n return context.config?.enabledTools || [];\n }\n\n /**\n * Clears the internal context cache. Useful if the underlying storage is manipulated externally\n * during an agent's processing cycle, though this is generally not recommended.\n * Or for testing purposes.\n */\n public clearCache(): void {\n this.contextCache.clear();\n // console.debug(\"StateManager: Internal context cache cleared.\");\n }\n\n // Potential future methods:\n // async updateThreadConfig(threadId: string, updates: Partial<ThreadConfig>): Promise<void> { ... }\n // async updateAgentState(threadId: string, updates: Partial<AgentState>): Promise<void> { ... }\n }","import { ObservationManager as ObservationManagerInterface, IObservationRepository } from '@/core/interfaces'; // Import the interface defined in core/interfaces\nimport { ObservationSocket } from '../ui/observation-socket'; // Import the class implementation\nimport { Observation, ObservationFilter } from '@/types'; // Kept ObservationType and Omit removed\nimport { generateUUID } from '@/utils/uuid'; // Assuming UUID utility exists as per Phase 0.9\nimport { Logger } from '@/utils/logger'; // Import Logger\n\n/**\n * Manages the lifecycle of agent observations: creation, persistence, retrieval, and notification.\n *\n * @remarks\n * It provides methods to record and retrieve observations, which are crucial for\n * debugging, monitoring, and analyzing agent behavior. The manager uses a\n * repository pattern to abstract the underlying storage mechanism.\n *\n * @see {@link ObservationManagerInterface} for the interface definition.\n * @see {@link IObservationRepository} for the storage repository interface.\n */\nexport class ObservationManager implements ObservationManagerInterface { // Implement the imported interface\n private observationRepository: IObservationRepository;\n private observationSocket: ObservationSocket;\n\n /**\n * Creates an instance of ObservationManager.\n *\n * @param observationRepository The repository for persisting observations.\n * @param observationSocket The socket for notifying UI about new observations.\n */\n constructor(observationRepository: IObservationRepository, observationSocket: ObservationSocket) {\n this.observationRepository = observationRepository;\n this.observationSocket = observationSocket;\n }\n\n /**\n * Creates, persists, and broadcasts a new observation record based on the provided data.\n *\n * @remarks\n * Automatically generates a unique `id`, `timestamp`, and a default `title`.\n * Uses the injected {@link IObservationRepository} for persistence and {@link ObservationSocket} for notification.\n *\n * @param observationData An object containing the core data for the observation (`threadId`, `type`, `content`, `metadata`, etc.), excluding fields generated by the manager (`id`, `timestamp`, `title`).\n * @returns A promise that resolves when the observation has been successfully saved and notified, or rejects if a critical error occurs during persistence. Notification errors are logged but generally do not cause rejection.\n */\n async record(observationData: Omit<Observation, 'id' | 'timestamp' | 'title'>): Promise<void> { // Corrected Omit and Promise syntax\n const observation: Observation = {\n ...observationData,\n id: generateUUID(),\n timestamp: Date.now(),\n // Generate a simple title based on the type for now\n title: `${observationData.type} Recorded`,\n };\n\n try {\n await this.observationRepository.addObservation(observation); // Assuming addObservation exists on IObservationRepository\n // Use the generic notify method from TypedSocket interface\n Logger.debug(`[ObservationManager] Notifying ObservationSocket for obsId: ${observation.id}, type: ${observation.type}`); // Log before notify\n this.observationSocket.notify(observation, { targetThreadId: observation.threadId });\n Logger.debug(`[ObservationManager] ObservationSocket notified for obsId: ${observation.id}`); // Log after notify\n } catch (error) {\n console.error(\"Error recording observation:\", error);\n // Decide on error handling strategy - rethrow, log, or generate an ERROR observation?\n // For now, just logging. Consider adding an ERROR observation itself.\n throw error; // Rethrowing for now so the caller is aware\n }\n }\n\n /**\n * Retrieves historical observations stored for a specific thread, using the repository.\n *\n * @remarks\n * Allows filtering based on criteria defined in {@link ObservationFilter}.\n *\n * @param threadId The ID of the thread whose observations are to be retrieved.\n * @param filter Optional criteria (`ObservationFilter`) to filter the observations (e.g., by type, timestamp).\n * @returns A promise resolving to an array of {@link Observation} objects matching the criteria.\n * @throws If the repository encounters an error during retrieval.\n */\n async getObservations(threadId: string, filter?: ObservationFilter): Promise<Observation[]> {\n try {\n // Assuming repository has a 'findObservations' method that accepts threadId and filter\n // Assuming repository has a method matching this signature\n return await this.observationRepository.getObservations(threadId, filter); // Assuming repository method is getObservations\n } catch (error) {\n console.error(`Error retrieving observations for thread ${threadId}:`, error);\n throw error; // Rethrowing for now\n }\n }\n}","// src/systems/tool/ToolRegistry.ts\nimport { ToolRegistry as IToolRegistry, IToolExecutor, StateManager } from '@/core/interfaces'; // Added StateManager import\nimport { ToolSchema } from '@/types';\nimport { Logger } from '@/utils/logger';\n\n/**\n * A simple in-memory implementation of the `ToolRegistry` interface.\n * Stores tool executors in a Map, keyed by the tool's unique name.\n */\nexport class ToolRegistry implements IToolRegistry {\n private executors: Map<string, IToolExecutor> = new Map();\n private stateManager: StateManager | undefined; // Added stateManager property\n\n /**\n * Creates an instance of ToolRegistry.\n * @param stateManager - Optional StateManager instance for advanced filtering.\n */\n constructor(stateManager?: StateManager) {\n this.stateManager = stateManager;\n Logger.debug(`ToolRegistry initialized ${stateManager ? 'with' : 'without'} StateManager.`);\n }\n\n /**\n * Registers a tool executor instance, making it available for lookup via `getToolExecutor`.\n * If a tool with the same name (from `executor.schema.name`) already exists, it will be overwritten, and a warning will be logged.\n * @param executor - The instance of the class implementing `IToolExecutor`. Must have a valid schema with a name.\n * @returns A promise that resolves when the tool is registered.\n * @throws {Error} If the provided executor or its schema is invalid.\n */\n async registerTool(executor: IToolExecutor): Promise<void> {\n if (!executor || !executor.schema || !executor.schema.name) {\n Logger.error('ToolRegistry: Attempted to register an invalid tool executor.');\n throw new Error('Invalid tool executor provided for registration.');\n }\n const toolName = executor.schema.name;\n if (this.executors.has(toolName)) {\n Logger.warn(`ToolRegistry: Overwriting existing tool registration for \"${toolName}\".`);\n }\n this.executors.set(toolName, executor);\n Logger.debug(`ToolRegistry: Registered tool \"${toolName}\".`);\n }\n\n /**\n * Retrieves a registered tool executor instance by its unique name.\n * @param toolName - The `name` property defined in the tool's schema.\n * @returns A promise resolving to the `IToolExecutor` instance, or `undefined` if no tool with that name is registered.\n */\n async getToolExecutor(toolName: string): Promise<IToolExecutor | undefined> {\n const executor = this.executors.get(toolName);\n if (!executor) {\n Logger.debug(`ToolRegistry: Tool \"${toolName}\" not found.`);\n }\n return executor;\n }\n\n /**\n * Retrieves the schemas of all currently registered tools.\n * Retrieves the schemas of available tools, optionally filtering by those enabled for a specific thread.\n * If `filter.enabledForThreadId` is provided and a `StateManager` was injected, it attempts to load the thread's configuration\n * and return only the schemas for tools listed in `enabledTools`. Otherwise, it returns all registered tool schemas.\n * @param filter - Optional filter criteria. `enabledForThreadId` triggers filtering based on thread config.\n * @returns A promise resolving to an array containing the `ToolSchema` of the available tools based on the filter.\n */\n async getAvailableTools(filter?: { enabledForThreadId?: string }): Promise<ToolSchema[]> {\n const allExecutors = Array.from(this.executors.values());\n const allSchemas = allExecutors.map(executor => executor.schema);\n\n if (filter?.enabledForThreadId && this.stateManager) {\n const threadId = filter.enabledForThreadId;\n Logger.debug(`ToolRegistry: Attempting to filter tools for threadId: ${threadId}`);\n try {\n // Assuming loadThreadContext returns null/undefined if not found or lacks config\n const threadContext = await this.stateManager.loadThreadContext(threadId);\n const enabledToolNames = threadContext?.config?.enabledTools;\n\n if (enabledToolNames && Array.isArray(enabledToolNames)) {\n Logger.debug(`ToolRegistry: Found enabled tools for thread ${threadId}: ${enabledToolNames.join(', ')}`);\n const enabledExecutors = allExecutors.filter(executor =>\n enabledToolNames.includes(executor.schema.name)\n );\n const enabledSchemas = enabledExecutors.map(executor => executor.schema);\n Logger.debug(`ToolRegistry: Returning ${enabledSchemas.length} enabled tool schemas for thread ${threadId}.`);\n return enabledSchemas;\n } else {\n Logger.warn(`ToolRegistry: No specific enabledTools found for thread ${threadId} or config missing. Returning all tools.`);\n }\n } catch (error: any) {\n Logger.error(`ToolRegistry: Error loading thread config for ${threadId}: ${error.message}. Returning all tools.`);\n // Fallback to returning all tools in case of error loading config\n }\n } else if (filter?.enabledForThreadId && !this.stateManager) {\n Logger.warn('ToolRegistry: Filtering by enabledForThreadId requested, but StateManager was not provided. Returning all tools.');\n }\n\n // Default: return all schemas if no filtering is applied or possible\n Logger.debug(`ToolRegistry: Returning all ${allSchemas.length} registered tool schemas.`);\n return allSchemas;\n }\n\n /**\n * Removes all registered tool executors from the registry.\n * Primarily useful for resetting state during testing or specific application scenarios.\n * @returns A promise that resolves when all tools have been cleared.\n */\n async clearAllTools(): Promise<void> {\n this.executors.clear();\n Logger.debug('ToolRegistry: Cleared all registered tools.');\n }\n\n /**\n * Unregister a single tool by name.\n */\n async unregisterTool(toolName: string): Promise<void> {\n if (this.executors.delete(toolName)) {\n Logger.debug(`ToolRegistry: Unregistered tool \"${toolName}\".`);\n }\n }\n\n /**\n * Unregister tools matching a predicate; returns count removed.\n */\n async unregisterTools(predicate: (schema: ToolSchema) => boolean): Promise<number> {\n let removed = 0;\n for (const [name, exec] of Array.from(this.executors.entries())) {\n try {\n if (predicate(exec.schema)) {\n this.executors.delete(name);\n removed++;\n }\n } catch {\n // ignore predicate errors\n }\n }\n if (removed > 0) {\n Logger.debug(`ToolRegistry: Unregistered ${removed} tool(s) via predicate.`);\n }\n return removed;\n }\n}","/**\n * @module utils/validation\n * Provides a utility function for validating data against JSON schemas using the Ajv library.\n */\nimport Ajv, { ValidateFunction, ErrorObject } from 'ajv';\nimport { Logger } from '@/utils/logger';\n\n// Initialize Ajv\n// We can configure Ajv options here if needed (e.g., strict mode, allErrors)\nconst ajv = new Ajv({ allErrors: true });\n\n// Cache compiled validation functions for performance\nconst compiledValidators: Map<string, ValidateFunction> = new Map();\n\n/**\n * Validates data against a given JSON schema using the Ajv library.\n *\n * @remarks\n * It caches compiled validation functions based on the schema's string representation\n * to improve performance for repeated validations against the same schema.\n *\n * @param schema - The JSON schema object to validate against.\n * @param data - The data object to be validated.\n * @returns An object containing the validation result.\n *\n * @example\n * const schema = { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] };\n * const validData = { name: 'ART' };\n * const invalidData = { name: 123 };\n *\n * const { isValid, errors } = validateJsonSchema(schema, validData); // isValid: true, errors: null\n * const { isValid: isInvalid, errors: errorDetails } = validateJsonSchema(schema, invalidData); // isInvalid: false, errors: [...]\n */\nexport function validateJsonSchema(schema: object, data: any): { isValid: boolean; errors: ErrorObject[] | null } {\n // Use a string representation of the schema as the cache key\n const schemaKey = JSON.stringify(schema);\n let validate: ValidateFunction;\n\n if (compiledValidators.has(schemaKey)) {\n validate = compiledValidators.get(schemaKey)!;\n Logger.debug('Using cached JSON schema validator.');\n } else {\n try {\n validate = ajv.compile(schema);\n compiledValidators.set(schemaKey, validate);\n Logger.debug('Compiled and cached new JSON schema validator.');\n } catch (error: any) {\n Logger.error(`Failed to compile JSON schema: ${error.message}`, { schema, error });\n // If schema compilation fails, treat validation as failed\n return {\n isValid: false,\n errors: [{\n keyword: 'compilation',\n instancePath: '',\n schemaPath: '',\n params: {},\n message: `Schema compilation failed: ${error.message}`\n }]\n };\n }\n }\n\n const isValid = validate(data);\n\n if (isValid) {\n return { isValid: true, errors: null };\n } else {\n Logger.warn('JSON schema validation failed.', { errors: validate.errors, data });\n return { isValid: false, errors: validate.errors || [] }; // Ensure errors is always an array\n }\n}\n\n/**\n * Clears the internal cache of compiled JSON schema validators.\n * This might be useful in testing scenarios or if schemas are dynamically updated\n * in a way that requires recompilation.\n */\nexport function clearJsonSchemaValidatorCache(): void {\n compiledValidators.clear();\n Logger.debug('Cleared JSON schema validator cache.');\n}","// src/systems/tool/ToolSystem.ts\nimport { ToolSystem as IToolSystem, ToolRegistry, StateManager, IToolExecutor, ObservationManager } from '@/core/interfaces'; // Added ObservationManager\nimport { ParsedToolCall, ToolResult, ExecutionContext, ObservationType } from '@/types'; // Added ObservationType\nimport { validateJsonSchema } from '@/utils/validation';\nimport { Logger } from '@/utils/logger';\n// import { v4 as uuidv4 } from 'uuid'; // Removed unused import\n\n/**\n * Implements the `ToolSystem` interface, responsible for orchestrating the execution\n * of tool calls requested by the agent's plan. It handles verification, validation,\n * execution via registered executors, and observation recording.\n */\nexport class ToolSystem implements IToolSystem {\n private toolRegistry: ToolRegistry;\n private stateManager: StateManager;\n private observationManager: ObservationManager; // Add when implementing observations\n\n /**\n * Creates an instance of the ToolSystem.\n * @param toolRegistry - The registry used to look up tool executors.\n * @param stateManager - The manager used to check if tools are enabled for a thread.\n * @param observationManager - The manager used to record TOOL_EXECUTION observations.\n * @throws {Error} If any of the required dependencies are missing.\n */\n constructor(\n toolRegistry: ToolRegistry,\n stateManager: StateManager,\n observationManager: ObservationManager\n ) {\n if (!toolRegistry) throw new Error('ToolSystem constructor requires a ToolRegistry instance.');\n if (!stateManager) throw new Error('ToolSystem constructor requires a StateManager instance.');\n if (!observationManager) throw new Error('ToolSystem constructor requires an ObservationManager instance.');\n\n this.toolRegistry = toolRegistry;\n this.stateManager = stateManager;\n this.observationManager = observationManager;\n Logger.info('ToolSystem initialized.');\n }\n\n /**\n /**\n * Executes a sequence of planned tool calls, handling verification, validation,\n * execution, and observation recording for each call.\n * Calls are typically executed sequentially in the order they appear in the `toolCalls` array.\n * @param toolCalls - An array of `ParsedToolCall` objects generated during the planning phase.\n * @param threadId - The ID of the current thread, used for context and checking tool permissions via `StateManager`.\n * @param traceId - Optional trace ID for correlating observations.\n * @returns A promise resolving to an array of `ToolResult` objects, one for each attempted tool call.\n * Each `ToolResult` indicates the success or failure of the individual call.\n * This method itself generally does not throw errors for individual tool failures, but logs them and includes them in the results. It might throw if a critical internal error occurs.\n */\n async executeTools(\n toolCalls: ParsedToolCall[],\n threadId: string,\n traceId?: string\n ): Promise<ToolResult[]> {\n const results: ToolResult[] = [];\n Logger.debug(`ToolSystem executing ${toolCalls.length} tool calls for thread ${threadId}`, { traceId });\n\n for (const call of toolCalls) {\n let result: ToolResult | null = null;\n let executor: IToolExecutor | undefined;\n const toolName = call.toolName;\n const callId = call.callId; // Use the ID from the planning output\n\n try {\n // 1. Check if tool is enabled for the thread\n const isEnabled = await this.stateManager.isToolEnabled(threadId, toolName);\n if (!isEnabled) {\n throw new Error(`Tool \"${toolName}\" is not enabled for thread \"${threadId}\".`);\n }\n\n // 2. Get the tool executor\n executor = await this.toolRegistry.getToolExecutor(toolName);\n if (!executor) {\n throw new Error(`Tool \"${toolName}\" not found in registry.`);\n }\n\n // 3. Validate arguments against the tool's schema\n const validationResult = validateJsonSchema(executor.schema.inputSchema, call.arguments);\n if (!validationResult.isValid) {\n const errorMessages = validationResult.errors?.map(e => `${e.instancePath || 'input'} ${e.message}`).join(', ') || 'Unknown validation error';\n throw new Error(`Invalid arguments for tool \"${toolName}\": ${errorMessages}`);\n }\n\n // 4. Execute the tool\n Logger.debug(`Executing tool \"${toolName}\" with callId \"${callId}\"`, { args: call.arguments, threadId, traceId });\n const executionContext: ExecutionContext = { threadId, traceId }; // Add userId if available/needed\n // TODO: Implement basic timeout mechanism\n const executionResult = await executor.execute(call.arguments, executionContext);\n\n // Ensure the result has the correct callId and toolName (executor might not set it)\n result = {\n ...executionResult,\n callId: callId,\n toolName: toolName,\n };\n Logger.debug(`Tool \"${toolName}\" execution successful`, { callId, result: result.output, threadId, traceId });\n\n } catch (error: any) {\n Logger.error(`Tool \"${toolName}\" execution failed for callId \"${callId}\": ${error.message}`, { error, threadId, traceId });\n result = {\n callId: callId,\n toolName: toolName,\n status: 'error',\n error: error.message || 'Unknown execution error',\n };\n }\n\n // Record TOOL_EXECUTION observation\n if (result) { // Ensure result is not null before recording\n this.observationManager.record({\n threadId: threadId,\n traceId: traceId,\n type: ObservationType.TOOL_EXECUTION,\n content: result, // The ToolResult object itself\n metadata: { timestamp: Date.now(), callId: call.callId } // Include callId for correlation\n }).catch(err => Logger.error(`Failed to record TOOL_EXECUTION observation for callId ${call.callId}:`, err));\n\n results.push(result);\n } else {\n // This case should ideally not happen if the try/catch always assigns to result\n Logger.error(`ToolSystem finished processing call ${call.callId} but result object was null.`);\n }\n }\n\n return results;\n }\n}","// src/systems/reasoning/SystemPromptResolver.ts\nimport { SystemPromptResolver as ISystemPromptResolver } from '@/core/interfaces';\nimport { SystemPromptsRegistry, SystemPromptOverride, SystemPromptMergeStrategy } from '@/types';\nimport { Logger } from '@/utils/logger';\n\nfunction applyStrategy(base: string, addition: string, strategy: SystemPromptMergeStrategy | undefined): string {\n const s = strategy || 'append';\n switch (s) {\n case 'prepend':\n return `${addition}\\n\\n${base}`;\n case 'append':\n default:\n return `${base}\\n\\n${addition}`;\n }\n}\n\nfunction normalizeOverride(input?: string | SystemPromptOverride): SystemPromptOverride | undefined {\n if (!input) return undefined;\n if (typeof input === 'string') {\n return { content: input, strategy: 'append' };\n }\n return input;\n}\n\n/**\n * Resolves layered system prompts using append/prepend-only merge.\n * Note: 'replace' is intentionally unsupported to prevent custom prompts\n * from overriding framework-required structural contracts.\n */\nexport class SystemPromptResolver implements ISystemPromptResolver {\n private readonly registry?: SystemPromptsRegistry;\n\n constructor(registry?: SystemPromptsRegistry) {\n this.registry = registry;\n }\n\n async resolve(input: { base: string; instance?: string | SystemPromptOverride; thread?: string | SystemPromptOverride; call?: string | SystemPromptOverride; }, traceId?: string): Promise<string> {\n let finalPrompt = input.base;\n\n const levels: Array<{ src: string; ov?: SystemPromptOverride }> = [\n { src: 'instance', ov: normalizeOverride(input.instance) },\n { src: 'thread', ov: normalizeOverride(input.thread) },\n { src: 'call', ov: normalizeOverride(input.call) },\n ];\n\n for (const lvl of levels) {\n const ov = lvl.ov;\n if (!ov) continue;\n\n let rendered = '';\n // Tag-based preset\n if (ov.tag && this.registry?.specs?.[ov.tag]) {\n const spec = this.registry.specs[ov.tag];\n const variables = { ...(spec.defaultVariables || {}), ...(ov.variables || {}) };\n rendered = this.renderTemplate(spec.template, variables);\n finalPrompt = applyStrategy(finalPrompt, rendered, ov.strategy || spec.mergeStrategy || 'append');\n Logger.debug?.(`[${traceId || 'no-trace'}] Applied system prompt tag '${ov.tag}' with strategy '${ov.strategy || spec.mergeStrategy || 'append'}'.`);\n }\n // Freeform content\n else if (ov.content) {\n rendered = ov.content;\n finalPrompt = applyStrategy(finalPrompt, rendered, ov.strategy || 'append');\n Logger.debug?.(`[${traceId || 'no-trace'}] Applied freeform system prompt with strategy '${ov.strategy || 'append'}'.`);\n }\n // No-op if neither tag nor content\n }\n\n return finalPrompt;\n }\n\n private renderTemplate(template: string, variables: Record<string, any>): string {\n // Replace simple variables: {{var}}\n return template.replace(/\\{\\{\\s*([^}:]+)\\s*\\}\\}/g, (_m, key) => {\n const v = variables[String(key).trim()];\n return v !== undefined ? String(v) : '';\n });\n }\n}\n","// src/systems/reasoning/ReasoningEngine.ts\nimport {\n ReasoningEngine as IReasoningEngine,\n // Removed ProviderAdapter import\n} from '@/core/interfaces';\nimport { FormattedPrompt, CallOptions, StreamEvent } from '@/types';\nimport { IProviderManager, ManagedAdapterAccessor, RuntimeProviderConfig } from '@/types/providers'; // Import ProviderManager types and RuntimeProviderConfig\nimport { Logger } from '@/utils/logger';\n\n/**\n * Default implementation of the `ReasoningEngine` interface.\n * This class uses the `ProviderManager` to dynamically obtain `ProviderAdapter` instances\n * based on the runtime configuration provided in `CallOptions`.\n *\n * It abstracts the details of interacting with a specific LLM provider by using a\n * `ProviderAdapter`. This allows the agent to switch between different LLM providers\n * (like OpenAI, Anthropic, Gemini) without changing its core logic.\n *\n * @see {@link IReasoningEngine} for the interface definition.\n * @see {@link ProviderAdapter} for the adapter interface to different LLM providers.\n */\nexport class ReasoningEngine implements IReasoningEngine {\n private providerManager: IProviderManager; // Replaced adapter with providerManager\n\n /**\n * Creates an instance of the ReasoningEngine.\n * @param providerManager - The `ProviderManager` instance used to obtain adapter instances at runtime.\n */\n constructor(providerManager: IProviderManager) {\n this.providerManager = providerManager;\n Logger.info('ReasoningEngine initialized with ProviderManager');\n }\n\n /**\n * Executes an LLM call by obtaining a `ProviderAdapter` instance from the `ProviderManager`\n * based on the `providerConfig` in `CallOptions`, and then delegating the call to the adapter.\n * Ensures the adapter instance is released back to the manager after the call.\n * @param prompt - The prompt to send to the LLM, potentially formatted specifically for the provider by the `PromptManager`.\n * @param options - Options controlling the LLM call, including mandatory `threadId`, tracing IDs, model parameters, streaming flags, and the crucial `providerConfig`.\n * @returns An AsyncIterable of StreamEvent objects, as returned by the adapter.\n * @throws {ARTError | Error} Re-throws any error encountered during adapter acquisition or initial call setup.\n */\n async call(prompt: FormattedPrompt, options: CallOptions): Promise<AsyncIterable<StreamEvent>> {\n const providerConfig: RuntimeProviderConfig = options.providerConfig; // Extract providerConfig\n\n if (!providerConfig) {\n throw new Error(\"CallOptions must include 'providerConfig' for multi-provider architecture.\");\n }\n\n Logger.debug(`ReasoningEngine requesting adapter for provider: ${providerConfig.providerName}, model: ${providerConfig.modelId}`, { threadId: options.threadId, traceId: options.traceId, stream: options.stream });\n\n let accessor: ManagedAdapterAccessor;\n try {\n // Obtain a managed adapter instance from the ProviderManager\n accessor = await this.providerManager.getAdapter(providerConfig);\n Logger.debug(`ReasoningEngine obtained adapter for signature: ${accessor.adapter.providerName}`, { threadId: options.threadId, traceId: options.traceId });\n } catch (error: any) {\n Logger.error(`ReasoningEngine failed to get adapter: ${error.message}`, { error, threadId: options.threadId, traceId: options.traceId });\n // Re-throw errors from getAdapter (e.g., unknown provider, limits, conflicts)\n throw error;\n }\n\n // Use a try...finally block to ensure the adapter is released after stream consumption\n try {\n // Delegate the call to the obtained adapter instance\n const streamResult = await accessor.adapter.call(prompt, options);\n\n // Wrap the AsyncIterable to ensure release() is called when iteration is done or errors\n const releasingGenerator = (async function*() {\n try {\n for await (const event of streamResult) {\n yield event;\n }\n } finally {\n // This block executes when the generator finishes (stream consumed) or is exited (break, return, throw)\n accessor.release();\n Logger.debug(`ReasoningEngine released adapter for signature: ${accessor.adapter.providerName}`, { threadId: options.threadId, traceId: options.traceId });\n }\n })();\n\n return releasingGenerator;\n\n } catch (error: any) {\n Logger.error(`ReasoningEngine encountered an error during adapter call or stream processing: ${error.message}`, { error, threadId: options.threadId, traceId: options.traceId });\n\n // Ensure release is called even if the initial call() or stream setup fails\n accessor.release();\n Logger.debug(`ReasoningEngine released adapter after error for signature: ${accessor.adapter.providerName}`, { threadId: options.threadId, traceId: options.traceId });\n\n // Re-throw the error to be handled by the Agent Core\n throw error;\n }\n }\n}","/**\n * @module utils/xml-matcher\n * Provides a utility class for incrementally parsing and extracting content\n * from XML-like text streams. It's designed to be robust against malformed or\n * incomplete XML.\n */\n\n/**\n * Represents a chunk of text processed by {@link XmlMatcher}, indicating whether\n * it was part of the matched XML tag's content or outside of it.\n *\n * @interface XmlMatcherChunk\n */\nexport interface XmlMatcherChunk {\n /**\n * True if this chunk was inside the matched XML tag, false otherwise.\n * @property {boolean} matched\n */\n matched: boolean;\n /**\n * The text content of this chunk.\n * @property {string} data\n */\n data: string;\n}\n\n/**\n * A utility class to find and extract content within a specific XML tag from a stream of text.\n *\n * @remarks\n * It processes text chunks incrementally and yields segments, marking whether each segment\n * was inside or outside the specified XML tag.\n *\n * @example\n * // Given tagName 'think', and input \"Some text <think>this is a thought</think> and more text.\",\n * // it would yield:\n * // - { matched: false, data: \"Some text \" }\n * // - { matched: true, data: \"this is a thought\" }\n * // - { matched: false, data: \" and more text.\" }\n *\n * @class XmlMatcher\n * @template Result - The type of the transformed chunk, defaults to {@link XmlMatcherChunk}.\n */\nexport class XmlMatcher<Result = XmlMatcherChunk> {\n private index = 0;\n private currentChunks: XmlMatcherChunk[] = [];\n private cachedBuffer: string[] = [];\n private isCurrentlyMatched: boolean = false;\n private tagDepth = 0;\n private pointer = 0; // Tracks overall character position for the `position` logic\n\n /**\n * Constructs an XmlMatcher.\n *\n * @param tagName The name of the XML tag to match (e.g., \"think\").\n * @param transform An optional function to transform the yielded {@link XmlMatcherChunk} into a custom Result type.\n * @param position The character position in the input stream at which matching should begin.\n * If 0, matching starts immediately. If greater than 0, characters before this\n * position are treated as unmatched text until the tag is encountered at or after\n * this position. This is useful if the tag is expected after some preamble.\n */\n constructor(\n readonly tagName: string,\n readonly transform?: (chunk: XmlMatcherChunk) => Result,\n readonly position = 0, // Character position to start active matching\n ) {}\n\n private S_TEXT = 0;\n private S_TAG_OPEN = 1; // Expecting tag name or '/'\n private S_TAG_NAME = 2; // Matching tag name characters\n private S_TAG_CLOSING_SLASH = 3; // Found '</', expecting tag name\n private S_IGNORE_UNTIL_GT = 4; // Inside a tag, but not the one we are tracking (e.g. attributes)\n\n private state: number = this.S_TEXT;\n\n\n private collectCurrentCache(newMatchStatus?: boolean): void {\n if (this.cachedBuffer.length === 0) {\n if (newMatchStatus !== undefined && this.currentChunks.length > 0) {\n // If there's a status change but no new data, ensure the last chunk reflects the old status.\n // This is more about ensuring the `isCurrentlyMatched` reflects the status of yielded data.\n }\n return;\n }\n\n const data = this.cachedBuffer.join(\"\");\n this.cachedBuffer = [];\n const statusToUse = newMatchStatus === undefined ? this.isCurrentlyMatched : !newMatchStatus; // if newMatchStatus is defined, it means we are exiting a state\n\n const lastChunk = this.currentChunks.length > 0 ? this.currentChunks[this.currentChunks.length - 1] : null;\n\n if (lastChunk && lastChunk.matched === statusToUse) {\n lastChunk.data += data;\n } else {\n this.currentChunks.push({\n matched: statusToUse,\n data: data,\n });\n }\n }\n\n private flushProcessedChunks(): Result[] {\n const chunksToYield = this.currentChunks;\n this.currentChunks = [];\n if (this.transform) {\n return chunksToYield.map(this.transform);\n }\n return chunksToYield as unknown as Result[];\n }\n\n /**\n * Processes an incoming chunk of text.\n *\n * @param chunk The text chunk to process.\n * @returns An array of transformed results based on the matched segments.\n */\n update(chunk: string): Result[] {\n for (let i = 0; i < chunk.length; i++) {\n const char = chunk[i];\n this.pointer++;\n\n if (this.state === this.S_TEXT) {\n if (char === '<' && (this.pointer > this.position || this.isCurrentlyMatched || this.tagDepth > 0) ) {\n this.collectCurrentCache();\n this.state = this.S_TAG_OPEN;\n this.cachedBuffer.push(char);\n } else {\n this.cachedBuffer.push(char);\n }\n } else if (this.state === this.S_TAG_OPEN) { // After '<'\n this.cachedBuffer.push(char);\n if (char === '/') {\n this.state = this.S_TAG_CLOSING_SLASH;\n this.index = 0;\n } else if (char.match(/[a-zA-Z]/)) { // Start of a tag name\n this.state = this.S_TAG_NAME;\n this.index = 0;\n // Re-evaluate this char in S_TAG_NAME state\n this.cachedBuffer.pop(); // Remove char from buffer as it's part of tag name\n i--; // Reprocess this character\n } else { // Not a valid tag start after '<' (e.g., '< foo'), treat as text\n this.state = this.S_TEXT;\n }\n } else if (this.state === this.S_TAG_NAME) { // Matching opening tag name\n if (this.index < this.tagName.length && char === this.tagName[this.index]) {\n this.cachedBuffer.push(char);\n this.index++;\n } else if (char === '>' && this.index === this.tagName.length) { // Matched full <tagName>\n this.cachedBuffer.push(char);\n this.collectCurrentCache(true); // Content before this tag was not matched\n this.isCurrentlyMatched = true;\n this.tagDepth++;\n this.state = this.S_TEXT;\n this.cachedBuffer = []; // Clear buffer like <think>\n } else if ((char === ' ' || char === '\\t' || char === '\\n' || char === '\\r' || char === '>') && this.index === this.tagName.length) {\n // Tag name matched, now expecting attributes or '>'\n this.cachedBuffer.push(char);\n if (char === '>') { // Self-closing or no attributes <tagName>\n this.collectCurrentCache(true);\n this.isCurrentlyMatched = true;\n this.tagDepth++;\n this.state = this.S_TEXT;\n this.cachedBuffer = [];\n } else { // Attributes might follow\n this.state = this.S_IGNORE_UNTIL_GT;\n }\n }\n else { // Mismatch or other tag\n this.state = this.S_IGNORE_UNTIL_GT; // Treat as part of some other tag\n this.cachedBuffer.push(char);\n }\n } else if (this.state === this.S_TAG_CLOSING_SLASH) { // After '</'\n this.cachedBuffer.push(char);\n if (this.index < this.tagName.length && char === this.tagName[this.index]) {\n this.index++;\n } else if (char === '>' && this.index === this.tagName.length) { // Matched full </tagName>\n this.collectCurrentCache(false); // Content before this was matched\n this.tagDepth--;\n this.isCurrentlyMatched = (this.tagDepth > 0);\n this.state = this.S_TEXT;\n this.cachedBuffer = []; // Clear buffer like </think>\n } else { // Mismatch or other closing tag\n this.state = this.S_IGNORE_UNTIL_GT; // Treat as part of some other tag\n }\n } else if (this.state === this.S_IGNORE_UNTIL_GT) {\n this.cachedBuffer.push(char);\n if (char === '>') { // End of an ignored tag\n this.state = this.S_TEXT;\n }\n }\n }\n return this.flushProcessedChunks();\n }\n\n /**\n * Finalizes processing, flushing any remaining buffered text.\n *\n * @param chunk An optional final text chunk to process.\n * @returns An array of transformed results.\n */\n final(chunk?: string): Result[] {\n if (chunk) {\n this.update(chunk); // Process final chunk, which will also call flushProcessedChunks\n }\n this.collectCurrentCache(); // Collect any remaining data in buffer\n return this.flushProcessedChunks();\n }\n}","// src/systems/reasoning/OutputParser.ts\nimport * as z from 'zod'; // Import Zod\nimport { OutputParser as IOutputParser } from '@/core/interfaces';\nimport { ParsedToolCall, TodoItem, TodoItemStatus, ExecutionOutput } from '@/types';\nimport { Logger } from '@/utils/logger'; // Import the Logger class\nimport { XmlMatcher } from '@/utils/xml-matcher'; // Import XmlMatcher\n\n// Define Zod schema for a single tool call\nconst parsedToolCallSchema = z.object({\n callId: z.string().min(1), // Ensure callId is a non-empty string\n toolName: z.string().min(1), // Ensure toolName is a non-empty string\n arguments: z.unknown(), // Arguments must exist but can be any type; specific tools validate further\n});\n\n// Define Zod schema for an array of tool calls\nconst toolCallsSchema = z.array(parsedToolCallSchema);\n\nconst todoItemSchema = z.object({\n id: z.string(),\n description: z.string(),\n status: z.nativeEnum(TodoItemStatus).optional().default(TodoItemStatus.PENDING),\n dependencies: z.array(z.string()).optional()\n});\nconst todoListSchema = z.array(todoItemSchema);\n\n/**\n * Default implementation of the `OutputParser` interface.\n */\nexport class OutputParser implements IOutputParser {\n\n /**\n * Parses the raw string output from the planning LLM call.\n * Expects JSON output with `title`, `intent`, `plan` (description), and `todoList`.\n */\n async parsePlanningOutput(output: string): Promise<{\n title?: string;\n intent?: string;\n plan?: string;\n toolCalls?: ParsedToolCall[];\n thoughts?: string;\n todoList?: TodoItem[];\n }> {\n const result: {\n title?: string;\n intent?: string;\n plan?: string;\n toolCalls?: ParsedToolCall[];\n thoughts?: string;\n todoList?: TodoItem[];\n } = {};\n\n let processedOutput = output;\n const thoughtsList: string[] = [];\n\n // Extract thoughts using XmlMatcher\n const xmlMatcher = new XmlMatcher('think');\n const chunks = xmlMatcher.final(output);\n\n let nonThinkingContent = \"\";\n chunks.forEach(chunk => {\n if (chunk.matched) {\n thoughtsList.push(chunk.data.trim());\n } else {\n nonThinkingContent += chunk.data;\n }\n });\n\n if (thoughtsList.length > 0) {\n result.thoughts = thoughtsList.join(\"\\n\\n---\\n\\n\");\n }\n\n processedOutput = nonThinkingContent;\n\n // Helper for JSON parsing\n const tryParseJson = (raw: string) => {\n if (!raw) return null;\n let s = raw.trim();\n s = s.replace(/^```(?:json)?\\s*/i, '').replace(/\\s*```$/i, '').trim();\n if (!s.startsWith('{') && s.includes('{') && s.includes('}')) {\n const first = s.indexOf('{');\n const last = s.lastIndexOf('}');\n if (first >= 0 && last > first) {\n s = s.slice(first, last + 1);\n }\n }\n try {\n return JSON.parse(s);\n } catch {\n return null;\n }\n };\n\n const obj = tryParseJson(processedOutput);\n\n if (obj && typeof obj === 'object') {\n if (typeof obj.title === 'string') result.title = obj.title;\n if (typeof obj.intent === 'string') result.intent = obj.intent;\n // Handle plan as string or array\n if (Array.isArray(obj.plan)) result.plan = obj.plan.map((p:any) => typeof p === 'string' ? p : JSON.stringify(p)).join('\\n');\n else if (typeof obj.plan === 'string') result.plan = obj.plan;\n\n if (Array.isArray(obj.toolCalls)) {\n const validation = toolCallsSchema.safeParse(obj.toolCalls);\n if (validation.success) result.toolCalls = validation.data as ParsedToolCall[];\n else result.toolCalls = [];\n }\n\n if (Array.isArray(obj.todoList)) {\n const validation = todoListSchema.safeParse(obj.todoList);\n if (validation.success) {\n result.todoList = (validation.data as any[]).map((item: any) => ({\n ...item,\n createdTimestamp: Date.now(),\n updatedTimestamp: Date.now()\n })) as TodoItem[];\n } else {\n Logger.warn(`OutputParser: TodoList validation failed: ${validation.error}`);\n }\n }\n } else {\n // Fallback for legacy section parsing or non-JSON output (Best effort)\n // For the new requirement, JSON is strongly preferred/enforced by prompt.\n // We can reuse the legacy regexes for title/intent/plan if JSON fails.\n const titleMatch = processedOutput.match(/Title:\\s*([\\s\\S]*?)(Intent:|Plan:|Tool Calls:|Todo List:|$)/i);\n if (titleMatch) result.title = titleMatch[1].trim();\n\n const intentMatch = processedOutput.match(/Intent:\\s*([\\s\\S]*?)(Plan:|Tool Calls:|Todo List:|$)/i);\n if (intentMatch) result.intent = intentMatch[1].trim();\n\n const planMatch = processedOutput.match(/Plan:\\s*([\\s\\S]*?)(Tool Calls:|Todo List:|$)/i);\n if (planMatch) result.plan = planMatch[1].trim();\n }\n\n return result;\n }\n\n /**\n * Parses the execution output (per todo item).\n */\n async parseExecutionOutput(output: string): Promise<ExecutionOutput> {\n const result: ExecutionOutput = {};\n let processedOutput = output;\n const thoughtsList: string[] = [];\n\n // Extract thoughts\n const xmlMatcher = new XmlMatcher('think');\n const chunks = xmlMatcher.final(output);\n\n let nonThinkingContent = \"\";\n chunks.forEach(chunk => {\n if (chunk.matched) {\n thoughtsList.push(chunk.data.trim());\n } else {\n nonThinkingContent += chunk.data;\n }\n });\n\n if (thoughtsList.length > 0) {\n result.thoughts = thoughtsList.join(\"\\n\\n---\\n\\n\");\n }\n processedOutput = nonThinkingContent.trim();\n\n // Try to parse as JSON first (if the prompt enforces JSON for execution)\n // If the prompt asks for \"text response\" + \"tool calls\" as JSON block, handle that.\n // Assuming a JSON structure for tool calls or updated plan.\n\n // Look for a JSON block for tool calls\n const jsonBlockMatch = processedOutput.match(/```json\\s*([\\s\\S]*?)\\s*```/);\n if (jsonBlockMatch) {\n try {\n const jsonContent = JSON.parse(jsonBlockMatch[1]);\n\n // Check for toolCalls\n if (Array.isArray(jsonContent.toolCalls)) {\n const validation = toolCallsSchema.safeParse(jsonContent.toolCalls);\n if (validation.success) result.toolCalls = validation.data as ParsedToolCall[];\n } else if (Array.isArray(jsonContent)) {\n // Sometimes tool calls are just the array\n const validation = toolCallsSchema.safeParse(jsonContent);\n if (validation.success) result.toolCalls = validation.data as ParsedToolCall[];\n }\n\n // Check for nextStepDecision or updatedPlan in JSON\n if (jsonContent.nextStepDecision) result.nextStepDecision = jsonContent.nextStepDecision;\n if (jsonContent.updatedPlan) result.updatedPlan = jsonContent.updatedPlan;\n\n // Remove the JSON block from content if it was just metadata/tools\n // But if the whole output is JSON, content is empty?\n // Let's assume content is the text *outside* the JSON block, or a 'content' field in JSON.\n if (jsonContent.content) {\n result.content = jsonContent.content;\n } else {\n // If content was outside, we need to strip the JSON block\n result.content = processedOutput.replace(jsonBlockMatch[0], '').trim();\n }\n } catch (e) {\n Logger.warn(`Failed to parse JSON block in execution output: ${e}`);\n result.content = processedOutput; // Fallback\n }\n } else {\n // No JSON block, treat everything as content\n result.content = processedOutput;\n }\n\n return result;\n }\n\n async parseSynthesisOutput(output: string): Promise<string> {\n return output.trim();\n }\n}\n","// src/systems/ui/observation-socket.ts\nimport { TypedSocket } from './typed-socket';\nimport { Observation, ObservationType, ObservationFilter } from '@/types';\nimport { Logger } from '@/utils/logger';\nimport { IObservationRepository } from '@/core/interfaces'; // Assuming this exists\n\n/**\n * A specialized TypedSocket for handling Observation data.\n * Allows filtering by ObservationType.\n * Can optionally fetch historical observations from a repository.\n */\nexport class ObservationSocket extends TypedSocket<Observation, ObservationType | ObservationType[]> {\n private observationRepository?: IObservationRepository;\n\n constructor(observationRepository?: IObservationRepository) {\n super(); // No logger instance needed\n this.observationRepository = observationRepository;\n Logger.debug('ObservationSocket initialized.');\n }\n\n /**\n * Notifies subscribers about a new observation.\n * @param observation - The observation data.\n */\n notifyObservation(observation: Observation): void {\n Logger.debug(`Notifying Observation: ${observation.id} (${observation.type}) for thread ${observation.threadId}`);\n super.notify(\n observation,\n { targetThreadId: observation.threadId },\n (data, filter) => {\n if (!filter) return true; // No filter, always notify\n if (Array.isArray(filter)) {\n return filter.includes(data.type); // Check if type is in the array\n }\n return data.type === filter; // Check for single type match\n }\n );\n }\n\n /**\n * Retrieves historical observations, optionally filtered by type and thread.\n * Requires an ObservationRepository to be configured.\n * @param filter - Optional ObservationType or array of types to filter by.\n * @param options - Optional threadId and limit.\n * @returns A promise resolving to an array of observations.\n */\n async getHistory(\n filter?: ObservationType | ObservationType[],\n options?: { threadId?: string; limit?: number }\n ): Promise<Observation[]> {\n if (!this.observationRepository) {\n Logger.warn('Cannot getHistory for ObservationSocket: ObservationRepository not configured.');\n return [];\n }\n if (!options?.threadId) {\n Logger.warn('Cannot getHistory for ObservationSocket: threadId is required.');\n return [];\n }\n\n Logger.debug(`Getting history for ObservationSocket: Thread ${options.threadId}, Filter: ${JSON.stringify(filter)}, Limit: ${options.limit}`);\n\n // Construct the ObservationFilter for the repository method\n const observationFilter: ObservationFilter = {};\n\n if (filter) {\n observationFilter.types = Array.isArray(filter) ? filter : [filter];\n }\n // Note: The limit option is not part of the ObservationFilter type.\n // It's expected that the IObservationRepository implementation\n // will handle limiting when querying the underlying StorageAdapter,\n // potentially by accepting limit directly or translating from options.\n // Sorting is also handled by the repository implementation.\n if (options.limit !== undefined) {\n // We don't assign options.limit to observationFilter directly.\n // The getObservations implementation needs to handle the limit.\n Logger.debug(`Limit requested: ${options.limit}. Repository implementation must handle this.`);\n }\n\n\n try {\n // Call the correct repository method\n const observations = await this.observationRepository.getObservations(\n options.threadId,\n observationFilter\n );\n // The repository method likely returns observations in a standard order (e.g., chronological or reverse chronological).\n // Assuming reverse chronological (newest first) based on common usage.\n return observations;\n } catch (error) {\n Logger.error(`Error fetching observation history for thread ${options.threadId} with filter ${JSON.stringify(observationFilter)}:`, error);\n return [];\n }\n }\n}","// src/systems/ui/conversation-socket.ts\nimport { TypedSocket } from './typed-socket';\nimport { ConversationMessage, MessageRole } from '@/types';\nimport { Logger } from '@/utils/logger';\nimport { IConversationRepository } from '@/core/interfaces'; // Assuming this exists\n\n/**\n * A specialized TypedSocket for handling ConversationMessage data.\n * Allows filtering by MessageRole.\n * Can optionally fetch historical messages from a repository.\n */\nexport class ConversationSocket extends TypedSocket<ConversationMessage, MessageRole | MessageRole[]> {\n private conversationRepository?: IConversationRepository;\n\n constructor(conversationRepository?: IConversationRepository) {\n super(); // No logger instance needed\n this.conversationRepository = conversationRepository;\n Logger.debug('ConversationSocket initialized.');\n }\n\n /**\n * Notifies subscribers about a new conversation message.\n * @param message - The conversation message data.\n */\n notifyMessage(message: ConversationMessage): void {\n Logger.debug(`Notifying Message: ${message.messageId} (${message.role}) for thread ${message.threadId}`);\n super.notify(\n message,\n { targetThreadId: message.threadId },\n (data, filter) => {\n if (!filter) return true; // No filter, always notify\n if (Array.isArray(filter)) {\n return filter.includes(data.role); // Check if role is in the array\n }\n return data.role === filter; // Check for single role match\n }\n );\n }\n\n /**\n * Retrieves historical messages, optionally filtered by role and thread.\n * Requires a ConversationRepository to be configured.\n * @param filter - Optional MessageRole or array of roles to filter by.\n * @param options - Optional threadId and limit.\n * @returns A promise resolving to an array of messages.\n */\n async getHistory(\n filter?: MessageRole | MessageRole[],\n options?: { threadId?: string; limit?: number } // Add other MessageOptions if needed\n ): Promise<ConversationMessage[]> {\n if (!this.conversationRepository) {\n Logger.warn('Cannot getHistory for ConversationSocket: ConversationRepository not configured.');\n return [];\n }\n if (!options?.threadId) {\n Logger.warn('Cannot getHistory for ConversationSocket: threadId is required.');\n return [];\n }\n\n Logger.debug(`Getting history for ConversationSocket: Thread ${options.threadId}, Filter: ${JSON.stringify(filter)}, Limit: ${options.limit}`);\n\n // Construct the MessageOptions for the repository method\n // Note: The IConversationRepository.getMessages interface uses MessageOptions,\n // which currently only defines limit and timestamps. Filtering by role needs\n // to be handled either within the repository implementation or client-side after fetching.\n // For now, we pass limit and assume the repository handles it. Role filtering is omitted here.\n const messageOptions: { limit?: number } = {};\n if (options.limit !== undefined) {\n messageOptions.limit = options.limit;\n }\n\n // TODO: If role filtering is crucial, the IConversationRepository interface\n // and its implementations might need updating to support filtering by role.\n if (filter) {\n Logger.warn(`Role filtering requested for ConversationSocket.getHistory, but not directly supported by IConversationRepository.getMessages. Fetching all roles up to limit.`);\n }\n\n try {\n const messages = await this.conversationRepository.getMessages(\n options.threadId,\n messageOptions\n );\n // Messages are typically returned in chronological order (oldest first).\n return messages;\n } catch (error) {\n Logger.error(`Error fetching message history for thread ${options.threadId}:`, error);\n return [];\n }\n }\n}","// src/systems/ui/ui-system.ts\nimport {\n UISystem as IUISystem,\n IObservationRepository,\n IConversationRepository,\n IA2ATaskRepository\n} from '@/core/interfaces';\nimport { ObservationSocket } from './observation-socket';\nimport { ConversationSocket } from './conversation-socket';\nimport { LLMStreamSocket } from './llm-stream-socket'; // Import the new socket\nimport { A2ATaskSocket } from './a2a-task-socket';\nimport { Logger } from '@/utils/logger';\n\n/**\n * Provides access to the UI communication sockets (Observation, Conversation, LLM Stream, and A2A Task).\n * Instantiates the sockets with their required dependencies.\n */\nexport class UISystem implements IUISystem {\n private observationSocketInstance: ObservationSocket;\n private conversationSocketInstance: ConversationSocket;\n private llmStreamSocketInstance: LLMStreamSocket; // Add the new socket instance\n private a2aTaskSocketInstance: A2ATaskSocket;\n\n /**\n * Creates an instance of UISystem.\n * @param observationRepository - Repository for observation data, passed to ObservationSocket.\n * @param conversationRepository - Repository for conversation data, passed to ConversationSocket.\n * @param a2aTaskRepository - Optional repository for A2A task data, passed to A2ATaskSocket.\n */\n constructor(\n observationRepository: IObservationRepository,\n conversationRepository: IConversationRepository,\n a2aTaskRepository?: IA2ATaskRepository\n ) {\n this.observationSocketInstance = new ObservationSocket(observationRepository);\n this.conversationSocketInstance = new ConversationSocket(conversationRepository);\n this.llmStreamSocketInstance = new LLMStreamSocket(); // Instantiate the new socket\n this.a2aTaskSocketInstance = new A2ATaskSocket(a2aTaskRepository);\n Logger.debug('UISystem initialized with Observation, Conversation, LLM Stream, and A2A Task sockets.');\n }\n\n /**\n * Gets the singleton instance of the ObservationSocket.\n * @returns The ObservationSocket instance.\n */\n getObservationSocket(): ObservationSocket {\n return this.observationSocketInstance;\n }\n\n /**\n * Gets the singleton instance of the ConversationSocket.\n * @returns The ConversationSocket instance.\n */\n getConversationSocket(): ConversationSocket {\n return this.conversationSocketInstance;\n }\n\n /**\n * Gets the singleton instance of the LLMStreamSocket.\n * @returns The LLMStreamSocket instance.\n */\n getLLMStreamSocket(): LLMStreamSocket {\n return this.llmStreamSocketInstance;\n }\n\n /**\n * Gets the singleton instance of the A2ATaskSocket.\n * @returns The A2ATaskSocket instance.\n */\n getA2ATaskSocket(): A2ATaskSocket {\n return this.a2aTaskSocketInstance;\n }\n}","import { IAuthStrategy } from '@/core/interfaces';\nimport { ARTError, ErrorCode } from '@/errors';\nimport { Logger } from '@/utils/logger';\n\n/**\n * Central authentication manager for handling multiple authentication strategies.\n * Manages registration and retrieval of different auth strategies for secure connections\n * to remote services like MCP servers and A2A agents.\n */\nexport class AuthManager {\n private strategies = new Map<string, IAuthStrategy>();\n\n constructor() {\n Logger.info('AuthManager initialized.');\n }\n\n /**\n * Registers an authentication strategy with the given ID.\n * @param strategyId - Unique identifier for the strategy (e.g., 'default_zyntopia_auth', 'api_key_strategy')\n * @param strategy - Implementation of IAuthStrategy\n * @throws {ARTError} If strategyId is empty or null\n */\n public registerStrategy(strategyId: string, strategy: IAuthStrategy): void {\n if (!strategyId || strategyId.trim() === '') {\n throw new ARTError('Strategy ID cannot be empty or null', ErrorCode.INVALID_CONFIG);\n }\n\n if (this.strategies.has(strategyId)) {\n Logger.warn(`AuthManager: Overwriting existing auth strategy with ID: ${strategyId}`);\n }\n \n this.strategies.set(strategyId, strategy);\n Logger.debug(`AuthManager: Registered strategy '${strategyId}'.`);\n }\n\n /**\n * Retrieves authentication headers from the specified strategy.\n * @param strategyId - The ID of the registered strategy to use\n * @returns Promise resolving to authentication headers\n * @throws {ARTError} If strategy is not found or authentication fails\n */\n public async getHeaders(strategyId: string): Promise<Record<string, string>> {\n const strategy = this.strategies.get(strategyId);\n if (!strategy) {\n // Convention: If a Zyntopia-related auth is needed but not found, guide the developer.\n if (strategyId.includes('zyntopia')) {\n Logger.error(`AuthManager: Strategy '${strategyId}' not found. Did you register a ZyntopiaOAuthStrategy with the ID 'default_zyntopia_auth'?`);\n }\n throw new ARTError(`Authentication strategy with ID '${strategyId}' not found.`, ErrorCode.INVALID_CONFIG);\n }\n\n try {\n return await strategy.getAuthHeaders();\n } catch (error) {\n const message = `Failed to get authentication headers from strategy '${strategyId}'`;\n Logger.error(message, error);\n throw new ARTError(message, ErrorCode.LLM_PROVIDER_ERROR, error instanceof Error ? error : new Error(String(error)));\n }\n }\n\n /**\n * Checks if a strategy with the given ID is registered.\n * @param strategyId - The ID to check\n * @returns True if the strategy exists, false otherwise\n */\n public hasStrategy(strategyId: string): boolean {\n return this.strategies.has(strategyId);\n }\n\n /**\n * Lists all registered strategy IDs.\n * @returns Array of registered strategy IDs\n */\n public getRegisteredStrategyIds(): string[] {\n return Array.from(this.strategies.keys());\n }\n\n /**\n * Removes a registered strategy.\n * @param strategyId - The ID of the strategy to remove\n * @returns True if strategy was removed, false if it didn't exist\n */\n public removeStrategy(strategyId: string): boolean {\n const removed = this.strategies.delete(strategyId);\n if (removed) {\n Logger.debug(`AuthManager: Removed strategy '${strategyId}'.`);\n }\n return removed;\n }\n\n /**\n * Clears all registered strategies.\n * Useful for testing or complete reconfiguration.\n */\n public clearAllStrategies(): void {\n const count = this.strategies.size;\n this.strategies.clear();\n Logger.debug(`AuthManager: Cleared ${count} strategies.`);\n }\n\n /**\n * Initiates the login flow for a specific strategy.\n * @param {string} strategyId - The ID of the strategy to use for login.\n * @returns {Promise<void>} A promise that resolves when the login process is initiated.\n * @throws {ARTError} If the strategy is not found or does not support login.\n */\n public async login(strategyId: string): Promise<void> {\n const strategy = this.strategies.get(strategyId);\n if (!strategy || !strategy.login) {\n throw new ARTError(`Login not supported for strategy '${strategyId}'.`, ErrorCode.INVALID_CONFIG);\n }\n await strategy.login();\n }\n\n /**\n * Handles the redirect from an OAuth provider.\n * @param {string} strategyId - The ID of the strategy that initiated the redirect.\n * @returns {Promise<void>} A promise that resolves when the redirect has been handled.\n * @throws {ARTError} If the strategy is not found or does not support handling redirects.\n */\n public async handleRedirect(strategyId: string): Promise<void> {\n const strategy = this.strategies.get(strategyId);\n if (!strategy || !strategy.handleRedirect) {\n throw new ARTError(`handleRedirect not supported for strategy '${strategyId}'.`, ErrorCode.INVALID_CONFIG);\n }\n await strategy.handleRedirect();\n }\n\n /**\n * Logs the user out of a specific strategy.\n * @param {string} strategyId - The ID of the strategy to use for logout.\n * @throws {ARTError} If the strategy is not found or does not support logout.\n */\n public logout(strategyId: string): void {\n const strategy = this.strategies.get(strategyId);\n if (!strategy || !strategy.logout) {\n throw new ARTError(`Logout not supported for strategy '${strategyId}'.`, ErrorCode.INVALID_CONFIG);\n }\n strategy.logout();\n }\n\n /**\n * Checks if the user is authenticated with a specific strategy.\n * @param {string} strategyId - The ID of the strategy to check.\n * @returns {Promise<boolean>} A promise that resolves to true if authenticated, false otherwise.\n */\n public async isAuthenticated(strategyId: string): Promise<boolean> {\n const strategy = this.strategies.get(strategyId);\n if (!strategy || !strategy.isAuthenticated) {\n return false;\n }\n return await strategy.isAuthenticated();\n }\n}","import { IToolExecutor } from '@/core/interfaces';\nimport { ToolSchema, ToolResult, ExecutionContext } from '@/types';\nimport { Logger } from '@/utils/logger';\nimport { McpManager } from './McpManager';\nimport { McpServerConfig, McpToolDefinition } from './types';\nimport { CallToolResultSchema } from '@modelcontextprotocol/sdk/types.js';\n\n/**\n * A proxy tool that wraps an MCP server tool and implements the {@link IToolExecutor} interface.\n *\n * @remarks\n * This allows MCP server tools to be used seamlessly within the ART Framework.\n *\n * @see {@link McpManager} for the system that manages these proxy tools.\n * @see {@link IToolExecutor} for the interface it implements.\n *\n * @class McpProxyTool\n */\nexport class McpProxyTool implements IToolExecutor {\n public readonly schema: ToolSchema;\n \n private card: McpServerConfig;\n private toolDefinition: McpToolDefinition;\n private mcpManager: McpManager;\n\n /**\n * Creates an instance of McpProxyTool.\n *\n * @param card Configuration for the MCP server hosting this tool.\n * @param toolDefinition The tool definition from the MCP server.\n * @param mcpManager The MCP manager for managing connections.\n */\n constructor(card: McpServerConfig, toolDefinition: McpToolDefinition, mcpManager: McpManager) {\n this.card = card;\n this.toolDefinition = toolDefinition;\n this.mcpManager = mcpManager;\n\n // Convert MCP tool definition to ART ToolSchema\n this.schema = {\n name: `mcp_${card.id}_${toolDefinition.name}`,\n description: toolDefinition.description || `Tool ${toolDefinition.name} from ${card.displayName || card.id}`,\n inputSchema: toolDefinition.inputSchema,\n outputSchema: toolDefinition.outputSchema\n };\n\n Logger.debug(`McpProxyTool: Created proxy for tool \"${toolDefinition.name}\" from server \"${card.displayName}\"`);\n }\n\n /**\n * Executes the tool by making a request to the MCP server.\n *\n * @param input Validated input arguments for the tool.\n * @param context Execution context containing threadId, traceId, etc.\n * @returns A promise resolving to the tool result.\n */\n async execute(input: any, context: ExecutionContext): Promise<ToolResult> {\n const startTime = Date.now();\n \n try {\n Logger.debug(`McpProxyTool: Execution requested for \"${this.schema.name}\". Getting or creating connection...`);\n const client = await this.mcpManager.getOrCreateConnection(this.card.id);\n\n Logger.debug(`McpProxyTool: Connection ready. Executing tool \"${this.toolDefinition.name}\" on server \"${this.card.displayName}\"`);\n const response = await client.callTool(this.toolDefinition.name, input);\n \n const duration = Date.now() - startTime;\n \n // Validate the raw response against the SDK's schema for robustness.\n // If validation fails, it will throw an error that is caught below.\n const validatedResponse = CallToolResultSchema.parse(response);\n \n // Adapt the response to the ToolResult format\n // This is a generic adaptation, specific tools might require more tailored logic\n // based on the shape of their response.\n const output = typeof validatedResponse === 'object' && validatedResponse !== null ? validatedResponse : { value: validatedResponse };\n\n return {\n callId: context.traceId || 'unknown',\n toolName: this.schema.name,\n status: 'success',\n output: [output], // Assuming the output should be wrapped in an array\n metadata: { \n executionTime: duration, \n mcpServer: { id: this.card.id, name: this.card.displayName },\n rawResponse: response \n }\n };\n } catch (error: any) {\n const duration = Date.now() - startTime;\n Logger.error(`McpProxyTool: Failed to execute tool \"${this.toolDefinition.name}\": ${error.message}`);\n return {\n callId: context.traceId || 'unknown',\n toolName: this.schema.name,\n status: 'error',\n error: `MCP execution failed: ${error.message}`,\n metadata: { executionTime: duration, mcpServer: { id: this.card.id, name: this.card.displayName }, originalError: error instanceof Error ? error.stack : String(error) }\n };\n }\n }\n\n /**\n * Gets the original tool name from the MCP server.\n *\n * @returns The original tool name.\n */\n getOriginalToolName(): string {\n return this.toolDefinition.name;\n }\n\n /**\n * Gets the MCP server configuration.\n *\n * @returns The server configuration.\n */\n getServerConfig(): McpServerConfig {\n return { ...this.card };\n }\n\n /**\n * Gets the MCP tool definition.\n *\n * @returns The tool definition.\n */\n getToolDefinition(): McpToolDefinition {\n return { ...this.toolDefinition };\n }\n} ","import { Logger } from '@/utils/logger';\nimport { ArtMcpConfig, McpServerConfig } from './types';\n\n/**\n * Manages the MCP configuration, handling loading, validation, and saving to localStorage.\n * It ensures that the MCP connection details are always available and well-formed.\n */\nexport class ConfigManager {\n private configKey = 'art_mcp_config';\n private config: ArtMcpConfig;\n\n /**\n * Initializes the ConfigManager by loading the configuration from localStorage.\n */\n constructor() {\n this.config = this.loadConfig();\n }\n\n /**\n * Loads the MCP configuration from localStorage, creating a default if none exists.\n * @private\n * @returns {ArtMcpConfig} The loaded or created MCP configuration.\n */\n private loadConfig(): ArtMcpConfig {\n try {\n const storedConfig = localStorage.getItem(this.configKey);\n if (storedConfig) {\n const rawConfig = JSON.parse(storedConfig) as ArtMcpConfig;\n const validatedConfig = this.validateAndFixConfig(rawConfig);\n \n // If config was fixed, save it back\n if (JSON.stringify(validatedConfig) !== JSON.stringify(rawConfig)) {\n Logger.info(`ConfigManager: Config was automatically validated and fixed`);\n this.writeConfig(validatedConfig);\n }\n return validatedConfig;\n }\n } catch (error: any) {\n Logger.error(`ConfigManager: Error reading or parsing config from localStorage: ${error.message}`);\n }\n \n Logger.info(`ConfigManager: Configuration not found in localStorage. Creating a new default config.`);\n const defaultConfig = this.createDefaultConfig();\n this.writeConfig(defaultConfig);\n return defaultConfig;\n }\n\n /**\n * Validates the loaded configuration and fixes any inconsistencies.\n * @private\n * @param {ArtMcpConfig} config - The configuration to validate.\n * @returns {ArtMcpConfig} The validated and fixed configuration.\n */\n private validateAndFixConfig(config: ArtMcpConfig): ArtMcpConfig {\n const cleanConfig: ArtMcpConfig = {\n mcpServers: {}\n };\n\n // Process each server entry\n for (const [serverId, serverConfig] of Object.entries(config.mcpServers)) {\n // Skip corrupted entries\n if (serverId === '[object Object]' || typeof serverConfig !== 'object' || !serverConfig) {\n Logger.warn(`ConfigManager: Removing corrupted entry: \"${serverId}\"`);\n continue;\n }\n\n // Ensure the server config has all required fields\n const fixedConfig: McpServerConfig = {\n id: serverConfig.id || serverId,\n type: serverConfig.type || 'streamable-http',\n enabled: serverConfig.enabled !== false, // Default to true\n displayName: serverConfig.displayName || serverId,\n description: serverConfig.description || `MCP server: ${serverId}`,\n connection: serverConfig.connection,\n installation: serverConfig.installation,\n timeout: serverConfig.timeout || 30000,\n tools: serverConfig.tools || [], // Add missing tools array\n resources: serverConfig.resources || [], // Add missing resources array\n resourceTemplates: serverConfig.resourceTemplates || [] // Add missing resourceTemplates array\n };\n\n // For Tavily specifically, ensure it has the proper tools definition\n if (serverId === 'tavily_search_stdio' && (!fixedConfig.tools || fixedConfig.tools.length === 0)) {\n fixedConfig.tools = [\n {\n name: 'tavily-search',\n description: 'A powerful web search tool that provides comprehensive, real-time results using Tavily\\'s AI search engine.',\n inputSchema: {\n type: 'object',\n properties: {\n query: { type: 'string', description: 'Search query' },\n search_depth: { type: 'string', enum: ['basic', 'advanced'], description: 'The depth of the search. It can be \\'basic\\' or \\'advanced\\'', default: 'basic' },\n topic: { type: 'string', enum: ['general', 'news'], description: 'The category of the search', default: 'general' },\n max_results: { type: 'number', description: 'The maximum number of search results to return', default: 10, minimum: 5, maximum: 20 },\n include_raw_content: { type: 'boolean', description: 'Include the cleaned and parsed HTML content of each search result', default: false }\n },\n required: ['query']\n }\n },\n {\n name: 'tavily-extract',\n description: 'A powerful web content extraction tool that retrieves and processes raw content from specified URLs.',\n inputSchema: {\n type: 'object',\n properties: {\n urls: { type: 'array', items: { type: 'string' }, description: 'List of URLs to extract content from' },\n extract_depth: { type: 'string', enum: ['basic', 'advanced'], description: 'Depth of extraction - \\'basic\\' or \\'advanced\\'', default: 'basic' },\n include_images: { type: 'boolean', description: 'Include a list of images extracted from the urls in the response', default: false }\n },\n required: ['urls']\n }\n }\n ];\n Logger.info(`ConfigManager: Added tools definition for Tavily server`);\n }\n\n cleanConfig.mcpServers[serverId] = fixedConfig;\n }\n\n return cleanConfig;\n }\n\n /**\n * Creates a default MCP configuration.\n * @private\n * @returns {ArtMcpConfig} The default MCP configuration.\n */\n private createDefaultConfig(): ArtMcpConfig {\n // Default to a remote, streamable-http Tavily server\n const tavilyCard: McpServerConfig = {\n id: \"tavily_search_remote\",\n type: \"streamable-http\",\n enabled: true,\n displayName: \"Tavily Search (Remote)\",\n description: \"Provides AI-powered search and web content extraction tools via a remote server.\",\n connection: {\n url: \"https://mcp.tavily.com/v1/stream\", // This is a placeholder URL\n authStrategyId: \"tavily_api_key\" // Assumes an ApiKeyStrategy is configured\n },\n tools: [\n {\n name: \"tavily-search\",\n description: \"A powerful web search tool...\",\n inputSchema: { /* ... schema ... */ }\n },\n {\n name: \"tavily-extract\",\n description: \"A powerful web content extraction tool...\",\n inputSchema: { /* ... schema ... */ }\n }\n ],\n resources: [],\n resourceTemplates: []\n };\n return { mcpServers: { \"tavily_search_remote\": tavilyCard } };\n }\n\n /**\n * Writes the MCP configuration to localStorage.\n * @private\n * @param {ArtMcpConfig} config - The configuration to write.\n */\n private writeConfig(config: ArtMcpConfig): void {\n try {\n localStorage.setItem(this.configKey, JSON.stringify(config, null, 2));\n Logger.debug(`ConfigManager: Configuration saved to localStorage.`);\n } catch (error: any) {\n Logger.error(`ConfigManager: Failed to write to localStorage: ${error.message}`);\n // Don't throw in browser context, as it could break the app\n }\n }\n\n /**\n * Gets the current MCP configuration.\n * @returns {ArtMcpConfig} The current MCP configuration.\n */\n public getConfig(): ArtMcpConfig {\n return this.config;\n }\n\n /**\n * Sets the configuration for a specific server and saves it.\n * @param {string} serverId - The ID of the server to configure.\n * @param {McpServerConfig} serverConfig - The configuration for the server.\n */\n public setServerConfig(serverId: string, serverConfig: McpServerConfig): void {\n this.config.mcpServers[serverId] = serverConfig;\n this.writeConfig(this.config);\n Logger.info(`ConfigManager: Updated configuration for server \"${serverId}\"`);\n }\n\n /**\n * Removes the configuration for a specific server and saves the changes.\n * @param {string} serverId - The ID of the server to remove.\n */\n public removeServerConfig(serverId: string): void {\n if (this.config.mcpServers[serverId]) {\n delete this.config.mcpServers[serverId];\n this.writeConfig(this.config);\n Logger.info(`ConfigManager: Removed configuration for server \"${serverId}\"`);\n } else {\n Logger.warn(`ConfigManager: Attempted to remove non-existent server config \"${serverId}\"`);\n }\n }\n} ","// Lazy import to avoid SSR/bundling path issues if SDK evolves\nimport { Client } from '@modelcontextprotocol/sdk/client/index.js'\nimport { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'\nimport { Logger } from '@/utils/logger';\nimport { ARTError, ErrorCode } from '@/errors';\n\n/**\n * @function base64UrlEncode\n * Encodes a buffer into a Base64URL string.\n * @param {Uint8Array} buffer - The buffer to encode.\n * @returns {string} The Base64URL encoded string.\n */\nfunction base64UrlEncode(buffer: Uint8Array): string {\n let s = ''\n for (let i = 0; i < buffer.length; i++) s += String.fromCharCode(buffer[i])\n return btoa(s).replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_')\n}\n\n/**\n * @function sha256Base64Url\n * Hashes a string using SHA-256 and encodes it as Base64URL.\n * @param {string} input - The string to hash.\n * @returns {Promise<string>} A promise that resolves to the Base64URL encoded hash.\n */\nasync function sha256Base64Url(input: string): Promise<string> {\n const data = new TextEncoder().encode(input)\n const digest = await crypto.subtle.digest('SHA-256', data)\n return base64UrlEncode(new Uint8Array(digest))\n}\n\n/**\n * @function generateRandomString\n * Generates a random string of a given length.\n * @param {number} [length=64] - The length of the string to generate.\n * @returns {string} The generated random string.\n */\nfunction generateRandomString(length = 64): string {\n const array = new Uint8Array(length)\n crypto.getRandomValues(array)\n return Array.from(array, (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\n/**\n * @class TokenManager\n * Manages OAuth tokens, including loading, updating, clearing, and refreshing them.\n */\nexport class TokenManager {\n private accessToken: string | null = null\n private refreshToken: string | null = null\n private expiresAt: number | null = null\n private clientId: string | null = null\n constructor(private oauthConfig: { token_endpoint?: string }) {}\n\n /**\n * Loads tokens from session storage.\n */\n load() {\n this.accessToken = sessionStorage.getItem('access_token')\n this.refreshToken = sessionStorage.getItem('refresh_token')\n const exp = sessionStorage.getItem('token_expires_at')\n if (exp) this.expiresAt = parseInt(exp, 10)\n this.clientId = localStorage.getItem('mcp_client_id')\n }\n\n /**\n * Sets the client ID.\n * @param {string} id - The client ID.\n */\n setClientId(id: string) { this.clientId = id }\n\n /**\n * Updates the tokens and stores them in session storage.\n * @param {any} token - The token object.\n */\n update(token: any) {\n this.accessToken = token.access_token\n if (token.refresh_token) this.refreshToken = token.refresh_token\n if (token.expires_in) this.expiresAt = Date.now() + token.expires_in * 1000\n sessionStorage.setItem('access_token', this.accessToken || '')\n if (this.refreshToken) sessionStorage.setItem('refresh_token', this.refreshToken)\n if (this.expiresAt) sessionStorage.setItem('token_expires_at', String(this.expiresAt))\n }\n\n /**\n * Clears the tokens from memory and session storage.\n */\n clear() {\n this.accessToken = null\n this.refreshToken = null\n this.expiresAt = null\n sessionStorage.removeItem('access_token')\n sessionStorage.removeItem('refresh_token')\n sessionStorage.removeItem('token_expires_at')\n }\n\n /**\n * Gets the access token.\n * @returns {string | null} The access token.\n */\n getAccessToken() { return this.accessToken }\n\n /**\n * Checks if the token needs to be refreshed.\n * @returns {boolean} True if the token needs to be refreshed, false otherwise.\n */\n needsRefresh(): boolean {\n if (!this.expiresAt) return false\n return Date.now() >= this.expiresAt - 5 * 60 * 1000\n }\n\n /**\n * Refreshes the access token using the refresh token.\n * @returns {Promise<void>}\n */\n async refresh(): Promise<void> {\n if (!this.refreshToken) throw new Error('No refresh token available')\n if (!this.oauthConfig.token_endpoint) throw new Error('Missing token endpoint')\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: this.refreshToken,\n })\n if (this.clientId) body.set('client_id', this.clientId)\n const res = await fetch(this.oauthConfig.token_endpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body,\n })\n if (!res.ok) {\n this.clear()\n throw new Error('Token refresh failed')\n }\n const token = await res.json()\n this.update(token)\n }\n\n /**\n * Checks if the user is authenticated.\n * @returns {boolean} True if the user is authenticated, false otherwise.\n */\n isAuthenticated(): boolean {\n return !!this.accessToken && (this.expiresAt ? this.expiresAt > Date.now() : true)\n }\n}\n\n/**\n * @class McpClientController\n * Controls the MCP client, including OAuth flow, connection, and tool calls.\n */\nexport class McpClientController {\n public baseUrl: URL\n private scopes: string[]\n private client: Client | null = null\n private transport: StreamableHTTPClientTransport | null = null\n private oauthDiscovery: any = null\n private tokenManager: TokenManager | null = null\n private sessionId: string | null = null\n private readonly protocolVersion: string = '2025-06-18'\n\n /**\n * Creates an instance of McpClientController.\n * @private\n * @param {string} baseUrl - The base URL of the MCP server.\n * @param {string[]} [scopes] - The OAuth scopes to request.\n */\n private constructor(baseUrl: string, scopes?: string[]) {\n this.baseUrl = new URL(baseUrl)\n this.scopes = scopes ?? ['read', 'write']\n }\n\n /**\n * Creates a new instance of McpClientController.\n * @param {string} baseUrl - The base URL of the MCP server.\n * @param {string[]} [scopes] - The OAuth scopes to request.\n * @returns {McpClientController} A new instance of McpClientController.\n */\n static create(baseUrl: string, scopes?: string[]): McpClientController {\n return new McpClientController(baseUrl, scopes)\n }\n\n /**\n * Discovers the authorization server metadata.\n * @private\n * @returns {Promise<void>}\n */\n private async discoverAuthorizationServer(): Promise<void> {\n if (this.oauthDiscovery) return\n\n // HACK: Bypassing full discovery flow to avoid WWW-Authenticate CORS issues.\n // This assumes the MCP server itself hosts the AS metadata endpoint.\n const asMetadataUrl = new URL('/.well-known/oauth-authorization-server', this.baseUrl).toString()\n const asMetadataRes = await fetch(asMetadataUrl)\n if (!asMetadataRes.ok) throw new ARTError(`Failed to fetch authorization server metadata from ${asMetadataUrl}`, ErrorCode.NETWORK_ERROR)\n this.oauthDiscovery = await asMetadataRes.json()\n sessionStorage.setItem('mcp_oauth_discovery', JSON.stringify(this.oauthDiscovery))\n\n /*\n const probeRes = await fetch(this.baseUrl.toString(), { method: 'GET' })\n\n if (probeRes.status !== 401) {\n throw new Error('MCP server did not respond with 401 Unauthorized. Cannot discover authorization server.')\n }\n\n const wwwAuthHeader = probeRes.headers.get('WWW-Authenticate')\n if (!wwwAuthHeader) throw new Error('Missing WWW-Authenticate header in 401 response')\n\n const metadataUrlMatch = /resource_metadata=\"([^\"]+)\"/.exec(wwwAuthHeader)\n if (!metadataUrlMatch) throw new Error('Could not find resource_metadata in WWW-Authenticate header')\n\n const resourceMetadataUrl = metadataUrlMatch[1]\n const resourceMetadataRes = await fetch(resourceMetadataUrl)\n if (!resourceMetadataRes.ok) throw new Error('Failed to fetch resource metadata')\n const resourceMetadata = await resourceMetadataRes.json()\n\n if (!resourceMetadata.authorization_servers || resourceMetadata.authorization_servers.length === 0) {\n throw new Error('No authorization_servers found in resource metadata')\n }\n\n const authorizationServerUrl = resourceMetadata.authorization_servers[0]\n const asMetadataUrl = new URL('/.well-known/oauth-authorization-server', authorizationServerUrl).toString()\n\n const asMetadataRes = await fetch(asMetadataUrl)\n if (!asMetadataRes.ok) throw new Error('Failed to fetch authorization server metadata')\n this.oauthDiscovery = await asMetadataRes.json()\n sessionStorage.setItem('mcp_oauth_discovery', JSON.stringify(this.oauthDiscovery))\n */\n }\n\n /**\n * Registers the client with the authorization server.\n * @private\n * @returns {Promise<string>} A promise that resolves to the client ID.\n */\n private async registerClient(): Promise<string> {\n if (!this.oauthDiscovery?.registration_endpoint) {\n // Assume pre-registered public client if dynamic registration not available\n const existing = localStorage.getItem('mcp_client_id')\n if (existing) return existing\n const randomId = 'public-' + generateRandomString(16)\n localStorage.setItem('mcp_client_id', randomId)\n return randomId\n }\n const body = {\n client_name: 'MCP Browser Demo',\n redirect_uris: [location.origin + '/callback'],\n grant_types: ['authorization_code', 'refresh_token'],\n response_types: ['code'],\n token_endpoint_auth_method: 'none',\n application_type: 'web',\n }\n const res = await fetch(this.oauthDiscovery.registration_endpoint, {\n method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),\n })\n if (!res.ok) throw new ARTError('Client registration failed', ErrorCode.EXTERNAL_SERVICE_ERROR)\n const data = await res.json()\n localStorage.setItem('mcp_client_id', data.client_id)\n return data.client_id\n }\n\n /**\n * Starts the OAuth flow by redirecting the user to the authorization server.\n * @returns {Promise<void>}\n */\n async startOAuth() {\n await this.discoverAuthorizationServer()\n if (!this.oauthDiscovery) throw new ARTError('Could not discover OAuth server details.', ErrorCode.INVALID_CONFIG)\n const clientId = await this.registerClient()\n const codeVerifier = base64UrlEncode(crypto.getRandomValues(new Uint8Array(64)))\n const codeChallenge = await sha256Base64Url(codeVerifier)\n sessionStorage.setItem('code_verifier', codeVerifier)\n const state = generateRandomString(16)\n sessionStorage.setItem('state', state)\n const authUrl = new URL(this.oauthDiscovery.authorization_endpoint)\n authUrl.searchParams.set('response_type', 'code')\n authUrl.searchParams.set('client_id', clientId)\n authUrl.searchParams.set('redirect_uri', location.origin + '/callback')\n authUrl.searchParams.set('scope', this.scopes.join(' '))\n authUrl.searchParams.set('code_challenge', codeChallenge)\n authUrl.searchParams.set('code_challenge_method', 'S256')\n authUrl.searchParams.set('state', state)\n authUrl.searchParams.set('resource', this.baseUrl.toString().replace(/\\/$/, ''))\n window.location.href = authUrl.toString()\n }\n\n /**\n * Handles the OAuth callback, exchanging the authorization code for an access token.\n * @returns {Promise<boolean>} A promise that resolves to true if the callback was handled, false otherwise.\n */\n async maybeHandleCallback(): Promise<boolean> {\n const url = new URL(window.location.href)\n const isCallback = url.pathname === '/callback' && (url.searchParams.get('code') || url.searchParams.get('error'))\n if (!isCallback) return false\n\n // Load discovery doc from session storage, assuming it was stored during startOAuth\n const discoveryDoc = sessionStorage.getItem('mcp_oauth_discovery')\n if (discoveryDoc) this.oauthDiscovery = JSON.parse(discoveryDoc)\n else await this.discoverAuthorizationServer() // Fallback just in case\n\n if (!this.oauthDiscovery) throw new ARTError('Could not determine OAuth server details for callback.', ErrorCode.INVALID_CONFIG)\n\n const code = url.searchParams.get('code')\n const state = url.searchParams.get('state')\n if (!code) throw new ARTError('Authorization code missing', ErrorCode.VALIDATION_ERROR)\n if (state !== sessionStorage.getItem('state')) throw new ARTError('State mismatch', ErrorCode.VALIDATION_ERROR)\n const clientId = localStorage.getItem('mcp_client_id') || (await this.registerClient())\n const codeVerifier = sessionStorage.getItem('code_verifier') || ''\n const body = new URLSearchParams({\n grant_type: 'authorization_code',\n code,\n code_verifier: codeVerifier,\n redirect_uri: location.origin + '/callback',\n client_id: clientId,\n })\n body.set('resource', this.baseUrl.toString().replace(/\\/$/, ''))\n\n const res = await fetch(this.oauthDiscovery.token_endpoint, {\n method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body,\n })\n if (!res.ok) {\n const err = await res.json().catch(() => ({}))\n throw new ARTError('Token exchange failed: ' + (err.error_description || err.error || res.status), ErrorCode.EXTERNAL_SERVICE_ERROR)\n }\n const token = await res.json()\n this.tokenManager = new TokenManager(this.oauthDiscovery)\n this.tokenManager.setClientId(clientId)\n this.tokenManager.update(token)\n sessionStorage.removeItem('code_verifier')\n sessionStorage.removeItem('state')\n history.replaceState({}, '', '/')\n return true\n }\n\n /**\n * Loads an existing session from session storage.\n */\n loadExistingSession() {\n const discoveryDoc = sessionStorage.getItem('mcp_oauth_discovery')\n if (discoveryDoc) this.oauthDiscovery = JSON.parse(discoveryDoc)\n this.tokenManager = new TokenManager(this.oauthDiscovery || {})\n this.tokenManager.load()\n this.sessionId = sessionStorage.getItem('mcp_session_id')\n }\n\n /**\n * Checks if the user is authenticated.\n * @returns {boolean} True if the user is authenticated, false otherwise.\n */\n isAuthenticated(): boolean {\n if (!this.tokenManager) return false\n return this.tokenManager.isAuthenticated()\n }\n\n /**\n * Connects to the MCP server.\n * @returns {Promise<void>}\n */\n async connect(): Promise<void> {\n if (!this.client) {\n const customFetch = async (url: RequestInfo | URL, options?: RequestInit): Promise<Response> => {\n this.tokenManager?.load()\n if (this.tokenManager?.needsRefresh()) {\n await this.tokenManager.refresh().catch((err) => {\n Logger.error('Token refresh failed:', err);\n // Optionally, trigger a full re-authentication flow\n })\n }\n\n const headers = new Headers(options?.headers)\n headers.set('Authorization', `Bearer ${this.tokenManager?.getAccessToken() || ''}`)\n headers.set('Accept', 'application/json, text/event-stream')\n headers.set('MCP-Protocol-Version', this.protocolVersion)\n if (this.sessionId) {\n headers.set('Mcp-Session-Id', this.sessionId)\n }\n\n const newOptions: RequestInit = { ...options, headers }\n const response = await fetch(url, newOptions)\n\n const sessionIdHeader = response.headers.get('Mcp-Session-Id')\n if (sessionIdHeader) {\n this.sessionId = sessionIdHeader\n sessionStorage.setItem('mcp_session_id', sessionIdHeader)\n }\n return response\n }\n\n this.transport = new StreamableHTTPClientTransport(this.baseUrl, { fetch: customFetch })\n this.client = new Client({ name: 'mcp-browser-demo', version: '1.0.0' })\n await this.client.connect(this.transport)\n }\n }\n\n /**\n * Ensures that the client is connected to the MCP server.\n * @returns {Promise<void>}\n */\n async ensureConnected(): Promise<void> {\n if (!this.client) await this.connect()\n }\n\n /**\n * Lists the available tools on the MCP server.\n * @returns {Promise<{ name: string; description?: string }[]>} A promise that resolves to a list of tools.\n */\n async listTools(): Promise<{ name: string; description?: string }[]> {\n if (!this.client) throw new ARTError('Not connected', ErrorCode.NOT_CONNECTED)\n const res = await this.client.listTools()\n return res.tools?.map((t: any) => ({ name: t.name, description: t.description })) ?? []\n }\n\n /**\n * Calls a tool on the MCP server.\n * @param {string} name - The name of the tool to call.\n * @param {any} args - The arguments to pass to the tool.\n * @returns {Promise<any>} A promise that resolves to the result of the tool call.\n */\n async callTool(name: string, args: any): Promise<any> {\n if (!this.client) throw new ARTError('Not connected', ErrorCode.NOT_CONNECTED)\n try {\n const result = await this.client.callTool({ name, arguments: args })\n return result\n } catch (e: any) {\n // Retry once if unauthorized and refresh is possible\n if (String(e?.message || '').includes('401') && this.tokenManager) {\n await this.tokenManager.refresh().catch((err) => {\n Logger.error('Token refresh failed during tool call:', err);\n throw e; // Re-throw original error if refresh fails\n })\n const result = await this.client.callTool({ name, arguments: args })\n return result\n }\n throw e\n }\n }\n\n /**\n * Logs out from the MCP server and clears the session.\n * @returns {Promise<void>}\n */\n async logout(): Promise<void> {\n try {\n if (this.transport) {\n const headers: Record<string, string> = {}\n const token = this.tokenManager?.getAccessToken()\n if (token) headers['Authorization'] = `Bearer ${token}`\n if (this.sessionId) headers['Mcp-Session-Id'] = this.sessionId\n await fetch(this.baseUrl.toString(), { method: 'DELETE', headers }).catch(() => {})\n }\n } finally {\n this.client = null\n this.transport = null\n this.tokenManager?.clear()\n this.sessionId = null\n sessionStorage.removeItem('mcp_session_id')\n sessionStorage.removeItem('mcp_oauth_discovery')\n }\n }\n}\n","import { ToolRegistry, StateManager } from '@/core/interfaces';\nimport { ARTError, ErrorCode } from '@/errors';\nimport { Logger } from '@/utils/logger';\nimport { AuthManager } from '../auth/AuthManager';\nimport { McpProxyTool } from './McpProxyTool';\nimport { ConfigManager } from './ConfigManager';\nimport { McpServerConfig, StreamableHttpConnection } from './types';\nimport { McpClientController } from './McpClient';\nimport { hasInstall, install, getAllowedInfo, requestHosts, getInstallUrl } from 'art-mcp-permission-manager'\n\n/**\n * Manages MCP (Model Context Protocol) server connections and tool registration.\n *\n * @remarks\n * The `McpManager` is responsible for:\n * - Connecting to configured MCP servers.\n * - Discovering available tools from servers.\n * - Creating proxy tools that wrap MCP server tools.\n * - Registering proxy tools with the {@link ToolRegistry}.\n * - Managing server health and status.\n * - Handling thread-specific tool activation/deactivation.\n *\n * This enables dynamic tool loading from external MCP servers while maintaining\n * seamless integration with the ART Framework's tool system.\n *\n * @see {@link McpProxyTool} for the tool wrapper implementation.\n * @see {@link McpClientController} for the underlying client implementation.\n *\n * @class McpManager\n */\nexport class McpManager {\n private configManager: ConfigManager;\n private toolRegistry: ToolRegistry;\n private authManager?: AuthManager;\n private activeConnections: Map<string, McpClientController> = new Map();\n\n /**\n * Creates an instance of McpManager.\n *\n * @param toolRegistry The tool registry to register proxy tools with.\n * @param _stateManager The state manager (not currently used).\n * @param authManager The authentication manager.\n */\n constructor(toolRegistry: ToolRegistry, _stateManager: StateManager, authManager?: AuthManager) {\n this.configManager = new ConfigManager();\n this.toolRegistry = toolRegistry;\n this.authManager = authManager;\n Logger.info(`McpManager: Hub initialized. Will load tools from config catalog.`);\n }\n\n /**\n * Initializes the McpManager, discovers and registers tools from configured servers.\n *\n * @param mcpConfig The MCP configuration.\n * @param [mcpConfig.enabled=true] Whether MCP is enabled.\n * @param mcpConfig.discoveryEndpoint The endpoint for discovering MCP servers.\n * @returns A promise that resolves when initialization is complete.\n */\n async initialize(mcpConfig?: { enabled?: boolean; discoveryEndpoint?: string }): Promise<void> {\n if (!mcpConfig?.enabled) {\n Logger.info('McpManager: MCP is disabled. Skipping initialization.');\n return;\n }\n\n Logger.info('McpManager: Initializing from multiple sources...');\n \n // 1. Get local config MCPCards\n const localServerConfigs = this.configManager.getConfig().mcpServers;\n Logger.info(`McpManager: Found ${Object.keys(localServerConfigs).length} servers in local config`);\n \n // 2. Discover remote MCPCards from Zyntopia API\n let discoveredServerConfigs: McpServerConfig[] = [];\n try {\n discoveredServerConfigs = await this.discoverAvailableServers(mcpConfig.discoveryEndpoint);\n Logger.info(`McpManager: Discovered ${discoveredServerConfigs.length} servers from discovery API`);\n } catch (error: any) {\n Logger.warn(`McpManager: Discovery API failed, continuing with local config only: ${error.message}`);\n }\n \n // 3. Merge all server configurations (local + discovered)\n const allServerConfigs = new Map<string, McpServerConfig>();\n \n // Add local configs first\n for (const [serverId, config] of Object.entries(localServerConfigs)) {\n allServerConfigs.set(serverId, config);\n }\n \n // Add discovered configs (with conflict resolution)\n for (const discoveredConfig of discoveredServerConfigs) {\n if (allServerConfigs.has(discoveredConfig.id)) {\n Logger.info(`McpManager: Server \"${discoveredConfig.id}\" exists in both local config and discovery API. Using local config.`);\n } else {\n allServerConfigs.set(discoveredConfig.id, discoveredConfig);\n Logger.info(`McpManager: Added discovered server \"${discoveredConfig.id}\" to available servers`);\n }\n }\n \n // 4. Register proxy tools based on current card hints only (non-blocking).\n // Live discovery and PKCE prompting can happen later during explicit install or first use.\n let registeredToolCount = 0;\n for (const [, card] of allServerConfigs) {\n if (!card.enabled) continue;\n const toolsToRegister = card.tools || [];\n if (Array.isArray(toolsToRegister)) {\n for (const toolDef of toolsToRegister) {\n const proxyTool = new McpProxyTool(card, toolDef as any, this);\n await this.toolRegistry.registerTool(proxyTool);\n registeredToolCount++;\n }\n }\n }\n\n Logger.info(`McpManager: Initialization complete. Registered ${registeredToolCount} proxy tools from ${allServerConfigs.size} total servers.`);\n }\n\n /**\n * Shuts down all active MCP connections.\n *\n * @returns A promise that resolves when all connections are shut down.\n */\n async shutdown(): Promise<void> {\n Logger.info('McpManager: Shutting down all active connections...');\n const disconnectionPromises = Array.from(this.activeConnections.values()).map(client => client.logout());\n await Promise.allSettled(disconnectionPromises);\n this.activeConnections.clear();\n Logger.info('McpManager: Shutdown complete.');\n }\n\n /**\n * Gets an existing connection or creates a new one for a given server ID.\n *\n * @param serverId The ID of the server to connect to.\n * @returns A promise that resolves to the MCP client controller.\n */\n public async getOrCreateConnection(serverId: string): Promise<McpClientController> {\n if (this.activeConnections.has(serverId)) {\n const existingClient = this.activeConnections.get(serverId)!;\n if (existingClient.isAuthenticated()) {\n await existingClient.ensureConnected();\n return existingClient;\n }\n }\n\n Logger.info(`McpManager: No active connection for \"${serverId}\". Creating one on-demand...`);\n const card = this.configManager.getConfig().mcpServers[serverId];\n if (!card) {\n throw new ARTError(`Configuration for server \"${serverId}\" not found.`, ErrorCode.SERVER_NOT_FOUND);\n }\n\n if (card.type !== 'streamable-http') {\n throw new ARTError(`Unsupported transport type \"${card.type}\" for server \"${serverId}\". Only 'streamable-http' is supported in the browser.`, ErrorCode.UNSUPPORTED_TRANSPORT);\n }\n\n const conn = card.connection as StreamableHttpConnection;\n\n await this.ensureCorsAccess(conn.url);\n\n const scopes = conn.oauth?.scopes;\n const client = McpClientController.create(conn.url, Array.isArray(scopes) ? scopes : (scopes ? [scopes] : undefined));\n\n const handled = await client.maybeHandleCallback();\n if(handled) {\n Logger.info(`McpManager: OAuth callback for server \"${serverId}\" handled successfully.`);\n }\n\n client.loadExistingSession();\n\n if(!client.isAuthenticated()) {\n await client.startOAuth();\n // The above call will redirect, so the code below might not be reached in that flow.\n // If it is (e.g. pop-up), we need to wait for authentication.\n await this.waitForAuth(client, 180000); // Wait for up to 3 minutes\n }\n \n await client.connect();\n\n this.activeConnections.set(serverId, client);\n Logger.info(`McpManager: On-demand connection for \"${serverId}\" established successfully.`);\n return client;\n }\n \n /**\n * Ensures that the application has CORS access to the target URL.\n *\n * @private\n * @param targetUrl The URL to check for CORS access.\n * @returns A promise that resolves when CORS access is confirmed or granted.\n */\n private async ensureCorsAccess(targetUrl: string): Promise<void> {\n if (!hasInstall()) {\n const opened = install({ browser: 'auto' });\n if (!opened) {\n const url = getInstallUrl();\n // In a real app, you'd show this in a dialog, not an alert\n alert('ART MCP requires a companion browser extension for CORS. Please install it: ' + url);\n throw new ARTError('Companion extension not installed.', ErrorCode.CORS_EXTENSION_REQUIRED);\n }\n throw new ARTError('Companion extension installation started. Please complete it and retry.', ErrorCode.CORS_EXTENSION_REQUIRED);\n }\n\n const { hostname } = new URL(targetUrl);\n const info = await getAllowedInfo();\n\n if (!info.enabled || (info.type === 'specific' && !info.hosts?.includes(hostname))) {\n const res = await requestHosts({ hosts: [hostname] });\n if (res !== 'accept') {\n throw new ARTError(`User did not grant permission for ${hostname}.`, ErrorCode.CORS_PERMISSION_REQUIRED);\n }\n }\n }\n\n // --- Discovery & Installation (Future Implementation) ---\n\n /**\n * Searches a discovery service for available MCP servers.\n *\n * @param [discoveryEndpoint] The URL of the discovery service.\n * @returns A promise resolving to an array of McpServerConfig.\n */\n async discoverAvailableServers(discoveryEndpoint?: string): Promise<McpServerConfig[]> {\n const url = discoveryEndpoint || 'http://localhost:4200/api/services'; // Default Zyntopia endpoint\n Logger.info(`McpManager: Discovering servers from ${url}...`);\n \n try {\n await this.ensureCorsAccess(url);\n const response = await fetch(url, {\n method: 'GET',\n headers: {\n 'Accept': 'application/json',\n 'User-Agent': 'ART-Framework-MCP/2.0'\n },\n // Add timeout to prevent hanging\n signal: AbortSignal.timeout(10000) // 10 second timeout\n });\n \n if (!response.ok) {\n throw new Error(`Discovery API returned ${response.status}: ${response.statusText}`);\n }\n \n const data = await response.json();\n \n // Filter for MCP services and convert to MCPCards\n const mcpServices = Array.isArray(data) ? data : (data.services || []);\n const mcpCards: McpServerConfig[] = mcpServices\n .filter((service: any) => service.service_type === 'MCP_SERVICE')\n .map((service: any) => this.convertServiceToMcpCard(service))\n .filter((card: McpServerConfig | null) => card !== null) as McpServerConfig[];\n \n Logger.info(`McpManager: Successfully discovered ${mcpCards.length} MCP servers from discovery API`);\n return mcpCards;\n \n } catch (error: any) {\n Logger.error(`McpManager: Failed to discover servers from ${url}: ${error.message}`);\n throw new ARTError(`Discovery API failed: ${error.message}`, ErrorCode.NETWORK_ERROR);\n }\n }\n \n /**\n * Converts a Zyntopia service entry to an McpServerConfig.\n *\n * @private\n * @param service The service entry to convert.\n * @returns The converted McpServerConfig or null if conversion fails.\n */\n private convertServiceToMcpCard(service: any): McpServerConfig | null {\n try {\n // Basic validation\n if (!service.id || !service.name || !service.connection) {\n Logger.warn(`McpManager: Skipping invalid service entry: missing required fields`);\n return null;\n }\n \n const mcpCard: McpServerConfig = {\n id: service.id,\n type: service.connection.type === 'sse' ? 'streamable-http' : service.connection.type,\n enabled: service.enabled !== false, // Default to enabled unless explicitly disabled\n displayName: service.name,\n description: service.description || `MCP service: ${service.name}`,\n connection: service.connection,\n timeout: service.timeout || 10000,\n tools: service.tools || [],\n resources: service.resources || [],\n resourceTemplates: service.resourceTemplates || [],\n installation: service.installation\n };\n \n Logger.debug(`McpManager: Converted service \"${service.id}\" to MCPCard`);\n return mcpCard;\n \n } catch (error: any) {\n Logger.warn(`McpManager: Failed to convert service to MCPCard: ${error.message}`);\n return null;\n }\n }\n\n // The generateAndInstallCard method is removed as it is based on the stdio transport,\n // which is not supported in a browser-only environment.\n\n /**\n * Installs a server by persisting its config, discovering tools via MCP, and\n * registering proxy tools. Returns the finalized config with accurate tools.\n *\n * @param server The server configuration to install.\n * @returns A promise that resolves to the finalized server configuration.\n */\n public async installServer(server: McpServerConfig): Promise<McpServerConfig> {\n // Save initial config\n this.configManager.setServerConfig(server.id, server);\n try {\n const conn = server.connection as StreamableHttpConnection;\n await this.ensureCorsAccess(conn.url);\n\n let client: McpClientController;\n try {\n client = await this.getOrCreateConnection(server.id);\n } catch (e: any) {\n // This might happen if startOAuth redirects. The user will need to try again.\n Logger.warn(`McpManager: Could not connect during install for \"${server.id}\": ${e?.message || e}. The user may need to complete authentication and retry.`);\n // We still save the server config, just without the live tools.\n return server;\n }\n\n const liveTools = await client.listTools();\n const normalized = (liveTools || []).map(t => ({ name: t.name, description: t.description } as any));\n const updated = { ...server, tools: normalized } as McpServerConfig;\n \n this.configManager.setServerConfig(server.id, updated);\n \n for (const t of normalized) {\n await this.toolRegistry.registerTool(new McpProxyTool(updated, t as any, this));\n }\n \n Logger.info(`McpManager: Installed server \"${server.id}\" with ${normalized.length} discovered tool(s).`);\n return updated;\n\n } catch (e: any) {\n Logger.warn(`McpManager: Could not complete live discovery during install for \"${server.id}\": ${e?.message || e}. Falling back to provided tools.`);\n const fallback = server.tools || [];\n for (const t of fallback) {\n await this.toolRegistry.registerTool(new McpProxyTool(server, t as any, this));\n }\n return server;\n }\n }\n\n /**\n * Waits for the client to be authenticated.\n *\n * @private\n * @param client The MCP client controller.\n * @param timeoutMs The timeout in milliseconds.\n * @returns A promise that resolves when the client is authenticated.\n * @throws {ARTError} If the authentication window times out.\n */\n private async waitForAuth(client: McpClientController, timeoutMs: number): Promise<void> {\n const start = Date.now();\n while (Date.now() - start < timeoutMs) {\n if (client.isAuthenticated()) {\n return;\n }\n await new Promise(r => setTimeout(r, 1000));\n }\n throw new ARTError('Authentication window timed out.', ErrorCode.TIMEOUT);\n }\n\n /**\n * Uninstalls a server: disconnects, removes registered proxy tools, and deletes config.\n *\n * @param serverId The ID of the server to uninstall.\n * @returns A promise that resolves when the server is uninstalled.\n */\n public async uninstallServer(serverId: string): Promise<void> {\n try {\n // Unregister tools by name prefix\n const prefix = `mcp_${serverId}_`;\n if ((this.toolRegistry as any).unregisterTools) {\n await (this.toolRegistry as any).unregisterTools((schema: any) => typeof schema?.name === 'string' && schema.name.startsWith(prefix));\n }\n\n // Disconnect\n const client = this.activeConnections.get(serverId);\n if (client) {\n await client.logout();\n this.activeConnections.delete(serverId);\n }\n\n // Remove config\n this.configManager.removeServerConfig(serverId);\n Logger.info(`McpManager: Server \"${serverId}\" uninstalled.`);\n } catch (e: any) {\n Logger.warn(`McpManager: Uninstall encountered issues for \"${serverId}\": ${e?.message || e}`);\n this.configManager.removeServerConfig(serverId);\n }\n }\n}","import { Logger } from '@/utils/logger';\nimport { ARTError, ErrorCode } from '@/errors';\nimport { A2AAgentInfo } from '@/types';\n\n/**\n * Interface for A2A Agent Card as defined in the A2A protocol standards.\n * This represents the digital \"business card\" that agents use to advertise their capabilities.\n */\nexport interface A2AAgentCard {\n /** Unique identifier for the agent */\n id: string;\n /** Human-readable name of the agent */\n name: string;\n /** Version of the agent */\n version: string;\n /** Brief description of what the agent does */\n description: string;\n /** Agent category (e.g., 'healthcare', 'research', 'analytics') */\n category: string;\n /** Base endpoint URL for A2A communication */\n endpoint: string;\n /** Array of capabilities the agent can perform */\n capabilities: string[];\n /** Authentication requirements */\n authentication: {\n type: string;\n required: boolean;\n };\n /** Input schema definition */\n inputSchema?: {\n type: string;\n properties: Record<string, any>;\n };\n /** Output schema definition */\n outputSchema?: {\n type: string;\n properties: Record<string, any>;\n };\n /** Rate limiting information */\n rateLimits?: {\n requestsPerMinute: number;\n };\n /** Tags for categorization */\n tags?: string[];\n}\n\n/**\n * Response structure from the discovery endpoint\n */\nexport interface DiscoveryResponse {\n services: Array<{\n id: string;\n service_type: string;\n card_data: A2AAgentCard;\n status: string;\n owner_id?: string;\n created_at: string;\n updated_at: string;\n }>;\n count: number;\n timestamp: string;\n}\n\n/**\n * Configuration for the AgentDiscoveryService\n */\nexport interface AgentDiscoveryConfig {\n /** Base URL for the discovery endpoint. If not provided, a default will be used. */\n discoveryEndpoint?: string;\n /** Timeout for discovery requests in milliseconds */\n timeoutMs?: number;\n /** Whether to cache discovered agents */\n enableCaching?: boolean;\n /** Cache TTL in milliseconds */\n cacheTtlMs?: number;\n}\n\n/**\n * Service for discovering A2A protocol compatible agents.\n * Implements the A2A discovery standards for finding and identifying compatible agents.\n */\nexport class AgentDiscoveryService {\n private readonly config: Required<AgentDiscoveryConfig>;\n private agentCache: Map<string, { agents: A2AAgentInfo[]; timestamp: number }> = new Map();\n\n /**\n * Creates an instance of AgentDiscoveryService.\n * @param {Partial<AgentDiscoveryConfig>} config - The configuration for the service.\n * @see A2AAgentCard\n */\n constructor(config?: Partial<AgentDiscoveryConfig>) {\n this.config = {\n discoveryEndpoint: 'https://api.zyntopia.com/a2a/discover', // Default endpoint\n timeoutMs: 10000, // 10 seconds default\n enableCaching: true,\n cacheTtlMs: 300000, // 5 minutes default\n ...config\n };\n \n Logger.debug(`AgentDiscoveryService initialized with endpoint: ${this.config.discoveryEndpoint}`);\n }\n\n /**\n * Discovers all available A2A agents from the discovery endpoint.\n * @param traceId - Optional trace ID for request tracking\n * @returns Promise resolving to array of discovered A2A agents\n * @throws {ARTError} If discovery fails or no agents are found\n */\n async discoverAgents(traceId?: string): Promise<A2AAgentInfo[]> {\n const cacheKey = 'all_agents';\n \n // Check cache first if enabled\n if (this.config.enableCaching) {\n const cached = this.getCachedAgents(cacheKey);\n if (cached) {\n Logger.debug(`[${traceId}] Returning ${cached.length} cached A2A agents`);\n return cached;\n }\n }\n\n try {\n Logger.debug(`[${traceId}] Discovering A2A agents from: ${this.config.discoveryEndpoint}`);\n \n // Create AbortController for timeout handling\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.config.timeoutMs);\n\n const response = await fetch(this.config.discoveryEndpoint, {\n method: 'GET',\n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n },\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n throw new ARTError(\n `Discovery endpoint returned ${response.status}: ${response.statusText}`,\n ErrorCode.EXTERNAL_SERVICE_ERROR\n );\n }\n\n const discoveryData: DiscoveryResponse = await response.json();\n \n // Filter for A2A agents only\n const a2aServices = discoveryData.services.filter(\n service => service.service_type === 'A2A_AGENT' && service.status === 'active'\n );\n\n if (a2aServices.length === 0) {\n Logger.warn(`[${traceId}] No active A2A agents found in discovery response`);\n return [];\n }\n\n // Transform to A2AAgentInfo format\n const agents = a2aServices.map(service => this.transformToA2AAgentInfo(service.card_data));\n \n // Cache the results\n if (this.config.enableCaching) {\n this.setCachedAgents(cacheKey, agents);\n }\n\n Logger.info(`[${traceId}] Discovered ${agents.length} A2A agents: ${agents.map(a => a.agentName).join(', ')}`);\n return agents;\n\n } catch (error: any) {\n if (error.name === 'AbortError') {\n throw new ARTError(\n `Agent discovery request timed out after ${this.config.timeoutMs}ms`,\n ErrorCode.TIMEOUT\n );\n }\n \n if (error instanceof ARTError) {\n throw error;\n }\n\n throw new ARTError(\n `Failed to discover A2A agents: ${error.message}`,\n ErrorCode.EXTERNAL_SERVICE_ERROR,\n error\n );\n }\n }\n\n /**\n * Finds the top K A2A agents for a specific task type, ranked by suitability.\n * This method acts as a pre-filter, returning a list of the most promising candidates\n * for an LLM to make the final selection from.\n * @param taskType - The type of task (e.g., 'analysis', 'research', 'generation')\n * @param topK - The maximum number of agents to return.\n * @param traceId - Optional trace ID for request tracking.\n * @returns Promise resolving to a ranked array of matching agents.\n * @remarks TODO: Revisit and enhance the scoring algorithm.\n */\n async findTopAgentsForTask(taskType: string, topK: number = 3, traceId?: string): Promise<A2AAgentInfo[]> {\n const agents = await this.discoverAgents(traceId);\n \n if (agents.length === 0) {\n Logger.warn(`[${traceId}] No A2A agents available for task type: ${taskType}`);\n return [];\n }\n\n // TODO: This scoring algorithm is a foundational heuristic. Revisit and enhance this\n // frequently. Future optimizations could include:\n // 1. LLM-based semantic scoring for more nuanced understanding.\n // 2. Incorporating a \"specialization score\" to reward agents with fewer, more focused capabilities.\n // 3. Factoring in agent metadata (name, description, tags) for contextual relevance.\n // 4. Caching individual agent scores for performance.\n\n // Score agents based on capability relevance to the task type\n const scoredAgents = agents.map(agent => {\n const capabilities = agent.capabilities || [];\n let totalScore = 0;\n const matchedCapabilities: string[] = [];\n\n for (const capability of capabilities) {\n const capLower = capability.toLowerCase();\n const taskLower = taskType.toLowerCase();\n let capabilityScore = 0;\n\n // Exact match with task type\n if (capLower === taskLower) {\n capabilityScore = 10;\n }\n // Capability contains task type\n else if (capLower.includes(taskLower)) {\n capabilityScore = 8;\n }\n // Task type contains capability (e.g., capability \"research\" matches task \"medical_research\")\n else if (taskLower.includes(capLower)) {\n capabilityScore = 6;\n }\n // Semantic similarity for common patterns\n else {\n // Check for semantic relationships\n const semanticScore = this.calculateSemanticScore(capLower, taskLower);\n capabilityScore = semanticScore;\n }\n\n if (capabilityScore > 0) {\n totalScore += capabilityScore;\n matchedCapabilities.push(capability);\n }\n }\n\n return {\n agent,\n score: totalScore,\n matchedCapabilities\n };\n });\n\n // Filter out agents with no score, sort by score (highest first), and take the top K\n const topMatches = scoredAgents\n .filter(a => a.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, topK);\n\n if (topMatches.length === 0) {\n Logger.warn(`[${traceId}] No suitable A2A agent found for task type: ${taskType}`);\n return [];\n }\n\n Logger.debug(`[${traceId}] Found ${topMatches.length} candidate agents for task type \"${taskType}\":`);\n topMatches.forEach(match => {\n Logger.debug(` - ${match.agent.agentName} (Score: ${match.score}, Matched: ${match.matchedCapabilities.join(', ')})`);\n });\n\n return topMatches.map(match => match.agent);\n }\n\n /**\n * Calculates semantic similarity score between capability and task type.\n * This uses common word patterns to identify relationships without hardcoded mappings.\n * @private\n */\n private calculateSemanticScore(capability: string, taskType: string): number {\n // Common semantic relationships\n const semanticPairs = [\n // Analysis-related\n ['analysis', 'analyze'], ['analysis', 'examine'], ['analysis', 'evaluate'],\n ['statistical', 'statistics'], ['data', 'information'],\n \n // Research-related \n ['research', 'investigate'], ['research', 'study'], ['research', 'explore'],\n ['medical', 'health'], ['web', 'online'], ['literature', 'document'],\n \n // Generation-related\n ['generation', 'generate'], ['generation', 'create'], ['generation', 'produce'],\n ['report', 'document'], ['visualization', 'visual'], ['chart', 'graph'],\n \n // Computation-related\n ['computation', 'compute'], ['computation', 'calculate'], ['computation', 'process'],\n ['mathematical', 'math'], ['algorithm', 'algorithmic'],\n \n // Transformation-related\n ['transformation', 'transform'], ['conversion', 'convert'], ['translation', 'translate'],\n \n // Validation-related\n ['validation', 'validate'], ['verification', 'verify'], ['testing', 'test']\n ];\n\n for (const [word1, word2] of semanticPairs) {\n if ((capability.includes(word1) && taskType.includes(word2)) ||\n (capability.includes(word2) && taskType.includes(word1))) {\n return 4; // Medium semantic match\n }\n }\n\n // Check for common word roots (basic stemming)\n const getWordRoot = (word: string) => {\n return word.replace(/ing$|ed$|er$|tion$|sion$|ment$|ness$|ly$|al$/, '');\n };\n\n const capWords = capability.split(/[_\\s-]/).map(getWordRoot);\n const taskWords = taskType.split(/[_\\s-]/).map(getWordRoot);\n\n for (const capWord of capWords) {\n for (const taskWord of taskWords) {\n if (capWord.length > 3 && taskWord.length > 3 && \n (capWord.includes(taskWord) || taskWord.includes(capWord))) {\n return 3; // Lower semantic match\n }\n }\n }\n\n return 0; // No semantic relationship found\n }\n\n /**\n * Finds agents by specific capabilities.\n * @param capabilities - Array of required capabilities\n * @param traceId - Optional trace ID for request tracking\n * @returns Promise resolving to agents that have all specified capabilities\n */\n async findAgentsByCapabilities(capabilities: string[], traceId?: string): Promise<A2AAgentInfo[]> {\n const agents = await this.discoverAgents(traceId);\n \n const matchingAgents = agents.filter(agent => {\n return capabilities.every(requiredCap => \n agent.capabilities?.some(agentCap => \n agentCap.toLowerCase().includes(requiredCap.toLowerCase()) ||\n requiredCap.toLowerCase().includes(agentCap.toLowerCase())\n )\n );\n });\n\n Logger.debug(`[${traceId}] Found ${matchingAgents.length} agents matching capabilities: ${capabilities.join(', ')}`);\n return matchingAgents;\n }\n\n /**\n * Clears the agent cache.\n */\n clearCache(): void {\n this.agentCache.clear();\n Logger.debug('Agent discovery cache cleared');\n }\n\n /**\n * Gets cached agents if they exist and are not expired.\n * @private\n */\n private getCachedAgents(cacheKey: string): A2AAgentInfo[] | null {\n const cached = this.agentCache.get(cacheKey);\n if (!cached) return null;\n\n const isExpired = Date.now() - cached.timestamp > this.config.cacheTtlMs;\n if (isExpired) {\n this.agentCache.delete(cacheKey);\n return null;\n }\n\n return cached.agents;\n }\n\n /**\n * Sets agents in cache with current timestamp.\n * @private\n */\n private setCachedAgents(cacheKey: string, agents: A2AAgentInfo[]): void {\n this.agentCache.set(cacheKey, {\n agents,\n timestamp: Date.now()\n });\n }\n\n /**\n * Transforms an A2A Agent Card to the ART framework's A2AAgentInfo format.\n * @private\n */\n private transformToA2AAgentInfo(card: A2AAgentCard): A2AAgentInfo {\n return {\n agentId: card.id,\n agentName: card.name,\n agentType: card.category || 'unknown',\n endpoint: card.endpoint,\n capabilities: card.capabilities || [],\n status: 'available' // Assume available since it was returned by discovery\n };\n }\n} ","// src/systems/a2a/TaskDelegationService.ts\n\nimport { Logger } from '@/utils/logger';\nimport { ARTError, ErrorCode } from '@/errors';\nimport { A2ATask, A2ATaskStatus, A2AAgentInfo, A2ATaskResult, A2ATaskMetadata } from '@/types';\nimport { IA2ATaskRepository } from '@/core/interfaces';\n// AgentDiscoveryService is no longer used here; discovery is handled by PESAgent.\n\n/**\n * Configuration options for the TaskDelegationService\n */\nexport interface TaskDelegationConfig {\n /** Default timeout for task delegation requests in milliseconds */\n defaultTimeoutMs?: number;\n /** Maximum number of retry attempts for failed requests */\n maxRetries?: number;\n /** Base delay between retry attempts in milliseconds */\n retryDelayMs?: number;\n /** Whether to use exponential backoff for retries */\n useExponentialBackoff?: boolean;\n /** The base callback URL for receiving A2A task updates. */\n callbackUrl?: string;\n}\n\n/**\n * Response structure for A2A task submission according to A2A protocol\n */\nexport interface TaskSubmissionResponse {\n /** Whether the task was successfully submitted */\n success: boolean;\n /** The unique task ID assigned by the remote agent */\n taskId: string;\n /** Current status of the submitted task */\n status: A2ATaskStatus;\n /** Optional message from the remote agent */\n message?: string;\n /** Estimated completion time in milliseconds (if provided) */\n estimatedCompletionMs?: number;\n /** Additional metadata from the remote agent */\n metadata?: Record<string, any>;\n}\n\n/**\n * Response structure for A2A task status queries\n */\nexport interface TaskStatusResponse {\n /** The task ID */\n taskId: string;\n /** Current status of the task */\n status: A2ATaskStatus;\n /** Progress percentage (0-100) if available */\n progress?: number;\n /** Task result if completed */\n result?: A2ATaskResult;\n /** Error information if failed */\n error?: string;\n /** Additional metadata */\n metadata?: Record<string, any>;\n}\n\n/**\n * Service responsible for delegating A2A tasks to remote agents.\n * Implements the A2A protocol for task submission, tracking, and completion.\n * \n * This service handles:\n * - Finding suitable agents for specific task types\n * - Submitting tasks to remote agents via HTTP API\n * - Tracking task status and handling updates\n * - Managing task lifecycle according to A2A protocol\n * - Error handling and retry logic\n * - Integration with local task repository for persistence\n */\nexport class TaskDelegationService {\n private readonly config: Required<TaskDelegationConfig>;\n private readonly taskRepository: IA2ATaskRepository;\n\n /**\n * Creates an instance of TaskDelegationService.\n * @param {IA2ATaskRepository} taskRepository - The repository for persisting task status.\n * @param {TaskDelegationConfig} [config={}] - Configuration for the service.\n */\n constructor(\n taskRepository: IA2ATaskRepository,\n config: TaskDelegationConfig = {}\n ) {\n this.taskRepository = taskRepository;\n \n // Set default configuration\n this.config = {\n defaultTimeoutMs: config.defaultTimeoutMs ?? 30000, // 30 seconds\n maxRetries: config.maxRetries ?? 3,\n retryDelayMs: config.retryDelayMs ?? 1000, // 1 second\n useExponentialBackoff: config.useExponentialBackoff ?? true,\n callbackUrl: config.callbackUrl ?? 'http://localhost:3000/api/a2a/callback'\n };\n\n Logger.debug('TaskDelegationService initialized with config:', this.config);\n }\n\n /**\n * Delegates a list of A2A tasks to suitable remote agents.\n * For each task, finds the best agent and submits the task.\n * \n * @param {A2ATask[]} tasks - Array of A2A tasks to delegate\n * @param {string} [traceId] - Optional trace ID for request tracking\n * @returns {Promise<A2ATask[]>} Promise resolving to array of successfully delegated tasks\n */\n async delegateTasks(tasks: A2ATask[], traceId?: string): Promise<A2ATask[]> {\n if (tasks.length === 0) {\n Logger.debug(`[${traceId}] No tasks to delegate`);\n return [];\n }\n\n Logger.info(`[${traceId}] Starting delegation of ${tasks.length} A2A task(s)`);\n const delegatedTasks: A2ATask[] = [];\n\n for (const task of tasks) {\n try {\n const delegatedTask = await this.delegateTask(task, traceId);\n if (delegatedTask) {\n delegatedTasks.push(delegatedTask);\n }\n } catch (error: any) {\n Logger.error(`[${traceId}] Failed to delegate task ${task.taskId}:`, error);\n // Continue with other tasks even if one fails\n }\n }\n\n Logger.info(`[${traceId}] Successfully delegated ${delegatedTasks.length}/${tasks.length} task(s)`);\n return delegatedTasks;\n }\n\n /**\n * Delegates a single A2A task to a suitable remote agent.\n * \n * @param {A2ATask} task - The A2A task to delegate\n * @param {string} [traceId] - Optional trace ID for request tracking\n * @returns {Promise<A2ATask | null>} Promise resolving to the updated task or null if delegation failed\n */\n async delegateTask(task: A2ATask, traceId?: string): Promise<A2ATask | null> {\n Logger.debug(`[${traceId}] Delegating task ${task.taskId} of type \"${task.payload.taskType}\"`);\n\n try {\n // Step 1: Validate that a target agent has been assigned to the task\n const targetAgent = task.targetAgent;\n if (!targetAgent) {\n throw new ARTError(\n `Task ${task.taskId} cannot be delegated without a targetAgent.`,\n ErrorCode.VALIDATION_ERROR\n );\n }\n\n Logger.debug(`[${traceId}] Confirmed target agent \"${targetAgent.agentName}\" for task ${task.taskId}`);\n\n // Step 2: Submit task to the remote agent\n const submissionResponse = await this.submitTaskToAgent(task, targetAgent, traceId);\n\n // Step 3: Update local task with delegation information\n const now = Date.now();\n const updatedTask: A2ATask = {\n ...task,\n status: submissionResponse.status,\n // targetAgent is already set\n metadata: {\n ...task.metadata,\n updatedAt: now,\n startedAt: submissionResponse.status === A2ATaskStatus.IN_PROGRESS ? now : task.metadata.startedAt,\n tags: [...(task.metadata.tags || []), 'delegated'],\n delegatedAt: now,\n estimatedCompletionMs: submissionResponse.estimatedCompletionMs\n }\n };\n\n // Step 4: Persist the updated task\n // Note: The task should already exist in a PENDING state. We update it.\n await this.taskRepository.updateTask(updatedTask.taskId, updatedTask);\n \n Logger.info(`[${traceId}] Successfully delegated task ${task.taskId} to agent \"${targetAgent.agentName}\" (status: ${submissionResponse.status})`);\n return updatedTask;\n\n } catch (error: any) {\n Logger.error(`[${traceId}] Task delegation failed for ${task.taskId}:`, error);\n \n // Update task status to failed and persist\n try {\n await this.taskRepository.updateTask(task.taskId, {\n status: A2ATaskStatus.FAILED,\n metadata: {\n ...task.metadata,\n updatedAt: Date.now(),\n completedAt: Date.now(),\n tags: [...(task.metadata.tags || []), 'delegation_failed']\n },\n result: {\n success: false,\n error: `Delegation failed: ${error.message}`,\n metadata: { errorType: 'delegation_error', timestamp: Date.now() }\n }\n });\n } catch (persistError: any) {\n Logger.error(`[${traceId}] Failed to persist task failure for ${task.taskId}:`, persistError);\n }\n\n // Re-throw the original error to be handled by the caller (e.g., PESAgent)\n throw error instanceof ARTError ? error : new ARTError(\n `Failed to delegate task ${task.taskId}: ${error.message}`,\n ErrorCode.DELEGATION_FAILED,\n error\n );\n }\n }\n\n /**\n * Submits a task to a specific remote agent using A2A protocol.\n * \n * @private\n * @param {A2ATask} task - The A2A task to submit\n * @param {A2AAgentInfo} targetAgent - The target agent to submit the task to\n * @param {string} [traceId] - Optional trace ID for request tracking\n * @returns {Promise<TaskSubmissionResponse>} Promise resolving to the submission response\n */\n private async submitTaskToAgent(\n task: A2ATask, \n targetAgent: A2AAgentInfo, \n traceId?: string\n ): Promise<TaskSubmissionResponse> {\n if (!targetAgent.endpoint) {\n throw new ARTError(\n `Target agent \"${targetAgent.agentName}\" has no endpoint configured`,\n ErrorCode.VALIDATION_ERROR\n );\n }\n\n const taskSubmissionUrl = `${targetAgent.endpoint.replace(/\\/$/, '')}/tasks`;\n \n // Prepare the task submission payload according to A2A protocol\n const submissionPayload = {\n taskId: task.taskId,\n taskType: task.payload.taskType,\n input: task.payload.input,\n instructions: task.payload.instructions,\n parameters: task.payload.parameters,\n priority: task.priority,\n sourceAgent: task.sourceAgent,\n timeoutMs: task.metadata.timeoutMs,\n maxRetries: task.metadata.maxRetries,\n callbackUrl: this.generateCallbackUrl(task.taskId), // For webhook notifications\n metadata: {\n traceId: traceId,\n submittedAt: Date.now(),\n sourceTimestamp: task.metadata.createdAt\n }\n };\n\n Logger.debug(`[${traceId}] Submitting task ${task.taskId} to ${taskSubmissionUrl}`);\n\n let lastError: Error = new Error('Unknown error');\n let attempt = 0;\n\n // Retry loop with exponential backoff\n while (attempt <= this.config.maxRetries) {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.config.defaultTimeoutMs);\n\n const response = await fetch(taskSubmissionUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'ART-Framework-A2A/1.0.0',\n 'X-Trace-ID': traceId || '',\n ...(targetAgent.authentication?.type === 'bearer' && targetAgent.authentication.token \n ? { 'Authorization': `Bearer ${targetAgent.authentication.token}` }\n : {}),\n ...(targetAgent.authentication?.type === 'api_key' && targetAgent.authentication.apiKey \n ? { 'X-API-Key': targetAgent.authentication.apiKey }\n : {})\n },\n body: JSON.stringify(submissionPayload),\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n const responseData: TaskSubmissionResponse = await response.json();\n \n // Validate the response structure\n if (!responseData.taskId || !responseData.status) {\n throw new Error('Invalid response format from remote agent');\n }\n\n Logger.debug(`[${traceId}] Task ${task.taskId} submitted successfully to \"${targetAgent.agentName}\" (remote task ID: ${responseData.taskId})`);\n return responseData;\n\n } catch (error: any) {\n lastError = error;\n attempt++;\n\n if (error.name === 'AbortError') {\n Logger.warn(`[${traceId}] Task submission timed out for ${task.taskId} (attempt ${attempt}/${this.config.maxRetries + 1})`);\n } else {\n Logger.warn(`[${traceId}] Task submission failed for ${task.taskId} (attempt ${attempt}/${this.config.maxRetries + 1}):`, error.message);\n }\n\n // Don't retry if we've exhausted attempts\n if (attempt > this.config.maxRetries) {\n break;\n }\n\n // Calculate delay with exponential backoff\n const delay = this.config.useExponentialBackoff \n ? this.config.retryDelayMs * Math.pow(2, attempt - 1)\n : this.config.retryDelayMs;\n\n Logger.debug(`[${traceId}] Retrying task submission in ${delay}ms...`);\n await new Promise(resolve => setTimeout(resolve, delay));\n }\n }\n\n throw new ARTError(\n `Failed to submit task ${task.taskId} to agent \"${targetAgent.agentName}\" after ${this.config.maxRetries + 1} attempts: ${lastError.message}`,\n ErrorCode.EXTERNAL_SERVICE_ERROR,\n lastError\n );\n }\n\n /**\n * Checks the status of a delegated task from the remote agent.\n * \n * @param {A2ATask} task - The A2A task to check status for\n * @param {string} [traceId] - Optional trace ID for request tracking\n * @returns {Promise<TaskStatusResponse | null>} Promise resolving to the current task status\n */\n async checkTaskStatus(task: A2ATask, traceId?: string): Promise<TaskStatusResponse | null> {\n if (!task.targetAgent?.endpoint) {\n Logger.warn(`[${traceId}] Cannot check status for task ${task.taskId}: no target agent endpoint`);\n return null;\n }\n\n const statusUrl = `${task.targetAgent.endpoint.replace(/\\/$/, '')}/tasks/${task.taskId}`;\n \n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.config.defaultTimeoutMs);\n\n const response = await fetch(statusUrl, {\n method: 'GET',\n headers: {\n 'User-Agent': 'ART-Framework-A2A/1.0.0',\n 'X-Trace-ID': traceId || '',\n ...(task.targetAgent.authentication?.type === 'bearer' && task.targetAgent.authentication.token \n ? { 'Authorization': `Bearer ${task.targetAgent.authentication.token}` }\n : {}),\n ...(task.targetAgent.authentication?.type === 'api_key' && task.targetAgent.authentication.apiKey \n ? { 'X-API-Key': task.targetAgent.authentication.apiKey }\n : {})\n },\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n if (response.status === 404) {\n Logger.warn(`[${traceId}] Task ${task.taskId} not found on remote agent`);\n return null;\n }\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n const statusData: TaskStatusResponse = await response.json();\n Logger.debug(`[${traceId}] Task ${task.taskId} status: ${statusData.status}`);\n \n return statusData;\n\n } catch (error: any) {\n Logger.error(`[${traceId}] Failed to check status for task ${task.taskId}:`, error);\n return null;\n }\n }\n\n /**\n * Updates a local A2A task based on remote status information.\n * \n * @param {A2ATask} task - The local A2A task to update\n * @param {TaskStatusResponse} statusResponse - The status response from the remote agent\n * @param {string} [traceId] - Optional trace ID for request tracking\n * @returns {Promise<A2ATask>} Promise resolving to the updated task\n */\n async updateTaskFromRemoteStatus(\n task: A2ATask, \n statusResponse: TaskStatusResponse, \n traceId?: string\n ): Promise<A2ATask> {\n const now = Date.now();\n const updatedMetadata: A2ATaskMetadata = {\n ...task.metadata,\n updatedAt: now\n };\n\n const updates: Partial<A2ATask> = {\n status: statusResponse.status,\n metadata: updatedMetadata\n };\n\n // Handle completion\n if (statusResponse.status === A2ATaskStatus.COMPLETED && statusResponse.result) {\n updates.result = statusResponse.result;\n updatedMetadata.completedAt = now;\n }\n\n // Handle failure\n if (statusResponse.status === A2ATaskStatus.FAILED && statusResponse.error) {\n updates.result = {\n success: false,\n error: statusResponse.error,\n metadata: { remoteError: true, timestamp: now }\n };\n updatedMetadata.completedAt = now;\n }\n\n // Update additional metadata\n if (statusResponse.metadata) {\n Object.assign(updatedMetadata, statusResponse.metadata);\n }\n\n // Update the updates object with the final metadata\n updates.metadata = updatedMetadata;\n\n await this.taskRepository.updateTask(task.taskId, updates);\n \n Logger.debug(`[${traceId}] Updated task ${task.taskId} with remote status: ${statusResponse.status}`);\n return { ...task, ...updates };\n }\n\n /**\n * Generates a callback URL for webhook notifications.\n * This would typically point to an endpoint in the local system.\n * \n * @private\n * @param {string} taskId - The task ID to generate callback URL for\n * @returns {string} The callback URL string\n */\n private generateCallbackUrl(taskId: string): string {\n const baseUrl = this.config.callbackUrl.replace(/\\/$/, ''); // Remove trailing slash\n return `${baseUrl}/${taskId}`;\n }\n\n /**\n * Cancels a delegated task on the remote agent.\n * \n * @param {A2ATask} task - The A2A task to cancel\n * @param {string} [traceId] - Optional trace ID for request tracking\n * @returns {Promise<boolean>} Promise resolving to whether cancellation was successful\n */\n async cancelTask(task: A2ATask, traceId?: string): Promise<boolean> {\n if (!task.targetAgent?.endpoint) {\n Logger.warn(`[${traceId}] Cannot cancel task ${task.taskId}: no target agent endpoint`);\n return false;\n }\n\n const cancelUrl = `${task.targetAgent.endpoint.replace(/\\/$/, '')}/tasks/${task.taskId}`;\n \n try {\n const response = await fetch(cancelUrl, {\n method: 'DELETE',\n headers: {\n 'User-Agent': 'ART-Framework-A2A/1.0.0',\n 'X-Trace-ID': traceId || '',\n ...(task.targetAgent.authentication?.type === 'bearer' && task.targetAgent.authentication.token \n ? { 'Authorization': `Bearer ${task.targetAgent.authentication.token}` }\n : {}),\n ...(task.targetAgent.authentication?.type === 'api_key' && task.targetAgent.authentication.apiKey \n ? { 'X-API-Key': task.targetAgent.authentication.apiKey }\n : {})\n }\n });\n\n if (response.ok) {\n // Update local task status\n await this.taskRepository.updateTask(task.taskId, {\n status: A2ATaskStatus.CANCELLED,\n metadata: {\n ...task.metadata,\n updatedAt: Date.now(),\n completedAt: Date.now()\n }\n });\n\n Logger.info(`[${traceId}] Successfully cancelled task ${task.taskId}`);\n return true;\n } else {\n Logger.warn(`[${traceId}] Failed to cancel task ${task.taskId}: HTTP ${response.status}`);\n return false;\n }\n\n } catch (error: any) {\n Logger.error(`[${traceId}] Error cancelling task ${task.taskId}:`, error);\n return false;\n }\n }\n} ","// src/core/agent-factory.ts\nimport {\n IAgentCore,\n StorageAdapter,\n IConversationRepository,\n IObservationRepository,\n IStateRepository,\n IA2ATaskRepository,\n ConversationManager,\n StateManager,\n ObservationManager,\n ToolRegistry,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n type IToolExecutor, // type-only import\n // ProviderAdapter, // Removed direct ProviderAdapter interface import\n ReasoningEngine,\n OutputParser,\n ToolSystem,\n UISystem\n // Removed ObservationSocket, ConversationSocket interface imports\n} from '@/core/interfaces';\nimport { IProviderManager } from '@/types/providers'; // Corrected path\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { ProviderManagerConfig } from '@/types/providers'; // type-only import\n// Import ArtInstanceConfig and StateSavingStrategy\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport { ArtInstanceConfig, StateSavingStrategy } from '@/types';\nimport { ProviderManagerImpl } from '@/systems/reasoning/ProviderManagerImpl'; // Corrected path\nimport { PESAgent } from '@/core/agents/pes-agent';\n\n// Import concrete implementations (assuming paths)\n// Storage Adapters\nimport { InMemoryStorageAdapter } from '@/integrations/storage/inMemory'; // Corrected path\nimport { IndexedDBStorageAdapter } from '@/integrations/storage/indexedDB'; // Corrected path\n// Repositories\nimport { ConversationRepository } from '@/systems/context/repositories/ConversationRepository'; // Corrected path\nimport { ObservationRepository } from '@/systems/context/repositories/ObservationRepository'; // Corrected path - Moved from observation system\nimport { StateRepository } from '@/systems/context/repositories/StateRepository'; // Corrected path\nimport { TaskStatusRepository } from '@/systems/context/repositories/TaskStatusRepository'; // A2A task repository\n// Managers\nimport { ConversationManager as ConversationManagerImpl } from '@/systems/context/managers/ConversationManager'; // Corrected path\nimport { StateManager as StateManagerImpl } from '@/systems/context/managers/StateManager'; // Corrected path\nimport { ObservationManager as ObservationManagerImpl } from '@/systems/observation/observation-manager'; // Correct path\n// Tool System\nimport { ToolRegistry as ToolRegistryImpl } from '@/systems/tool/ToolRegistry'; // Correct path\nimport { ToolSystem as ToolSystemImpl } from '@/systems/tool/ToolSystem'; // Correct path\n// Reasoning System\nimport { SystemPromptResolver as SystemPromptResolverImpl } from '@/systems/reasoning/SystemPromptResolver';\nimport { ReasoningEngine as ReasoningEngineImpl } from '@/systems/reasoning/ReasoningEngine'; // Correct path\nimport { OutputParser as OutputParserImpl } from '@/systems/reasoning/OutputParser'; // Correct path\n// Provider Adapters are now managed by ProviderManagerImpl\n// UI System\nimport { UISystem as UISystemImpl } from '@/systems/ui/ui-system'; // Correct path\n// Auth and MCP Systems\nimport { AuthManager } from '@/systems/auth/AuthManager'; // Import AuthManager\nimport { McpManager } from '@/systems/mcp/McpManager'; // Import McpManager\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { McpManagerConfig } from '@/systems/mcp/types'; // type-only import for McpManagerConfig\nimport { AgentDiscoveryService } from '@/systems/a2a/AgentDiscoveryService';\nimport { TaskDelegationService } from '@/systems/a2a/TaskDelegationService';\n// Removed direct imports of concrete socket classes - they will be accessed via UISystem instance\n// Removed unused type imports: Observation, ConversationMessage, ObservationType, MessageRole\nimport { Logger } from '@/utils/logger'; // Import Logger\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { LogLevel } from '@/utils/logger'; // type-only import\n\n\n/**\n * Configuration for the Storage System adapter.\n */\nexport interface StorageConfig {\n /** Specifies the type of storage adapter to use. */\n type: 'memory' | 'indexedDB';\n /** The name of the database to use (required for 'indexedDB'). */\n dbName?: string;\n /** Optional: Database version for schema migrations (for 'indexedDB'). Defaults might apply. */\n version?: number;\n /** Optional: Advanced configuration for IndexedDB object stores and indexes. Defaults are usually sufficient. */\n objectStores?: any[]; // Define a more specific type if possible\n // Add other adapter-specific config options as needed\n}\n\n/**\n * Configuration for the Reasoning System provider adapter.\n */\nexport interface ReasoningConfig {\n /** The identifier of the LLM provider to use. */\n provider: 'openai' | 'gemini' | 'anthropic' | 'openrouter' | 'deepseek'; // Add others as implemented\n /** The API key for the selected provider. Handle securely (e.g., via environment variables). */\n apiKey: string;\n /** Optional: The default model ID to use for this provider if not specified elsewhere (e.g., in ThreadConfig). */\n model?: string;\n /** Optional: Custom base URL for the provider's API (e.g., for proxies or self-hosted models). */\n baseURL?: string;\n /** Optional: Default parameters to pass to the LLM provider on each call (e.g., temperature). */\n defaultParams?: Record<string, any>;\n // Add other provider-specific options as needed\n}\n\n/**\n * Configuration object required by the AgentFactory and createArtInstance function.\n * This will now use ArtInstanceConfig from types.ts which includes stateSavingStrategy.\n */\n// export interface AgentFactoryConfig { // Commented out, will use ArtInstanceConfig\n// /** Configuration for the storage adapter. */\n// storage: StorageConfig;\n// /** Configuration for the Provider Manager, defining available adapters and rules. */\n// providers: ProviderManagerConfig; // Changed from reasoning: ReasoningConfig\n// /** Optional array of tool executor instances to register at initialization. */\n// tools?: IToolExecutor[];\n// /** Optional: Specify a different Agent Core implementation class (defaults to PESAgent). */\n// agentCore?: new (dependencies: any) => IAgentCore;\n// /** Optional: Configuration for the logger. */\n// logger?: { level?: LogLevel }; // Assuming LogLevel enum exists\n// // TODO: Add other potential global configurations (e.g., default ThreadConfig, UI system options)\n// }\n\n/**\n * Handles the instantiation and wiring of all core ART framework components based on provided configuration.\n * This class performs the dependency injection needed to create a functional `ArtInstance`.\n * It's typically used internally by the `createArtInstance` function.\n */\nexport class AgentFactory {\n private config: ArtInstanceConfig; // Changed to ArtInstanceConfig\n private storageAdapter: StorageAdapter | null = null;\n private uiSystem: UISystem | null = null;\n private conversationRepository: IConversationRepository | null = null;\n private observationRepository: IObservationRepository | null = null;\n private stateRepository: IStateRepository | null = null;\n private a2aTaskRepository: IA2ATaskRepository | null = null;\n private conversationManager: ConversationManager | null = null;\n private stateManager: StateManager | null = null;\n private observationManager: ObservationManager | null = null;\n private toolRegistry: ToolRegistry | null = null;\n // private providerAdapter: ProviderAdapter | null = null; // Replaced with providerManager\n private providerManager: IProviderManager | null = null; // Added providerManager\n private reasoningEngine: ReasoningEngine | null = null;\n private outputParser: OutputParser | null = null;\n private systemPromptResolver: any | null = null;\n private toolSystem: ToolSystem | null = null;\n private authManager: AuthManager | null = null;\n private mcpManager: McpManager | null = null;\n private agentDiscoveryService: AgentDiscoveryService | null = null;\n private taskDelegationService: TaskDelegationService | null = null;\n\n\n /**\n * Creates a new AgentFactory instance.\n * @param config - The configuration specifying which adapters and components to use.\n */\n constructor(config: ArtInstanceConfig) { // Changed to ArtInstanceConfig\n this.config = config;\n // Basic validation\n if (!config.storage) throw new Error(\"ArtInstanceConfig requires 'storage' configuration.\");\n if (!config.providers) throw new Error(\"ArtInstanceConfig requires 'providers' configuration.\");\n }\n\n /**\n * Asynchronously initializes all core components based on the configuration.\n * This includes setting up the storage adapter, repositories, managers, tool registry,\n * reasoning engine, and UI system.\n * This method MUST be called before `createAgent()`.\n * @returns A promise that resolves when initialization is complete.\n * @throws {Error} If configuration is invalid or initialization fails for a component.\n */\n async initialize(): Promise<void> {\n // --- Initialize Storage ---\n if ('type' in this.config.storage) { // Type guard for storage config object\n const storageConfig = this.config.storage; // storageConfig is now { type: 'memory' | 'indexedDB', ... }\n switch (storageConfig.type) {\n case 'indexedDB':\n this.storageAdapter = new IndexedDBStorageAdapter({\n dbName: storageConfig.dbName || 'ARTDB',\n objectStores: storageConfig.objectStores || ['conversations', 'observations', 'state', 'a2a_tasks']\n });\n break;\n case 'memory':\n default:\n this.storageAdapter = new InMemoryStorageAdapter();\n break;\n }\n } else { // It's a pre-configured StorageAdapter instance\n this.storageAdapter = this.config.storage;\n }\n await this.storageAdapter!.init?.(); // Add non-null assertion\n\n // --- Initialize Repositories ---\n // Add non-null assertions assuming storageAdapter is initialized above\n this.conversationRepository = new ConversationRepository(this.storageAdapter!);\n this.observationRepository = new ObservationRepository(this.storageAdapter!);\n this.stateRepository = new StateRepository(this.storageAdapter!);\n this.a2aTaskRepository = new TaskStatusRepository(this.storageAdapter!);\n\n // --- Initialize UI System ---\n // UISystem constructor expects repositories, not sockets\n this.uiSystem = new UISystemImpl(this.observationRepository!, this.conversationRepository!, this.a2aTaskRepository || undefined); // Pass repositories including A2A task repository\n\n // --- Initialize Managers ---\n // Pass the actual socket instances obtained from the initialized uiSystem\n this.conversationManager = new ConversationManagerImpl(this.conversationRepository!, this.uiSystem.getConversationSocket());\n // Pass the stateSavingStrategy to StateManagerImpl constructor\n const strategy = this.config.stateSavingStrategy || 'explicit'; // Default to 'explicit'\n this.stateManager = new StateManagerImpl(this.stateRepository!, strategy);\n this.observationManager = new ObservationManagerImpl(this.observationRepository!, this.uiSystem.getObservationSocket());\n\n // --- Initialize Tool Registry & Register Tools ---\n // Pass the initialized StateManager to the ToolRegistry constructor\n this.toolRegistry = new ToolRegistryImpl(this.stateManager!);\n if (this.config.tools) {\n for (const tool of this.config.tools) {\n await this.toolRegistry!.registerTool(tool); // Add non-null assertion\n }\n }\n\n // --- Initialize Provider Manager ---\n // ProviderManagerImpl likely needs configuration for *all* potential providers.\n // The current AgentFactoryConfig only holds one reasoning config. This needs refactoring\n // for a true multi-provider setup where the manager knows all potential credentials/configs.\n // For now, instantiate it simply to fix the type error. Runtime provider selection might fail\n // Pass the provider configuration from the main config\n this.providerManager = new ProviderManagerImpl(this.config.providers);\n Logger.info(\"ProviderManager initialized.\");\n\n\n // --- Initialize Reasoning Components ---\n this.reasoningEngine = new ReasoningEngineImpl(this.providerManager!); // Pass ProviderManager\n // Initialize SystemPromptResolver with registry from config if provided\n const registry = (this.config as any).systemPrompts as import('../types').SystemPromptsRegistry | undefined;\n this.systemPromptResolver = new SystemPromptResolverImpl(registry);\n this.outputParser = new OutputParserImpl(); // Basic implementation for now\n\n // --- Initialize Tool System ---\n // Inject ToolRegistry, StateManager, and ObservationManager into ToolSystem\n this.toolSystem = new ToolSystemImpl(this.toolRegistry!, this.stateManager!, this.observationManager!); // Added observationManager\n\n // --- Initialize Auth Manager ---\n if (this.config.authConfig?.enabled) {\n this.authManager = new AuthManager();\n // Register any pre-configured strategies\n if (this.config.authConfig.strategies) {\n for (const { id, strategy } of this.config.authConfig.strategies) {\n this.authManager.registerStrategy(id, strategy);\n }\n }\n Logger.info(\"AuthManager initialized.\");\n }\n\n // --- Initialize A2A Services ---\n if (this.config.a2aConfig) {\n this.agentDiscoveryService = new AgentDiscoveryService({\n discoveryEndpoint: this.config.a2aConfig.discoveryEndpoint,\n });\n this.taskDelegationService = new TaskDelegationService(\n this.a2aTaskRepository!,\n { callbackUrl: this.config.a2aConfig.callbackUrl }\n );\n Logger.info(\"A2A Services (Discovery, Delegation) initialized.\");\n }\n\n // --- Initialize MCP Manager ---\n if (this.config.mcpConfig) {\n if (!this.toolRegistry || !this.stateManager) {\n throw new Error(\"MCP Manager requires ToolRegistry and StateManager to be initialized first.\");\n }\n // McpManager now reads its own config from the file system and discovers from Zyntopia.\n this.mcpManager = new McpManager(\n this.toolRegistry,\n this.stateManager,\n this.authManager || undefined\n );\n // Initialize with both local config and Zyntopia discovery\n await this.mcpManager.initialize(this.config.mcpConfig);\n Logger.info(\"McpManager Hub initialized with local config and Zyntopia discovery.\");\n }\n }\n\n /**\n * Creates an instance of the configured Agent Core (e.g., `PESAgent`) and injects\n * all necessary initialized dependencies (managers, systems, etc.).\n * Requires `initialize()` to have been successfully called beforehand.\n * @returns An instance implementing the `IAgentCore` interface.\n * @throws {Error} If `initialize()` was not called or if essential components failed to initialize.\n */\n createAgent(): IAgentCore {\n // Check for all required components after initialization\n if (!this.stateManager || !this.conversationManager || !this.toolRegistry ||\n !this.reasoningEngine || !this.outputParser ||\n !this.observationManager || !this.toolSystem || !this.providerManager ||\n !this.a2aTaskRepository) { // Check A2A task repository\n throw new Error(\"AgentFactory not fully initialized. Call initialize() before creating an agent.\");\n }\n\n // Pass dependencies to the agent constructor\n // This object's structure should align with what the Agent Core implementation expects (e.g., PESAgentDependencies)\n const dependencies = {\n stateManager: this.stateManager,\n conversationManager: this.conversationManager,\n toolRegistry: this.toolRegistry,\n reasoningEngine: this.reasoningEngine,\n outputParser: this.outputParser,\n observationManager: this.observationManager,\n toolSystem: this.toolSystem,\n uiSystem: this.uiSystem!, // Include the UI System (non-null assertion)\n systemPromptResolver: this.systemPromptResolver,\n a2aTaskRepository: this.a2aTaskRepository, // Include A2A task repository\n authManager: this.authManager, // Include Auth Manager (may be null if not configured)\n mcpManager: this.mcpManager, // Include MCP Manager (may be null if not configured)\n agentDiscoveryService: this.agentDiscoveryService, // Include A2A Discovery Service\n taskDelegationService: this.taskDelegationService, // Include A2A Delegation Service\n persona: this.config.persona, // Pass the persona from the main config\n // Note: providerAdapter is used by reasoningEngine, not directly by agent core usually\n };\n\n // Instantiate the specified Agent Core or default to PESAgent\n const AgentCoreImplementation = this.config.agentCore || PESAgent;\n const agent = new AgentCoreImplementation(dependencies);\n return agent;\n }\n\n // --- Getters for initialized components (primarily for createArtInstance) ---\n /** Gets the initialized Storage Adapter instance. */\n getStorageAdapter(): StorageAdapter | null { return this.storageAdapter; }\n /** Gets the initialized UI System instance. */\n getUISystem(): UISystem | null { return this.uiSystem; }\n /** Gets the initialized Tool Registry instance. */\n getToolRegistry(): ToolRegistry | null { return this.toolRegistry; }\n /** Gets the initialized State Manager instance. */\n getStateManager(): StateManager | null { return this.stateManager; }\n /** Gets the initialized Conversation Manager instance. */\n getConversationManager(): ConversationManager | null { return this.conversationManager; }\n /** Gets the initialized Observation Manager instance. */\n getObservationManager(): ObservationManager | null { return this.observationManager; }\n /** Gets the initialized Auth Manager instance. */\n getAuthManager(): AuthManager | null { return this.authManager; }\n /** Gets the initialized MCP Manager instance. */\n getMcpManager(): McpManager | null { return this.mcpManager; }\n // Add getters for other components like reasoningEngine, toolSystem if needed\n}\n\n// --- Convenience Factory Function ---\nimport { ArtInstance } from '@/core/interfaces'; // Import the new interface\n\n/**\n * High-level factory function to create and initialize a complete ART framework instance.\n * This simplifies the setup process by handling the instantiation and wiring of all\n * necessary components based on the provided configuration.\n * @param config - The configuration object specifying storage, reasoning, tools, etc.\n * @returns A promise that resolves to a ready-to-use `ArtInstance` object, providing access to the core `process` method and essential managers/systems.\n * @throws {Error} If initialization fails (e.g., invalid config, storage connection error).\n * @example\n * const art = await createArtInstance({\n * storage: { type: 'indexedDB', dbName: 'myAgentDb' },\n * reasoning: { provider: 'openai', apiKey: '...' },\n * tools: [new CalculatorTool()]\n * });\n * const response = await art.process({ query: \"Calculate 5*5\", threadId: \"thread1\" });\n */\nexport async function createArtInstance(config: ArtInstanceConfig): Promise<ArtInstance> { // Changed to ArtInstanceConfig\n const factory = new AgentFactory(config);\n await factory.initialize();\n const agentCore = factory.createAgent();\n\n // Retrieve initialized components from the factory\n const uiSystem = factory.getUISystem();\n const stateManager = factory.getStateManager(); // Assuming getStateManager getter exists\n const conversationManager = factory.getConversationManager(); // Assuming getter exists\n const toolRegistry = factory.getToolRegistry(); // Assuming getter exists\n const observationManager = factory.getObservationManager(); // Assuming getter exists\n const authManager = factory.getAuthManager();\n\n // Ensure all required components were initialized\n if (!uiSystem || !stateManager || !conversationManager || !toolRegistry || !observationManager) {\n throw new Error(\"Failed to initialize one or more core components within AgentFactory.\");\n }\n\n return {\n process: agentCore.process.bind(agentCore), // Bind the process method\n uiSystem: uiSystem,\n stateManager: stateManager,\n conversationManager: conversationManager,\n toolRegistry: toolRegistry,\n observationManager: observationManager,\n authManager: authManager,\n };\n}","import { StorageAdapter } from '@/core/interfaces';\nimport { FilterOptions } from '@/types';\nimport { Logger } from '@/utils/logger';\n\nexport interface SupabaseConfig {\n /** Supabase project URL, e.g., https://xyzcompany.supabase.co */\n url: string;\n /** Supabase anon or service key. Prefer service key on server-side only. */\n apiKey: string;\n /** Optional schema name (default 'public'). */\n schema?: string;\n /**\n * Table names to use. These map ART collections to Supabase.\n * If you customize collection names in repositories, adjust accordingly.\n */\n tables?: {\n conversations?: string;\n observations?: string;\n state?: string;\n a2a_tasks?: string;\n };\n /**\n * Optional: pass a pre-initialized Supabase client (from @supabase/supabase-js)\n * Useful in environments where you already manage the client and auth.\n */\n client?: any;\n}\n\n/**\n * A Supabase-backed StorageAdapter implementation.\n *\n * Expectations/assumptions:\n * - Each collection maps to a table with a primary key column named 'id' (text/uuid).\n * - We store JSON columns for flexible data where needed. However, repositories\n * store fully shaped rows; this adapter just persists and retrieves whole objects.\n * - For query(), we implement basic equality filters per FilterOptions.filter keys,\n * plus limit/skip and a single-key sort.\n */\nexport class SupabaseStorageAdapter implements StorageAdapter {\n private client: any | null = null;\n private config!: SupabaseConfig;\n private schema: string = 'public';\n private tables = {\n conversations: 'conversations',\n observations: 'observations',\n state: 'state',\n a2a_tasks: 'a2a_tasks',\n };\n\n /**\n * Creates an instance of SupabaseStorageAdapter.\n * @see SupabaseConfig\n */\n constructor(config: SupabaseConfig) {\n this.configure(config);\n }\n\n /**\n * Configures the adapter with the provided Supabase settings.\n * @private\n * @param {SupabaseConfig} config - The configuration for the adapter.\n */\n private configure(config: SupabaseConfig) {\n this.config = config;\n if (config.schema) this.schema = config.schema;\n if (config.tables) {\n this.tables = { ...this.tables, ...config.tables };\n }\n this.client = config.client ?? null;\n }\n\n /**\n * Initializes the Supabase client if it hasn't been provided already.\n * @returns {Promise<void>} A promise that resolves when the client is initialized.\n */\n async init(): Promise<void> {\n if (this.client) return; // Already provided\n try {\n // Lazy import to avoid bundling if unused\n const { createClient } = await import('@supabase/supabase-js');\n this.client = createClient(this.config.url, this.config.apiKey, {\n db: { schema: this.schema },\n auth: { persistSession: false },\n });\n Logger.info('SupabaseStorageAdapter: Client initialized.');\n } catch (err: any) {\n Logger.error('SupabaseStorageAdapter: Failed to initialize client', err);\n throw err;\n }\n }\n\n /**\n * Maps a collection name to a Supabase table name.\n * @private\n * @param {string} collection - The name of the collection.\n * @returns {string} The name of the Supabase table.\n */\n private tableForCollection(collection: string): string {\n // Allow direct pass-through for custom collections; otherwise map known ones\n switch (collection) {\n case 'conversations':\n return this.tables.conversations;\n case 'observations':\n return this.tables.observations;\n case 'state':\n return this.tables.state;\n case 'a2a_tasks':\n return this.tables.a2a_tasks;\n default:\n return collection; // Use collection name as-is for custom use\n }\n }\n\n /**\n * Retrieves a single item from a collection by its ID.\n * @template T\n * @param {string} collection - The name of the collection.\n * @param {string} id - The ID of the item to retrieve.\n * @returns {Promise<T | null>} A promise that resolves with the item, or null if not found.\n */\n async get<T>(collection: string, id: string): Promise<T | null> {\n await this.init();\n const table = this.tableForCollection(collection);\n const { data, error } = await this.client\n .from(table)\n .select('*')\n .eq('id', id)\n .limit(1)\n .maybeSingle();\n if (error) {\n Logger.error(`SupabaseStorageAdapter: get error for ${table}/${id}`, error);\n throw new Error(error.message);\n }\n return (data ? { ...data } : null) as T | null;\n }\n\n /**\n * Saves (upserts) an item in a collection.\n * @template T\n * @param {string} collection - The name of the collection.\n * @param {string} id - The ID of the item to save.\n * @param {T} data - The data to save.\n * @returns {Promise<void>} A promise that resolves when the item is saved.\n */\n async set<T>(collection: string, id: string, data: T): Promise<void> {\n await this.init();\n const table = this.tableForCollection(collection);\n const row: any = { ...(data as any) };\n if (typeof row.id === 'undefined') {\n throw new Error(`SupabaseStorageAdapter: Data for collection '${collection}' must have an 'id' property.`);\n }\n // Upsert by primary key 'id'\n const { error } = await this.client\n .from(table)\n .upsert(row, { onConflict: 'id' });\n if (error) {\n Logger.error(`SupabaseStorageAdapter: set error for ${table}/${id}`, error);\n throw new Error(error.message);\n }\n }\n\n /**\n * Deletes an item from a collection by its ID.\n * @param {string} collection - The name of the collection.\n * @param {string} id - The ID of the item to delete.\n * @returns {Promise<void>} A promise that resolves when the item is deleted.\n */\n async delete(collection: string, id: string): Promise<void> {\n await this.init();\n const table = this.tableForCollection(collection);\n const { error } = await this.client\n .from(table)\n .delete()\n .eq('id', id);\n if (error) {\n Logger.error(`SupabaseStorageAdapter: delete error for ${table}/${id}`, error);\n throw new Error(error.message);\n }\n }\n\n /**\n * Queries items in a collection.\n * @template T\n * @param {string} collection - The name of the collection.\n * @param {FilterOptions} filterOptions - The options for filtering, sorting, and pagination.\n * @returns {Promise<T[]>} A promise that resolves with an array of items.\n */\n async query<T>(collection: string, filterOptions: FilterOptions): Promise<T[]> {\n await this.init();\n const table = this.tableForCollection(collection);\n let query = this.client.from(table).select('*');\n\n // Basic equality filters: key = value\n if (filterOptions?.filter) {\n for (const [key, value] of Object.entries(filterOptions.filter)) {\n // For array filter, use 'in'\n if (Array.isArray(value)) {\n query = query.in(key, value);\n } else if (value !== undefined && value !== null) {\n query = query.eq(key, value);\n }\n }\n }\n\n // Sorting: single key supported (choose first)\n if (filterOptions?.sort) {\n const [sortKey, sortDir] = Object.entries(filterOptions.sort)[0] || [];\n if (sortKey) {\n query = query.order(sortKey, { ascending: sortDir === 'asc' });\n }\n }\n\n // Pagination\n const skip = filterOptions?.skip || 0;\n const limit = filterOptions?.limit ?? null;\n if (limit !== null && limit >= 0) {\n query = query.range(skip, skip + Math.max(0, limit) - 1);\n } else if (skip > 0) {\n // Supabase requires a range; if only skip is provided without limit, we pick a large window\n query = query.range(skip, skip + 9999);\n }\n\n const { data, error } = await query;\n if (error) {\n Logger.error(`SupabaseStorageAdapter: query error for ${table}`, error);\n throw new Error(error.message);\n }\n return (data ?? []).map((row: any) => ({ ...row })) as T[];\n }\n\n /**\n * Clears all items from a collection.\n * @param {string} collection - The name of the collection.\n * @returns {Promise<void>} A promise that resolves when the collection is cleared.\n */\n async clearCollection(collection: string): Promise<void> {\n await this.init();\n const table = this.tableForCollection(collection);\n const { error } = await this.client.from(table).delete().neq('id', null);\n if (error) {\n Logger.error(`SupabaseStorageAdapter: clearCollection error for ${table}`, error);\n throw new Error(error.message);\n }\n }\n\n /**\n * Clears all items from all collections.\n * @returns {Promise<void>} A promise that resolves when all collections are cleared.\n */\n async clearAll(): Promise<void> {\n await this.init();\n const tables = Object.values(this.tables);\n for (const table of tables) {\n const { error } = await this.client.from(table).delete().neq('id', null);\n if (error) {\n Logger.error(`SupabaseStorageAdapter: clearAll error for ${table}`, error);\n throw new Error(error.message);\n }\n }\n }\n}\n\n\n","// src/adapters/reasoning/gemini.ts\n// Use correct import based on documentation for @google/genai\nimport { GoogleGenAI, Content, Part, GenerationConfig, GenerateContentResponse } from \"@google/genai\"; // Import SDK components\nimport { ProviderAdapter } from '@/core/interfaces';\nimport {\n ArtStandardPrompt, // Use the new standard type\n // ArtStandardMessage, // Removed unused import\n // ArtStandardMessageRole, // Removed unused import\n CallOptions,\n StreamEvent,\n LLMMetadata,\n // Removed ConversationMessage, MessageRole as they are replaced by ArtStandard types for input\n} from '@/types';\nimport { Logger } from '@/utils/logger';\nimport { ARTError, ErrorCode } from '@/errors'; // Import ARTError and ErrorCode\n\n// Define expected options for the Gemini adapter constructor\n/**\n * Configuration options required for the `GeminiAdapter`.\n */\nexport interface GeminiAdapterOptions {\n /** Your Google AI API key (e.g., from Google AI Studio). Handle securely. */\n apiKey: string;\n /** The default Gemini model ID to use (e.g., 'gemini-2.5-flash', 'gemini-pro'). Defaults to 'gemini-2.5-flash' if not provided. */\n model?: string;\n /** Optional: Override the base URL for the Google Generative AI API. */\n apiBaseUrl?: string; // Note: Not directly used by SDK basic setup\n /** Optional: Specify the API version to use (e.g., 'v1beta'). Defaults to 'v1beta'. */\n apiVersion?: string; // Note: Not directly used by SDK basic setup\n}\n\n\n// Retry configuration\nconst DEFAULT_MAX_RETRIES = 3;\nconst DEFAULT_INITIAL_DELAY_MS = 1000;\nconst DEFAULT_MAX_DELAY_MS = 30000;\nconst RETRYABLE_STATUS_CODES = [503, 429, 500, 502, 504];\n\n/**\n * Helper function to check if an error is retryable\n */\nfunction isRetryableError(error: any): boolean {\n // Check for status code in various error formats\n const statusCode = error?.code || error?.status || error?.error?.code;\n if (statusCode && RETRYABLE_STATUS_CODES.includes(Number(statusCode))) {\n return true;\n }\n // Check for common retryable error messages\n const message = String(error?.message || error?.error?.message || '').toLowerCase();\n return message.includes('overloaded') ||\n message.includes('rate limit') ||\n message.includes('temporarily unavailable') ||\n message.includes('503') ||\n message.includes('429');\n}\n\n/**\n * Executes a function with exponential backoff retry logic\n */\nasync function withRetry<T>(\n fn: () => Promise<T>,\n options: {\n maxRetries?: number;\n initialDelayMs?: number;\n maxDelayMs?: number;\n onRetry?: (error: any, attempt: number, delayMs: number) => void;\n } = {}\n): Promise<T> {\n const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;\n const initialDelayMs = options.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;\n const maxDelayMs = options.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;\n\n let lastError: any;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n return await fn();\n } catch (error: any) {\n lastError = error;\n\n if (attempt === maxRetries || !isRetryableError(error)) {\n throw error;\n }\n\n // Calculate delay with exponential backoff and jitter\n const baseDelay = initialDelayMs * Math.pow(2, attempt);\n const jitter = Math.random() * 0.3 * baseDelay; // 0-30% jitter\n const delayMs = Math.min(baseDelay + jitter, maxDelayMs);\n\n if (options.onRetry) {\n options.onRetry(error, attempt + 1, delayMs);\n }\n\n Logger.warn(`Gemini API call failed (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${Math.round(delayMs)}ms...`, {\n error: error?.message || error,\n statusCode: error?.code || error?.status || error?.error?.code\n });\n\n await new Promise(resolve => setTimeout(resolve, delayMs));\n }\n }\n\n throw lastError;\n}\n\nexport class GeminiAdapter implements ProviderAdapter {\n readonly providerName = 'gemini';\n private apiKey: string;\n private defaultModel: string; // Renamed for clarity\n private genAI: GoogleGenAI; // Stores the initialized GoogleGenAI SDK instance.\n\n /**\n * Creates an instance of GeminiAdapter.\n * @param {GeminiAdapterOptions} options - Configuration options for the adapter.\n * @throws {Error} If `apiKey` is missing in the options.\n * @see https://ai.google.dev/api/rest\n */\n constructor(options: GeminiAdapterOptions) {\n if (!options.apiKey) {\n throw new Error('GeminiAdapter requires an apiKey in options.');\n }\n this.apiKey = options.apiKey;\n this.defaultModel = options.model || 'gemini-2.5-flash'; // Default to latest stable flash model\n // Initialize the SDK\n // Use correct constructor based on documentation\n this.genAI = new GoogleGenAI({ apiKey: this.apiKey });\n // Note: apiBaseUrl and apiVersion from options are not directly used by the SDK in this basic setup.\n // Advanced SDK configuration might allow proxies if needed.\n Logger.debug(`GeminiAdapter initialized with default model: ${this.defaultModel}`);\n }\n\n /**\n * Makes a call to the configured Gemini model.\n * Translates the `ArtStandardPrompt` into the Gemini API format, sends the request\n * using the `@google/genai` SDK, and yields `StreamEvent` objects representing\n * the response (tokens, metadata, errors, end signal).\n *\n * Handles both streaming and non-streaming requests based on `options.stream`.\n *\n * Thinking tokens (Gemini):\n * - On supported Gemini models (e.g., `gemini-2.5-*`), you can enable thought output via `config.thinkingConfig`.\n * - This adapter reads provider-specific flags from the call options:\n * - `options.gemini.thinking.includeThoughts: boolean` — when `true`, requests thought (reasoning) output.\n * - `options.gemini.thinking.thinkingBudget?: number` — optional token budget for thinking.\n * - When enabled and supported, the adapter will attempt to differentiate thought vs response parts and set\n * `StreamEvent.tokenType` accordingly:\n * - For planning calls (`callContext === 'AGENT_THOUGHT'`): `AGENT_THOUGHT_LLM_THINKING` or `AGENT_THOUGHT_LLM_RESPONSE`.\n * - For synthesis calls (`callContext === 'FINAL_SYNTHESIS'`): `FINAL_SYNTHESIS_LLM_THINKING` or `FINAL_SYNTHESIS_LLM_RESPONSE`.\n * - `LLMMetadata.thinkingTokens` will be populated if the provider reports separate thinking token usage.\n * - If the SDK/model does not expose thought parts, the adapter falls back to labeling tokens as `...LLM_RESPONSE`.\n *\n * @param {ArtStandardPrompt} prompt - The standardized prompt messages.\n * @param {CallOptions} options - Options for the LLM call, including streaming preference, model override, and execution context.\n * @returns {Promise<AsyncIterable<StreamEvent>>} An async iterable that yields `StreamEvent` objects.\n * - `TOKEN`: Contains a chunk of the response text. `tokenType` indicates if it's part of agent thought or final synthesis.\n * When Gemini thinking is enabled and available, `tokenType` may be one of the `...LLM_THINKING` or\n * `...LLM_RESPONSE` variants to separate thought vs response tokens.\n * - `METADATA`: Contains information like stop reason, token counts, and timing, yielded once at the end.\n * - `ERROR`: Contains any error encountered during translation, SDK call, or response processing.\n * - `END`: Signals the completion of the stream.\n * @see {ArtStandardPrompt}\n * @see {CallOptions}\n * @see {StreamEvent}\n * @see {LLMMetadata}\n * @see https://ai.google.dev/api/rest/v1beta/models/generateContent\n *\n * @example\n * // Enable Gemini thinking (if supported by the selected model)\n * const stream = await geminiAdapter.call(prompt, {\n * threadId,\n * stream: true,\n * callContext: 'FINAL_SYNTHESIS',\n * providerConfig, // your RuntimeProviderConfig\n * gemini: {\n * thinking: { includeThoughts: true, thinkingBudget: 8096 }\n * }\n * });\n * for await (const evt of stream) {\n * if (evt.type === 'TOKEN') {\n * // evt.tokenType may be FINAL_SYNTHESIS_LLM_THINKING or FINAL_SYNTHESIS_LLM_RESPONSE\n * }\n * }\n */\n async call(prompt: ArtStandardPrompt, options: CallOptions): Promise<AsyncIterable<StreamEvent>> {\n const { threadId, traceId = `gemini-trace-${Date.now()}`, sessionId, stream, callContext, model: modelOverride } = options;\n const modelToUse = modelOverride || this.defaultModel;\n\n // --- Format Payload for SDK ---\n let contents: Content[];\n try {\n contents = this.translateToGemini(prompt); // Use the new translation function\n } catch (error: any) {\n Logger.error(`Error translating ArtStandardPrompt to Gemini format: ${error.message}`, { error, threadId, traceId });\n // Immediately yield error and end if translation fails\n const generator = async function* (): AsyncIterable<StreamEvent> {\n yield { type: 'ERROR', data: error instanceof Error ? error : new Error(String(error)), threadId, traceId, sessionId };\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n }\n return generator();\n }\n\n const generationConfig: GenerationConfig = { // Use SDK GenerationConfig type\n temperature: options.temperature,\n maxOutputTokens: options.max_tokens || options.maxOutputTokens, // Allow both snake_case and camelCase\n topP: options.top_p || options.topP,\n topK: options.top_k || options.topK,\n stopSequences: options.stop || options.stop_sequences || options.stopSequences,\n // candidateCount: options.n // Map 'n' if needed\n };\n // Remove undefined generationConfig parameters\n Object.keys(generationConfig).forEach(key =>\n generationConfig[key as keyof GenerationConfig] === undefined &&\n delete generationConfig[key as keyof GenerationConfig]\n );\n // Build optional thinking configuration from CallOptions (feature flag)\n // Expecting shape: options.gemini?.thinking?.{ includeThoughts?: boolean; thinkingBudget?: number }\n const includeThoughts: boolean = !!(options as any)?.gemini?.thinking?.includeThoughts;\n const thinkingBudget: number | undefined = (options as any)?.gemini?.thinking?.thinkingBudget;\n // Merge into a requestConfig that is leniently typed to allow SDK preview fields\n const requestConfig: any = includeThoughts\n ? {\n ...generationConfig,\n thinkingConfig: {\n includeThoughts: true,\n ...(thinkingBudget !== undefined ? { thinkingBudget } : {}),\n },\n }\n : { ...generationConfig };\n // --- End Format Payload ---\n\n Logger.debug(`Calling Gemini SDK with model ${modelToUse}, stream: ${!!stream}`, { threadId, traceId });\n\n // Capture 'this.genAI' for use inside the generator function\n const genAIInstance = this.genAI;\n // Use an async generator function\n const generator = async function* (): AsyncIterable<StreamEvent> {\n const startTime = Date.now(); // Use const\n let timeToFirstTokenMs: number | undefined;\n let streamUsageMetadata: any = undefined; // Variable to hold aggregated usage metadata from stream\n let streamFinishReason: string | undefined; // Will hold finishReason from the LAST chunk\n let lastChunk: GenerateContentResponse | undefined = undefined; // Variable to store the last chunk\n // Removed unused aggregatedResponseText\n\n try {\n // --- Handle Streaming Response using SDK ---\n if (stream) {\n // Let TypeScript infer the type of streamResult\n // Use the new SDK pattern: genAI.models.generateContentStream with retry logic\n const streamResult = await withRetry(\n () => genAIInstance.models.generateContentStream({\n model: modelToUse,\n contents,\n config: requestConfig,\n }),\n {\n onRetry: (error, attempt, delayMs) => {\n Logger.info(`Retrying Gemini stream call (attempt ${attempt})`, { threadId, traceId, delayMs });\n }\n }\n );\n\n // Process the stream by iterating directly over streamResult (based on docs)\n for await (const chunk of streamResult) {\n lastChunk = chunk; // Store the current chunk as the potential last one\n if (!timeToFirstTokenMs) {\n timeToFirstTokenMs = Date.now() - startTime;\n }\n // Prefer structured parts if available to differentiate thinking vs response\n const candidate = (chunk as any)?.candidates?.[0];\n const parts = candidate?.content?.parts;\n if (Array.isArray(parts) && parts.length > 0) {\n for (const part of parts) {\n const partText: string | undefined = (part as any)?.text;\n if (!partText) continue;\n const isThought: boolean = !!(\n (part as any)?.thought ||\n (part as any)?.metadata?.thought ||\n (part as any)?.inlineMetadata?.thought\n );\n const tokenType = callContext === 'AGENT_THOUGHT'\n ? (isThought ? 'AGENT_THOUGHT_LLM_THINKING' : 'AGENT_THOUGHT_LLM_RESPONSE')\n : (isThought ? 'FINAL_SYNTHESIS_LLM_THINKING' : 'FINAL_SYNTHESIS_LLM_RESPONSE');\n yield { type: 'TOKEN', data: partText, threadId, traceId, sessionId, tokenType };\n }\n } else {\n const textPart = (chunk as any).text; // Access as property (fallback)\n if (textPart) {\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n yield { type: 'TOKEN', data: textPart, threadId, traceId, sessionId, tokenType };\n }\n }\n // Log potential usage metadata if available in chunks (less common)\n // Capture usage metadata if present in chunks\n if (chunk.usageMetadata) {\n // Note: Based on testing, usageMetadata usually appears only in the *last* chunk,\n // but we check here just in case the behavior changes or varies.\n Logger.debug(\"Gemini stream chunk usageMetadata:\", { usageMetadata: chunk.usageMetadata, threadId, traceId });\n // Simple merge/overwrite for now, might need more sophisticated aggregation\n streamUsageMetadata = { ...(streamUsageMetadata || {}), ...chunk.usageMetadata };\n }\n }\n\n // NOTE: The new SDK stream example doesn't show accessing a final .response\n // We might need to aggregate metadata from chunks or handle it differently.\n // For now, remove the finalResponse logic and associated metadata yield for streaming.\n // We still need to yield END.\n const totalGenerationTimeMs = Date.now() - startTime; // Keep total time calculation\n Logger.debug(\"Gemini stream finished processing chunks.\", { totalGenerationTimeMs, threadId, traceId });\n\n // TODO: Revisit how to get final metadata (stopReason, token counts) for streams if needed.\n // --- Extract metadata from the LAST chunk AFTER the loop ---\n if (lastChunk) {\n streamFinishReason = lastChunk.candidates?.[0]?.finishReason;\n streamUsageMetadata = lastChunk.usageMetadata; // Get metadata directly from last chunk\n Logger.debug(\"Gemini stream - Extracted from last chunk:\", { finishReason: streamFinishReason, usageMetadata: streamUsageMetadata, threadId, traceId });\n } else {\n Logger.warn(\"Gemini stream - No last chunk found after loop.\", { threadId, traceId });\n }\n // --- End extraction from last chunk ---\n\n // Yield final METADATA using values extracted from the last chunk\n const finalUsage = streamUsageMetadata || {}; // Use extracted metadata or empty object\n const metadata: LLMMetadata = {\n stopReason: streamFinishReason, // Use finishReason from last chunk\n inputTokens: finalUsage?.promptTokenCount,\n outputTokens: finalUsage?.candidatesTokenCount, // Or totalTokenCount? Check SDK details\n thinkingTokens: finalUsage?.thinkingTokenCount ?? finalUsage?.thoughtTokens,\n timeToFirstTokenMs: timeToFirstTokenMs,\n totalGenerationTimeMs: totalGenerationTimeMs,\n providerRawUsage: finalUsage, // Use usage from last chunk\n traceId: traceId,\n };\n yield { type: 'METADATA', data: metadata, threadId, traceId, sessionId };\n\n // --- Handle Non-Streaming Response using SDK ---\n } else {\n // Use the new SDK pattern: genAIInstance.models.generateContent with retry logic\n const result: GenerateContentResponse = await withRetry(\n () => genAIInstance.models.generateContent({\n model: modelToUse,\n contents,\n config: requestConfig,\n }),\n {\n onRetry: (error, attempt, delayMs) => {\n Logger.info(`Retrying Gemini call (attempt ${attempt})`, { threadId, traceId, delayMs });\n }\n }\n );\n // Removed incorrect line: const response = result.response;\n const firstCandidate = result.candidates?.[0]; // Access directly from result\n const responseText = result.text; // Access as a property\n const finishReason = firstCandidate?.finishReason;\n const usageMetadata = result.usageMetadata; // Access directly from result\n const totalGenerationTimeMs = Date.now() - startTime;\n\n\n // If structured parts are present, prefer splitting into thought vs response tokens\n const nonStreamParts = (firstCandidate as any)?.content?.parts;\n if (Array.isArray(nonStreamParts) && nonStreamParts.length > 0) {\n for (const part of nonStreamParts) {\n const partText: string | undefined = (part as any)?.text;\n if (!partText) continue;\n const isThought: boolean = !!(\n (part as any)?.thought ||\n (part as any)?.metadata?.thought ||\n (part as any)?.inlineMetadata?.thought\n );\n const tokenType = callContext === 'AGENT_THOUGHT'\n ? (isThought ? 'AGENT_THOUGHT_LLM_THINKING' : 'AGENT_THOUGHT_LLM_RESPONSE')\n : (isThought ? 'FINAL_SYNTHESIS_LLM_THINKING' : 'FINAL_SYNTHESIS_LLM_RESPONSE');\n yield { type: 'TOKEN', data: partText.trim(), threadId, traceId, sessionId, tokenType };\n }\n } else if (!firstCandidate || !responseText) {\n if (result.promptFeedback?.blockReason) { // Access directly from result\n Logger.error('Gemini SDK call blocked.', { feedback: result.promptFeedback, threadId, traceId });\n yield { type: 'ERROR', data: new Error(`Gemini API call blocked: ${result.promptFeedback.blockReason}`), threadId, traceId, sessionId };\n return;\n }\n Logger.error('Invalid response structure from Gemini SDK: No text content found', { responseData: result, threadId, traceId }); // Log the whole result\n yield { type: 'ERROR', data: new Error('Invalid response structure from Gemini SDK: No text content found.'), threadId, traceId, sessionId };\n return;\n } else {\n // Yield TOKEN (fallback single text)\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'LLM_RESPONSE';\n yield { type: 'TOKEN', data: responseText.trim(), threadId, traceId, sessionId, tokenType };\n }\n\n // Yield METADATA\n const metadata: LLMMetadata = {\n stopReason: finishReason,\n inputTokens: usageMetadata?.promptTokenCount,\n outputTokens: usageMetadata?.candidatesTokenCount,\n thinkingTokens: (usageMetadata as any)?.thinkingTokenCount ?? (usageMetadata as any)?.thoughtTokens,\n totalGenerationTimeMs: totalGenerationTimeMs,\n providerRawUsage: usageMetadata,\n traceId: traceId,\n };\n yield { type: 'METADATA', data: metadata, threadId, traceId, sessionId };\n }\n\n // Yield END signal\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n\n } catch (error: any) {\n Logger.error(`Error during Gemini SDK call: ${error.message}`, { error, threadId, traceId });\n yield { type: 'ERROR', data: error instanceof Error ? error : new Error(String(error)), threadId, traceId, sessionId };\n // Ensure END is yielded even after an error\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n }\n };\n\n return generator();\n }\n\n /**\n * Translates the provider-agnostic `ArtStandardPrompt` into the Gemini API's `Content[]` format.\n *\n * Key translations:\n * - `system` role: Merged into the first `user` message.\n * - `user` role: Maps to Gemini's `user` role.\n * - `assistant` role: Maps to Gemini's `model` role. Handles text content and `tool_calls` (mapped to `functionCall`).\n * - `tool_result` role: Maps to Gemini's `user` role with a `functionResponse` part.\n * - `tool_request` role: Skipped (implicitly handled by `assistant`'s `tool_calls`).\n *\n * Adds validation to ensure the conversation doesn't start with a 'model' role.\n *\n * @private\n * @param {ArtStandardPrompt} artPrompt - The input `ArtStandardPrompt` array.\n * @returns {Content[]} The `Content[]` array formatted for the Gemini API.\n * @throws {ARTError} If translation encounters an issue, such as a `tool_result` missing required fields (ErrorCode.PROMPT_TRANSLATION_FAILED).\n * @see https://ai.google.dev/api/rest/v1beta/Content\n */\n private translateToGemini(artPrompt: ArtStandardPrompt): Content[] {\n const geminiContents: Content[] = [];\n\n // System prompt handling: Gemini prefers system instructions via specific parameters or\n // potentially as the first part of the first 'user' message. For simplicity,\n // we'll merge the system prompt content into the first user message if present.\n let systemPromptContent: string | null = null;\n\n for (const message of artPrompt) {\n let role: 'user' | 'model';\n const parts: Part[] = [];\n\n switch (message.role) {\n case 'system':\n // Store system prompt content to potentially merge later.\n if (typeof message.content === 'string') {\n systemPromptContent = message.content;\n } else {\n Logger.warn(`GeminiAdapter: Ignoring non-string system prompt content.`, { content: message.content });\n }\n continue; // Don't add a separate 'system' role message\n\n case 'user': { // Added braces to fix ESLint error\n role = 'user';\n let userContent = '';\n // Prepend system prompt if this is the first user message\n if (systemPromptContent) {\n userContent += systemPromptContent + \"\\n\\n\";\n systemPromptContent = null; // Clear after merging\n }\n if (typeof message.content === 'string') {\n userContent += message.content;\n } else {\n Logger.warn(`GeminiAdapter: Stringifying non-string user content.`, { content: message.content });\n userContent += JSON.stringify(message.content);\n }\n parts.push({ text: userContent });\n break;\n } // Added braces\n\n case 'assistant':\n role = 'model';\n // Handle text content\n if (typeof message.content === 'string' && message.content.trim() !== '') {\n parts.push({ text: message.content });\n }\n // Handle tool calls (function calls in Gemini)\n if (message.tool_calls && message.tool_calls.length > 0) {\n message.tool_calls.forEach(toolCall => {\n if (toolCall.type === 'function') {\n parts.push({\n functionCall: {\n name: toolCall.function.name,\n args: JSON.parse(toolCall.function.arguments || '{}'), // Gemini expects parsed args object\n }\n });\n } else {\n Logger.warn(`GeminiAdapter: Skipping unsupported tool call type: ${toolCall.type}`);\n }\n });\n }\n // If assistant message has neither content nor tool calls, add empty text part? Gemini might require it.\n if (parts.length === 0) {\n parts.push({ text: \"\" }); // Add empty text part if no content or tool calls\n }\n break;\n\n case 'tool_result':\n role = 'user'; // Gemini expects tool results within a 'user' role message\n if (!message.tool_call_id || !message.name) {\n throw new ARTError(\n `GeminiAdapter: 'tool_result' message missing required 'tool_call_id' or 'name'.`,\n ErrorCode.PROMPT_TRANSLATION_FAILED\n );\n }\n parts.push({\n functionResponse: {\n name: message.name, // Tool name\n response: {\n // Gemini expects the result content under a 'content' key within 'response'\n // The content should be the stringified output/error from ArtStandardMessage.content\n content: message.content // Assuming content is already stringified result/error\n }\n }\n });\n break;\n\n case 'tool_request':\n // This role is implicitly handled by 'tool_calls' in the preceding 'assistant' message.\n Logger.debug(`GeminiAdapter: Skipping 'tool_request' role message as it's handled by assistant's tool_calls.`);\n continue; // Skip this message\n\n default:\n Logger.warn(`GeminiAdapter: Skipping message with unhandled role: ${message.role}`);\n continue;\n }\n\n geminiContents.push({ role, parts });\n }\n\n // Handle case where system prompt was provided but no user message followed\n if (systemPromptContent) {\n Logger.warn(\"GeminiAdapter: System prompt provided but no user message found to merge it into. Adding as a separate initial user message.\");\n geminiContents.unshift({ role: 'user', parts: [{ text: systemPromptContent }] });\n }\n\n // Gemini specific validation: Ensure conversation doesn't start with 'model'\n if (geminiContents.length > 0 && geminiContents[0].role === 'model') {\n Logger.warn(\"Gemini conversation history starts with 'model' role. Prepending a dummy 'user' turn.\", { firstRole: geminiContents[0].role });\n geminiContents.unshift({ role: 'user', parts: [{ text: \"(Initial context)\" }] }); // Prepend a generic user turn\n }\n\n return geminiContents;\n }\n}","// src/integrations/reasoning/openai.ts\nimport OpenAI from 'openai';\nimport { ProviderAdapter, ToolSchema } from '@/core/interfaces';\nimport {\n ArtStandardPrompt,\n ArtStandardMessage,\n CallOptions,\n StreamEvent,\n LLMMetadata,\n} from '@/types';\nimport { Logger } from '@/utils/logger';\nimport { ARTError, ErrorCode } from '@/errors';\n\n// Default model configuration\nconst OPENAI_DEFAULT_MODEL_ID = 'gpt-4o';\nconst OPENAI_DEFAULT_MAX_TOKENS = 4096;\nconst OPENAI_DEFAULT_TEMPERATURE = 0.7;\n\n/**\n * Configuration options required for the `OpenAIAdapter`.\n */\nexport interface OpenAIAdapterOptions {\n /** Your OpenAI API key. Handle securely. */\n apiKey: string;\n /** The default OpenAI model ID to use (e.g., 'gpt-4o', 'gpt-5', 'gpt-5-mini'). */\n model?: string;\n /** Optional: Override the base URL for the OpenAI API (e.g., for Azure OpenAI or custom proxies). */\n apiBaseUrl?: string;\n /** Optional: Default maximum tokens for responses. */\n defaultMaxTokens?: number;\n /** Optional: Default temperature for responses. */\n defaultTemperature?: number;\n}\n\n// Types for OpenAI Responses API\ninterface OpenAIResponsesInputMessage {\n role: 'user' | 'assistant';\n content: Array<{\n type: 'input_text' | 'output_text' | 'input_image';\n text?: string;\n image_url?: string;\n }>;\n}\n\ninterface OpenAIResponsesPayload {\n model: string;\n input: OpenAIResponsesInputMessage[];\n instructions?: string; // System prompt goes here\n temperature?: number;\n max_output_tokens?: number;\n stream?: boolean;\n store?: boolean;\n reasoning?: {\n effort?: 'low' | 'medium' | 'high';\n summary?: 'auto' | 'concise' | 'detailed';\n };\n tools?: OpenAIResponsesTool[];\n}\n\ninterface OpenAIResponsesTool {\n type: 'function';\n function: {\n name: string;\n description: string;\n parameters: object; // JSON Schema\n };\n}\n\ninterface OpenAIResponsesUsage {\n input_tokens?: number;\n output_tokens?: number;\n output_tokens_details?: {\n reasoning_tokens?: number;\n };\n total_tokens?: number;\n}\n\ninterface OpenAIResponsesResponse {\n id: string;\n object: string;\n created: number;\n model: string;\n output?: Array<{\n type: 'message' | 'reasoning';\n id?: string;\n content?: Array<{\n type: 'output_text';\n text: string;\n }>;\n summary?: Array<{\n type: 'summary_text';\n text: string;\n }>;\n }>;\n status: 'completed' | 'incomplete' | 'failed';\n usage?: OpenAIResponsesUsage;\n}\n\n/**\n * Implements the `ProviderAdapter` interface for interacting with OpenAI's\n * Responses API (supports reasoning models like GPT-5 family and other models).\n *\n * Handles formatting requests, parsing responses, streaming, reasoning token detection, and tool use.\n * Uses the official OpenAI SDK with the new Responses API for full reasoning model support.\n *\n * @see {@link ProviderAdapter} for the interface definition.\n * @see {@link OpenAIAdapterOptions} for configuration options.\n */\nexport class OpenAIAdapter implements ProviderAdapter {\n readonly providerName = 'openai';\n private client: OpenAI;\n private defaultModel: string;\n private defaultMaxTokens: number;\n private defaultTemperature: number;\n\n /**\n * Creates an instance of the OpenAIAdapter.\n * @param options - Configuration options including the API key and optional model/baseURL/defaults.\n * @throws {ARTError} If the API key is missing.\n */\n constructor(options: OpenAIAdapterOptions) {\n if (!options.apiKey) {\n throw new ARTError('OpenAIAdapter requires an apiKey in options.', ErrorCode.INVALID_CONFIG);\n }\n\n this.client = new OpenAI({\n apiKey: options.apiKey,\n baseURL: options.apiBaseUrl || undefined,\n });\n\n this.defaultModel = options.model || OPENAI_DEFAULT_MODEL_ID;\n this.defaultMaxTokens = options.defaultMaxTokens || OPENAI_DEFAULT_MAX_TOKENS;\n this.defaultTemperature = options.defaultTemperature || OPENAI_DEFAULT_TEMPERATURE;\n\n Logger.debug(`OpenAIAdapter initialized with model: ${this.defaultModel}`);\n }\n\n /**\n * Sends a request to the OpenAI Responses API.\n * Translates `ArtStandardPrompt` to the Responses API format and handles streaming/reasoning.\n *\n * @param {ArtStandardPrompt} prompt - The standardized prompt messages.\n * @param {CallOptions} options - Call options, including streaming, reasoning options, and model parameters.\n * @returns {Promise<AsyncIterable<StreamEvent>>} A promise resolving to an AsyncIterable of StreamEvent objects.\n */\n async call(prompt: ArtStandardPrompt, options: CallOptions): Promise<AsyncIterable<StreamEvent>> {\n const {\n threadId,\n traceId = `openai-trace-${Date.now()}`,\n sessionId,\n stream = false,\n callContext,\n model: modelOverride,\n tools: availableArtTools,\n providerConfig,\n } = options;\n\n const modelToUse = providerConfig?.modelId || modelOverride || this.defaultModel;\n\n // Extract OpenAI specific parameters\n const openaiApiParams = providerConfig?.adapterOptions || {};\n const maxTokens = openaiApiParams.max_tokens || openaiApiParams.maxTokens || options.max_tokens || options.maxOutputTokens || this.defaultMaxTokens;\n const temperature = openaiApiParams.temperature ?? options.temperature ?? this.defaultTemperature;\n \n // Extract reasoning configuration from options\n const openaiOptions = (options as any).openai || {};\n const reasoningEffort = openaiOptions.reasoning?.effort || 'medium';\n const reasoningSummary = openaiOptions.reasoning?.summary || 'auto';\n\n let systemPrompt: string | undefined;\n let responsesInput: OpenAIResponsesInputMessage[];\n try {\n const translationResult = this.translateToResponsesFormat(prompt);\n systemPrompt = translationResult.systemPrompt;\n responsesInput = translationResult.input;\n } catch (error: any) {\n Logger.error(`Error translating ArtStandardPrompt to OpenAI Responses format: ${error.message}`, { error, threadId, traceId });\n const artError = error instanceof ARTError ? error : new ARTError(`Prompt translation failed: ${error.message}`, ErrorCode.PROMPT_TRANSLATION_FAILED, error);\n const errorGenerator = async function* (): AsyncIterable<StreamEvent> {\n yield { type: 'ERROR', data: artError, threadId, traceId, sessionId };\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n };\n return errorGenerator();\n }\n\n const openaiTools: OpenAIResponsesTool[] | undefined = availableArtTools\n ? this.translateArtToolsToOpenAI(availableArtTools)\n : undefined;\n\n const requestBody: OpenAIResponsesPayload = {\n model: modelToUse,\n input: responsesInput,\n instructions: systemPrompt,\n temperature: temperature,\n max_output_tokens: maxTokens,\n stream: stream,\n store: true, // Enable conversation continuity\n reasoning: {\n effort: reasoningEffort,\n summary: reasoningSummary,\n },\n tools: openaiTools,\n };\n\n // Remove undefined keys from the request body\n Object.keys(requestBody).forEach(key => {\n const K = key as keyof OpenAIResponsesPayload;\n if (requestBody[K] === undefined) {\n delete requestBody[K];\n }\n });\n\n Logger.debug(`Calling OpenAI Responses API with model ${modelToUse}`, { stream, tools: !!openaiTools, threadId, traceId });\n\n // Use an async generator function\n const generator = async function* (this: OpenAIAdapter): AsyncIterable<StreamEvent> {\n try {\n const startTime = Date.now();\n let timeToFirstTokenMs: number | undefined;\n \n if (stream) {\n // Use the OpenAI SDK's responses.create method for streaming\n const streamInstance = await (this.client as any).responses.create({\n ...requestBody,\n stream: true,\n });\n\n let accumulatedText = \"\";\n let accumulatedReasoning = \"\";\n let finalStopReason: string | undefined;\n let finalUsage: OpenAIResponsesUsage | undefined;\n let accumulatedToolCalls: any[] = [];\n\n // Process the stream\n for await (const event of streamInstance) {\n if (timeToFirstTokenMs === undefined) {\n timeToFirstTokenMs = Date.now() - startTime;\n }\n\n // Handle reasoning deltas\n if (event.type === 'response.reasoning.delta' || event.type === 'response.reasoning_text.delta') {\n if (event.delta) {\n accumulatedReasoning += event.delta;\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_THINKING' : 'FINAL_SYNTHESIS_LLM_THINKING';\n yield { type: 'TOKEN', data: event.delta, threadId, traceId, sessionId, tokenType };\n }\n }\n // Handle reasoning summary deltas\n else if (event.type === 'response.reasoning_summary.delta' || event.type === 'response.reasoning_summary_text.delta') {\n if (event.delta) {\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_THINKING' : 'FINAL_SYNTHESIS_LLM_THINKING';\n yield { type: 'TOKEN', data: event.delta, threadId, traceId, sessionId, tokenType };\n }\n }\n // Handle text/output deltas\n else if (event.type === 'response.text.delta' || event.type === 'response.output_text.delta') {\n if (event.delta) {\n accumulatedText += event.delta;\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n yield { type: 'TOKEN', data: event.delta, threadId, traceId, sessionId, tokenType };\n }\n }\n // Handle output item additions (alternative format for complete items)\n else if (event.type === 'response.output_item.added') {\n if (event.item) {\n if (event.item.type === 'text' && event.item.text) {\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n yield { type: 'TOKEN', data: event.item.text, threadId, traceId, sessionId, tokenType };\n } else if (event.item.type === 'reasoning' && event.item.text) {\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_THINKING' : 'FINAL_SYNTHESIS_LLM_THINKING';\n yield { type: 'TOKEN', data: event.item.text, threadId, traceId, sessionId, tokenType };\n } else if (event.item.type === 'message' && event.item.content) {\n for (const content of event.item.content) {\n if (content.type === 'output_text' && content.text) {\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n yield { type: 'TOKEN', data: content.text, threadId, traceId, sessionId, tokenType };\n }\n }\n }\n }\n }\n // Handle completion events with usage data\n else if (event.type === 'response.done' || event.type === 'response.completed') {\n if (event.response?.usage) {\n finalUsage = event.response.usage;\n }\n if (event.response?.status) {\n // Map status to finish reason\n finalStopReason = event.response.status === 'completed' ? 'stop' : event.response.status;\n }\n }\n // Handle error events\n else if (event.type === 'response.error' || event.type === 'error') {\n const errorMessage = event.error?.message || event.message || 'Unknown OpenAI Responses API error';\n throw new ARTError(`OpenAI Responses API Error: ${errorMessage}`, ErrorCode.LLM_PROVIDER_ERROR, new Error(errorMessage));\n }\n }\n\n // Yield final metadata for streaming\n const totalGenerationTimeMs = Date.now() - startTime;\n const metadata: LLMMetadata = {\n inputTokens: finalUsage?.input_tokens,\n outputTokens: finalUsage?.output_tokens,\n thinkingTokens: finalUsage?.output_tokens_details?.reasoning_tokens,\n stopReason: finalStopReason,\n timeToFirstTokenMs,\n totalGenerationTimeMs,\n providerRawUsage: finalUsage,\n traceId: traceId,\n };\n yield { type: 'METADATA', data: metadata, threadId, traceId, sessionId };\n\n } else {\n // Non-streaming response using the Responses API\n const response = await (this.client as any).responses.create({\n ...requestBody,\n stream: false,\n }) as OpenAIResponsesResponse;\n\n Logger.debug(`OpenAI Responses API call successful (non-streaming). Status: ${response.status}`, { threadId, traceId });\n\n let responseText = \"\";\n let reasoningText = \"\";\n const toolUseBlocks: any[] = [];\n\n // Extract content from response\n if (response.output && Array.isArray(response.output)) {\n for (const outputItem of response.output) {\n if (outputItem.type === 'message' && outputItem.content) {\n for (const content of outputItem.content) {\n if (content.type === 'output_text') {\n responseText += content.text;\n }\n }\n } else if (outputItem.type === 'reasoning' && outputItem.summary) {\n for (const summary of outputItem.summary) {\n if (summary.type === 'summary_text') {\n reasoningText += summary.text;\n }\n }\n }\n }\n }\n\n // Yield reasoning tokens first if available\n if (reasoningText.trim()) {\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_THINKING' : 'FINAL_SYNTHESIS_LLM_THINKING';\n yield { type: 'TOKEN', data: reasoningText.trim(), threadId, traceId, sessionId, tokenType };\n }\n\n // Then yield response tokens\n if (responseText.trim()) {\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n yield { type: 'TOKEN', data: responseText.trim(), threadId, traceId, sessionId, tokenType };\n }\n\n // Handle tool calls if present\n if (toolUseBlocks.length > 0) {\n const toolData = toolUseBlocks.map(tu => ({\n type: 'tool_use',\n id: tu.id,\n name: tu.name,\n input: tu.input,\n }));\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n yield { type: 'TOKEN', data: toolData, threadId, traceId, sessionId, tokenType };\n }\n\n // Yield metadata for non-streaming\n if (response.usage) {\n const totalGenerationTimeMs = Date.now() - startTime;\n const metadata: LLMMetadata = {\n inputTokens: response.usage.input_tokens,\n outputTokens: response.usage.output_tokens,\n thinkingTokens: response.usage.output_tokens_details?.reasoning_tokens,\n stopReason: response.status === 'completed' ? 'stop' : response.status,\n totalGenerationTimeMs,\n providerRawUsage: { usage: response.usage, status: response.status },\n traceId: traceId,\n };\n yield { type: 'METADATA', data: metadata, threadId, traceId, sessionId };\n }\n }\n\n // Yield END signal for both streaming and non-streaming\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n\n } catch (error: any) {\n Logger.error(`Error during OpenAI Responses API call: ${error.message}`, { error, threadId, traceId });\n const artError = error instanceof ARTError ? error :\n (error instanceof Error && error.message.includes('OpenAI') ? \n new ARTError(`OpenAI API Error: ${error.message}`, ErrorCode.LLM_PROVIDER_ERROR, error) :\n new ARTError(error.message || 'Unknown OpenAI adapter error', ErrorCode.LLM_PROVIDER_ERROR, error));\n yield { type: 'ERROR', data: artError, threadId, traceId, sessionId };\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n }\n }.bind(this);\n\n return generator();\n }\n\n /**\n * Optional: Method for graceful shutdown\n */\n async shutdown(): Promise<void> {\n Logger.debug(`OpenAIAdapter shutdown called.`);\n // Clean up any resources if needed\n }\n\n /**\n * Translates the provider-agnostic `ArtStandardPrompt` into the OpenAI Responses API format.\n * Extracts system prompt separately and formats messages as input array.\n *\n * @private\n * @param {ArtStandardPrompt} artPrompt - The input `ArtStandardPrompt` array.\n * @returns {{ systemPrompt?: string; input: OpenAIResponsesInputMessage[] }} An object containing the extracted system prompt and the array of Responses API formatted input messages.\n * @throws {ARTError} If translation encounters an issue.\n */\n private translateToResponsesFormat(artPrompt: ArtStandardPrompt): { systemPrompt?: string; input: OpenAIResponsesInputMessage[] } {\n let systemPrompt: string | undefined;\n const input: OpenAIResponsesInputMessage[] = [];\n\n for (const artMsg of artPrompt) {\n if (artMsg.role === 'system') {\n const systemText = (typeof artMsg.content === 'string') ? artMsg.content : String(artMsg.content);\n if (!systemPrompt) {\n systemPrompt = systemText;\n } else {\n Logger.warn(`OpenAIAdapter: Multiple system messages found. Appending to existing system prompt.`);\n systemPrompt += `\\n${systemText}`;\n }\n continue;\n }\n\n const translatedContent = this.mapArtMessageToResponsesContent(artMsg);\n if (translatedContent) {\n input.push(translatedContent);\n }\n }\n\n return { systemPrompt, input };\n }\n\n /**\n * Maps a single `ArtStandardMessage` to OpenAI Responses API input format.\n *\n * @private\n * @param {ArtStandardMessage} artMsg - The ART standard message to map.\n * @returns {OpenAIResponsesInputMessage | null} The translated message for the Responses API, or null if should be skipped.\n * @throws {ARTError} If tool call arguments are not valid JSON.\n */\n private mapArtMessageToResponsesContent(artMsg: ArtStandardMessage): OpenAIResponsesInputMessage | null {\n switch (artMsg.role) {\n case 'user':\n case 'tool_result': {\n // Both user and tool_result messages become 'user' role in Responses API\n const content: Array<{ type: 'input_text'; text: string }> = [];\n \n if (artMsg.role === 'tool_result') {\n // Format tool result with context\n const toolResultText = `Tool result for ${artMsg.name || 'unknown tool'}: ${String(artMsg.content)}`;\n content.push({ type: 'input_text', text: toolResultText });\n } else {\n // Regular user message\n const userText = typeof artMsg.content === 'string' ? artMsg.content : String(artMsg.content);\n content.push({ type: 'input_text', text: userText });\n }\n\n return { role: 'user', content };\n }\n\n case 'assistant': {\n const content: Array<{ type: 'output_text'; text: string }> = [];\n \n // Handle text content\n if (typeof artMsg.content === 'string' && artMsg.content.trim() !== '') {\n content.push({ type: 'output_text', text: artMsg.content });\n }\n\n // Handle tool calls - convert to text description for Responses API\n if (artMsg.tool_calls && artMsg.tool_calls.length > 0) {\n const toolCallsText = artMsg.tool_calls.map(tc => {\n try {\n const args = JSON.parse(tc.function.arguments || '{}');\n return `Called tool ${tc.function.name} with arguments: ${JSON.stringify(args)}`;\n } catch (e: any) {\n throw new ARTError(\n `OpenAIAdapter: Failed to parse tool call arguments for tool ${tc.function.name} (ID: ${tc.id}). Arguments must be valid JSON. Error: ${e.message}`,\n ErrorCode.PROMPT_TRANSLATION_FAILED, e\n );\n }\n }).join('\\n');\n \n if (content.length > 0) {\n content[0].text += '\\n\\n' + toolCallsText;\n } else {\n content.push({ type: 'output_text', text: toolCallsText });\n }\n }\n\n // If no content at all, add empty text\n if (content.length === 0) {\n content.push({ type: 'output_text', text: '' });\n }\n\n return { role: 'assistant', content };\n }\n\n case 'tool_request': {\n // Skip tool_request messages - they're handled by assistant's tool_calls\n Logger.debug(`OpenAIAdapter: Skipping 'tool_request' role message as it's handled by assistant's tool_calls.`);\n return null;\n }\n\n default: {\n Logger.warn(`OpenAIAdapter: Skipping message with unhandled role: ${artMsg.role}`);\n return null;\n }\n }\n }\n\n /**\n * Translates an array of `ToolSchema` from the ART framework format to OpenAI's Responses API tool format.\n * @private\n * @param {ToolSchema[]} artTools - An array of ART tool schemas.\n * @returns {OpenAIResponsesTool[]} An array of tools formatted for the OpenAI Responses API.\n * @throws {ARTError} If a tool's `inputSchema` is invalid.\n */\n private translateArtToolsToOpenAI(artTools: ToolSchema[]): OpenAIResponsesTool[] {\n return artTools.map(artTool => {\n if (!artTool.inputSchema || typeof artTool.inputSchema !== 'object') {\n throw new ARTError(`Invalid inputSchema definition for tool '${artTool.name}'. Expected a JSON schema object.`, ErrorCode.INVALID_CONFIG);\n }\n return {\n type: 'function',\n function: {\n name: artTool.name,\n description: artTool.description,\n parameters: artTool.inputSchema,\n },\n };\n });\n }\n}","// src/adapters/reasoning/anthropic.ts\nimport { Anthropic } from '@anthropic-ai/sdk';\nimport { ProviderAdapter, ToolSchema } from '@/core/interfaces';\nimport {\n ArtStandardPrompt,\n ArtStandardMessage,\n CallOptions,\n StreamEvent,\n LLMMetadata,\n} from '@/types';\nimport { Logger } from '@/utils/logger';\nimport { ARTError, ErrorCode } from '@/errors';\n\n// Default model if not specified\nconst ANTHROPIC_DEFAULT_MODEL_ID = 'claude-3-7-sonnet-20250219';\nconst ANTHROPIC_DEFAULT_MAX_TOKENS = 4096;\n\n/**\n * Configuration options required for the `AnthropicAdapter`.\n */\nexport interface AnthropicAdapterOptions {\n /** Your Anthropic API key. Handle securely. */\n apiKey: string;\n /** The default Anthropic model ID to use (e.g., 'claude-3-opus-20240229', 'claude-3-5-sonnet-20240620'). */\n model?: string;\n /** Optional: Override the base URL for the Anthropic API. */\n apiBaseUrl?: string;\n /** Optional: Default maximum tokens for responses. */\n defaultMaxTokens?: number;\n /** Optional: Default temperature for responses. */\n defaultTemperature?: number;\n}\n\n// Types for Anthropic API interaction using the SDK\ntype AnthropicSDKMessageParam = Anthropic.Messages.MessageParam;\ntype AnthropicSDKContentBlockParam = Anthropic.Messages.TextBlockParam | Anthropic.Messages.ImageBlockParam | Anthropic.Messages.ToolUseBlockParam | Anthropic.Messages.ToolResultBlockParam;\ntype AnthropicSDKTool = Anthropic.Tool;\ntype AnthropicSDKToolUseBlock = Anthropic.ToolUseBlock;\n\n/**\n * Implements the `ProviderAdapter` interface for interacting with Anthropic's\n * Messages API (Claude models) using the official SDK.\n *\n * Handles formatting requests, parsing responses, streaming, and tool use.\n *\n * @see {@link ProviderAdapter} for the interface definition.\n * @see {@link AnthropicAdapterOptions} for configuration options.\n */\nexport class AnthropicAdapter implements ProviderAdapter {\n readonly providerName = 'anthropic';\n private client: Anthropic;\n private defaultModel: string;\n private defaultMaxTokens: number;\n private defaultTemperature?: number;\n\n /**\n * Creates an instance of the AnthropicAdapter.\n * @param options - Configuration options including the API key and optional model/baseURL/defaults.\n * @throws {ARTError} If the API key is missing.\n */\n constructor(options: AnthropicAdapterOptions) {\n if (!options.apiKey) {\n throw new ARTError('AnthropicAdapter requires an apiKey in options.', ErrorCode.INVALID_CONFIG);\n }\n\n this.client = new Anthropic({\n apiKey: options.apiKey,\n baseURL: options.apiBaseUrl || undefined,\n });\n\n this.defaultModel = options.model || ANTHROPIC_DEFAULT_MODEL_ID;\n this.defaultMaxTokens = options.defaultMaxTokens || ANTHROPIC_DEFAULT_MAX_TOKENS;\n this.defaultTemperature = options.defaultTemperature;\n\n Logger.debug(`AnthropicAdapter initialized with model: ${this.defaultModel}`);\n }\n\n /**\n * Sends a request to the Anthropic Messages API.\n * Translates `ArtStandardPrompt` to the Anthropic format and handles streaming and tool use.\n *\n * @param {ArtStandardPrompt} prompt - The standardized prompt messages.\n * @param {CallOptions} options - Call options, including `threadId`, `traceId`, `stream`, `callContext`,\n * `model` (override), `tools` (available tools), and Anthropic-specific\n * generation parameters from `providerConfig.adapterOptions`.\n * @returns {Promise<AsyncIterable<StreamEvent>>} A promise resolving to an AsyncIterable of StreamEvent objects.\n */\n async call(prompt: ArtStandardPrompt, options: CallOptions): Promise<AsyncIterable<StreamEvent>> {\n const {\n threadId,\n traceId = `anthropic-trace-${Date.now()}`,\n sessionId,\n stream = false,\n callContext,\n model: modelOverride,\n tools: availableArtTools,\n providerConfig,\n } = options;\n\n const modelToUse = providerConfig?.modelId || modelOverride || this.defaultModel;\n\n // Extract Anthropic specific parameters from providerConfig.adapterOptions or options\n const anthropicApiParams = providerConfig?.adapterOptions || {};\n const maxTokens = anthropicApiParams.max_tokens || anthropicApiParams.maxTokens || options.max_tokens || options.maxOutputTokens || this.defaultMaxTokens;\n const temperature = anthropicApiParams.temperature ?? options.temperature ?? this.defaultTemperature;\n const topP = anthropicApiParams.top_p || anthropicApiParams.topP || options.top_p || options.topP;\n const topK = anthropicApiParams.top_k || anthropicApiParams.topK || options.top_k || options.topK;\n const stopSequences = anthropicApiParams.stop_sequences || anthropicApiParams.stopSequences || options.stop || options.stop_sequences || options.stopSequences;\n // Anthropic thinking config for Claude 3.7 Sonnet (reasoning): { type: 'enabled', budget_tokens?: number }\n const thinking = anthropicApiParams.thinking || options.thinking;\n\n if (!maxTokens) {\n const err = new ARTError(\"Anthropic API requires 'max_tokens'.\", ErrorCode.INVALID_CONFIG);\n const errorGenerator = async function* (): AsyncIterable<StreamEvent> {\n yield { type: 'ERROR', data: err, threadId, traceId, sessionId };\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n };\n return errorGenerator();\n }\n\n let systemPrompt: string | undefined;\n let anthropicMessages: AnthropicSDKMessageParam[];\n try {\n const translationResult = this.translateToAnthropicSdk(prompt);\n systemPrompt = translationResult.systemPrompt;\n anthropicMessages = translationResult.messages;\n } catch (error: any) {\n Logger.error(`Error translating ArtStandardPrompt to Anthropic SDK format: ${error.message}`, { error, threadId, traceId });\n const artError = error instanceof ARTError ? error : new ARTError(`Prompt translation failed: ${error.message}`, ErrorCode.PROMPT_TRANSLATION_FAILED, error);\n const errorGenerator = async function* (): AsyncIterable<StreamEvent> {\n yield { type: 'ERROR', data: artError, threadId, traceId, sessionId };\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n };\n return errorGenerator();\n }\n\n const anthropicTools: AnthropicSDKTool[] | undefined = availableArtTools\n ? this.translateArtToolsToAnthropic(availableArtTools)\n : undefined;\n\n const requestBody: Anthropic.Messages.MessageCreateParams = {\n model: modelToUse,\n messages: anthropicMessages,\n max_tokens: maxTokens,\n system: systemPrompt,\n temperature: temperature,\n top_p: topP,\n top_k: topK,\n stop_sequences: stopSequences,\n // pass-through optional provider features\n thinking: thinking as any,\n stream: stream,\n tools: anthropicTools,\n };\n\n // Remove undefined keys from the request body\n Object.keys(requestBody).forEach(key => {\n const K = key as keyof Anthropic.Messages.MessageCreateParams;\n if (requestBody[K] === undefined) {\n delete requestBody[K];\n }\n });\n\n Logger.debug(`Calling Anthropic API with model ${modelToUse}`, { stream, tools: !!anthropicTools, threadId, traceId });\n\n // Use an async generator function\n const generator = async function* (this: AnthropicAdapter): AsyncIterable<StreamEvent> {\n try {\n const startTime = Date.now();\n let timeToFirstTokenMs: number | undefined;\n if (stream) {\n const streamInstance = await this.client.messages.create(\n requestBody as Anthropic.Messages.MessageCreateParamsStreaming,\n this.getRequestOptions(modelToUse)\n );\n\n let accumulatedText = \"\";\n const accumulatedToolUses: Array<{ id: string; name: string; input: any }> = [];\n const toolUseAcc = new Map<number, { id: string; name: string; chunks: string[] }>();\n const thinkingBlockIndexes = new Set<number>();\n let currentInputTokens: number | undefined;\n let currentOutputTokens: number | undefined;\n let finalStopReason: string | null = null;\n const finalUsage: Partial<Anthropic.Messages.Usage> = {\n input_tokens: undefined,\n output_tokens: undefined\n };\n\n let initialMetadata: LLMMetadata | undefined;\n let deltaMetadata: LLMMetadata | undefined;\n\n for await (const event of streamInstance) {\n switch (event.type) {\n case 'message_start':\n Logger.debug('Anthropic stream: message_start', { usage: event.message.usage, threadId, traceId });\n finalUsage.input_tokens = event.message.usage.input_tokens;\n finalUsage.output_tokens = event.message.usage.output_tokens;\n currentInputTokens = finalUsage.input_tokens;\n currentOutputTokens = finalUsage.output_tokens;\n\n initialMetadata = {\n inputTokens: currentInputTokens,\n outputTokens: currentOutputTokens,\n providerRawUsage: { usage: { ...event.message.usage } },\n traceId: traceId,\n };\n yield { type: 'METADATA', data: initialMetadata, threadId, traceId, sessionId };\n break;\n\n case 'content_block_start':\n Logger.debug('Anthropic stream: content_block_start', { index: event.index, block: event.content_block, threadId, traceId });\n // Track thinking blocks for correct token typing\n if ((event as any).content_block?.type === 'thinking') {\n thinkingBlockIndexes.add(event.index);\n const thinkingText = (event.content_block as any).thinking || '';\n if (thinkingText) {\n if (timeToFirstTokenMs === undefined) timeToFirstTokenMs = Date.now() - startTime;\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_THINKING' : 'FINAL_SYNTHESIS_LLM_THINKING';\n yield { type: 'TOKEN', data: thinkingText, threadId, traceId, sessionId, tokenType };\n }\n }\n // Initialize tool_use accumulation for this block index\n if ((event as any).content_block?.type === 'tool_use') {\n const block = event.content_block as Anthropic.ToolUseBlock;\n toolUseAcc.set(event.index, { id: block.id, name: block.name, chunks: [] });\n }\n break;\n\n case 'content_block_delta':\n Logger.debug('Anthropic stream: content_block_delta', { index: event.index, delta: event.delta, threadId, traceId });\n if (event.delta.type === 'text_delta') {\n const textDelta = event.delta.text;\n accumulatedText += textDelta;\n if (timeToFirstTokenMs === undefined) timeToFirstTokenMs = Date.now() - startTime;\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n yield { type: 'TOKEN', data: textDelta, threadId, traceId, sessionId, tokenType };\n } else if ((event.delta as any).type === 'thinking_delta') {\n const thinkingDelta = (event.delta as any).thinking || '';\n if (thinkingDelta) {\n if (timeToFirstTokenMs === undefined) timeToFirstTokenMs = Date.now() - startTime;\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_THINKING' : 'FINAL_SYNTHESIS_LLM_THINKING';\n yield { type: 'TOKEN', data: thinkingDelta, threadId, traceId, sessionId, tokenType };\n }\n } else if ((event.delta as any).type === 'input_json_delta') {\n const entry = toolUseAcc.get(event.index);\n if (entry) {\n const partial = (event.delta as any).partial_json ?? '';\n if (partial) entry.chunks.push(partial);\n }\n }\n break;\n\n case 'content_block_stop':\n Logger.debug('Anthropic stream: content_block_stop', { index: event.index, threadId, traceId });\n // Finalize tool_use input assembly for this block index\n if (toolUseAcc.has(event.index)) {\n const entry = toolUseAcc.get(event.index)!;\n const joined = entry.chunks.join('');\n let parsed: any = {};\n try {\n parsed = joined ? JSON.parse(joined) : {};\n } catch {\n // leave as empty object if parse fails\n }\n accumulatedToolUses.push({ id: entry.id, name: entry.name, input: parsed });\n toolUseAcc.delete(event.index);\n }\n break;\n\n case 'message_delta':\n Logger.debug('Anthropic stream: message_delta', { delta: event.delta, usage: event.usage, threadId, traceId });\n finalStopReason = event.delta.stop_reason ?? finalStopReason;\n if (event.usage.output_tokens !== undefined && event.usage.output_tokens !== null) {\n finalUsage.output_tokens = event.usage.output_tokens;\n }\n currentOutputTokens = finalUsage.output_tokens;\n\n deltaMetadata = {\n inputTokens: currentInputTokens,\n outputTokens: currentOutputTokens,\n stopReason: event.delta.stop_reason ?? undefined,\n providerRawUsage: {\n usage: {\n input_tokens: currentInputTokens,\n output_tokens: event.usage.output_tokens ?? undefined,\n },\n delta: event.delta\n },\n traceId: traceId,\n };\n yield { type: 'METADATA', data: deltaMetadata, threadId, traceId, sessionId };\n break;\n\n case 'message_stop': {\n Logger.debug('Anthropic stream: message_stop. Using accumulated data.', { threadId, traceId });\n // Flush any remaining tool_use blocks (defensive)\n for (const [idx, entry] of toolUseAcc.entries()) {\n const joined = entry.chunks.join('');\n let parsed: any = {};\n try {\n parsed = joined ? JSON.parse(joined) : {};\n } catch (e) {\n Logger.warn('AnthropicAdapter: Failed to parse tool_use input JSON in final flush.', { error: e, threadId, traceId });\n }\n accumulatedToolUses.push({ id: entry.id, name: entry.name, input: parsed });\n toolUseAcc.delete(idx);\n }\n\n if (finalStopReason === 'tool_use' && accumulatedToolUses.length > 0) {\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n const toolData = accumulatedToolUses.map(tu => ({\n type: 'tool_use',\n id: tu.id,\n name: tu.name,\n input: tu.input,\n }));\n if (accumulatedText.trim()) {\n yield { type: 'TOKEN', data: [{ type: 'text', text: accumulatedText.trim() }, ...toolData], threadId, traceId, sessionId, tokenType };\n } else {\n yield { type: 'TOKEN', data: toolData, threadId, traceId, sessionId, tokenType };\n }\n } else if (accumulatedText.trim()) {\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n yield { type: 'TOKEN', data: accumulatedText.trim(), threadId, traceId, sessionId, tokenType };\n }\n\n const totalGenerationTimeMs = Date.now() - startTime;\n const finalMetadataReport: LLMMetadata = {\n inputTokens: finalUsage.input_tokens ?? undefined,\n outputTokens: finalUsage.output_tokens ?? undefined,\n stopReason: finalStopReason ?? undefined,\n timeToFirstTokenMs,\n totalGenerationTimeMs,\n providerRawUsage: {\n usage: {\n input_tokens: finalUsage.input_tokens ?? undefined,\n output_tokens: finalUsage.output_tokens ?? undefined,\n },\n stop_reason: finalStopReason,\n },\n traceId: traceId,\n };\n yield { type: 'METADATA', data: finalMetadataReport, threadId, traceId, sessionId };\n break;\n }\n default: {\n Logger.warn('Anthropic stream: unhandled raw stream event type', { eventType: (event as any).type, event, threadId, traceId });\n break;\n }\n }\n }\n } else {\n const response = await this.client.messages.create(\n requestBody as Anthropic.Messages.MessageCreateParamsNonStreaming,\n this.getRequestOptions(modelToUse)\n );\n\n Logger.debug(`Anthropic API call successful (non-streaming). Stop Reason: ${response.stop_reason}`, { threadId, traceId });\n\n let responseText = \"\";\n const toolUseBlocks: AnthropicSDKToolUseBlock[] = [];\n\n response.content.forEach((block: Anthropic.Messages.ContentBlock) => {\n if (block.type === 'text') {\n responseText += block.text;\n } else if (block.type === 'tool_use') {\n toolUseBlocks.push(block);\n }\n });\n responseText = responseText.trim();\n\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n\n if (response.stop_reason === 'tool_use' && toolUseBlocks.length > 0) {\n const toolData = toolUseBlocks.map(tu => ({\n type: 'tool_use',\n id: tu.id,\n name: tu.name,\n input: tu.input,\n }));\n if (responseText) {\n yield { type: 'TOKEN', data: [{type: 'text', text: responseText}, ...toolData], threadId, traceId, sessionId, tokenType };\n } else {\n yield { type: 'TOKEN', data: toolData, threadId, traceId, sessionId, tokenType };\n }\n } else if (responseText) {\n yield { type: 'TOKEN', data: responseText, threadId, traceId, sessionId, tokenType };\n } else if (response.stop_reason !== 'tool_use') {\n Logger.warn('Anthropic API (non-streaming): Empty response text and not a tool_use stop_reason.', { response, threadId, traceId });\n }\n\n if (response.usage) {\n const metadata: LLMMetadata = {\n inputTokens: response.usage.input_tokens,\n outputTokens: response.usage.output_tokens,\n stopReason: response.stop_reason ?? undefined,\n totalGenerationTimeMs: Date.now() - startTime,\n providerRawUsage: { usage: response.usage, stop_reason: response.stop_reason, stop_sequence: response.stop_sequence },\n traceId: traceId,\n };\n yield { type: 'METADATA', data: metadata, threadId, traceId, sessionId };\n }\n }\n\n // Yield END signal for both streaming and non-streaming\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n\n } catch (error: any) {\n Logger.error(`Error during Anthropic API call: ${error.message}`, { error, threadId, traceId });\n const artError = error instanceof ARTError ? error :\n (error instanceof Anthropic.APIError ? new ARTError(`Anthropic API Error (${error.status}): ${error.message}`, ErrorCode.LLM_PROVIDER_ERROR, error) :\n new ARTError(error.message || 'Unknown Anthropic adapter error', ErrorCode.LLM_PROVIDER_ERROR, error));\n yield { type: 'ERROR', data: artError, threadId, traceId, sessionId };\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n }\n }.bind(this);\n\n return generator();\n }\n\n /**\n * Optional: Method for graceful shutdown\n */\n async shutdown(): Promise<void> {\n Logger.debug(`AnthropicAdapter shutdown called.`);\n // Clean up any resources if needed\n }\n\n /**\n * Prepares request options, adding Anthropic beta headers if applicable for features like prompt caching.\n * @private\n * @param {string} modelId - The model ID being used for the request, to determine which beta features may apply.\n * @returns {Anthropic.RequestOptions} The request options object, potentially with custom headers.\n */\n private getRequestOptions(modelId: string): Anthropic.RequestOptions {\n const betas: string[] = [];\n // Add beta features as needed\n if (modelId.startsWith(\"claude-3-5-sonnet\") || modelId.startsWith(\"claude-3-opus\")) {\n // Example: betas.push(\"prompt-caching-2024-07-31\");\n }\n\n if (betas.length > 0) {\n return { headers: { \"anthropic-beta\": betas.join(\",\") } };\n }\n return {};\n }\n\n /**\n * Translates the provider-agnostic `ArtStandardPrompt` into the Anthropic SDK Messages format.\n * It handles system prompts, message merging for consecutive roles, and validates message structure.\n *\n * @private\n * @param {ArtStandardPrompt} artPrompt - The input `ArtStandardPrompt` array.\n * @returns {{ systemPrompt?: string; messages: Anthropic.Messages.MessageParam[] }} An object containing the extracted system prompt and the array of Anthropic-formatted messages.\n * @throws {ARTError} If translation encounters an issue, such as multiple system messages or invalid message roles.\n */\n private translateToAnthropicSdk(artPrompt: ArtStandardPrompt): { systemPrompt?: string; messages: Anthropic.Messages.MessageParam[] } {\n let systemPrompt: string | undefined;\n const messages: Anthropic.Messages.MessageParam[] = [];\n let currentRoleInternal: 'user' | 'assistant' | null = null;\n\n for (const artMsg of artPrompt) {\n if (artMsg.role === 'system') {\n const systemText = (typeof artMsg.content === 'string') ? artMsg.content : String(artMsg.content);\n if (!systemPrompt) {\n systemPrompt = systemText;\n } else {\n Logger.warn(`AnthropicAdapter: Multiple system messages found. Appending to existing system prompt.`);\n systemPrompt += `\\n${systemText}`;\n }\n continue;\n }\n\n const translatedContent = this.mapArtMessageToAnthropicContent(artMsg);\n const messageRoleToPush: 'user' | 'assistant' = (artMsg.role === 'user' || artMsg.role === 'tool_result') ? 'user' : 'assistant';\n\n if (currentRoleInternal === messageRoleToPush && messages.length > 0) {\n const lastMessage = messages[messages.length - 1];\n \n let currentLastMessageContentArray: Anthropic.Messages.ContentBlockParam[];\n if (typeof lastMessage.content === 'string') {\n currentLastMessageContentArray = [{ type: 'text', text: lastMessage.content } as Anthropic.Messages.TextBlockParam];\n } else {\n currentLastMessageContentArray = lastMessage.content;\n }\n\n const contentToMergeArray: Anthropic.Messages.ContentBlockParam[] =\n typeof translatedContent === 'string'\n ? [{ type: 'text', text: translatedContent } as Anthropic.Messages.TextBlockParam]\n : translatedContent;\n\n const mergedContent: Anthropic.Messages.ContentBlockParam[] = [...currentLastMessageContentArray, ...contentToMergeArray];\n lastMessage.content = mergedContent;\n Logger.debug(`AnthropicAdapter: Merged consecutive ${messageRoleToPush} messages.`);\n } else {\n messages.push({ role: messageRoleToPush, content: translatedContent });\n currentRoleInternal = messageRoleToPush;\n }\n }\n\n // Anthropic requires the first message to be 'user' if messages exist and no system prompt.\n if (!systemPrompt && messages.length > 0 && messages[0].role !== 'user') {\n Logger.warn(\"AnthropicAdapter: Prompt does not start with user message and has no system prompt. Prepending an empty user message for compatibility.\");\n messages.unshift({ role: 'user', content: '(Previous turn context)'});\n }\n \n // Ensure conversation doesn't end on an assistant message if expecting tool results\n const lastArtMsg = artPrompt[artPrompt.length -1];\n if (lastArtMsg?.role === 'assistant' && lastArtMsg.tool_calls && lastArtMsg.tool_calls.length > 0) {\n Logger.debug(\"AnthropicAdapter: Prompt ends with assistant requesting tool calls.\");\n }\n\n return { systemPrompt, messages };\n }\n\n /**\n * Maps a single `ArtStandardMessage` to Anthropic SDK's content format.\n * This can be a simple string or an array of `ContentBlockParam` for complex content\n * like tool calls and tool results.\n *\n * @private\n * @param {ArtStandardMessage} artMsg - The ART standard message to map.\n * @returns {string | AnthropicSDKContentBlockParam[]} The translated content for the Anthropic API.\n * @throws {ARTError} If tool call arguments are not valid JSON or if a tool result is missing its ID.\n */\n private mapArtMessageToAnthropicContent(artMsg: ArtStandardMessage): string | AnthropicSDKContentBlockParam[] {\n const blocks: AnthropicSDKContentBlockParam[] = [];\n\n // Handle text content\n if (artMsg.content && typeof artMsg.content === 'string' && artMsg.content.trim() !== '') {\n blocks.push({ type: 'text', text: artMsg.content });\n } else if (artMsg.content && typeof artMsg.content !== 'string' && artMsg.role !== 'tool_result' && (!artMsg.tool_calls || artMsg.tool_calls.length === 0) ) {\n Logger.warn(`AnthropicAdapter: Non-string, non-tool_result, non-tool_call-only content for role ${artMsg.role}, stringifying.`, { content: artMsg.content });\n blocks.push({ type: 'text', text: JSON.stringify(artMsg.content) });\n }\n\n // Handle tool_calls for assistant messages (these become 'tool_use' blocks)\n if (artMsg.role === 'assistant' && artMsg.tool_calls && artMsg.tool_calls.length > 0) {\n artMsg.tool_calls.forEach(tc => {\n if (tc.type === 'function') {\n try {\n blocks.push({\n type: 'tool_use',\n id: tc.id,\n name: tc.function.name,\n input: JSON.parse(tc.function.arguments || '{}'),\n });\n } catch (e: any) {\n throw new ARTError(\n `AnthropicAdapter: Failed to parse tool call arguments for tool ${tc.function.name} (ID: ${tc.id}). Arguments must be valid JSON. Error: ${e.message}`,\n ErrorCode.PROMPT_TRANSLATION_FAILED, e\n );\n }\n } else {\n Logger.warn(`AnthropicAdapter: Skipping non-function tool_call type: ${tc.type}`);\n }\n });\n }\n\n // Handle tool_result messages (these become 'tool_result' blocks)\n if (artMsg.role === 'tool_result') {\n if (!artMsg.tool_call_id) {\n throw new ARTError(\"AnthropicAdapter: 'tool_result' message missing required 'tool_call_id'.\", ErrorCode.PROMPT_TRANSLATION_FAILED);\n }\n const toolResultBlock: Anthropic.ToolResultBlockParam = {\n type: 'tool_result',\n tool_use_id: artMsg.tool_call_id,\n };\n\n if (typeof artMsg.content === 'string') {\n toolResultBlock.content = artMsg.content;\n } else if (Array.isArray(artMsg.content) && artMsg.content.every(c => typeof c === 'object' && c.type === 'text' && typeof c.text === 'string')) {\n toolResultBlock.content = artMsg.content.map(c => ({type: 'text', text: (c as any).text}));\n } else if (artMsg.content !== null && artMsg.content !== undefined) {\n toolResultBlock.content = JSON.stringify(artMsg.content);\n }\n\n blocks.push(toolResultBlock);\n }\n\n // If only one text block and no other block types, Anthropic SDK allows content to be a simple string.\n if (blocks.length === 1 && blocks[0].type === 'text') {\n return (blocks[0] as Anthropic.TextBlockParam).text;\n }\n \n // If blocks is empty, return empty string\n if (blocks.length === 0) {\n return \"\";\n }\n\n return blocks;\n }\n\n /**\n * Translates an array of `ToolSchema` from the ART framework format to Anthropic's specific tool format.\n * @private\n * @param {ToolSchema[]} artTools - An array of ART tool schemas.\n * @returns {AnthropicSDKTool[]} An array of tools formatted for the Anthropic API.\n * @throws {ARTError} If a tool's `inputSchema` is invalid.\n */\n private translateArtToolsToAnthropic(artTools: ToolSchema[]): AnthropicSDKTool[] {\n return artTools.map(artTool => {\n if (!artTool.inputSchema || typeof artTool.inputSchema !== 'object') {\n throw new ARTError(`Invalid inputSchema definition for tool '${artTool.name}'. Expected a JSON schema object.`, ErrorCode.INVALID_CONFIG);\n }\n return {\n name: artTool.name,\n description: artTool.description,\n input_schema: artTool.inputSchema as Anthropic.Tool.InputSchema,\n };\n });\n }\n}","// src/adapters/reasoning/openrouter.ts\nimport { ProviderAdapter } from '@/core/interfaces';\nimport {\n ArtStandardPrompt,\n ArtStandardMessage,\n CallOptions,\n StreamEvent,\n LLMMetadata,\n ToolSchema,\n} from '@/types';\nimport { Logger } from '@/utils/logger';\nimport { ARTError, ErrorCode } from '@/errors';\n\n// Using OpenAI-compatible structures, as OpenRouter adheres to them.\n// Based on https://openrouter.ai/docs#api-reference-chat-completions\ninterface OpenRouterMessage {\n role: 'system' | 'user' | 'assistant' | 'tool';\n content: string | null;\n name?: string;\n tool_calls?: OpenRouterToolCall[];\n tool_call_id?: string;\n}\n\ninterface OpenRouterToolCall {\n id: string;\n type: 'function';\n function: {\n name: string;\n arguments: string; // Stringified JSON\n };\n}\n\ninterface OpenRouterTool {\n type: 'function';\n function: {\n name: string;\n description: string;\n parameters: object; // JSON Schema\n };\n}\n\ninterface OpenRouterChatCompletionPayload {\n model: string;\n messages: OpenRouterMessage[];\n temperature?: number;\n max_tokens?: number;\n top_p?: number;\n frequency_penalty?: number;\n presence_penalty?: number;\n stop?: string | string[];\n stream?: boolean;\n stream_options?: { include_usage: boolean };\n tools?: OpenRouterTool[];\n tool_choice?: 'auto' | 'any' | 'none' | { type: 'function'; function: { name: string } };\n // OpenRouter specific extensions\n provider?: {\n order?: string[];\n only?: string[];\n allow_fallbacks?: boolean;\n };\n transforms?: string[];\n reasoning?: {\n exclude?: boolean;\n effort?: 'low' | 'medium' | 'high';\n tokens?: number;\n };\n // Legacy toggle allowed by OpenRouter; maps to reasoning include/exclude\n include_reasoning?: boolean;\n}\n\n// See https://openrouter.ai/docs/use-cases/usage-accounting\ninterface OpenRouterUsage {\n completion_tokens?: number;\n completion_tokens_details?: {\n reasoning_tokens?: number;\n };\n prompt_tokens?: number;\n prompt_tokens_details?: {\n cached_tokens?: number;\n };\n total_tokens?: number;\n cost?: number;\n cost_details?: {\n upstream_inference_cost?: number;\n };\n}\n\ninterface OpenRouterChatCompletionResponse {\n id: string;\n object: string;\n created: number;\n model: string;\n choices: {\n index: number;\n message: OpenRouterMessage;\n finish_reason: string;\n }[];\n usage?: OpenRouterUsage;\n}\n\nexport interface OpenRouterAdapterOptions {\n apiKey: string;\n model: string;\n apiBaseUrl?: string;\n siteUrl?: string;\n appName?: string;\n}\n\nexport class OpenRouterAdapter implements ProviderAdapter {\n readonly providerName = 'openrouter';\n private apiKey: string;\n private model: string;\n private apiBaseUrl: string;\n private siteUrl?: string;\n private appName?: string;\n\n constructor(options: OpenRouterAdapterOptions) {\n if (!options.apiKey) {\n throw new Error('OpenRouterAdapter requires an apiKey in options.');\n }\n if (!options.model) {\n throw new Error('OpenRouterAdapter requires a model identifier in options (e.g., \\'google/gemini-pro\\').');\n }\n this.apiKey = options.apiKey;\n this.model = options.model;\n this.apiBaseUrl = options.apiBaseUrl || 'https://openrouter.ai/api/v1';\n this.siteUrl = options.siteUrl;\n this.appName = options.appName;\n Logger.debug(`OpenRouterAdapter initialized for model: ${this.model}`);\n }\n\n async call(prompt: ArtStandardPrompt, options: CallOptions): Promise<AsyncIterable<StreamEvent>> {\n const {\n threadId,\n traceId = `openrouter-trace-${Date.now()}`,\n sessionId,\n stream,\n callContext,\n model: modelOverride,\n tools: artTools,\n } = options;\n const modelToUse = modelOverride || this.model;\n\n let openAiMessages: OpenRouterMessage[];\n let openAiTools: OpenRouterTool[] | undefined;\n try {\n openAiMessages = this.translateToOpenAI(prompt);\n if (artTools && artTools.length > 0) {\n openAiTools = this.translateArtToolsToOpenAI(artTools);\n }\n } catch (error: any) {\n Logger.error(`Error translating prompt/tools for OpenRouter: ${error.message}`, { error, threadId, traceId });\n const generator = async function* (): AsyncIterable<StreamEvent> {\n const err =\n error instanceof ARTError\n ? error\n : new ARTError(`Prompt translation failed: ${error.message}`, ErrorCode.PROMPT_TRANSLATION_FAILED, error);\n yield { type: 'ERROR', data: err, threadId, traceId, sessionId };\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n };\n return generator();\n }\n\n const openRouterOptions = (options as any).openrouter || {};\n // Determine legacy include_reasoning flag per OpenRouter docs\n const includeReasoning: boolean | undefined =\n typeof openRouterOptions?.include_reasoning === 'boolean'\n ? openRouterOptions.include_reasoning\n : (openRouterOptions?.reasoning\n ? (openRouterOptions.reasoning.exclude === true ? false : true)\n : undefined);\n\n const payload: OpenRouterChatCompletionPayload = {\n model: modelToUse,\n messages: openAiMessages,\n temperature: options.temperature,\n max_tokens: options.max_tokens || options.maxOutputTokens,\n top_p: options.top_p || options.topP,\n stop: options.stop || options.stop_sequences || options.stopSequences,\n stream: !!stream,\n ...(stream ? { stream_options: { include_usage: true } } : {}),\n tools: openAiTools,\n tool_choice: options.tool_choice,\n // OpenRouter specific fields from options\n provider: openRouterOptions.provider,\n transforms: openRouterOptions.useMiddleOutTransform === false ? undefined : ['middle-out'],\n reasoning: openRouterOptions.reasoning,\n ...(includeReasoning !== undefined ? { include_reasoning: includeReasoning } : {}),\n };\n\n Object.keys(payload).forEach(\n (key) => payload[key as keyof OpenRouterChatCompletionPayload] === undefined && delete payload[key as keyof OpenRouterChatCompletionPayload],\n );\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n };\n if (this.siteUrl) headers['HTTP-Referer'] = this.siteUrl;\n if (this.appName) headers['X-Title'] = this.appName;\n\n const apiUrl = `${this.apiBaseUrl}/chat/completions`;\n Logger.debug(`Calling OpenRouter API: ${apiUrl} with model ${modelToUse}, stream: ${!!stream}`, { threadId, traceId });\n\n try {\n const response = await fetch(apiUrl, {\n method: 'POST',\n headers: headers,\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const errorBody = await response.text();\n const err = new ARTError(\n `OpenRouter API request failed: ${response.status} ${response.statusText} - ${errorBody}`,\n ErrorCode.LLM_PROVIDER_ERROR,\n new Error(errorBody),\n );\n const errorGenerator = async function* (): AsyncIterable<StreamEvent> {\n yield { type: 'ERROR', data: err, threadId, traceId, sessionId };\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n };\n return errorGenerator();\n }\n\n if (stream && response.body) {\n return this.processStream(response.body, options);\n } else {\n const data = (await response.json()) as OpenRouterChatCompletionResponse;\n return this.processNonStreamingResponse(data, options);\n }\n } catch (error: any) {\n Logger.error(`Error during OpenRouter API call: ${error.message}`, { error, threadId, traceId });\n const artError = error instanceof ARTError ? error : new ARTError(error.message, ErrorCode.LLM_PROVIDER_ERROR, error);\n const errorGenerator = async function* (): AsyncIterable<StreamEvent> {\n yield { type: 'ERROR', data: artError, threadId, traceId, sessionId };\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n };\n return errorGenerator();\n }\n }\n\n private async *processStream(\n stream: ReadableStream<Uint8Array>,\n options: CallOptions,\n ): AsyncIterable<StreamEvent> {\n const { threadId, traceId, sessionId, callContext } = options;\n const tid = (threadId || '') as string;\n const trid = (traceId || '') as string;\n const sid = (sessionId || '') as string;\n\n const startTime = Date.now();\n let timeToFirstTokenMs: number | undefined;\n let finalStopReason: string | undefined;\n let finalUsage: OpenRouterUsage | undefined;\n const aggregatedToolCalls: any[] = [];\n\n // Use TextDecoder + getReader to avoid DOM lib typing issues\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n while (true) {\n try {\n const { value, done } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() || ''; // Keep incomplete line in buffer\n\n for (const raw of lines) {\n const line = raw.trim();\n if (!line || !line.startsWith('data: ')) continue;\n\n const dataContent = line.substring(6);\n if (dataContent === '[DONE]') {\n // End of stream signal\n break;\n }\n\n const chunk = JSON.parse(dataContent);\n if (chunk?.error) {\n throw new ARTError(\n `OpenRouter stream error: ${chunk.error?.message ?? 'unknown'}`,\n ErrorCode.LLM_PROVIDER_ERROR,\n new Error(JSON.stringify(chunk.error)),\n );\n }\n\n const choice = chunk.choices?.[0];\n if (!choice) continue;\n\n if (timeToFirstTokenMs === undefined) {\n timeToFirstTokenMs = Date.now() - startTime;\n }\n\n const delta = choice.delta ?? {};\n\n // 1) Reasoning text (simple field)\n if (typeof delta.reasoning === 'string' && delta.reasoning.length > 0) {\n const tokenType = callContext === 'AGENT_THOUGHT'\n ? 'AGENT_THOUGHT_LLM_THINKING'\n : 'FINAL_SYNTHESIS_LLM_THINKING';\n yield { type: 'TOKEN', data: delta.reasoning, threadId: tid, traceId: trid, sessionId: sid, tokenType };\n }\n\n // 2) Reasoning details array (normalized across providers)\n const reasoningDetails = (delta as any).reasoning_details;\n if (Array.isArray(reasoningDetails)) {\n for (const rd of reasoningDetails) {\n // Prefer raw reasoning.text, else summarize/ignore encrypted\n if (rd?.type === 'reasoning.text' && typeof rd.text === 'string' && rd.text.length > 0) {\n const tokenType = callContext === 'AGENT_THOUGHT'\n ? 'AGENT_THOUGHT_LLM_THINKING'\n : 'FINAL_SYNTHESIS_LLM_THINKING';\n yield { type: 'TOKEN', data: rd.text, threadId: tid, traceId: trid, sessionId: sid, tokenType };\n } else if (rd?.type === 'reasoning.summary' && typeof rd.summary === 'string' && rd.summary.length > 0) {\n const tokenType = callContext === 'AGENT_THOUGHT'\n ? 'AGENT_THOUGHT_LLM_THINKING'\n : 'FINAL_SYNTHESIS_LLM_THINKING';\n yield { type: 'TOKEN', data: rd.summary, threadId: tid, traceId: trid, sessionId: sid, tokenType };\n }\n // Encrypted or unknown formats are ignored for token streaming\n }\n }\n\n // 3) Content delta (normal response tokens)\n if (typeof delta.content === 'string' && delta.content.length > 0) {\n const tokenType = callContext === 'AGENT_THOUGHT'\n ? 'AGENT_THOUGHT_LLM_RESPONSE'\n : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n yield { type: 'TOKEN', data: delta.content, threadId: tid, traceId: trid, sessionId: sid, tokenType };\n }\n\n // 4) Tool call deltas\n if (Array.isArray(delta.tool_calls)) {\n for (const tcDelta of delta.tool_calls) {\n if (typeof tcDelta?.index === 'number') {\n if (!aggregatedToolCalls[tcDelta.index]) aggregatedToolCalls[tcDelta.index] = {};\n if (tcDelta.id) aggregatedToolCalls[tcDelta.index].id = tcDelta.id;\n if (tcDelta.type) aggregatedToolCalls[tcDelta.index].type = tcDelta.type;\n if (tcDelta.function) {\n const dst = (aggregatedToolCalls[tcDelta.index].function ||= {});\n if (tcDelta.function.name) dst.name = tcDelta.function.name;\n if (typeof tcDelta.function.arguments === 'string') {\n dst.arguments = (dst.arguments || '') + tcDelta.function.arguments;\n }\n }\n }\n }\n }\n\n // 5) Finish/usage\n if (choice.finish_reason) finalStopReason = choice.finish_reason;\n if (chunk.usage) finalUsage = chunk.usage as OpenRouterUsage;\n }\n } catch (error: any) {\n const artError =\n error instanceof ARTError\n ? error\n : new ARTError(`Error reading OpenRouter stream: ${error.message}`, ErrorCode.LLM_PROVIDER_ERROR, error);\n yield { type: 'ERROR', data: artError, threadId: tid, traceId: trid, sessionId: sid };\n return; // End generation on error\n }\n }\n\n // If the stream ended with tool_calls, emit accumulated calls\n if (finalStopReason === 'tool_calls' && aggregatedToolCalls.length > 0) {\n const toolData = aggregatedToolCalls.map((tc) => ({\n type: 'tool_use',\n id: String(tc?.id ?? ''),\n name: String(tc?.function?.name ?? ''),\n input: JSON.parse((tc?.function?.arguments as string | undefined) ?? '{}'),\n }));\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n yield { type: 'TOKEN', data: toolData, threadId: tid, traceId: trid, sessionId: sid, tokenType };\n }\n\n const totalGenerationTimeMs = Date.now() - startTime;\n const metadata: LLMMetadata = {\n stopReason: finalStopReason,\n inputTokens: finalUsage?.prompt_tokens,\n outputTokens: finalUsage?.completion_tokens,\n thinkingTokens: finalUsage?.completion_tokens_details?.reasoning_tokens,\n timeToFirstTokenMs,\n totalGenerationTimeMs,\n providerRawUsage: { ...finalUsage, finish_reason: finalStopReason },\n traceId: trid,\n };\n yield { type: 'METADATA', data: metadata, threadId: tid, traceId: trid, sessionId: sid };\n yield { type: 'END', data: null, threadId: tid, traceId: trid, sessionId: sid };\n }\n\n private async *processNonStreamingResponse(\n data: OpenRouterChatCompletionResponse,\n options: CallOptions,\n ): AsyncIterable<StreamEvent> {\n const { threadId, traceId, sessionId, callContext } = options;\n const tid = (threadId || '') as string;\n const trid = (traceId || '') as string;\n const sid = (sessionId || '') as string;\n\n const firstChoice = data.choices?.[0];\n\n if (!firstChoice?.message) {\n const err = new ARTError(\n 'Invalid response structure from OpenRouter API: No message found.',\n ErrorCode.LLM_PROVIDER_ERROR,\n new Error(JSON.stringify(data)),\n );\n yield { type: 'ERROR', data: err, threadId: tid, traceId: trid, sessionId: sid };\n yield { type: 'END', data: null, threadId: tid, traceId: trid, sessionId: sid };\n return;\n }\n\n const responseMessage: any = firstChoice.message;\n\n // Emit reasoning (non-streaming) if present\n if (typeof responseMessage.reasoning === 'string' && responseMessage.reasoning.length > 0) {\n const thinkingType = callContext === 'AGENT_THOUGHT'\n ? 'AGENT_THOUGHT_LLM_THINKING'\n : 'FINAL_SYNTHESIS_LLM_THINKING';\n yield { type: 'TOKEN', data: responseMessage.reasoning, threadId: tid, traceId: trid, sessionId: sid, tokenType: thinkingType };\n }\n if (Array.isArray(responseMessage.reasoning_details)) {\n for (const rd of responseMessage.reasoning_details) {\n if (rd?.type === 'reasoning.text' && typeof rd.text === 'string' && rd.text.length > 0) {\n const thinkingType = callContext === 'AGENT_THOUGHT'\n ? 'AGENT_THOUGHT_LLM_THINKING'\n : 'FINAL_SYNTHESIS_LLM_THINKING';\n yield { type: 'TOKEN', data: rd.text, threadId: tid, traceId: trid, sessionId: sid, tokenType: thinkingType };\n } else if (rd?.type === 'reasoning.summary' && typeof rd.summary === 'string' && rd.summary.length > 0) {\n const thinkingType = callContext === 'AGENT_THOUGHT'\n ? 'AGENT_THOUGHT_LLM_THINKING'\n : 'FINAL_SYNTHESIS_LLM_THINKING';\n yield { type: 'TOKEN', data: rd.summary, threadId: tid, traceId: trid, sessionId: sid, tokenType: thinkingType };\n }\n }\n }\n\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n\n const toolData =\n (responseMessage.tool_calls as any[] | undefined)?.map((tc) => ({\n type: 'tool_use',\n id: String(tc?.id ?? ''),\n name: String(tc?.function?.name ?? ''),\n input: JSON.parse((tc?.function?.arguments as string | undefined) ?? '{}'),\n })) || [];\n\n const responseContent = (responseMessage.content as string | null) ?? '';\n const tokenPayload: any[] = [];\n if (responseContent.trim()) {\n tokenPayload.push({ type: 'text', text: responseContent.trim() });\n }\n tokenPayload.push(...toolData);\n\n if (tokenPayload.length > 0) {\n yield {\n type: 'TOKEN',\n data: tokenPayload.length === 1 && tokenPayload[0].type === 'text' ? tokenPayload[0].text : tokenPayload,\n threadId: tid,\n traceId: trid,\n sessionId: sid,\n tokenType,\n };\n }\n\n const usage = data.usage;\n const metadata: LLMMetadata = {\n stopReason: firstChoice.finish_reason,\n inputTokens: usage?.prompt_tokens,\n outputTokens: usage?.completion_tokens,\n thinkingTokens: usage?.completion_tokens_details?.reasoning_tokens,\n providerRawUsage: { ...usage, finish_reason: firstChoice.finish_reason },\n traceId: trid,\n };\n yield { type: 'METADATA', data: metadata, threadId: tid, traceId: trid, sessionId: sid };\n yield { type: 'END', data: null, threadId: tid, traceId: trid, sessionId: sid };\n }\n\n private translateArtToolsToOpenAI(artTools: ToolSchema[]): OpenRouterTool[] {\n return artTools.map((artTool) => ({\n type: 'function',\n function: {\n name: artTool.name,\n description: artTool.description,\n parameters: artTool.inputSchema,\n },\n }));\n }\n\n private translateToOpenAI(artPrompt: ArtStandardPrompt): OpenRouterMessage[] {\n return artPrompt.map((message: ArtStandardMessage): OpenRouterMessage => {\n switch (message.role) {\n case 'system':\n return { role: 'system', content: String(message.content) };\n case 'user':\n return { role: 'user', content: String(message.content) };\n case 'assistant': {\n const assistantMsg: OpenRouterMessage = {\n role: 'assistant',\n content: typeof message.content === 'string' ? message.content : null,\n };\n if (message.tool_calls && message.tool_calls.length > 0) {\n assistantMsg.tool_calls = message.tool_calls.map((tc) => {\n if (tc.type !== 'function' || !tc.function?.name || typeof tc.function?.arguments !== 'string') {\n throw new ARTError(\n `OpenRouterAdapter: Invalid tool_call structure in assistant message. ID: ${tc.id}`,\n ErrorCode.PROMPT_TRANSLATION_FAILED,\n );\n }\n return {\n id: tc.id,\n type: tc.type,\n function: {\n name: tc.function.name,\n arguments: tc.function.arguments,\n },\n };\n });\n }\n if (assistantMsg.content === '' && assistantMsg.tool_calls) {\n assistantMsg.content = null;\n }\n return assistantMsg;\n }\n case 'tool_result': {\n if (!message.tool_call_id) {\n throw new ARTError(\n `OpenRouterAdapter: 'tool_result' message missing required 'tool_call_id'.`,\n ErrorCode.PROMPT_TRANSLATION_FAILED,\n );\n }\n return {\n role: 'tool',\n tool_call_id: message.tool_call_id,\n content: String(message.content),\n };\n }\n case 'tool_request': {\n throw new ARTError(\n `OpenRouterAdapter: Unexpected 'tool_request' role. This should be handled by 'tool_calls' in an assistant message.`,\n ErrorCode.PROMPT_TRANSLATION_FAILED,\n );\n }\n default: {\n throw new ARTError(\n `OpenRouterAdapter: Unknown message role '${message.role}' encountered.`,\n ErrorCode.PROMPT_TRANSLATION_FAILED,\n );\n }\n }\n });\n }\n}","// src/adapters/reasoning/deepseek.ts\nimport { ProviderAdapter } from '@/core/interfaces';\nimport {\n ArtStandardPrompt, // Use the new standard type\n ArtStandardMessage, // Keep for translation function type hint\n CallOptions,\n StreamEvent,\n LLMMetadata,\n} from '@/types';\nimport { Logger } from '@/utils/logger';\nimport { ARTError, ErrorCode } from '@/errors'; // Import ARTError and ErrorCode\n\n// TODO: Implement streaming support for DeepSeek.\n// TODO: Implement support for 'tools' and 'tool_choice'.\n\n/**\n * Configuration options required for the `DeepSeekAdapter`.\n */\nexport interface DeepSeekAdapterOptions {\n /** Your DeepSeek API key. Handle securely. */\n apiKey: string;\n /** The default DeepSeek model ID to use (e.g., 'deepseek-chat', 'deepseek-coder'). Defaults to 'deepseek-chat' if not provided. */\n model?: string;\n /** Optional: Override the base URL for the DeepSeek API. Defaults to 'https://api.deepseek.com/v1'. */\n apiBaseUrl?: string;\n}\n\n// Use OpenAI-compatible structures\n// Based on https://platform.deepseek.com/api-docs/api/create-chat-completion/index.html\ninterface OpenAIMessage {\n role: 'system' | 'user' | 'assistant' | 'tool';\n content: string | null;\n name?: string;\n tool_calls?: OpenAIToolCall[];\n tool_call_id?: string;\n}\n\ninterface OpenAIToolCall {\n id: string;\n type: 'function';\n function: {\n name: string;\n arguments: string; // Stringified JSON\n };\n}\n\ninterface OpenAIChatCompletionPayload {\n model: string;\n messages: OpenAIMessage[];\n temperature?: number;\n max_tokens?: number;\n top_p?: number;\n frequency_penalty?: number;\n presence_penalty?: number;\n stop?: string | string[];\n stream?: boolean; // DeepSeek supports streaming\n // TODO: Add support for 'tools' and 'tool_choice' if needed later\n}\n\ninterface OpenAIChatCompletionResponse {\n id: string;\n object: string;\n created: number;\n model: string;\n choices: {\n index: number;\n message: OpenAIMessage; // Use the defined OpenAIMessage type\n finish_reason: string; // e.g., 'stop', 'length', 'tool_calls'\n }[];\n usage: { // Note: DeepSeek usage structure matches OpenAI\n prompt_tokens: number;\n completion_tokens: number;\n total_tokens: number;\n };\n}\n\n/**\n * This adapter provides a consistent interface for ART agents to use DeepSeek models,\n * handling the conversion of standard ART prompts to the DeepSeek API format and\n * parsing the responses into the ART `StreamEvent` format.\n *\n * @see {@link ProviderAdapter} for the interface it implements.\n */\nexport class DeepSeekAdapter implements ProviderAdapter {\n readonly providerName = 'deepseek';\n private apiKey: string;\n private model: string;\n private apiBaseUrl: string;\n\n /**\n * Creates an instance of the DeepSeekAdapter.\n * @param {DeepSeekAdapterOptions} options - Configuration options including the API key and optional model/baseURL overrides.\n * @throws {Error} If the API key is missing.\n * @see https://platform.deepseek.com/api-docs\n */\n constructor(options: DeepSeekAdapterOptions) {\n if (!options.apiKey) {\n throw new Error('DeepSeekAdapter requires an apiKey in options.');\n }\n this.apiKey = options.apiKey;\n this.model = options.model || 'deepseek-chat'; // Default model\n this.apiBaseUrl = options.apiBaseUrl || 'https://api.deepseek.com/v1';\n Logger.debug(`DeepSeekAdapter initialized with model: ${this.model}`);\n }\n\n /**\n * Sends a request to the DeepSeek Chat Completions API endpoint.\n * Translates `ArtStandardPrompt` to the OpenAI-compatible format.\n *\n * **Note:** Streaming is **not yet implemented**.\n *\n * @param {ArtStandardPrompt} prompt - The standardized prompt messages.\n * @param {CallOptions} options - Call options, including `threadId`, `traceId`, `stream`, and any OpenAI-compatible generation parameters.\n * @returns {Promise<AsyncIterable<StreamEvent>>} A promise resolving to an AsyncIterable of StreamEvent objects. If streaming is requested, it yields an error event and ends.\n * @see https://platform.deepseek.com/api-docs/api/create-chat-completion/index.html\n */\n async call(prompt: ArtStandardPrompt, options: CallOptions): Promise<AsyncIterable<StreamEvent>> {\n const { threadId, traceId = `deepseek-trace-${Date.now()}`, sessionId, stream, callContext, model: modelOverride } = options;\n const modelToUse = modelOverride || this.model;\n\n // --- Placeholder for Streaming ---\n // TODO: Implement streaming for DeepSeek\n if (stream) {\n Logger.warn(`DeepSeekAdapter: Streaming requested but not implemented. Returning error stream.`, { threadId, traceId });\n const errorGenerator = async function*(): AsyncIterable<StreamEvent> {\n const err = new ARTError(\"Streaming is not yet implemented for the DeepSeekAdapter.\", ErrorCode.LLM_PROVIDER_ERROR);\n yield { type: 'ERROR', data: err, threadId: threadId ?? '', traceId: traceId ?? '', sessionId };\n yield { type: 'END', data: null, threadId: threadId ?? '', traceId: traceId ?? '', sessionId };\n };\n return errorGenerator();\n }\n\n // --- Non-Streaming Logic ---\n\n // --- Translate Prompt ---\n let openAiMessages: OpenAIMessage[];\n try {\n // Reuse the same translation logic as OpenAI adapter\n openAiMessages = this.translateToOpenAI(prompt);\n } catch (error: any) {\n Logger.error(`Error translating ArtStandardPrompt to DeepSeek/OpenAI format: ${error.message}`, { error, threadId, traceId });\n const generator = async function*(): AsyncIterable<StreamEvent> {\n const err = error instanceof ARTError ? error : new ARTError(`Prompt translation failed: ${error.message}`, ErrorCode.PROMPT_TRANSLATION_FAILED, error);\n yield { type: 'ERROR', data: err, threadId, traceId, sessionId };\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n }\n return generator();\n }\n // --- End Translate Prompt ---\n\n const apiUrl = `${this.apiBaseUrl}/chat/completions`;\n const stopSequences = options.stop || options.stop_sequences || options.stopSequences;\n\n const payload: OpenAIChatCompletionPayload = {\n model: modelToUse,\n messages: openAiMessages,\n temperature: options.temperature,\n max_tokens: options.max_tokens || options.maxOutputTokens,\n top_p: options.top_p || options.topP,\n stop: stopSequences,\n stream: false, // Explicitly false for non-streaming\n // TODO: Add tools/tool_choice if needed\n };\n\n Object.keys(payload).forEach(key => payload[key as keyof OpenAIChatCompletionPayload] === undefined && delete payload[key as keyof OpenAIChatCompletionPayload]);\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.apiKey}`,\n };\n \n Logger.debug(`Calling DeepSeek API (non-streaming): ${apiUrl} with model ${this.model}`, { threadId, traceId });\n \n // Use an async generator for non-streaming case too\n const generator = async function*(): AsyncIterable<StreamEvent> {\n try {\n const response = await fetch(apiUrl, {\n method: 'POST',\n headers: headers,\n body: JSON.stringify(payload),\n });\n \n if (!response.ok) {\n const errorBody = await response.text();\n let errorMessage = errorBody;\n try {\n const parsedError = JSON.parse(errorBody);\n if (parsedError?.error?.message) errorMessage = parsedError.error.message;\n } catch (e) { /* Ignore */ }\n const err = new ARTError(\n `DeepSeek API request failed: ${response.status} ${response.statusText} - ${errorMessage}`,\n ErrorCode.LLM_PROVIDER_ERROR,\n new Error(errorBody) // Pass underlying error context\n );\n yield { type: 'ERROR', data: err, threadId, traceId, sessionId };\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n return; // Stop the generator on error\n }\n\n const data = await response.json() as OpenAIChatCompletionResponse;\n const firstChoice = data.choices?.[0];\n\n if (!firstChoice?.message) {\n const err = new ARTError('Invalid response structure from DeepSeek API: No message found.', ErrorCode.LLM_PROVIDER_ERROR, new Error(JSON.stringify(data)));\n yield { type: 'ERROR', data: err, threadId, traceId, sessionId };\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n return; // Stop the generator\n }\n\n const responseMessage = firstChoice.message;\n // TODO: Handle tool_calls in non-streaming response if needed by agent logic\n if (responseMessage.tool_calls) {\n Logger.debug(\"DeepSeek response included tool calls (non-streaming)\", { toolCalls: responseMessage.tool_calls, threadId, traceId });\n }\n Logger.debug(`DeepSeek API call successful. Finish reason: ${firstChoice.finish_reason}`, { threadId, traceId });\n\n // Yield TOKEN\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n const responseContent = responseMessage.content ?? '';\n yield { type: 'TOKEN', data: responseContent.trim(), threadId, traceId, sessionId, tokenType };\n\n // Yield METADATA\n const metadata: LLMMetadata = {\n inputTokens: data.usage?.prompt_tokens,\n outputTokens: data.usage?.completion_tokens,\n stopReason: firstChoice.finish_reason,\n providerRawUsage: { usage: data.usage, finish_reason: firstChoice.finish_reason },\n traceId: traceId,\n };\n yield { type: 'METADATA', data: metadata, threadId, traceId, sessionId };\n\n // Yield END\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n\n } catch (error: any) {\n Logger.error(`Error during DeepSeek API call: ${error.message}`, { error, threadId, traceId });\n const artError = error instanceof ARTError ? error : new ARTError(error.message, ErrorCode.LLM_PROVIDER_ERROR, error);\n yield { type: 'ERROR', data: artError, threadId, traceId, sessionId };\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n }\n }; // No need for .bind(this)\n\n return generator();\n }\n\n /**\n * Translates the provider-agnostic `ArtStandardPrompt` into the OpenAI API's `OpenAIMessage[]` format.\n * (Copied from OpenAIAdapter - assumes DeepSeek compatibility)\n *\n * @private\n * @param {ArtStandardPrompt} artPrompt - The input `ArtStandardPrompt` array.\n * @returns {OpenAIMessage[]} The `OpenAIMessage[]` array formatted for the OpenAI API.\n * @throws {ARTError} If translation encounters an issue (ErrorCode.PROMPT_TRANSLATION_FAILED).\n */\n private translateToOpenAI(artPrompt: ArtStandardPrompt): OpenAIMessage[] {\n // Identical implementation to OpenAIAdapter's translateToOpenAI\n return artPrompt.map((message: ArtStandardMessage): OpenAIMessage => {\n switch (message.role) {\n case 'system': {\n if (typeof message.content !== 'string') {\n Logger.warn(`DeepSeekAdapter: System message content is not a string. Stringifying.`, { content: message.content });\n return { role: 'system', content: String(message.content) };\n }\n return { role: 'system', content: message.content };\n }\n case 'user': {\n if (typeof message.content !== 'string') {\n Logger.warn(`DeepSeekAdapter: User message content is not a string. Stringifying.`, { content: message.content });\n return { role: 'user', content: String(message.content) };\n }\n return { role: 'user', content: message.content };\n }\n case 'assistant': {\n const assistantMsg: OpenAIMessage = {\n role: 'assistant',\n content: typeof message.content === 'string' ? message.content : null,\n };\n if (message.tool_calls && message.tool_calls.length > 0) {\n assistantMsg.tool_calls = message.tool_calls.map(tc => {\n if (tc.type !== 'function' || !tc.function?.name || typeof tc.function?.arguments !== 'string') {\n throw new ARTError(\n `DeepSeekAdapter: Invalid tool_call structure in assistant message. ID: ${tc.id}`,\n ErrorCode.PROMPT_TRANSLATION_FAILED\n );\n }\n return {\n id: tc.id,\n type: tc.type,\n function: {\n name: tc.function.name,\n arguments: tc.function.arguments,\n }\n };\n });\n }\n if (assistantMsg.content === '' && !assistantMsg.tool_calls) {\n assistantMsg.content = null;\n }\n if (assistantMsg.content === '' && assistantMsg.tool_calls) {\n assistantMsg.content = null;\n }\n if (typeof assistantMsg.content !== 'string' && assistantMsg.content !== null) {\n assistantMsg.content = null;\n }\n return assistantMsg;\n }\n case 'tool_result': {\n if (!message.tool_call_id) {\n throw new ARTError(\n `DeepSeekAdapter: 'tool_result' message missing required 'tool_call_id'.`,\n ErrorCode.PROMPT_TRANSLATION_FAILED\n );\n }\n if (typeof message.content !== 'string') {\n Logger.warn(`DeepSeekAdapter: Tool result content is not a string. Stringifying.`, { content: message.content });\n }\n return {\n role: 'tool',\n tool_call_id: message.tool_call_id,\n content: String(message.content),\n };\n }\n case 'tool_request': {\n throw new ARTError(\n `DeepSeekAdapter: Unexpected 'tool_request' role encountered during translation.`,\n ErrorCode.PROMPT_TRANSLATION_FAILED\n );\n }\n default: {\n throw new ARTError(\n `DeepSeekAdapter: Unknown message role '${message.role}' encountered during translation.`,\n ErrorCode.PROMPT_TRANSLATION_FAILED\n );\n }\n }\n });\n }\n }","// src/adapters/reasoning/ollama.ts\nimport OpenAI from \"openai\";\n\nimport { ProviderAdapter } from '@/core/interfaces';\nimport {\n ArtStandardPrompt,\n ArtStandardMessage,\n CallOptions,\n StreamEvent,\n LLMMetadata,\n ToolSchema, // Added for tool support\n} from '@/types';\nimport { Logger } from '@/utils/logger';\nimport { ARTError, ErrorCode } from '@/errors';\n// XmlMatcher removed, parsing of embedded XML is responsibility of OutputParser\n\n// Define expected options for the Ollama adapter constructor\n/**\n * Configuration options required for the `OllamaAdapter`.\n */\nexport interface OllamaAdapterOptions {\n /**\n * The base URL for the Ollama API. Defaults to 'http://localhost:11434'.\n * The '/v1' suffix for OpenAI compatibility will be added automatically.\n */\n ollamaBaseUrl?: string;\n /**\n * The default Ollama model ID to use (e.g., 'llama3', 'mistral').\n * This can be overridden by `RuntimeProviderConfig.modelId` or `CallOptions.model`.\n * It's recommended to set this if you primarily use one model with Ollama.\n */\n defaultModel?: string;\n /**\n * API key for Ollama (if secured). Defaults to \"ollama\" as commonly used.\n */\n apiKey?: string;\n}\n\n// OpenAI-compatible structures (can be shared or adapted from openai.ts)\ninterface OpenAIMessage {\n role: 'system' | 'user' | 'assistant' | 'tool';\n content: string | null;\n name?: string;\n tool_calls?: OpenAIToolCall[];\n tool_call_id?: string;\n}\n\ninterface OpenAIToolCall {\n id: string;\n type: 'function';\n function: {\n name: string;\n arguments: string; // Stringified JSON\n };\n}\n\n// Note: Payload and Response types are from 'openai' package directly.\n\n/**\n * Implements the `ProviderAdapter` interface for interacting with Ollama's\n * OpenAI-compatible API endpoint.\n *\n * Handles formatting requests, parsing responses, streaming, and tool use.\n *\n * @see {@link ProviderAdapter} for the interface definition.\n * @see {@link OllamaAdapterOptions} for configuration options.\n */\nexport class OllamaAdapter implements ProviderAdapter {\n readonly providerName = 'ollama';\n private client: OpenAI;\n private defaultModel?: string;\n private ollamaBaseUrl: string;\n\n /**\n * Creates an instance of the OllamaAdapter.\n * @param options - Configuration options.\n */\n constructor(options: OllamaAdapterOptions) {\n this.ollamaBaseUrl = options.ollamaBaseUrl || 'http://localhost:11434';\n this.defaultModel = options.defaultModel;\n\n // Ensure ollamaBaseUrl doesn't end with /v1 or /\n const cleanBaseUrl = this.ollamaBaseUrl.replace(/\\/v1$/, \"\").replace(/\\/$/, \"\");\n\n this.client = new OpenAI({\n baseURL: `${cleanBaseUrl}/v1`,\n apiKey: options.apiKey || \"ollama\", // Default API key for local Ollama\n dangerouslyAllowBrowser: true, // Necessary if running in a browser-like environment for local calls\n });\n\n Logger.debug(`OllamaAdapter initialized. Base URL: ${cleanBaseUrl}/v1, Default Model: ${this.defaultModel || 'Not set'}`);\n }\n\n /**\n * Sends a request to the Ollama API.\n * Translates `ArtStandardPrompt` to the OpenAI format and handles streaming and tool use.\n *\n * @param {ArtStandardPrompt} prompt - The standardized prompt messages.\n * @param {CallOptions} options - Call options.\n * @returns {Promise<AsyncIterable<StreamEvent>>} A promise resolving to an AsyncIterable of StreamEvent objects.\n */\n async call(prompt: ArtStandardPrompt, options: CallOptions): Promise<AsyncIterable<StreamEvent>> {\n const {\n threadId,\n traceId = `ollama-trace-${Date.now()}`,\n sessionId,\n stream = false,\n callContext,\n model: modelOverride,\n tools: availableArtTools,\n providerConfig,\n } = options;\n\n const modelToUse = providerConfig?.modelId || modelOverride || this.defaultModel;\n\n if (!modelToUse) {\n const err = new ARTError(\n \"Ollama model ID is not specified. Provide it in adapter options, runtime config, or call options.\",\n ErrorCode.INVALID_CONFIG\n );\n const errorGenerator = async function* (): AsyncIterable<StreamEvent> {\n yield { type: 'ERROR', data: err, threadId, traceId, sessionId };\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n };\n return errorGenerator();\n }\n\n let openAiMessages: OpenAIMessage[];\n try {\n openAiMessages = this.translateToOpenAI(prompt, modelToUse); // Pass modelToUse here\n } catch (error: any) {\n Logger.error(`Error translating ArtStandardPrompt to OpenAI format for Ollama: ${error.message}`, { error, threadId, traceId });\n const artError = error instanceof ARTError ? error : new ARTError(`Prompt translation failed: ${error.message}`, ErrorCode.PROMPT_TRANSLATION_FAILED, error);\n const errorGenerator = async function* (): AsyncIterable<StreamEvent> {\n yield { type: 'ERROR', data: artError, threadId, traceId, sessionId };\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n };\n return errorGenerator();\n }\n\n const openAiTools: OpenAI.Chat.Completions.ChatCompletionTool[] | undefined = availableArtTools\n ? this.translateArtToolsToOpenAI(availableArtTools)\n : undefined;\n\n const requestBody: OpenAI.Chat.Completions.ChatCompletionCreateParams = {\n model: modelToUse,\n messages: openAiMessages as OpenAI.Chat.ChatCompletionMessageParam[], // Cast needed\n temperature: options.temperature ?? providerConfig?.adapterOptions?.temperature,\n max_tokens: options.max_tokens ?? options.maxOutputTokens ?? providerConfig?.adapterOptions?.max_tokens,\n top_p: options.top_p ?? options.topP ?? providerConfig?.adapterOptions?.top_p,\n stop: (options.stop || options.stop_sequences || options.stopSequences) ?? providerConfig?.adapterOptions?.stop,\n stream: stream,\n tools: openAiTools,\n tool_choice: options.tool_choice ?? providerConfig?.adapterOptions?.tool_choice,\n };\n\n // Remove undefined keys from the request body\n Object.keys(requestBody).forEach(key => {\n const K = key as keyof OpenAI.Chat.Completions.ChatCompletionCreateParams;\n if (requestBody[K] === undefined) {\n delete requestBody[K];\n }\n });\n\n Logger.debug(`Calling Ollama API (via OpenAI client) with model ${modelToUse}`, { stream, tools: !!openAiTools, threadId, traceId });\n\n const generator = async function* (this: OllamaAdapter): AsyncIterable<StreamEvent> {\n const startTime = Date.now();\n let timeToFirstTokenMs: number | undefined;\n let accumulatedOutputTokens = 0;\n let finalApiResponseUsage: OpenAI.CompletionUsage | undefined;\n let finalStopReason: string | undefined;\n\n try {\n if (stream) {\n const streamInstance = await this.client.chat.completions.create(\n requestBody as OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming\n );\n \n // let accumulatedText = \"\"; // Not strictly needed here as text is yielded token by token\n const accumulatedToolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] = [];\n\n for await (const chunk of streamInstance) {\n if (!timeToFirstTokenMs) {\n timeToFirstTokenMs = Date.now() - startTime;\n }\n\n const delta = chunk.choices[0]?.delta;\n finalStopReason = chunk.choices[0]?.finish_reason ?? finalStopReason;\n\n if (delta?.content) {\n accumulatedOutputTokens++; // Approximation: count each content chunk as one token\n // If XML parsing is needed for <think> tags, it should be done by OutputParser\n // Adapter streams raw content.\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n yield { type: 'TOKEN', data: delta.content, threadId, traceId, sessionId, tokenType };\n }\n\n if (delta?.tool_calls) {\n delta.tool_calls.forEach((tcDelta: OpenAI.Chat.Completions.ChatCompletionChunk.Choice.Delta.ToolCall) => {\n if (tcDelta.index === undefined) return;\n\n if (!accumulatedToolCalls[tcDelta.index]) {\n accumulatedToolCalls[tcDelta.index] = {\n id: tcDelta.id || '',\n type: 'function', // Type is always 'function' for OpenAI tools\n function: {\n name: tcDelta.function?.name || '',\n arguments: tcDelta.function?.arguments || ''\n }\n };\n } else {\n if (tcDelta.id) accumulatedToolCalls[tcDelta.index].id = tcDelta.id;\n if (tcDelta.function?.name) accumulatedToolCalls[tcDelta.index].function.name = tcDelta.function.name;\n if (tcDelta.function?.arguments) {\n // Ensure function object exists if not initialized by name first\n if (!accumulatedToolCalls[tcDelta.index].function) {\n accumulatedToolCalls[tcDelta.index].function = { name: '', arguments: ''};\n }\n accumulatedToolCalls[tcDelta.index].function.arguments += tcDelta.function.arguments;\n }\n }\n });\n }\n // Ollama's OpenAI compatible stream might not include usage per chunk.\n // We'll rely on the final non-streaming call for accurate usage if possible,\n // or estimate for streaming.\n if (chunk.usage) { // Check if usage is present in the chunk\n finalApiResponseUsage = chunk.usage;\n }\n }\n \n // If streaming and stop reason is tool_calls, yield the accumulated tool calls.\n // Text content would have been yielded incrementally.\n if (finalStopReason === 'tool_calls' && accumulatedToolCalls.length > 0) {\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n const toolData = accumulatedToolCalls.map(tc => ({\n type: 'tool_use', // ART specific marker\n id: tc.id,\n name: tc.function.name,\n input: JSON.parse(tc.function.arguments || '{}'),\n }));\n yield { type: 'TOKEN', data: toolData, threadId, traceId, sessionId, tokenType };\n }\n // Note: accumulatedText is not explicitly yielded here as all text content from delta.content\n // was already yielded token by token. If there's a scenario where text needs to be combined\n // with tool_calls in a single final stream TOKEN event, this logic would need adjustment,\n // but typically stream consumers aggregate individual TOKENs.\n\n } else { // Non-streaming\n const response = await this.client.chat.completions.create(\n requestBody as OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming\n );\n\n const firstChoice = response.choices[0];\n if (!firstChoice || !firstChoice.message) {\n throw new ARTError('Invalid response structure from Ollama API: No message found.', ErrorCode.LLM_PROVIDER_ERROR, new Error(JSON.stringify(response)));\n }\n\n finalStopReason = firstChoice.finish_reason ?? undefined;\n finalApiResponseUsage = response.usage;\n const responseMessage = firstChoice.message;\n\n const tokenType = callContext === 'AGENT_THOUGHT' ? 'AGENT_THOUGHT_LLM_RESPONSE' : 'FINAL_SYNTHESIS_LLM_RESPONSE';\n\n if (responseMessage.tool_calls && responseMessage.tool_calls.length > 0) {\n const toolData = responseMessage.tool_calls.map((tc: OpenAI.Chat.Completions.ChatCompletionMessageToolCall) => ({\n type: 'tool_use',\n id: tc.id,\n name: tc.function.name,\n input: JSON.parse(tc.function.arguments || '{}'),\n }));\n if (responseMessage.content) {\n yield { type: 'TOKEN', data: [{type: 'text', text: responseMessage.content.trim()}, ...toolData], threadId, traceId, sessionId, tokenType };\n } else {\n yield { type: 'TOKEN', data: toolData, threadId, traceId, sessionId, tokenType };\n }\n } else if (responseMessage.content) {\n yield { type: 'TOKEN', data: responseMessage.content.trim(), threadId, traceId, sessionId, tokenType };\n }\n }\n\n const totalGenerationTimeMs = Date.now() - startTime;\n const metadata: LLMMetadata = {\n stopReason: finalStopReason,\n inputTokens: finalApiResponseUsage?.prompt_tokens,\n outputTokens: finalApiResponseUsage?.completion_tokens ?? (stream ? accumulatedOutputTokens : undefined),\n timeToFirstTokenMs: stream ? timeToFirstTokenMs : undefined, // TTFT only for stream\n totalGenerationTimeMs: totalGenerationTimeMs,\n providerRawUsage: { usage: finalApiResponseUsage, finish_reason: finalStopReason },\n traceId: traceId,\n };\n yield { type: 'METADATA', data: metadata, threadId, traceId, sessionId };\n\n } catch (error: any) {\n Logger.error(`Error during Ollama API call: ${error.message}`, { error, threadId, traceId });\n const artError = error instanceof ARTError ? error :\n (error.constructor.name === 'APIError' ? new ARTError(`Ollama API Error (${(error as any).status}): ${(error as any).message}`, ErrorCode.LLM_PROVIDER_ERROR, error) :\n new ARTError(error.message || 'Unknown Ollama adapter error', ErrorCode.LLM_PROVIDER_ERROR, error));\n yield { type: 'ERROR', data: artError, threadId, traceId, sessionId };\n } finally {\n yield { type: 'END', data: null, threadId, traceId, sessionId };\n }\n }.bind(this);\n\n return generator();\n }\n\n /**\n * Translates the provider-agnostic `ArtStandardPrompt` into the OpenAI API's `OpenAIMessage[]` format.\n * This method can handle model-specific formatting, such as merging consecutive messages for certain models.\n * @private\n * @param {ArtStandardPrompt} artPrompt - The input `ArtStandardPrompt` array.\n * @param {string} [modelIdForTransform] - The model ID, used to determine if special formatting is needed.\n * @returns {OpenAIMessage[]} The `OpenAIMessage[]` array formatted for the OpenAI API.\n */\n private translateToOpenAI(artPrompt: ArtStandardPrompt, modelIdForTransform?: string): OpenAIMessage[] {\n const messagesToProcess = [...artPrompt];\n const translatedMessages: OpenAIMessage[] = [];\n\n // Determine if R1-style merging is needed (e.g., for deepseek-r1)\n const useR1Format = modelIdForTransform?.toLowerCase().includes(\"deepseek-r1\");\n\n if (useR1Format) {\n Logger.debug(`OllamaAdapter: Applying R1-style message merging for model: ${modelIdForTransform}`);\n let lastMessage: OpenAIMessage | null = null;\n for (const artMsg of messagesToProcess) {\n // Map current ArtStandardMessage to a basic OpenAIMessage structure first\n // This mapping needs to be careful about roles, as 'tool_result' becomes 'tool'\n let currentRoleForCompare: 'system' | 'user' | 'assistant' | 'tool' = 'user'; // default\n if (artMsg.role === 'system') currentRoleForCompare = 'system';\n else if (artMsg.role === 'user') currentRoleForCompare = 'user';\n else if (artMsg.role === 'assistant') currentRoleForCompare = 'assistant';\n else if (artMsg.role === 'tool_result') currentRoleForCompare = 'tool';\n // 'tool_request' is an error case handled by mapArtMessageToOpenAIMessage\n\n const currentOpenAIMsgPart = this.mapArtMessageToOpenAIMessage(artMsg);\n\n\n if (lastMessage && lastMessage.role === currentRoleForCompare && currentRoleForCompare !== 'system' && currentRoleForCompare !== 'tool') {\n // Merge content for 'user' or 'assistant' roles\n // Note: OpenAI API generally allows consecutive 'tool' messages if they have different tool_call_ids.\n // And 'system' messages are usually single or handled specially.\n // The primary concern for merging is consecutive 'user' or 'assistant' messages for models like DeepSeek R1.\n\n let mergedContent = \"\";\n if (typeof lastMessage.content === 'string' && typeof currentOpenAIMsgPart.content === 'string') {\n mergedContent = `${lastMessage.content}\\n${currentOpenAIMsgPart.content}`;\n } else if (typeof lastMessage.content === 'string') {\n mergedContent = `${lastMessage.content}\\n${currentOpenAIMsgPart.content === null ? '' : String(currentOpenAIMsgPart.content)}`;\n } else if (typeof currentOpenAIMsgPart.content === 'string') {\n mergedContent = `${lastMessage.content === null ? '' : String(lastMessage.content)}\\n${currentOpenAIMsgPart.content}`;\n } else { // both might be null or non-string\n mergedContent = `${lastMessage.content === null ? '' : String(lastMessage.content)}\\n${currentOpenAIMsgPart.content === null ? '' : String(currentOpenAIMsgPart.content)}`;\n }\n lastMessage.content = mergedContent.trim() || null;\n\n // Merge tool_calls for assistant messages\n if (lastMessage.role === 'assistant' && currentOpenAIMsgPart.role === 'assistant' && currentOpenAIMsgPart.tool_calls) {\n lastMessage.tool_calls = [...(lastMessage.tool_calls || []), ...currentOpenAIMsgPart.tool_calls];\n }\n // Ensure content is null if only tool_calls are present after merge\n if (lastMessage.role === 'assistant' && !lastMessage.content && lastMessage.tool_calls && lastMessage.tool_calls.length > 0) {\n lastMessage.content = null;\n }\n\n } else {\n // If roles are different, or it's a system/tool message not needing merge, or it's the first message\n lastMessage = currentOpenAIMsgPart;\n translatedMessages.push(lastMessage);\n }\n }\n } else {\n // Standard mapping without R1-specific merging\n for (const artMsg of messagesToProcess) {\n translatedMessages.push(this.mapArtMessageToOpenAIMessage(artMsg));\n }\n }\n return translatedMessages;\n }\n\n // Helper function to map a single ArtStandardMessage to an OpenAIMessage\n // This is called by translateToOpenAI\n /**\n * Maps a single `ArtStandardMessage` to an `OpenAIMessage`.\n * @private\n * @param {ArtStandardMessage} message - The message to map.\n * @returns {OpenAIMessage} The mapped message.\n * @throws {ARTError} If an unsupported or invalid message role is encountered.\n */\n private mapArtMessageToOpenAIMessage(message: ArtStandardMessage): OpenAIMessage {\n switch (message.role) {\n case 'system':\n return { role: 'system', content: typeof message.content === 'string' ? message.content : String(message.content) };\n case 'user':\n // User content can be complex (e.g. multipart with images for some providers, but OpenAI expects string or array of content parts)\n // For Ollama with OpenAI client, we assume string content for user messages for now.\n // If ArtStandardMessage.content for user can be an array of parts, this needs adjustment.\n return { role: 'user', content: typeof message.content === 'string' ? message.content : JSON.stringify(message.content) };\n case 'assistant': {\n const assistantMsg: OpenAIMessage = {\n role: 'assistant',\n content: typeof message.content === 'string' ? message.content : null,\n };\n if (message.tool_calls && message.tool_calls.length > 0) {\n assistantMsg.tool_calls = message.tool_calls.map(tc => {\n if (tc.type !== 'function' || !tc.function?.name || typeof tc.function?.arguments !== 'string') {\n throw new ARTError(`OllamaAdapter: Invalid tool_call structure in assistant message. ID: ${tc.id}`, ErrorCode.PROMPT_TRANSLATION_FAILED);\n }\n return {\n id: tc.id,\n type: tc.type,\n function: { name: tc.function.name, arguments: tc.function.arguments },\n };\n });\n }\n // OpenAI API: content is required unless tool_calls is present.\n // If content is an empty string and tool_calls are present, set content to null.\n if (assistantMsg.content === '' && assistantMsg.tool_calls && assistantMsg.tool_calls.length > 0) {\n assistantMsg.content = null;\n } else if (assistantMsg.content === '' && (!assistantMsg.tool_calls || assistantMsg.tool_calls.length === 0)) {\n // If content is empty string and no tool_calls, it might be an issue for some models.\n // However, OpenAI allows empty string content. For safety, can be null.\n // Let's stick to null if it was not a string initially or became empty.\n if (typeof message.content !== 'string') assistantMsg.content = null;\n }\n // Ensure content is explicitly null if it's not a string and not empty (e.g. if it was an object that didn't become a string)\n if (typeof assistantMsg.content !== 'string' && assistantMsg.content !== null) {\n assistantMsg.content = null;\n }\n return assistantMsg;\n }\n case 'tool_result': {\n if (!message.tool_call_id) {\n throw new ARTError(\"OllamaAdapter: 'tool_result' message missing required 'tool_call_id'.\", ErrorCode.PROMPT_TRANSLATION_FAILED);\n }\n return {\n role: 'tool',\n tool_call_id: message.tool_call_id,\n content: String(message.content), // Content is the stringified result/error\n };\n }\n case 'tool_request': // This role should not be directly translated as it's part of assistant's tool_calls\n throw new ARTError(\"OllamaAdapter: Unexpected 'tool_request' role during mapping. This should be handled via assistant's tool_calls.\", ErrorCode.PROMPT_TRANSLATION_FAILED);\n default:\n // This should ideally not be reached if ArtStandardMessageRole is comprehensive\n throw new ARTError(`OllamaAdapter: Unknown message role '${(message as ArtStandardMessage).role}' encountered during mapping.`, ErrorCode.PROMPT_TRANSLATION_FAILED);\n }\n }\n\n /**\n * Translates an array of `ToolSchema` from the ART framework format to OpenAI's specific tool format.\n * @private\n * @param {ToolSchema[]} artTools - An array of ART tool schemas.\n * @returns {OpenAI.Chat.Completions.ChatCompletionTool[]} An array of tools formatted for the OpenAI API.\n * @throws {ARTError} If a tool's schema is invalid.\n */\n private translateArtToolsToOpenAI(artTools: ToolSchema[]): OpenAI.Chat.Completions.ChatCompletionTool[] {\n return artTools.map(artTool => {\n // ART's ToolSchema directly provides name, description, and inputSchema.\n // OpenAI tools are always of type 'function'.\n if (!artTool.name || !artTool.inputSchema) {\n throw new ARTError(`Invalid ART ToolSchema for tool '${artTool.name || 'unknown'}'. Must include name and inputSchema.`, ErrorCode.INVALID_CONFIG);\n }\n return {\n type: 'function', // OpenAI tool type is always 'function'\n function: {\n name: artTool.name,\n description: artTool.description,\n parameters: artTool.inputSchema as OpenAI.FunctionParameters, // artTool.inputSchema is the JSON schema\n },\n };\n });\n }\n\n /**\n * Optional method for graceful shutdown. For Ollama, which is typically a separate\n * local server, this adapter doesn't manage persistent connections that need explicit closing.\n * @returns {Promise<void>} A promise that resolves when the shutdown is complete.\n */\n async shutdown(): Promise<void> {\n Logger.debug(`OllamaAdapter shutdown called. No specific resources to release for model ${this.defaultModel || 'not set'}.`);\n // No explicit resources to release for a typical Ollama HTTP API client.\n return Promise.resolve();\n }\n}\n// TODO: Management Features as below\n{/*\n Model Management (List, Pull, Delete):\n\nThese are administrative tasks. In a complex application, these might be handled by a separate \"Ollama Management Service\" or utility functions within the application that interact directly with these Ollama API endpoints.\nThey don't fit naturally into the ProviderAdapter.call() flow, which is about sending a prompt and receiving a response.\nExposing these directly on the OllamaAdapter instance might be possible but could blur its primary responsibility.\n\n\nAborting a Stream:\n\nThe AsyncIterable<StreamEvent> returned by ProviderAdapter.call() can be aborted by the consumer of the stream. When the consumer stops iterating (e.g., breaks from a for await...of loop or the underlying mechanism like an AbortController signals an abort to the fetch call within the adapter), the adapter's fetch request should be cancelled. This, in turn, should close the connection to the Ollama server, effectively aborting the stream from Ollama's perspective.\nThe openai SDK (which my OllamaAdapter uses) supports passing an AbortSignal to its methods. This is the standard way to handle cancellation. The OllamaAdapter.call method could accept an AbortSignal in its CallOptions if ART's ReasoningEngine and AgentCore were designed to propagate such a signal.\nCurrently, CallOptions in ART does not have a standard abortSignal property. Adding this would be a framework-level change.\nWithout a framework-level abort signal, the adapter itself cannot easily expose an \"abort\" method for a stream initiated by call(), because the stream consumption is managed externally by the AgentCore.\n */}","// src/tools/CalculatorTool.ts\nimport { IToolExecutor } from '@/core/interfaces';\nimport { ToolSchema, ExecutionContext, ToolResult } from '@/types';\nimport { Logger } from '@/utils/logger';\n// Import necessary parts from mathjs\nimport { evaluate, type Complex } from 'mathjs'; // Removed unused MathJsStatic, MathNode\nimport * as math from 'mathjs'; // Import the full math object to access functions\n\n/**\n * A restricted set of safe functions allowed from the mathjs library.\n * Prevents access to potentially unsafe functions like `import`, `evaluate`, etc.\n * @internal\n */\nconst allowedFunctions: Record<string, any> = {\n // Basic arithmetic & roots\n sqrt: math.sqrt,\n cbrt: math.cbrt,\n abs: math.abs,\n pow: math.pow, // Note: ^ operator also works\n exp: math.exp,\n log: math.log,\n log10: math.log10,\n log2: math.log2,\n // Trigonometry\n sin: math.sin,\n cos: math.cos,\n tan: math.tan,\n asin: math.asin,\n acos: math.acos,\n atan: math.atan,\n atan2: math.atan2,\n // Rounding & Modulo\n round: math.round,\n floor: math.floor,\n ceil: math.ceil,\n mod: math.mod, // Note: % operator also works\n // Statistical functions\n mean: math.mean,\n median: math.median,\n std: math.std,\n variance: math.variance,\n max: math.max,\n min: math.min,\n // Additional mathematical functions\n factorial: math.factorial,\n gamma: math.gamma,\n combinations: math.combinations,\n permutations: math.permutations,\n // Number formatting\n format: math.format,\n // Constants (implicitly allowed via evaluate, but good to be aware)\n // pi: math.pi,\n // e: math.e,\n};\n\n/**\n * An ART Framework tool that safely evaluates mathematical expressions using the mathjs library.\n * It supports basic arithmetic, variables via a scope, complex numbers, and a predefined list of safe functions.\n *\n * This tool is designed to be used within the ART framework's `ToolSystem`.\n * It provides a safe way to perform mathematical calculations by leveraging\n * the `mathjs` library. The tool validates the input expression to ensure it's a\n * single, valid mathematical expression before evaluation.\n *\n * @see {@link IToolExecutor} for the interface it implements.\n * @see {@link ToolSystem} for the system that manages and executes tools.\n */\nexport class CalculatorTool implements IToolExecutor {\n /** The unique name identifier for this tool. */\n public static readonly toolName = \"calculator\";\n \n /** Store for previous calculation results by threadId */\n private resultStore: Map<string, any> = new Map();\n\n /**\n * The schema definition for the CalculatorTool, conforming to the `ToolSchema` interface.\n * It defines the tool's name, description, input parameters (expression and optional scope),\n * and provides examples for the LLM.\n */\n // TODO: Consider renaming this property to `getSchema()` for better idiomatic consistency? (See sample-app feedback)\n readonly schema: ToolSchema = {\n name: CalculatorTool.toolName,\n description: `Evaluates mathematical expressions using a sandboxed mathjs environment.\nYou can reference previous calculation results using the 'ans' variable.\nSupports standard operators (+, -, *, /, %, ^), variables via 'scope', complex numbers, and the following allowed functions:\nsqrt, cbrt, abs, pow, exp, log, log10, log2, sin, cos, tan, asin, acos, atan, atan2, round, floor, ceil, mod, \nmean, median, std, variance, max, min, factorial, gamma, combinations, permutations, format.`,\n inputSchema: {\n type: 'object',\n properties: {\n expression: {\n type: 'string',\n description: 'The mathematical expression to evaluate (e.g., \"2 + 2\", \"sqrt(a)\", \"a * b\", \"sqrt(-4)\", \"factorial(5)\", \"ans + 10\").',\n },\n scope: {\n type: 'object',\n description: 'An optional object containing variables and their values (numbers only) to be used in the expression (e.g., {\"a\": 16, \"b\": 3}).',\n additionalProperties: { type: 'number' },\n default: {},\n },\n },\n required: ['expression'],\n },\n // Note: outputSchema is omitted as the result can be number or string (for complex numbers).\n // A more complex schema using 'oneOf' could be defined if strict output validation is needed.\n examples: [\n { input: { expression: \"2 + 2\" }, output: { result: 4 }, description: \"Simple addition\" },\n { input: { expression: \"12 % 5\" }, output: { result: 2 }, description: \"Modulo operation\" },\n { input: { expression: \"sqrt(16)\" }, output: { result: 4 }, description: \"Square root function\" },\n { input: { expression: \"a + b\", scope: { a: 7, b: 3 } }, output: { result: 10 }, description: \"Expression with variables\" },\n { input: { expression: \"result % 13\", scope: { result: 347 } }, output: { result: 9 }, description: \"Modulo with variable\" },\n { input: { expression: \"sqrt(-4)\" }, output: { result: \"2i\" }, description: \"Square root of negative (complex result)\" },\n { input: { expression: \"pow(i, 2)\" }, output: { result: -1 }, description: \"Complex number calculation (i^2)\" },\n { input: { expression: \"log(10)\" }, output: { result: 2.302585092994046 }, description: \"Natural logarithm\" },\n { input: { expression: \"factorial(5)\" }, output: { result: 120 }, description: \"Factorial function\" },\n { input: { expression: \"ans + 10\" }, output: { result: 130 }, description: \"Using previous result with 'ans'\" },\n { input: { expression: \"mean([1, 2, 3, 4, 5])\" }, output: { result: 3 }, description: \"Statistical function\" },\n // Example of how an error might be represented if a disallowed function were used:\n // { input: { expression: \"factorial(5)\" }, error: \"Failed to evaluate expression: Function factorial is not allowed\" },\n ],\n };\n\n /**\n * Executes the calculator tool by evaluating the provided mathematical expression.\n * It uses a restricted scope including only allowed mathjs functions and any variables\n * passed in the `input.scope`. Handles basic number and complex number results.\n *\n * @param input - An object containing the `expression` (string) and optional `scope` (object). Must match `inputSchema`.\n * @param context - The execution context containing `threadId`, `traceId`, etc.\n * @returns A promise resolving to a `ToolResult` object.\n * On success, `status` is 'success' and `output` is `{ result: number | string }`.\n * On failure, `status` is 'error' and `error` contains the error message.\n */\n async execute(input: any, context: ExecutionContext): Promise<ToolResult> {\n const expression = input.expression as string;\n const threadId = context.threadId || 'default-thread';\n \n // Get previous result for this thread if available\n const previousResult = this.resultStore.get(threadId);\n \n // Combine user scope with allowed functions and previous result. User scope takes precedence if names clash.\n const executionScope = { \n ...allowedFunctions, \n ...(input.scope || {}),\n // Add 'ans' variable referencing the previous result\n ...(previousResult !== undefined ? { ans: previousResult } : {})\n };\n \n const callId = context.traceId || 'calculator-call';\n\n Logger.debug(`CalculatorTool executing with expression: \"${expression}\" and combined scope keys: ${Object.keys(executionScope).join(', ')}`, { callId, context });\n\n try {\n // Use mathjs.evaluate with the restricted scope\n const resultValue = evaluate(expression, executionScope);\n\n let outputResult: number | string;\n\n // Check if the result is a finite number\n if (typeof resultValue === 'number' && Number.isFinite(resultValue)) {\n outputResult = resultValue;\n }\n // Check if the result is a Complex number\n else if (math.isComplex(resultValue)) {\n // Convert complex number to string representation (e.g., \"2 + 3i\")\n outputResult = (resultValue as Complex).toString();\n }\n // Handle other types (like matrices, units, functions returned) as errors for now\n else {\n throw new Error(`Evaluation resulted in an unsupported type: ${math.typeOf(resultValue)}`);\n }\n\n // Store the result for future reference\n this.resultStore.set(threadId, resultValue);\n\n Logger.info(`CalculatorTool evaluated \"${expression}\" to ${outputResult}`, { callId });\n\n return {\n callId: callId,\n toolName: this.schema.name,\n status: 'success',\n output: { result: outputResult }, // Use the processed result\n };\n } catch (error: any) {\n Logger.error(`CalculatorTool failed to evaluate expression \"${expression}\": ${error.message}`, { callId, error });\n // Return the specific error message from mathjs or our validation\n return {\n callId: callId,\n toolName: this.schema.name,\n status: 'error',\n error: `Failed to evaluate expression: ${error.message}`, // More specific error\n };\n }\n }\n}","import { IAuthStrategy } from '@/core/interfaces';\nimport { ARTError, ErrorCode } from '@/errors';\nimport { Logger } from '@/utils/logger';\n\n/**\n * Configuration for the PKCE OAuth 2.0 authentication strategy.\n */\nexport interface PKCEOAuthConfig {\n /** The OAuth 2.0 authorization endpoint URL. */\n authorizationEndpoint: string;\n /** The OAuth 2.0 token endpoint URL. */\n tokenEndpoint: string;\n /** The client ID for the application. */\n clientId: string;\n /** The redirect URI for the application. */\n redirectUri: string;\n /** The scopes to request (space-separated). */\n scopes: string;\n /** Optional: The resource parameter to specify the target audience (for MCP servers). */\n resource?: string;\n /** Open login in a new tab (default true for ART MCP flows). */\n openInNewTab?: boolean;\n /** BroadcastChannel name used to receive auth codes from callback tab (default 'art-auth'). */\n channelName?: string;\n}\n\ninterface CachedToken {\n accessToken: string;\n refreshToken?: string;\n expiresAt: number;\n}\n\n/**\n * Implements the OAuth 2.0 Authorization Code Flow with PKCE (Proof Key for Code Exchange).\n * This is the recommended, most secure method for authenticating users in browser-based applications.\n */\nexport class PKCEOAuthStrategy implements IAuthStrategy {\n private config: PKCEOAuthConfig;\n private cachedToken: CachedToken | null = null;\n private codeVerifierForPendingLogin: string | null = null;\n private loginWaiter: { resolve: () => void; reject: (e: any) => void } | null = null;\n private channel?: BroadcastChannel;\n\n /**\n * Creates an instance of PKCEOAuthStrategy.\n * @param {PKCEOAuthConfig} config - The configuration for the PKCE OAuth 2.0 strategy.\n */\n constructor(config: PKCEOAuthConfig) {\n if (!config.authorizationEndpoint || !config.tokenEndpoint || !config.clientId || !config.redirectUri || !config.scopes) {\n throw new ARTError(\n 'PKCEOAuthStrategy requires authorizationEndpoint, tokenEndpoint, clientId, redirectUri, and scopes.',\n ErrorCode.INVALID_CONFIG,\n );\n }\n this.config = { openInNewTab: true, channelName: 'art-auth', ...config };\n\n // Setup BroadcastChannel to receive auth codes from the callback tab (new-tab flow)\n try {\n this.channel = new BroadcastChannel(this.config.channelName!);\n this.channel.onmessage = async (evt: MessageEvent) => {\n const msg = evt.data || {};\n if (msg?.type === 'art-auth-code' && typeof msg?.code === 'string') {\n try {\n await this.exchangeCodeForToken(msg.code);\n if (this.loginWaiter) this.loginWaiter.resolve();\n } catch (e) {\n if (this.loginWaiter) this.loginWaiter.reject(e);\n } finally {\n this.loginWaiter = null;\n }\n }\n };\n } catch {\n // BroadcastChannel not available; new-tab flow will not work in this environment\n }\n }\n\n /**\n * Initiates the PKCE login flow by redirecting the user to the authorization endpoint.\n * @returns {Promise<void>} A promise that resolves when the login process is complete.\n */\n public async login(): Promise<void> {\n const codeVerifier = this.generateCodeVerifier();\n const codeChallenge = await this.generateCodeChallenge(codeVerifier);\n\n // Store verifier for same-tab fallback and keep in-memory for new-tab token exchange\n sessionStorage.setItem('pkce_code_verifier', codeVerifier);\n this.codeVerifierForPendingLogin = codeVerifier;\n\n const params = new URLSearchParams({\n client_id: this.config.clientId,\n redirect_uri: this.config.redirectUri,\n scope: this.config.scopes,\n response_type: 'code',\n code_challenge: codeChallenge,\n code_challenge_method: 'S256',\n });\n\n if (this.config.resource) {\n params.append('resource', this.config.resource);\n }\n\n // Include a minimal state that carries the BroadcastChannel name for the callback tab\n try {\n const statePayload = { ch: this.config.channelName };\n const state = btoa(unescape(encodeURIComponent(JSON.stringify(statePayload)))).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n params.append('state', state);\n } catch {/* ignore */}\n\n const authorizationUrl = `${this.config.authorizationEndpoint}?${params.toString()}`;\n Logger.info('Starting PKCE login at authorization endpoint.');\n\n if (this.config.openInNewTab) {\n const popup = window.open(authorizationUrl, '_blank', 'noopener,noreferrer');\n if (!popup) {\n throw new ARTError('Popup blocked. Please allow popups to continue login.', ErrorCode.INVALID_CONFIG);\n }\n // Wait for token acquisition via BroadcastChannel\n await new Promise<void>((resolve, reject) => {\n this.loginWaiter = { resolve, reject };\n setTimeout(() => {\n if (this.loginWaiter) {\n this.loginWaiter = null;\n reject(new ARTError('Login timed out. Please try again.', ErrorCode.TIMEOUT));\n }\n }, 180000); // 3 minutes\n });\n return;\n }\n\n // Same-tab redirect fallback (not preferred for ART MCP flows)\n window.location.assign(authorizationUrl);\n }\n\n /**\n * Handles the redirect from the authorization server.\n * This method should be called on the redirect URI page.\n * It exchanges the authorization code for an access token.\n * @returns {Promise<void>} A promise that resolves when the redirect has been handled.\n */\n public async handleRedirect(): Promise<void> {\n const params = new URLSearchParams(window.location.search);\n const code = params.get('code');\n\n if (!code) {\n const error = params.get('error');\n const errorDescription = params.get('error_description');\n throw new ARTError(\n `OAuth error on redirect: ${error} - ${errorDescription || 'No description provided.'}`,\n ErrorCode.EXTERNAL_SERVICE_ERROR,\n );\n }\n\n const codeVerifier = sessionStorage.getItem('pkce_code_verifier');\n if (!codeVerifier) {\n throw new ARTError('No PKCE code verifier found in session storage. Please initiate login again.', ErrorCode.INVALID_CONFIG);\n }\n\n try {\n const tokenResponse = await fetch(this.config.tokenEndpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n grant_type: 'authorization_code',\n client_id: this.config.clientId,\n redirect_uri: this.config.redirectUri,\n code: code,\n code_verifier: codeVerifier,\n }),\n });\n\n if (!tokenResponse.ok) {\n const errorText = await tokenResponse.text();\n throw new ARTError(`Failed to exchange authorization code for token: ${errorText}`, ErrorCode.NETWORK_ERROR);\n }\n\n const tokenData = await tokenResponse.json();\n this.cachedToken = {\n accessToken: tokenData.access_token,\n refreshToken: tokenData.refresh_token,\n expiresAt: Date.now() + (tokenData.expires_in || 3600) * 1000,\n };\n\n Logger.info('Successfully obtained access token.');\n } catch (error) {\n Logger.error('Error during token exchange:', error);\n throw new ARTError('An unexpected error occurred during the token exchange process.', ErrorCode.UNKNOWN_ERROR, error as Error);\n } finally {\n sessionStorage.removeItem('pkce_code_verifier');\n }\n }\n\n /**\n * Gets the authentication headers, automatically handling token refresh if needed.\n * @returns {Promise<Record<string, string>>} A promise that resolves to the authentication headers.\n */\n public async getAuthHeaders(): Promise<Record<string, string>> {\n if (!this.cachedToken) {\n throw new ARTError('No cached token available. Please login first.', ErrorCode.INVALID_CONFIG);\n }\n\n if (Date.now() >= this.cachedToken.expiresAt) {\n Logger.info('Access token expired, attempting to refresh.');\n await this.refreshToken();\n }\n\n return {\n Authorization: `Bearer ${this.cachedToken!.accessToken}`,\n };\n }\n\n /**\n * Clears the cached token.\n */\n public logout(): void {\n this.cachedToken = null;\n sessionStorage.removeItem('pkce_code_verifier');\n Logger.info('Cached token and PKCE code verifier cleared.');\n }\n\n /**\n * Checks if there is a valid, non-expired token.\n * @returns {Promise<boolean>} A promise that resolves to true if the token is valid, false otherwise.\n */\n public async isAuthenticated(): Promise<boolean> {\n if (!this.cachedToken) {\n return false;\n }\n\n if (Date.now() >= this.cachedToken.expiresAt) {\n try {\n await this.refreshToken();\n return true;\n } catch (error) {\n return false;\n }\n }\n\n return true;\n }\n\n // --- Private Helper Methods ---\n\n /**\n * Generates a random string for the code verifier.\n * @returns {string} The generated code verifier.\n */\n private generateCodeVerifier(): string {\n const randomBytes = new Uint8Array(32);\n window.crypto.getRandomValues(randomBytes);\n return this.base64UrlEncode(randomBytes);\n }\n\n /**\n * Generates a code challenge from a code verifier.\n * @param {string} verifier - The code verifier.\n * @returns {Promise<string>} A promise that resolves to the code challenge.\n */\n private async generateCodeChallenge(verifier: string): Promise<string> {\n const encoder = new TextEncoder();\n const data = encoder.encode(verifier);\n const hashBuffer = await window.crypto.subtle.digest('SHA-256', data);\n return this.base64UrlEncode(new Uint8Array(hashBuffer));\n }\n\n /**\n * Encodes a byte array into a base64 URL-safe string.\n * @param {Uint8Array} bytes - The byte array to encode.\n * @returns {string} The base64 URL-safe encoded string.\n */\n private base64UrlEncode(bytes: Uint8Array): string {\n return btoa(String.fromCharCode.apply(null, Array.from(bytes)))\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n }\n\n /**\n * Refreshes the access token using the refresh token.\n * @returns {Promise<void>} A promise that resolves when the token has been refreshed.\n */\n private async refreshToken(): Promise<void> {\n if (!this.cachedToken?.refreshToken) {\n this.logout(); // Clear expired token\n throw new ARTError('No refresh token available. User must re-authenticate.', ErrorCode.INVALID_CONFIG);\n }\n\n try {\n const tokenResponse = await fetch(this.config.tokenEndpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: this.config.clientId,\n refresh_token: this.cachedToken.refreshToken,\n }),\n });\n\n if (!tokenResponse.ok) {\n const errorText = await tokenResponse.text();\n this.logout(); // Clear tokens on failure\n throw new ARTError(`Failed to refresh token: ${errorText}`, ErrorCode.NETWORK_ERROR);\n }\n\n const tokenData = await tokenResponse.json();\n this.cachedToken = {\n accessToken: tokenData.access_token,\n // Keep the same refresh token if a new one isn't provided\n refreshToken: tokenData.refresh_token || this.cachedToken.refreshToken,\n expiresAt: Date.now() + (tokenData.expires_in || 3600) * 1000,\n };\n\n Logger.info('Successfully refreshed access token.');\n } catch (error) {\n this.logout();\n Logger.error('Error during token refresh:', error);\n throw new ARTError('An unexpected error occurred during the token refresh process.', ErrorCode.UNKNOWN_ERROR, error as Error);\n }\n }\n\n // --- Private: Exchange code to token using stored verifier (new-tab flow) ---\n /**\n * Exchanges an authorization code for an access token.\n * @param {string} code - The authorization code.\n * @returns {Promise<void>} A promise that resolves when the token exchange is complete.\n */\n private async exchangeCodeForToken(code: string): Promise<void> {\n if (!this.codeVerifierForPendingLogin) {\n throw new ARTError('Missing code verifier for PKCE exchange.', ErrorCode.INVALID_CONFIG);\n }\n\n const tokenResponse = await fetch(this.config.tokenEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'authorization_code',\n client_id: this.config.clientId,\n redirect_uri: this.config.redirectUri,\n code,\n code_verifier: this.codeVerifierForPendingLogin,\n }),\n });\n\n if (!tokenResponse.ok) {\n const errorText = await tokenResponse.text();\n throw new ARTError(`Failed to exchange authorization code for token: ${errorText}`, ErrorCode.NETWORK_ERROR);\n }\n\n const tokenData = await tokenResponse.json();\n this.cachedToken = {\n accessToken: tokenData.access_token,\n refreshToken: tokenData.refresh_token,\n expiresAt: Date.now() + (tokenData.expires_in || 3600) * 1000,\n };\n\n // Clear pending verifier\n this.codeVerifierForPendingLogin = null;\n sessionStorage.removeItem('pkce_code_verifier');\n }\n}","import { IAuthStrategy } from '@/core/interfaces';\n\n/**\n * Simple API key authentication strategy.\n * Supports configurable header names for different service requirements.\n */\nexport class ApiKeyStrategy implements IAuthStrategy {\n /**\n * Creates a new API key authentication strategy.\n * @param apiKey - The API key to use for authentication\n * @param headerName - The header name to use (defaults to 'Authorization')\n */\n constructor(\n private readonly apiKey: string,\n private readonly headerName: string = 'Authorization'\n ) {\n if (!apiKey || apiKey.trim() === '') {\n throw new Error('API key cannot be empty or null');\n }\n if (!headerName || headerName.trim() === '') {\n throw new Error('Header name cannot be empty or null');\n }\n }\n\n /**\n * Generates authentication headers for API key-based authentication.\n * Uses Bearer token format for Authorization header, plain key for custom headers.\n * @returns Promise resolving to authentication headers\n */\n async getAuthHeaders(): Promise<Record<string, string>> {\n // Use Bearer token format for Authorization header, plain key for custom headers\n const value = this.headerName === 'Authorization' \n ? `Bearer ${this.apiKey}` \n : this.apiKey;\n \n return { [this.headerName]: value };\n }\n\n /**\n * Gets the configured header name for this strategy.\n * @returns The header name that will be used\n */\n public getHeaderName(): string {\n return this.headerName;\n }\n\n /**\n * Checks if this strategy uses the standard Authorization header.\n * @returns True if using Authorization header, false for custom headers\n */\n public isUsingAuthorizationHeader(): boolean {\n return this.headerName === 'Authorization';\n }\n} ","import { IAuthStrategy } from '@/core/interfaces';\nimport { ARTError, ErrorCode } from '@/errors';\nimport { Logger } from '@/utils/logger';\n\n/**\n * Configuration for OAuth 2.0 authentication strategy\n */\nexport interface OAuthConfig {\n /** Client ID for OAuth authentication */\n clientId: string;\n /** Client secret for OAuth authentication */\n clientSecret: string;\n /** OAuth token endpoint URL */\n tokenEndpoint: string;\n /** OAuth scopes to request (space-separated) */\n scopes?: string;\n /** Grant type to use (defaults to 'client_credentials') */\n grantType?: 'client_credentials' | 'authorization_code' | 'refresh_token';\n /** Additional headers to send with token requests */\n tokenRequestHeaders?: Record<string, string>;\n /** Custom timeout for token requests in milliseconds (default: 30000) */\n tokenTimeoutMs?: number;\n /** Buffer time before token expiry to trigger refresh (default: 300000 = 5 minutes) */\n tokenRefreshBufferMs?: number;\n}\n\n/**\n * OAuth token response structure\n */\ninterface TokenResponse {\n access_token: string;\n token_type: string;\n expires_in?: number;\n refresh_token?: string;\n scope?: string;\n}\n\n/**\n * Cached token with expiry information\n */\ninterface CachedToken {\n accessToken: string;\n tokenType: string;\n expiresAt: number; // Unix timestamp\n refreshToken?: string;\n scope?: string;\n}\n\n/**\n * Generic OAuth 2.0 authentication strategy with token caching and refresh capabilities.\n * Supports client credentials flow and authorization code flow with automatic token refresh.\n * @deprecated This strategy is not recommended for browser-based applications as it uses the insecure client_credentials grant type. Please use PKCEOAuthStrategy instead.\n */\nexport class GenericOAuthStrategy implements IAuthStrategy {\n private config: OAuthConfig;\n private cachedToken: CachedToken | null = null;\n private refreshPromise: Promise<CachedToken> | null = null;\n\n /**\n * Creates a new OAuth authentication strategy.\n * @param {OAuthConfig} config - OAuth configuration including endpoints, credentials, and options\n */\n constructor(config: OAuthConfig) {\n this.validateConfig(config);\n this.config = {\n grantType: 'client_credentials',\n tokenTimeoutMs: 30000,\n tokenRefreshBufferMs: 300000, // 5 minutes\n ...config\n };\n \n Logger.debug(`GenericOAuthStrategy: Initialized with endpoint ${config.tokenEndpoint} and grant type ${this.config.grantType}`);\n }\n\n /**\n * Validates the OAuth configuration to ensure required fields are present.\n * @param {OAuthConfig} config - The OAuth configuration to validate.\n * @throws {ARTError} If the configuration is invalid.\n */\n private validateConfig(config: OAuthConfig): void {\n if (!config.clientId || config.clientId.trim() === '') {\n throw new ARTError('OAuth client ID cannot be empty', ErrorCode.VALIDATION_ERROR);\n }\n if (!config.clientSecret || config.clientSecret.trim() === '') {\n throw new ARTError('OAuth client secret cannot be empty', ErrorCode.VALIDATION_ERROR);\n }\n if (!config.tokenEndpoint || config.tokenEndpoint.trim() === '') {\n throw new ARTError('OAuth token endpoint cannot be empty', ErrorCode.VALIDATION_ERROR);\n }\n \n // Validate URL format\n try {\n new URL(config.tokenEndpoint);\n } catch (error) {\n throw new ARTError('Invalid OAuth token endpoint URL', ErrorCode.VALIDATION_ERROR, error instanceof Error ? error : new Error(String(error)));\n }\n }\n\n /**\n * Gets authentication headers, automatically handling token refresh if needed.\n * @returns {Promise<Record<string, string>>} A promise that resolves to the authentication headers.\n */\n async getAuthHeaders(): Promise<Record<string, string>> {\n try {\n const token = await this.getValidToken();\n return {\n 'Authorization': `${token.tokenType} ${token.accessToken}`\n };\n } catch (error) {\n const message = 'Failed to get OAuth authentication headers';\n Logger.error(message, error);\n throw new ARTError(message, ErrorCode.LLM_PROVIDER_ERROR, error instanceof Error ? error : new Error(String(error)));\n }\n }\n\n /**\n * Gets a valid access token, refreshing if necessary.\n * @returns {Promise<CachedToken>} A promise that resolves to a valid cached token.\n */\n private async getValidToken(): Promise<CachedToken> {\n // Check if we have a valid cached token\n if (this.cachedToken && this.isTokenValid(this.cachedToken)) {\n Logger.debug('GenericOAuthStrategy: Using cached token');\n return this.cachedToken;\n }\n\n // If a refresh is already in progress, wait for it\n if (this.refreshPromise) {\n Logger.debug('GenericOAuthStrategy: Waiting for ongoing token refresh');\n return await this.refreshPromise;\n }\n\n // Start new token acquisition\n this.refreshPromise = this.acquireNewToken();\n \n try {\n const token = await this.refreshPromise;\n this.cachedToken = token;\n return token;\n } finally {\n this.refreshPromise = null;\n }\n }\n\n /**\n * Checks if a token is still valid (not expired with buffer).\n * @param {CachedToken} token - The token to validate.\n * @returns {boolean} True if the token is valid, false otherwise.\n */\n private isTokenValid(token: CachedToken): boolean {\n const now = Date.now();\n const buffer = this.config.tokenRefreshBufferMs!;\n return token.expiresAt > (now + buffer);\n }\n\n /**\n * Acquires a new token from the OAuth provider.\n * @returns {Promise<CachedToken>} A promise that resolves to a new cached token.\n */\n private async acquireNewToken(): Promise<CachedToken> {\n Logger.debug(`GenericOAuthStrategy: Acquiring new token from ${this.config.tokenEndpoint}`);\n\n const tokenRequest = this.buildTokenRequest();\n \n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.config.tokenTimeoutMs!);\n\n const response = await fetch(this.config.tokenEndpoint, {\n ...tokenRequest,\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => 'Unknown error');\n throw new ARTError(\n `OAuth token request failed: ${response.status} ${response.statusText}: ${errorText}`,\n ErrorCode.EXTERNAL_SERVICE_ERROR\n );\n }\n\n const tokenResponse: TokenResponse = await response.json();\n return this.processTokenResponse(tokenResponse);\n\n } catch (error) {\n if (error instanceof ARTError) {\n throw error;\n }\n \n const message = `Failed to acquire OAuth token: ${error instanceof Error ? error.message : String(error)}`;\n Logger.error(message, error);\n throw new ARTError(message, ErrorCode.EXTERNAL_SERVICE_ERROR, error instanceof Error ? error : new Error(String(error)));\n }\n }\n\n /**\n * Builds the token request configuration based on grant type.\n * @returns {RequestInit} The request initialization object for the token request.\n */\n private buildTokenRequest(): RequestInit {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Accept': 'application/json',\n ...this.config.tokenRequestHeaders\n };\n\n let body: string;\n \n if (this.config.grantType === 'client_credentials') {\n const params = new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: this.config.clientId,\n client_secret: this.config.clientSecret\n });\n \n if (this.config.scopes) {\n params.append('scope', this.config.scopes);\n }\n \n body = params.toString();\n } else if (this.config.grantType === 'refresh_token' && this.cachedToken?.refreshToken) {\n const params = new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: this.cachedToken.refreshToken,\n client_id: this.config.clientId,\n client_secret: this.config.clientSecret\n });\n \n body = params.toString();\n } else {\n throw new ARTError(`Unsupported grant type: ${this.config.grantType}`, ErrorCode.NOT_IMPLEMENTED);\n }\n\n return {\n method: 'POST',\n headers,\n body\n };\n }\n\n /**\n * Processes the token response and creates a cached token object.\n * @param {TokenResponse} response - The token response from the provider.\n * @returns {CachedToken} The processed and cached token.\n */\n private processTokenResponse(response: TokenResponse): CachedToken {\n if (!response.access_token) {\n throw new ARTError('OAuth token response missing access_token', ErrorCode.EXTERNAL_SERVICE_ERROR);\n }\n\n const now = Date.now();\n const expiresIn = response.expires_in || 3600; // Default to 1 hour if not specified\n const expiresAt = now + (expiresIn * 1000);\n\n const cachedToken: CachedToken = {\n accessToken: response.access_token,\n tokenType: response.token_type || 'Bearer',\n expiresAt,\n refreshToken: response.refresh_token,\n scope: response.scope\n };\n\n Logger.debug(`GenericOAuthStrategy: Token acquired, expires at ${new Date(expiresAt).toISOString()}`);\n return cachedToken;\n }\n\n /**\n * Manually refreshes the cached token.\n * @returns {Promise<Record<string, string>>} A promise that resolves to new authentication headers.\n */\n public async refreshToken(): Promise<Record<string, string>> {\n Logger.debug('GenericOAuthStrategy: Manual token refresh requested');\n this.cachedToken = null; // Force refresh\n this.refreshPromise = null;\n return await this.getAuthHeaders();\n }\n\n /**\n * Clears the cached token, forcing a new token request on next use.\n */\n public clearTokenCache(): void {\n Logger.debug('GenericOAuthStrategy: Clearing token cache');\n this.cachedToken = null;\n this.refreshPromise = null;\n }\n\n /**\n * Gets information about the current cached token.\n * @returns {{ expiresAt: Date; scope?: string; hasRefreshToken: boolean } | null} Token information or null if no token is cached.\n */\n public getTokenInfo(): { expiresAt: Date; scope?: string; hasRefreshToken: boolean } | null {\n if (!this.cachedToken) {\n return null;\n }\n\n return {\n expiresAt: new Date(this.cachedToken.expiresAt),\n scope: this.cachedToken.scope,\n hasRefreshToken: !!this.cachedToken.refreshToken\n };\n }\n\n /**\n * Gets the configured OAuth endpoints and settings.\n * @returns {Omit<OAuthConfig, 'clientSecret'>} Configuration information (excluding sensitive data).\n */\n public getConfig(): Omit<OAuthConfig, 'clientSecret'> {\n return {\n clientId: this.config.clientId,\n tokenEndpoint: this.config.tokenEndpoint,\n scopes: this.config.scopes,\n grantType: this.config.grantType,\n tokenRequestHeaders: this.config.tokenRequestHeaders,\n tokenTimeoutMs: this.config.tokenTimeoutMs,\n tokenRefreshBufferMs: this.config.tokenRefreshBufferMs\n };\n }\n} ","import { GenericOAuthStrategy, type OAuthConfig } from '@/auth/GenericOAuthStrategy';\nimport { Logger } from '@/utils/logger';\n\n/**\n * Configuration specific to Zyntopia OAuth strategy\n */\nexport interface ZyntopiaOAuthConfig {\n /** Client ID for Zyntopia OAuth authentication */\n clientId: string;\n /** Client secret for Zyntopia OAuth authentication */\n clientSecret: string;\n /** Optional custom token endpoint (defaults to Zyntopia's standard endpoint) */\n tokenEndpoint?: string;\n /** Optional custom scopes (defaults to Zyntopia's standard scopes) */\n scopes?: string;\n /** Optional environment ('production' | 'staging' | 'development') */\n environment?: 'production' | 'staging' | 'development';\n /** Optional custom timeout for token requests in milliseconds */\n tokenTimeoutMs?: number;\n /** Optional custom buffer time before token expiry to trigger refresh */\n tokenRefreshBufferMs?: number;\n /** Additional custom headers for Zyntopia API requirements */\n customHeaders?: Record<string, string>;\n}\n\n/**\n * Zyntopia-specific OAuth 2.0 authentication strategy.\n * Pre-configured for Zyntopia services with standard endpoints, scopes, and authentication flows.\n * Extends GenericOAuthStrategy with Zyntopia-specific defaults and configurations.\n */\nexport class ZyntopiaOAuthStrategy extends GenericOAuthStrategy {\n private static readonly ZYNTOPIA_ENDPOINTS = {\n production: 'https://auth.zyntopia.com/oauth/token',\n staging: 'https://staging-auth.zyntopia.com/oauth/token',\n development: 'https://dev-auth.zyntopia.com/oauth/token'\n };\n\n private static readonly ZYNTOPIA_DEFAULT_SCOPES = {\n production: 'zyntopia:read zyntopia:write zyntopia:admin',\n staging: 'zyntopia:read zyntopia:write zyntopia:admin zyntopia:debug',\n development: 'zyntopia:read zyntopia:write zyntopia:admin zyntopia:debug zyntopia:test'\n };\n\n private zyntopiaConfig: Required<ZyntopiaOAuthConfig>;\n\n /**\n * Creates a new Zyntopia OAuth authentication strategy.\n * @param {ZyntopiaOAuthConfig} config - Zyntopia-specific OAuth configuration\n */\n constructor(config: ZyntopiaOAuthConfig) {\n // Set defaults for Zyntopia\n const environment = config.environment || 'production';\n const defaultTokenEndpoint = ZyntopiaOAuthStrategy.ZYNTOPIA_ENDPOINTS[environment];\n const defaultScopes = ZyntopiaOAuthStrategy.ZYNTOPIA_DEFAULT_SCOPES[environment];\n\n // Build the complete configuration with Zyntopia defaults\n const zyntopiaConfig: Required<ZyntopiaOAuthConfig> = {\n clientId: config.clientId,\n clientSecret: config.clientSecret,\n tokenEndpoint: config.tokenEndpoint || defaultTokenEndpoint,\n scopes: config.scopes || defaultScopes,\n environment,\n tokenTimeoutMs: config.tokenTimeoutMs || 30000,\n tokenRefreshBufferMs: config.tokenRefreshBufferMs || 300000, // 5 minutes\n customHeaders: config.customHeaders || {}\n };\n\n // Create the generic OAuth config with Zyntopia-specific settings\n const genericConfig: OAuthConfig = {\n clientId: zyntopiaConfig.clientId,\n clientSecret: zyntopiaConfig.clientSecret,\n tokenEndpoint: zyntopiaConfig.tokenEndpoint,\n scopes: zyntopiaConfig.scopes,\n grantType: 'client_credentials', // Zyntopia uses client credentials flow\n tokenTimeoutMs: zyntopiaConfig.tokenTimeoutMs,\n tokenRefreshBufferMs: zyntopiaConfig.tokenRefreshBufferMs,\n tokenRequestHeaders: {\n 'User-Agent': 'ART-Framework-Zyntopia/1.0',\n 'X-Zyntopia-Client': 'art-framework',\n 'X-Zyntopia-Environment': environment,\n ...zyntopiaConfig.customHeaders\n }\n };\n\n // Initialize the parent GenericOAuthStrategy\n super(genericConfig);\n\n this.zyntopiaConfig = zyntopiaConfig;\n\n Logger.debug(`ZyntopiaOAuthStrategy: Initialized for ${environment} environment with endpoint ${zyntopiaConfig.tokenEndpoint}`);\n }\n\n /**\n * Gets the Zyntopia-specific configuration.\n * @returns {Omit<ZyntopiaOAuthConfig, 'clientSecret'>} Zyntopia configuration (excluding sensitive data).\n */\n public getZyntopiaConfig(): Omit<ZyntopiaOAuthConfig, 'clientSecret'> {\n return {\n clientId: this.zyntopiaConfig.clientId,\n tokenEndpoint: this.zyntopiaConfig.tokenEndpoint,\n scopes: this.zyntopiaConfig.scopes,\n environment: this.zyntopiaConfig.environment,\n tokenTimeoutMs: this.zyntopiaConfig.tokenTimeoutMs,\n tokenRefreshBufferMs: this.zyntopiaConfig.tokenRefreshBufferMs,\n customHeaders: this.zyntopiaConfig.customHeaders\n };\n }\n\n /**\n * Gets the current environment this strategy is configured for.\n * @returns {'production' | 'staging' | 'development'} The environment ('production', 'staging', or 'development').\n */\n public getEnvironment(): 'production' | 'staging' | 'development' {\n return this.zyntopiaConfig.environment;\n }\n\n /**\n * Checks if this strategy is configured for production environment.\n * @returns {boolean} True if configured for production, false otherwise.\n */\n public isProduction(): boolean {\n return this.zyntopiaConfig.environment === 'production';\n }\n\n /**\n * Checks if this strategy is configured for development/testing.\n * @returns {boolean} True if configured for development or staging, false for production.\n */\n public isDevelopment(): boolean {\n return this.zyntopiaConfig.environment !== 'production';\n }\n\n /**\n * Creates a ZyntopiaOAuthStrategy instance pre-configured for production.\n * @param {string} clientId - Zyntopia client ID\n * @param {string} clientSecret - Zyntopia client secret\n * @param {string} [customScopes] - Optional custom scopes (defaults to production scopes)\n * @returns {ZyntopiaOAuthStrategy} Configured ZyntopiaOAuthStrategy for production.\n */\n public static forProduction(\n clientId: string, \n clientSecret: string, \n customScopes?: string\n ): ZyntopiaOAuthStrategy {\n return new ZyntopiaOAuthStrategy({\n clientId,\n clientSecret,\n environment: 'production',\n scopes: customScopes\n });\n }\n\n /**\n * Creates a ZyntopiaOAuthStrategy instance pre-configured for staging.\n * @param {string} clientId - Zyntopia client ID\n * @param {string} clientSecret - Zyntopia client secret\n * @param {string} [customScopes] - Optional custom scopes (defaults to staging scopes)\n * @returns {ZyntopiaOAuthStrategy} Configured ZyntopiaOAuthStrategy for staging.\n */\n public static forStaging(\n clientId: string, \n clientSecret: string, \n customScopes?: string\n ): ZyntopiaOAuthStrategy {\n return new ZyntopiaOAuthStrategy({\n clientId,\n clientSecret,\n environment: 'staging',\n scopes: customScopes\n });\n }\n\n /**\n * Creates a ZyntopiaOAuthStrategy instance pre-configured for development.\n * @param {string} clientId - Zyntopia client ID\n * @param {string} clientSecret - Zyntopia client secret\n * @param {string} [customScopes] - Optional custom scopes (defaults to development scopes)\n * @returns {ZyntopiaOAuthStrategy} Configured ZyntopiaOAuthStrategy for development.\n */\n public static forDevelopment(\n clientId: string, \n clientSecret: string, \n customScopes?: string\n ): ZyntopiaOAuthStrategy {\n return new ZyntopiaOAuthStrategy({\n clientId,\n clientSecret,\n environment: 'development',\n scopes: customScopes\n });\n }\n\n /**\n * Gets the default scopes for a specific environment.\n * @param {'production' | 'staging' | 'development'} environment - The environment to get scopes for\n * @returns {string} Default scopes for the specified environment.\n */\n public static getDefaultScopes(environment: 'production' | 'staging' | 'development'): string {\n return ZyntopiaOAuthStrategy.ZYNTOPIA_DEFAULT_SCOPES[environment];\n }\n\n /**\n * Gets the token endpoint for a specific environment.\n * @param {'production' | 'staging' | 'development'} environment - The environment to get endpoint for\n * @returns {string} Token endpoint URL for the specified environment.\n */\n public static getTokenEndpoint(environment: 'production' | 'staging' | 'development'): string {\n return ZyntopiaOAuthStrategy.ZYNTOPIA_ENDPOINTS[environment];\n }\n\n /**\n * Validates Zyntopia-specific configuration requirements.\n * @param {ZyntopiaOAuthConfig} config - Configuration to validate\n * @throws {Error} If configuration is invalid.\n */\n public static validateZyntopiaConfig(config: ZyntopiaOAuthConfig): void {\n if (!config.clientId || config.clientId.trim() === '') {\n throw new Error('Zyntopia client ID is required');\n }\n if (!config.clientSecret || config.clientSecret.trim() === '') {\n throw new Error('Zyntopia client secret is required');\n }\n if (config.environment && !['production', 'staging', 'development'].includes(config.environment)) {\n throw new Error('Zyntopia environment must be one of: production, staging, development');\n }\n if (config.tokenTimeoutMs && (config.tokenTimeoutMs < 1000 || config.tokenTimeoutMs > 60000)) {\n throw new Error('Zyntopia token timeout must be between 1000ms and 60000ms');\n }\n if (config.tokenRefreshBufferMs && (config.tokenRefreshBufferMs < 30000 || config.tokenRefreshBufferMs > 600000)) {\n throw new Error('Zyntopia token refresh buffer must be between 30000ms and 600000ms');\n }\n }\n} ","/**\n * ART (Agentic Reasoning & Tool-use) Framework - Main Entry Point\n * -----------------------------------------------------------------\n *\n * Welcome to the ART framework! This file is the primary public API surface for the library.\n * It's structured to provide a clear and intuitive experience for developers,\n * whether you're just getting started or building advanced, custom agentic systems.\n *\n * --- Quick Start ---\n * For most use cases, you'll only need `createArtInstance` and the associated types.\n *\n * Example:\n * ```ts\n * import { createArtInstance } from 'art-framework';\n * import type { ArtInstanceConfig } from 'art-framework';\n *\n * const config: ArtInstanceConfig = {\n * storage: { type: 'memory' },\n * providers: {\n * openai: { adapter: 'openai', apiKey: '...' }\n * },\n * tools: [new CalculatorTool()],\n * persona: {\n * name: 'MyAgent',\n * prompts: {\n * synthesis: 'You are MyAgent. Always answer in rhyme.'\n * }\n * }\n * };\n *\n * const art = await createArtInstance(config);\n * const response = await art.process({ query: \"Hello, world!\" });\n * ```\n *\n * --- API Structure ---\n * 1. **Core Factory**: The main function to create an ART instance.\n * 2. **Primary Interfaces & Types**: Essential types for configuration and interaction.\n * 3. **Built-in Components**: Concrete implementations of adapters, tools, and agents.\n * 4. **Advanced Systems & Managers**: Lower-level components for building custom logic.\n * 5. **Utilities**: Helper functions and classes.\n *\n * @module ART\n */\n\n// --- 1. Core Factory ---\n\n/**\n * The main factory function to create and initialize a complete ART framework instance.\n * This is the recommended starting point for all users. It simplifies setup by\n * assembling all necessary components based on the provided configuration.\n * @param {ArtInstanceConfig} config - The configuration object for the ART instance.\n * @returns {Promise<ArtInstance>} A promise that resolves to a ready-to-use ART instance.\n * @see {@link ArtInstanceConfig} for configuration options.\n */\nexport { createArtInstance, AgentFactory } from '@/core/agent-factory';\n\n// --- 2. Primary Interfaces & Types ---\n\n/**\n * Core interfaces that define the contracts for key components of the ART framework.\n * Use these to build your own custom components (e.g., agents, tools, storage adapters).\n */\nexport * from '@/core/interfaces';\n\n/**\n * Core data structures, enums, and type definitions used throughout the framework.\n * This includes types for messages, observations, agent state, and more.\n */\nexport * from '@/types';\n\n/**\n * The main configuration object for creating an ART instance.\n * Explicitly exported for clarity and ease of use.\n */\nexport type { ArtInstanceConfig, AgentPersona } from '@/types';\n\n/**\n * Types related to LLM Provider management.\n * Useful for advanced scenarios, such as dynamically configuring providers at runtime.\n */\nexport type {\n ProviderManagerConfig,\n AvailableProviderEntry,\n RuntimeProviderConfig,\n ManagedAdapterAccessor,\n IProviderManager,\n} from '@/types/providers';\n\n// --- 3. Built-in Components ---\n\n// --- Agent Implementations ---\n\n/**\n * The default agent core implementation based on the Plan-Execute-Synthesize model.\n * It's suitable for a wide range of general-purpose tasks.\n * When to use: As the default reasoning engine unless you have a specific need for a different agent architecture.\n */\nexport { PESAgent } from '@/core/agents/pes-agent';\n\n// --- Storage Adapters ---\n\n/**\n * A non-persistent storage adapter that keeps all data in memory.\n * When to use: Ideal for testing, short-lived scripts, or scenarios\n * where data persistence across sessions is not required.\n */\nexport { InMemoryStorageAdapter } from '@/integrations/storage/inMemory';\n\n/**\n * A persistent storage adapter that uses the browser's IndexedDB.\n * When to use: The recommended choice for web-based applications to persist\n * conversation history and agent state on the client-side.\n */\nexport { IndexedDBStorageAdapter } from '@/integrations/storage/indexedDB';\n\n/**\n * A persistent storage adapter for connecting to a Supabase (Postgres) database.\n * When to use: Suitable for server-side environments, or for applications\n * requiring data to be shared or persisted in the cloud.\n */\nexport { SupabaseStorageAdapter } from '@/integrations/storage/supabase';\n\n// --- Reasoning Provider Adapters ---\n\n/**\n * Adapter for Google's Gemini models.\n */\nexport { GeminiAdapter } from '@/integrations/reasoning/gemini';\nexport type { GeminiAdapterOptions } from '@/integrations/reasoning/gemini';\n\n/**\n * Adapter for OpenAI's models (e.g., GPT-3.5, GPT-4).\n */\nexport { OpenAIAdapter } from '@/integrations/reasoning/openai';\nexport type { OpenAIAdapterOptions } from '@/integrations/reasoning/openai';\n\n/**\n * Adapter for Anthropic's Claude models.\n */\nexport { AnthropicAdapter } from '@/integrations/reasoning/anthropic';\nexport type { AnthropicAdapterOptions } from '@/integrations/reasoning/anthropic';\n\n/**\n * Adapter for OpenRouter, which acts as a proxy to a wide variety of models.\n */\nexport { OpenRouterAdapter } from '@/integrations/reasoning/openrouter';\nexport type { OpenRouterAdapterOptions } from '@/integrations/reasoning/openrouter';\n\n/**\n * Adapter for DeepSeek models.\n */\nexport { DeepSeekAdapter } from '@/integrations/reasoning/deepseek';\nexport type { DeepSeekAdapterOptions } from '@/integrations/reasoning/deepseek';\n\n/**\n * Adapter for running local LLMs through the Ollama service.\n */\nexport { OllamaAdapter } from '@/integrations/reasoning/ollama';\nexport type { OllamaAdapterOptions } from '@/integrations/reasoning/ollama';\n\n// --- Built-in Tools ---\n\n/**\n * A basic tool that allows the agent to evaluate mathematical expressions.\n */\nexport { CalculatorTool } from '@/tools/CalculatorTool';\n\n// --- 4. Advanced Systems & Managers ---\n// For developers who need to directly interact with or extend ART's internal systems.\n\n// --- UI & Sockets ---\n/**\n * Provides a real-time connection to an agent's conversation history.\n * When to use: For building custom UI components that display the back-and-forth\n * interaction between a user and the agent.\n */\nexport { ConversationSocket } from '@/systems/ui/conversation-socket';\n\n/**\n * Provides a real-time stream of agent observations (e.g., tool calls, state changes).\n * When to use: For building developer tools, debug panels, or UIs that visualize\n * the agent's internal thought process.\n */\nexport { ObservationSocket } from '@/systems/ui/observation-socket';\nexport type { StreamEventTypeFilter } from '@/systems/ui/llm-stream-socket';\n/**\n * Provides a real-time stream of raw token output from the LLM as it's generated.\n * When to use: For building UIs with a typewriter effect and fine-grained stream control.\n */\nexport { LLMStreamSocket } from '@/systems/ui/llm-stream-socket';\n/**\n * Provides real-time updates for A2A task lifecycle events.\n * When to use: For dashboards/monitors tracking delegated task progress.\n */\nexport { A2ATaskSocket } from '@/systems/ui/a2a-task-socket';\n/**\n * Facade providing access to all UI sockets.\n */\nexport { UISystem } from '@/systems/ui/ui-system';\n\n// --- Authentication ---\n/**\n * Manages authentication strategies and token lifecycle for external services.\n * When to use: When your tools or providers require secure authentication (e.g., OAuth2).\n * You can register different strategies with this manager.\n */\nexport { AuthManager } from '@/systems/auth/AuthManager';\n\n/**\n * An implementation of the PKCE (Proof Key for Code Exchange) OAuth2 flow.\n * When to use: As a strategy in the `AuthManager` for services that support\n * the PKCE flow, common in public clients and SPAs.\n */\nexport { PKCEOAuthStrategy } from '@/auth/PKCEOAuthStrategy';\nexport type { PKCEOAuthConfig } from '@/auth/PKCEOAuthStrategy';\n/**\n * Simple API key authentication strategy and generic OAuth strategy variants.\n */\nexport { ApiKeyStrategy } from '@/auth/ApiKeyStrategy';\nexport { GenericOAuthStrategy } from '@/auth/GenericOAuthStrategy';\nexport type { OAuthConfig } from '@/auth/GenericOAuthStrategy';\nexport { ZyntopiaOAuthStrategy } from '@/auth/ZyntopiaOAuthStrategy';\nexport type { ZyntopiaOAuthConfig } from '@/auth/ZyntopiaOAuthStrategy';\n\n// --- MCP (Model Context Protocol) ---\n/**\n * The core manager for handling connections to MCP servers.\n * When to use: When integrating ART with an MCP server to dynamically load tools and resources.\n */\nexport { McpManager } from '@/systems/mcp';\nexport type { McpManagerConfig } from '@/systems/mcp/types';\n\n/**\n * A special tool that acts as a proxy for all tools provided by an MCP server.\n * When to use: This is typically registered automatically when MCP is configured,\n * but can be used manually for advanced MCP integrations.\n */\nexport { McpProxyTool } from '@/systems/mcp';\n\n/**\n * Client controller for making direct requests to an MCP server.\n * When to use: If you need to interact with an MCP server's resources outside\n * of the standard agent tool-use loop.\n */\nexport { McpClientController } from '@/systems/mcp';\nexport type {\n McpServerConfig,\n McpToolDefinition,\n McpResource,\n McpResourceTemplate,\n McpServerStatus,\n} from '@/systems/mcp/types';\n\n// --- A2A (Agent-to-Agent Communication) ---\n/**\n * Service for discovering other agents available on an A2A network.\n * When to use: When building collaborative agent systems where one agent\n * needs to find and delegate tasks to another.\n */\nexport { AgentDiscoveryService } from '@/systems/a2a/AgentDiscoveryService';\nexport type { AgentDiscoveryConfig } from '@/systems/a2a/AgentDiscoveryService';\n\n/**\n * Service for delegating tasks to other agents and monitoring their status.\n * When to use: After discovering an agent, use this service to assign it a task\n * and receive updates on its progress.\n */\nexport { TaskDelegationService } from '@/systems/a2a/TaskDelegationService';\nexport type { TaskDelegationConfig, TaskStatusResponse } from '@/systems/a2a/TaskDelegationService';\nexport type { A2ATaskEvent, A2ATaskFilter } from '@/systems/ui/a2a-task-socket';\n\n\n// --- 5. Utilities ---\n\n// --- Managers & Registries (advanced) ---\n/**\n * State manager for thread config/state with explicit/implicit save strategies.\n */\nexport { StateManager } from '@/systems/context/managers/StateManager';\n/**\n * In-memory tool registry for registering and querying tool executors.\n */\nexport { ToolRegistry } from '@/systems/tool/ToolRegistry';\n/**\n * Provider manager implementation controlling adapter lifecycles and concurrency.\n */\nexport { ProviderManagerImpl } from '@/systems/reasoning/ProviderManagerImpl';\n\n/**\n * A simple logging utility with configurable levels.\n * When to use: For adding consistent logging throughout your custom components.\n * An instance is available on `ArtInstance.logger`.\n */\nexport { Logger, LogLevel } from '@/utils/logger';\nexport type { LoggerConfig } from '@/utils/logger';\n\n/**\n * A function to generate RFC4122 v4 compliant UUIDs.\n * When to use: For creating unique identifiers for threads, messages, or other entities.\n */\nexport { generateUUID } from '@/utils/uuid';\n\n// --- Framework Version ---\n/**\n * The current version of the ART Framework package.\n */\nexport const VERSION = '0.3.8';"]}
|