art-framework 0.2.4
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 +0 -0
- package/dist/index.cjs +47 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +937 -0
- package/dist/index.d.ts +937 -0
- package/dist/index.js +47 -0
- package/dist/index.js.map +1 -0
- package/package.json +71 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/types/index.ts","../src/utils/uuid.ts","../src/errors.ts","../src/core/agents/pes-agent.ts","../src/adapters/storage/inMemory.ts","../src/adapters/storage/indexedDB.ts","../src/systems/context/repositories/ConversationRepository.ts","../src/systems/context/repositories/ObservationRepository.ts","../src/systems/context/repositories/StateRepository.ts","../src/systems/context/managers/ConversationManager.ts","../src/systems/context/managers/StateManager.ts","../src/systems/observation/observation-manager.ts","../src/utils/logger.ts","../src/systems/tool/ToolRegistry.ts","../src/utils/validation.ts","../src/systems/tool/ToolSystem.ts","../src/systems/reasoning/PromptManager.ts","../src/systems/reasoning/ReasoningEngine.ts","../src/systems/reasoning/OutputParser.ts","../src/adapters/reasoning/openai.ts","../src/adapters/reasoning/gemini.ts","../src/adapters/reasoning/anthropic.ts","../src/adapters/reasoning/openrouter.ts","../src/adapters/reasoning/deepseek.ts","../src/systems/ui/typed-socket.ts","../src/systems/ui/observation-socket.ts","../src/systems/ui/conversation-socket.ts","../src/systems/ui/ui-system.ts","../src/core/agent-factory.ts","../src/tools/CalculatorTool.ts","../src/index.ts"],"names":["MessageRole","ObservationType","generateUUID","uuidv4","ARTError","_ARTError","message","code","originalError","str","PESAgent","dependencies","props","startTime","traceId","status","errorMessage","llmCalls","toolCallsCount","finalAiMessage","threadContext","systemPrompt","historyOptions","history","availableTools","planningPrompt","planningOptions","thought","err","planningOutputText","parsedPlanningOutput","toolResults","r","synthesisPrompt","synthesisOptions","finalResponseContent","synthesisOutputText","synthesisErrorMessage","finalTimestamp","error","saveError","endTime","metadata","InMemoryStorageAdapter","_config","collection","id","collectionMap","item","data","filterOptions","results","key","DEFAULT_DB_NAME","DEFAULT_DB_VERSION","IndexedDBStorageAdapter","config","resolve","reject","request","event","existingStores","missingStores","store","errorEvent","existingStoreNames","storeName","mode","sName","dataAsAny","dataToStore","transaction","sortKey","sortDir","a","b","valA","valB","skip","limit","storeNames","clearCount","totalStores","ConversationRepository","storageAdapter","threadId","messages","setPromises","messageToStore","options","filteredMessages","m","_id","rest","ObservationRepository","observation","filter","filteredObservations","typeSet","obs","StateRepository","storedContext","context","contextToStore","currentContext","newContext","state","ConversationManager","conversationRepository","conversationSocket","StateManager","stateRepository","_userId","toolName","ObservationManager","observationRepository","observationSocket","observationData","LogLevel","Logger","_Logger","args","ToolRegistry","executor","schemas","ajv","Ajv","compiledValidators","validateJsonSchema","schema","schemaKey","validate","ToolSystem","toolRegistry","stateManager","observationManager","toolCalls","call","result","callId","validationResult","errorMessages","e","executionContext","simpleTemplate","template","match","PromptManager","query","_threadContext","historyString","msg","toolsString","tool","promptData","intent","plan","toolResultsString","output","ReasoningEngine","adapter","prompt","parsedToolCallSchema","toolCallsSchema","OutputParser","intentMatch","planMatch","toolCallsMatch","toolCallsString","jsonArrayString","parsedJson","jsonRegex","jsonMatch","cleanedJsonString","OpenAIAdapter","apiUrl","payload","response","errorBody","responseContent","GeminiAdapter","responseText","part","AnthropicAdapter","maxTokens","K","parsedError","c","OpenRouterAdapter","stopSequences","headers","DeepSeekAdapter","TypedSocket","callback","subscription","filterCheck","sub","_filter","_options","ObservationSocket","observationFilter","ConversationSocket","messageOptions","UISystem","AgentFactory","reasoningConfig","AgentCoreImplementation","createArtInstance","factory","agentCore","uiSystem","conversationManager","allowedFunctions","CalculatorTool","_CalculatorTool","input","expression","executionScope","resultValue","evaluate","outputResult","VERSION"],"mappings":"uHAKYA,IAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACVA,EAAA,IAAO,CAAA,MAAA,CACPA,EAAA,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,CAAA9E,CAAQ,CAAA,OAAA,CAAArC,CAAQ,CACpB,CAAA,CAEA,GAAI,CAEF,IAAMoH,CAAcC,CAAAA,QAAAA,CAASH,CAAYC,CAAAA,CAAc,EAEnDG,CAGJ,CAAA,GAAI,OAAOF,CAAAA,EAAgB,UAAY,MAAO,CAAA,QAAA,CAASA,CAAW,CAAA,CAChEE,EAAeF,CAGH,CAAA,KAAA,GAAA,CAAA,CAAA,SAAA,CAAUA,CAAW,CAAA,CAEjCE,EAAgBF,CAAwB,CAAA,QAAA,EAIxC,CAAA,KAAA,MAAM,IAAI,KAAA,CAAM,CAAoD,4CAAA,EAAA,CAAA,CAAA,MAAA,CAAOA,CAAW,CAAC,CAAA,CAAE,CAG3F,CAAA,OAAAnG,EAAO,IAAK,CAAA,CAAA,0BAAA,EAA6BiG,CAAU,CAAA,KAAA,EAAQI,CAAY,CAAI,CAAA,CAAA,CAAE,MAAAjF,CAAAA,CAAO,CAAC,CAE9E,CAAA,CACL,MAAQA,CAAAA,CAAAA,CACR,SAAU,IAAK,CAAA,MAAA,CAAO,IACtB,CAAA,MAAA,CAAQ,UACR,MAAQ,CAAA,CAAE,MAAQiF,CAAAA,CAAa,CACjC,CACF,CAAA,MAASrL,CAAY,CAAA,CACnB,OAAAgF,CAAAA,CAAO,KACL,CAAA,CAAA,8CAAA,EAAiDiG,CAAU,CAAMjL,GAAAA,EAAAA,CAAAA,CAAM,OAAO,CAAA,CAAA,CAC9E,CAAE,MAAAoG,CAAAA,CAAAA,CAAQ,KAAApG,CAAAA,CAAM,CAClB,CAEO,CAAA,CACL,MAAQoG,CAAAA,CAAAA,CACR,SAAU,IAAK,CAAA,MAAA,CAAO,IACtB,CAAA,MAAA,CAAQ,QACR,KAAO,CAAA,CAAA,+BAAA,EAAkCpG,CAAM,CAAA,OAAO,EACxD,CACF,CACF,CACF,MC/HasL,EAAU,CAAA","file":"index.js","sourcesContent":["// src/types/index.ts\n\n/**\n * Represents the role of a message sender in a conversation.\n */\nexport enum MessageRole {\n USER = 'USER',\n AI = 'AI',\n SYSTEM = 'SYSTEM', // Added for system prompts, though not explicitly in checklist message interface\n TOOL = 'TOOL', // Added for tool results, though not explicitly in checklist message interface\n}\n\n/**\n * Represents a single message within a conversation thread.\n */\nexport interface ConversationMessage {\n messageId: string;\n threadId: string;\n role: MessageRole;\n content: string;\n timestamp: number; // Unix timestamp (milliseconds)\n metadata?: Record<string, any>; // For additional context, tool call IDs, etc.\n}\n\n/**\n * Represents the type of an observation record.\n */\nexport enum ObservationType {\n INTENT = 'INTENT',\n PLAN = 'PLAN',\n THOUGHTS = 'THOUGHTS',\n TOOL_CALL = 'TOOL_CALL', // Renamed from checklist for clarity\n TOOL_EXECUTION = 'TOOL_EXECUTION',\n SYNTHESIS = 'SYNTHESIS', // Added for final synthesis step\n ERROR = 'ERROR',\n FINAL_RESPONSE = 'FINAL_RESPONSE', // Added for the final AI response message\n STATE_UPDATE = 'STATE_UPDATE', // Added for state changes\n}\n\n/**\n * Represents a recorded event during the agent's execution.\n */\nexport interface Observation {\n id: string; // Unique identifier for the observation\n threadId: string;\n traceId?: string; // Optional end-to-end trace identifier\n timestamp: number; // Unix timestamp (milliseconds)\n type: ObservationType;\n title: string; // Human-readable title for the observation type\n content: any; // Structured data specific to the observation type\n metadata?: Record<string, any>; // Additional context\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 */\nexport interface JsonObjectSchema {\n type: 'object';\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 =\n | JsonObjectSchema\n | { type: 'string' | 'number' | 'boolean' | 'array'; [key: string]: any };\n\n/**\n * Defines the schema for a tool, including its input parameters.\n * Uses JSON Schema format for inputSchema.\n */\nexport interface ToolSchema {\n name: string; // Must be unique within the registry\n description: string;\n inputSchema: JsonSchema; // Use the more specific JSON Schema type\n outputSchema?: JsonSchema; // Optional JSON Schema for the output\n examples?: Array<{ input: any; output?: any; description?: string }>; // Optional examples\n}\n\n/**\n * Represents the structured result of a tool execution.\n */\nexport interface ToolResult {\n callId: string; // Identifier linking back to the specific tool call request\n toolName: string;\n status: 'success' | 'error';\n output?: any; // The data returned by the tool on success\n error?: string; // Error message on failure\n metadata?: Record<string, any>; // Execution time, cost, etc.\n}\n\n/**\n * Represents a parsed request from the LLM to call a specific tool.\n */\nexport interface ParsedToolCall {\n callId: string; // Unique ID generated for this specific call attempt\n toolName: string;\n arguments: any; // Parsed arguments object for the tool\n}\n\n/**\n * Configuration specific to a conversation thread.\n */\nexport interface ThreadConfig {\n reasoning: {\n provider: string; // Identifier for the LLM provider (e.g., 'openai')\n model: string; // Specific model name (e.g., 'gpt-4-turbo')\n parameters?: Record<string, any>; // Temperature, top_p, etc.\n // Potentially add prompt template overrides here\n };\n enabledTools: string[]; // List of tool names allowed for this thread\n historyLimit: number; // Max number of messages to keep in context\n systemPrompt?: string; // Overrides default system prompt\n // Other thread-specific settings\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 */\nexport interface AgentState {\n [key: string]: any; // Flexible structure for now\n}\n\n/**\n * Encapsulates the configuration and state for a specific thread.\n */\nexport interface ThreadContext {\n config: ThreadConfig;\n state: AgentState | null; // State might not always exist\n}\n\n/**\n * Properties required to initiate an agent processing cycle.\n */\nexport interface AgentProps {\n query: string; // The user's input/request\n threadId: string; // Mandatory identifier for the conversation thread\n sessionId?: string; // Optional session identifier\n userId?: string; // Optional user identifier\n traceId?: string; // Optional end-to-end trace identifier\n options?: AgentOptions; // Runtime overrides for configuration\n // Dependencies will be injected by the factory, not passed directly here in v1.0 design\n}\n\n/**\n * Options to override agent behavior at runtime.\n */\nexport interface AgentOptions {\n // Example: Override specific LLM parameters for this call\n llmParams?: Record<string, any>;\n // Example: Force use of specific tools for this call\n forceTools?: string[];\n // Add other potential overrides\n}\n\n/**\n * The final structured response returned by the agent core after processing.\n */\nexport interface AgentFinalResponse {\n response: ConversationMessage; // The final AI message added to the conversation\n metadata: ExecutionMetadata; // Metadata about the entire execution cycle\n}\n\n/**\n * Metadata summarizing an agent execution cycle.\n */\nexport interface ExecutionMetadata {\n threadId: string;\n traceId?: string;\n userId?: string;\n status: 'success' | 'error' | 'partial'; // Overall status\n totalDurationMs: number; // Total time taken for the process call\n llmCalls: number; // Count of LLM calls made\n toolCalls: number; // Count of tool calls made\n llmCost?: number; // Optional estimated cost\n error?: string; // Top-level error message if status is 'error' or 'partial'\n}\n\n/**\n * Context provided to a tool during its execution.\n */\nexport interface ExecutionContext {\n threadId: string;\n traceId?: string;\n userId?: string;\n // Potentially include access tokens or credentials if needed securely\n // Access to StateManager or other relevant context could be added if required\n}\n\n/**\n * Options for configuring an LLM call.\n */\nexport interface CallOptions {\n threadId: string; // Essential for context/config lookup\n traceId?: string;\n userId?: string;\n onThought?: (thought: string) => void; // Callback for streaming intermediate thoughts\n // Include LLM-specific parameters like temperature, max_tokens, stop_sequences, etc.\n // These might be nested under a provider-specific key or flattened\n [key: string]: any; // Allow arbitrary LLM parameters\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 */\nexport type FormattedPrompt = string | object | Array<object>;\n\n/**\n * Options for filtering data retrieved from storage.\n * Structure depends heavily on the underlying adapter's capabilities.\n */\nexport interface FilterOptions {\n filter?: Record<string, any>; // Key-value pairs for filtering (e.g., { type: 'PLAN', threadId: '...' }) // Made optional\n sort?: Record<string, 'asc' | 'desc'>; // Key-value pairs for sorting\n limit?: number; // Maximum number of results to return\n skip?: number; // Number of results to skip (for pagination)\n // Adapter-specific options might be needed\n}\n\n/**\n * Options for retrieving conversation messages.\n */\nexport interface MessageOptions {\n limit?: number; // Max number of messages\n beforeTimestamp?: number; // Retrieve messages before this timestamp\n afterTimestamp?: number; // Retrieve messages after this timestamp\n // Potentially filter by role\n}\n\n/**\n * Options for filtering observations.\n */\nexport interface ObservationFilter {\n types?: ObservationType[]; // Filter by specific observation types\n beforeTimestamp?: number;\n afterTimestamp?: number;\n // Add other potential criteria like content matching if needed\n}\n","import { v4 as uuidv4 } from 'uuid';\n\nexport const generateUUID = (): string => {\n return uuidv4();\n};\n","// src/errors.ts\n\n/**\n * Defines standard error codes for the ART framework.\n */\nexport enum ErrorCode {\n // Configuration Errors\n INVALID_CONFIG = 'INVALID_CONFIG',\n MISSING_API_KEY = 'MISSING_API_KEY',\n\n // Storage Errors\n STORAGE_ERROR = 'STORAGE_ERROR',\n THREAD_NOT_FOUND = 'THREAD_NOT_FOUND',\n SAVE_FAILED = 'SAVE_FAILED',\n\n // Reasoning Errors\n LLM_PROVIDER_ERROR = 'LLM_PROVIDER_ERROR',\n PROMPT_GENERATION_FAILED = 'PROMPT_GENERATION_FAILED',\n OUTPUT_PARSING_FAILED = 'OUTPUT_PARSING_FAILED',\n\n // Tool Errors\n TOOL_NOT_FOUND = 'TOOL_NOT_FOUND',\n TOOL_SCHEMA_VALIDATION_FAILED = 'TOOL_SCHEMA_VALIDATION_FAILED',\n TOOL_EXECUTION_ERROR = 'TOOL_EXECUTION_ERROR', // Generic tool execution error\n TOOL_DISABLED = 'TOOL_DISABLED',\n\n // Agent Core / Orchestration Errors\n PLANNING_FAILED = 'PLANNING_FAILED',\n TOOL_EXECUTION_FAILED = 'TOOL_EXECUTION_FAILED', // Error within the ToolSystem execution loop\n SYNTHESIS_FAILED = 'SYNTHESIS_FAILED',\n AGENT_PROCESSING_ERROR = 'AGENT_PROCESSING_ERROR', // General error during agent.process\n\n // General Errors\n NETWORK_ERROR = 'NETWORK_ERROR',\n TIMEOUT_ERROR = 'TIMEOUT_ERROR',\n UNKNOWN_ERROR = 'UNKNOWN_ERROR',\n}\n\n/**\n * Custom error class for ART framework specific errors.\n */\nexport class ARTError extends Error {\n public readonly code: ErrorCode;\n public readonly originalError?: Error;\n\n constructor(message: string, code: ErrorCode, originalError?: Error) {\n super(message);\n this.name = 'ARTError';\n this.code = code;\n this.originalError = originalError;\n\n // Maintains proper stack trace in V8 environments (Node, Chrome)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, ARTError);\n }\n }\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","// src/core/agents/pes-agent.ts\nimport {\n IAgentCore,\n StateManager,\n ConversationManager,\n ToolRegistry,\n PromptManager,\n ReasoningEngine,\n OutputParser,\n ObservationManager,\n ToolSystem,\n // Assuming repository interfaces might be needed indirectly or for type safety, though not directly used\n} from '../interfaces';\nimport {\n AgentProps,\n AgentFinalResponse,\n ConversationMessage,\n // ThreadContext,\n // ToolSchema,\n ParsedToolCall,\n ToolResult,\n ObservationType,\n ExecutionMetadata,\n MessageRole,\n CallOptions,\n // Omit removed, using built-in implicitly\n} from '../../types';\nimport { generateUUID } from '../../utils/uuid';\nimport { ARTError, ErrorCode } from '../../errors'; // Assuming a custom error class exists\n\ninterface PESAgentDependencies {\n stateManager: StateManager;\n conversationManager: ConversationManager;\n toolRegistry: ToolRegistry;\n promptManager: PromptManager;\n reasoningEngine: ReasoningEngine;\n outputParser: OutputParser;\n observationManager: ObservationManager;\n toolSystem: ToolSystem;\n}\n\n/**\n * Implements the Plan-Execute-Synthesize (PES) agent orchestration logic.\n */\nexport class PESAgent implements IAgentCore {\n private readonly deps: PESAgentDependencies;\n\n constructor(dependencies: PESAgentDependencies) {\n this.deps = dependencies;\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; // Renamed to avoid conflict with ParsedToolCall[]\n let finalAiMessage: ConversationMessage | undefined;\n\n try {\n // --- Stage 1: Initiation & Config ---\n console.log(`[${traceId}] Stage 1: Initiation & Config`);\n const threadContext = await this.deps.stateManager.loadThreadContext(\n props.threadId,\n props.userId\n );\n if (!threadContext) {\n throw new ARTError(\n `Thread context not found for threadId: ${props.threadId}`,\n ErrorCode.THREAD_NOT_FOUND\n );\n }\n const systemPrompt = threadContext.config.systemPrompt; // Use thread-specific or default\n\n // --- Stage 2: Planning Context ---\n console.log(`[${traceId}] Stage 2: Planning Context`);\n const historyOptions = { limit: threadContext.config.historyLimit };\n const history = await this.deps.conversationManager.getMessages(\n props.threadId,\n historyOptions\n );\n // const enabledToolNames = threadContext.config.enabledTools; // Removed unused variable\n const availableTools = await this.deps.toolRegistry.getAvailableTools({\n enabledForThreadId: props.threadId,\n }); // Assuming registry can filter\n\n // --- Stage 3: Planning Call ---\n console.log(`[${traceId}] Stage 3: Planning Call`);\n const planningPrompt = await this.deps.promptManager.createPlanningPrompt(\n props.query,\n history,\n systemPrompt,\n availableTools,\n threadContext\n );\n\n const planningOptions: CallOptions = {\n threadId: props.threadId,\n traceId: traceId,\n userId: props.userId,\n onThought: (thought: string) => {\n this.deps.observationManager\n .record({\n threadId: props.threadId,\n traceId,\n type: ObservationType.THOUGHTS,\n content: { phase: 'planning', thought },\n metadata: { timestamp: Date.now() },\n })\n .catch((err) =>\n console.error(`[${traceId}] Failed to record planning thought observation:`, err)\n );\n },\n // Pass LLM parameters from config, potentially overridden by props.options\n ...(threadContext.config.reasoning.parameters ?? {}),\n ...(props.options?.llmParams ?? {}),\n };\n\n let planningOutputText: string;\n let parsedPlanningOutput: { intent?: string; plan?: string; toolCalls?: ParsedToolCall[] } =\n {};\n try {\n llmCalls++;\n planningOutputText = await this.deps.reasoningEngine.call(planningPrompt, planningOptions);\n parsedPlanningOutput = await this.deps.outputParser.parsePlanningOutput(planningOutputText);\n\n await this.deps.observationManager.record({\n threadId: props.threadId,\n traceId,\n type: ObservationType.INTENT,\n content: { intent: parsedPlanningOutput.intent },\n metadata: { timestamp: Date.now() },\n });\n await this.deps.observationManager.record({\n threadId: props.threadId,\n traceId,\n 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,\n traceId,\n type: ObservationType.TOOL_CALL,\n content: { toolCalls: parsedPlanningOutput.toolCalls },\n metadata: { timestamp: Date.now() },\n });\n }\n } catch (err: any) {\n status = 'error';\n errorMessage = `Planning phase failed: ${err.message}`;\n console.error(`[${traceId}] Planning Error:`, err);\n await this.deps.observationManager.record({\n threadId: props.threadId,\n traceId,\n type: ObservationType.ERROR,\n content: { phase: 'planning', error: err.message, stack: err.stack },\n metadata: { timestamp: Date.now() },\n });\n throw new ARTError(errorMessage, ErrorCode.PLANNING_FAILED, err); // Rethrow to stop execution\n }\n\n // --- Stage 4: Tool Execution ---\n let toolResults: ToolResult[] = [];\n if (parsedPlanningOutput.toolCalls && parsedPlanningOutput.toolCalls.length > 0) {\n console.log(\n `[${traceId}] Stage 4: Tool Execution (${parsedPlanningOutput.toolCalls.length} calls)`\n );\n try {\n // ToolSystem is responsible for validation, execution, and recording TOOL_EXECUTION/ERROR observations\n toolResults = await this.deps.toolSystem.executeTools(\n parsedPlanningOutput.toolCalls,\n props.threadId,\n traceId\n );\n toolCallsCount = toolResults.length; // Count actual executions/results\n // Check results for errors to potentially set status to 'partial'\n if (toolResults.some((r) => r.status === 'error')) {\n status = 'partial';\n console.warn(`[${traceId}] Partial success in tool execution.`);\n // Optionally collect specific tool errors for the final metadata\n errorMessage = errorMessage\n ? `${errorMessage}; Tool execution errors occurred.`\n : 'Tool execution errors occurred.';\n }\n } catch (err: any) {\n // This catch block might be redundant if ToolSystem handles internal errors and returns ToolResult[]\n // However, ToolSystem itself could throw an unexpected error.\n status = 'error';\n errorMessage = `Tool execution phase failed: ${err.message}`;\n console.error(`[${traceId}] Tool Execution System Error:`, err);\n await this.deps.observationManager.record({\n threadId: props.threadId,\n traceId,\n 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); // Rethrow\n }\n } else {\n console.log(`[${traceId}] Stage 4: Tool Execution (No tool calls)`);\n }\n\n // --- Stage 5: Synthesis Call ---\n console.log(`[${traceId}] Stage 5: Synthesis Call`);\n const synthesisPrompt = await this.deps.promptManager.createSynthesisPrompt(\n props.query,\n parsedPlanningOutput.intent,\n parsedPlanningOutput.plan,\n toolResults,\n history,\n systemPrompt,\n threadContext\n );\n\n const synthesisOptions: CallOptions = {\n threadId: props.threadId,\n traceId: traceId,\n userId: props.userId,\n onThought: (thought: string) => {\n this.deps.observationManager\n .record({\n threadId: props.threadId,\n traceId,\n type: ObservationType.THOUGHTS,\n content: { phase: 'synthesis', thought },\n metadata: { timestamp: Date.now() },\n })\n .catch((err) =>\n console.error(`[${traceId}] Failed to record synthesis thought observation:`, err)\n );\n },\n ...(threadContext.config.reasoning.parameters ?? {}),\n ...(props.options?.llmParams ?? {}),\n };\n\n let finalResponseContent: string;\n try {\n llmCalls++;\n const synthesisOutputText = await this.deps.reasoningEngine.call(\n synthesisPrompt,\n synthesisOptions\n );\n await this.deps.observationManager.record({\n threadId: props.threadId,\n traceId,\n type: ObservationType.SYNTHESIS,\n content: { rawOutput: synthesisOutputText },\n metadata: { timestamp: Date.now() },\n });\n finalResponseContent =\n await this.deps.outputParser.parseSynthesisOutput(synthesisOutputText);\n } catch (err: any) {\n // If synthesis fails after partial tool success, status remains 'partial' but add synthesis error\n status = status === 'partial' ? 'partial' : 'error';\n const synthesisErrorMessage = `Synthesis phase failed: ${err.message}`;\n errorMessage = errorMessage\n ? `${errorMessage}; ${synthesisErrorMessage}`\n : synthesisErrorMessage;\n console.error(`[${traceId}] Synthesis Error:`, err);\n await this.deps.observationManager.record({\n threadId: props.threadId,\n traceId,\n type: ObservationType.ERROR,\n content: { phase: 'synthesis', error: err.message, stack: err.stack },\n metadata: { timestamp: Date.now() },\n });\n // Decide whether to throw or allow returning partial results\n // For now, let's allow returning partial if tools ran, otherwise throw\n if (status !== 'partial') {\n throw new ARTError(synthesisErrorMessage, ErrorCode.SYNTHESIS_FAILED, err);\n }\n finalResponseContent = errorMessage; // Use error message as content if synthesis failed partially\n }\n\n // --- Stage 6: Finalization ---\n console.log(`[${traceId}] Stage 6: Finalization`);\n const finalTimestamp = Date.now();\n finalAiMessage = {\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: { message: finalAiMessage },\n metadata: { timestamp: finalTimestamp },\n });\n\n // Save state if modified (StateManager handles the check)\n await this.deps.stateManager.saveStateIfModified(props.threadId);\n } catch (error: any) {\n console.error(`[${traceId}] PESAgent process error:`, error);\n status = status === 'partial' ? 'partial' : 'error'; // Keep partial if it was set before the catch\n errorMessage =\n errorMessage ??\n (error instanceof ARTError ? error.message : 'An unexpected error occurred.');\n // Ensure finalAiMessage is undefined if a critical error occurred before synthesis\n if (status === 'error') finalAiMessage = undefined;\n\n // Record top-level error if not already recorded in specific phases\n if (\n !(\n error instanceof ARTError &&\n (error.code === ErrorCode.PLANNING_FAILED ||\n error.code === ErrorCode.TOOL_EXECUTION_FAILED ||\n error.code === ErrorCode.SYNTHESIS_FAILED)\n )\n ) {\n await this.deps.observationManager\n .record({\n threadId: props.threadId,\n traceId,\n type: ObservationType.ERROR,\n content: { phase: 'agent_process', error: error.message, stack: error.stack },\n metadata: { timestamp: Date.now() },\n })\n .catch((err) =>\n console.error(`[${traceId}] Failed to record top-level error observation:`, err)\n );\n }\n } finally {\n // Ensure state is attempted to be saved even if errors occurred mid-process\n // (unless the error was during state loading itself)\n try {\n await this.deps.stateManager.saveStateIfModified(props.threadId);\n } catch (saveError: any) {\n console.error(`[${traceId}] Failed to save state during finalization:`, saveError);\n // Potentially record another error observation\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, // Use the count of executed tools\n // llmCost: calculateCost(), // TODO: Implement cost calculation if needed\n error: errorMessage,\n };\n\n if (!finalAiMessage && status !== 'success') {\n // If we had an error before generating a final message, create a placeholder error response\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 // Optionally save this error message to history? For now, just return it.\n } else if (!finalAiMessage) {\n // This case should ideally not happen if status is success, but as a fallback:\n throw new ARTError(\n 'Agent finished with success status but no final message was generated.',\n ErrorCode.UNKNOWN_ERROR\n );\n }\n\n return {\n response: finalAiMessage,\n metadata: metadata,\n };\n }\n}\n\n// Helper function placeholder for cost calculation\n// function calculateCost(): number | undefined {\n// // Implementation depends on tracking token usage per call and provider pricing\n// return undefined;\n// }\n","import { StorageAdapter } from '../../core/interfaces';\nimport { FilterOptions } from '../../types';\n\n/**\n * An in-memory implementation of the StorageAdapter interface.\n * Useful for testing, development, or simple scenarios where persistence\n * across sessions is not required.\n */\nexport class InMemoryStorageAdapter implements StorageAdapter {\n private storage: Map<string, Map<string, any>> = new Map();\n\n /**\n * Initializes the adapter (no-op for in-memory).\n * @param _config Optional configuration (ignored).\n */\n async init(_config?: any): Promise<void> {\n // Renamed config to _config\n // No initialization needed for in-memory storage\n return Promise.resolve();\n }\n\n /**\n * Retrieves a single item from a collection by its ID.\n * @param collection The name of the data collection.\n * @param id The unique ID of the item.\n * @returns The item or null if not found.\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 collection.\n * @param collection The name of the collection.\n * @param id The unique ID of the item.\n * @param data The data to save (will be deep copied).\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 collection by its ID.\n * @param collection The name of the collection.\n * @param id The unique ID of the item.\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 in a collection based on simple filter options.\n * Note: This is a basic implementation. It only supports exact matches\n * on top-level properties defined in the filter object. It does not\n * support complex queries, sorting, or deep filtering.\n * @param collection The name of the collection.\n * @param filterOptions Filtering options. Only `filter` is partially supported.\n * @returns An array of matching items (deep copies).\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 * Clears all items from a specific collection.\n * @param collection The name of the collection to clear.\n */\n async clearCollection(collection: string): Promise<void> {\n this.storage.delete(collection);\n return Promise.resolve();\n }\n\n /**\n * Clears all data managed by the adapter.\n */\n async clearAll(): Promise<void> {\n this.storage.clear();\n return Promise.resolve();\n }\n}\n","import { StorageAdapter } from '../../core/interfaces';\nimport { FilterOptions } from '../../types';\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 the IndexedDBStorageAdapter.\n */\nexport interface IndexedDBConfig {\n dbName?: string;\n dbVersion?: number;\n objectStores: string[]; // List of required collection names (object stores)\n}\n\n/**\n * An implementation of the StorageAdapter interface using IndexedDB\n * for persistent storage in the browser.\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 constructor(config: IndexedDBConfig) {\n this.dbName = config.dbName || DEFAULT_DB_NAME;\n this.dbVersion = config.dbVersion || DEFAULT_DB_VERSION;\n // Ensure core stores are always present if needed by repositories\n this.requiredObjectStores = new Set([\n 'conversations', // Example core store\n 'observations', // Example core store\n 'state', // Example core store\n ...config.objectStores, // Add user-defined stores\n ]);\n }\n\n /**\n * Initializes the IndexedDB database connection and ensures object stores exist.\n * This method should be called before any other operations.\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 console.error('IndexedDBStorageAdapter: IndexedDB not supported in this browser.');\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 console.error(`IndexedDBStorageAdapter: Database error: ${request.error}`, event);\n reject(new Error(`IndexedDB error: ${request.error?.message}`));\n };\n\n request.onsuccess = (event) => {\n this.db = (event.target as IDBOpenDBRequest).result;\n console.log(\n `IndexedDBStorageAdapter: Database '${this.dbName}' opened successfully (Version: ${this.db.version}).`\n );\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(\n (store) => !existingStores.has(store)\n );\n if (missingStores.length > 0) {\n console.warn(\n `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.`\n );\n // Depending on strictness, you might reject here\n }\n\n this.db.onerror = (errorEvent) => {\n // Generic error handler for the database connection\n console.error(`IndexedDBStorageAdapter: Generic database error:`, errorEvent);\n };\n resolve();\n };\n\n request.onupgradeneeded = (event) => {\n console.log(\n `IndexedDBStorageAdapter: Upgrading database '${this.dbName}' from version ${event.oldVersion} to ${event.newVersion}...`\n );\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 console.error('IndexedDBStorageAdapter: Upgrade transaction is null!');\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 console.log(`IndexedDBStorageAdapter: Creating object store '${storeName}'...`);\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 // console.log(`IndexedDBStorageAdapter: Deleting old object store '${storeName}'...`);\n // this.db?.deleteObjectStore(storeName);\n // }\n // });\n\n console.log(`IndexedDBStorageAdapter: Database upgrade complete.`);\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 console.warn(\n `IndexedDBStorageAdapter: Database open request blocked for '${this.dbName}'. Please close other tabs/connections using an older version of this database.`,\n event\n );\n reject(new Error(`IndexedDB open blocked for ${this.dbName}. Close other connections.`));\n };\n });\n\n return this.initPromise;\n }\n\n // --- Helper Method to get a transaction ---\n private getTransaction(storeName: string | string[], mode: IDBTransactionMode): IDBTransaction {\n if (!this.db) {\n throw new Error('IndexedDBStorageAdapter: Database not initialized. Call init() first.');\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(\n `IndexedDBStorageAdapter: Object store \"${sName}\" does not exist in the database.`\n );\n }\n });\n\n return this.db.transaction(storeName, mode);\n }\n\n // --- CRUD Methods ---\n\n async get<T>(collection: string, id: string): Promise<T | null> {\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.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 console.error(\n `IndexedDBStorageAdapter: Error getting item '${id}' from '${collection}':`,\n request.error\n );\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 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(\n new Error(\n `IndexedDBStorageAdapter: Data for collection '${collection}' must have an 'id' property matching the keyPath.`\n )\n );\n }\n if (dataAsAny.id !== id) {\n console.warn(\n `IndexedDBStorageAdapter: Provided id ('${id}') and data.id ('${dataAsAny.id}') mismatch for collection '${collection}'. Using data.id as the key.`\n );\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 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 console.error(\n `IndexedDBStorageAdapter: Error setting item with id '${dataAsAny.id}' in '${collection}':`,\n request.error\n );\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 console.error(\n `IndexedDBStorageAdapter: Transaction error setting item with id '${dataAsAny.id}' in '${collection}':`,\n transaction.error,\n event\n );\n reject(new Error(`Transaction failed: ${transaction.error?.message}`));\n };\n } catch (error) {\n reject(error);\n }\n });\n }\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 console.error(\n `IndexedDBStorageAdapter: Error deleting item '${id}' from '${collection}':`,\n request.error\n );\n reject(new Error(`Failed to delete item: ${request.error?.message}`));\n };\n\n transaction.onerror = (event) => {\n console.error(\n `IndexedDBStorageAdapter: Transaction error deleting item '${id}' from '${collection}':`,\n transaction.error,\n event\n );\n reject(new Error(`Transaction failed: ${transaction.error?.message}`));\n };\n } catch (error) {\n reject(error);\n }\n });\n }\n\n async query<T>(collection: string, filterOptions: FilterOptions): Promise<T[]> {\n await this.init();\n // Basic implementation using getAll and client-side filtering/sorting/limiting\n // More advanced implementation would use IndexedDB cursors and indexes.\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 // Return copies\n resolve(results.map((item) => ({ ...item })));\n };\n\n request.onerror = () => {\n console.error(\n `IndexedDBStorageAdapter: Error querying collection '${collection}':`,\n request.error\n );\n reject(new Error(`Failed to query collection: ${request.error?.message}`));\n };\n } catch (error) {\n reject(error);\n }\n });\n }\n\n async clearCollection(collection: string): Promise<void> {\n await this.init();\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 console.error(\n `IndexedDBStorageAdapter: Error clearing collection '${collection}':`,\n request.error\n );\n reject(new Error(`Failed to clear collection: ${request.error?.message}`));\n };\n\n transaction.onerror = (event) => {\n console.error(\n `IndexedDBStorageAdapter: Transaction error clearing collection '${collection}':`,\n transaction.error,\n event\n );\n reject(new Error(`Transaction failed: ${transaction.error?.message}`));\n };\n } catch (error) {\n reject(error);\n }\n });\n }\n\n async clearAll(): Promise<void> {\n await this.init();\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 console.error(\n `IndexedDBStorageAdapter: Error clearing object store '${storeName}':`,\n request.error\n );\n // Don't reject immediately, let transaction handle overall status\n };\n });\n\n transaction.oncomplete = () => {\n console.log(`IndexedDBStorageAdapter: All object stores cleared successfully.`);\n resolve();\n };\n\n transaction.onerror = (event) => {\n console.error(\n `IndexedDBStorageAdapter: Transaction error during clearAll:`,\n transaction.error,\n event\n );\n reject(new Error(`Failed to clear all stores: ${transaction.error?.message}`));\n };\n } catch (error) {\n reject(error);\n }\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 * Repository for managing ConversationMessages using a StorageAdapter.\n */\nexport class ConversationRepository implements IConversationRepository {\n private adapter: StorageAdapter;\n private readonly collectionName = 'conversations'; // Define the collection name\n\n constructor(storageAdapter: StorageAdapter) {\n this.adapter = storageAdapter;\n // Ensure the adapter is initialized (though init might be called elsewhere)\n // It's generally better to ensure init is called at the application setup level.\n // this.adapter.init?.();\n }\n\n /**\n * Adds multiple messages to the storage for a specific thread.\n * @param threadId The ID of the thread (used for potential indexing/querying, though not strictly needed if messages have it).\n * @param messages An array of ConversationMessage objects to add.\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(\n `ConversationRepository: Message ${message.messageId} has mismatching threadId (${message.threadId}) for repository operation on thread ${threadId}.`\n );\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>(\n this.collectionName,\n messageToStore.id,\n messageToStore\n );\n });\n\n await Promise.all(setPromises);\n }\n\n /**\n * Retrieves messages for a specific thread, with optional filtering and limiting.\n * Note: Timestamp filtering and sorting are currently handled client-side after retrieval.\n * @param threadId The ID of the thread to retrieve messages for.\n * @param options Optional parameters like limit and timestamp filters.\n * @returns A promise resolving to an array of ConversationMessages.\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(\n ({ id: _id, ...rest }) => rest\n );\n\n return finalMessages;\n }\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 * Repository for managing Observations using a StorageAdapter.\n */\nexport class ObservationRepository implements IObservationRepository {\n private adapter: StorageAdapter;\n private readonly collectionName = 'observations'; // Define the collection name\n\n constructor(storageAdapter: StorageAdapter) {\n this.adapter = storageAdapter;\n // Initialization of the adapter should ideally happen at application setup.\n }\n\n /**\n * Adds a single observation to the storage.\n * @param observation The Observation object to add.\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(\n new Error(`ObservationRepository: Observation must have an 'id' property.`)\n );\n }\n await this.adapter.set<Observation>(this.collectionName, observation.id, observation);\n }\n\n /**\n * Retrieves observations for a specific thread, with optional filtering.\n * Note: Filtering by type and timestamp is currently handled client-side.\n * @param threadId The ID of the thread to retrieve observations for.\n * @param filter Optional filtering criteria like types and timestamps.\n * @returns A promise resolving to an array of Observations.\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(\n (obs) => obs.timestamp < filter.beforeTimestamp!\n );\n }\n if (filter?.afterTimestamp !== undefined) {\n filteredObservations = filteredObservations.filter(\n (obs) => obs.timestamp > filter.afterTimestamp!\n );\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}\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 * Repository for managing ThreadContext (ThreadConfig and AgentState) using a StorageAdapter.\n * Stores one context object per threadId in the 'state' collection.\n */\nexport class StateRepository implements IStateRepository {\n private adapter: StorageAdapter;\n private readonly collectionName = 'state'; // Define the collection name\n\n constructor(storageAdapter: StorageAdapter) {\n this.adapter = storageAdapter;\n // Adapter initialization should happen at application setup.\n }\n\n /**\n * Retrieves the full ThreadContext for a given threadId.\n * @param threadId The ID of the thread.\n * @returns The ThreadContext object or null if not found.\n */\n async getThreadContext(threadId: string): Promise<ThreadContext | null> {\n const storedContext = await this.adapter.get<StoredThreadContext>(\n this.collectionName,\n threadId\n );\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 the full ThreadContext for a given threadId.\n * This will overwrite any existing context for the thread.\n * @param threadId The ID of the thread.\n * @param context The ThreadContext object to save.\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(\n new Error(\"StateRepository: ThreadContext must contain a 'config' property.\")\n );\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 for a given threadId.\n * @param threadId The ID of the thread.\n * @returns The ThreadConfig object or null if not found.\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 * Saves only the ThreadConfig for a given threadId.\n * Retrieves the existing context, updates the config part, and saves it back.\n * If no context exists, creates a new one with the provided config and null state.\n * @param threadId The ID of the thread.\n * @param config The ThreadConfig object to save.\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 for a given threadId.\n * @param threadId The ID of the thread.\n * @returns The AgentState object or null if not found or not set.\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 * Saves only the AgentState for a given threadId.\n * Retrieves the existing context, updates the state part, and saves it back.\n * Throws an error if no configuration context exists for the thread,\n * as state typically depends on an existing configuration.\n * @param threadId The ID of the thread.\n * @param state The AgentState object to save.\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(\n new Error(\n `StateRepository: Cannot set AgentState for thread '${threadId}' because no ThreadConfig exists. Set config first.`\n )\n );\n }\n const newContext: ThreadContext = {\n config: currentContext.config, // Preserve existing config\n state: state,\n };\n await this.setThreadContext(threadId, newContext);\n }\n}\n","import {\n ConversationManager as IConversationManager,\n IConversationRepository,\n} from '../../../core/interfaces';\nimport { ConversationSocket } from '../../ui/conversation-socket'; // Import the class\nimport { ConversationMessage, MessageOptions } from '../../../types';\n\n/**\n * Manages conversation history for different threads using an underlying repository.\n */\nexport class ConversationManager implements IConversationManager {\n private repository: IConversationRepository;\n private conversationSocket: ConversationSocket; // Add socket property\n\n constructor(\n conversationRepository: IConversationRepository,\n conversationSocket: ConversationSocket // Add socket to constructor\n ) {\n this.repository = conversationRepository;\n this.conversationSocket = conversationSocket; // Assign socket\n }\n\n /**\n * Adds one or more messages to a thread's history via the repository.\n * @param threadId The ID of the thread.\n * @param messages An array of messages to add.\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 try {\n this.conversationSocket.notifyMessage(message);\n } catch (error) {\n // Log error but don't let notification failure stop the flow\n console.error(\n `ConversationManager: Failed to notify message ${message.messageId} via socket`,\n error\n );\n }\n });\n }\n\n /**\n * Retrieves messages from a thread's history via the repository.\n * @param threadId The ID of the thread.\n * @param options Filtering and pagination options.\n * @returns An array of conversation messages.\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}\n","import { StateManager as IStateManager, IStateRepository } from '../../../core/interfaces';\nimport { ThreadContext, ThreadConfig } from '../../../types'; // Import ThreadConfig\n\n/**\n * Manages thread-specific configuration (ThreadConfig) and state (AgentState)\n * using an underlying StateRepository.\n */\nexport class StateManager implements IStateManager {\n private repository: IStateRepository;\n\n constructor(stateRepository: IStateRepository) {\n this.repository = stateRepository;\n }\n\n /**\n * Loads the full context (config + state) for a given thread from the repository.\n * Throws an error if the context is not found.\n * @param threadId The ID of the thread.\n * @param _userId Optional user ID (currently unused, for future access control).\n * @returns The thread context.\n * @throws {Error} If the thread context is not found.\n */\n // Changed return type to Promise<ThreadContext> to match interface\n async loadThreadContext(threadId: string, _userId?: string): Promise<ThreadContext> {\n if (!threadId) {\n throw new Error('StateManager: threadId cannot be empty.');\n }\n const context = await this.repository.getThreadContext(threadId);\n if (!context) {\n // Throw error if context is not found, as per interface contract\n throw new Error(`StateManager: Thread context not found for threadId '${threadId}'.`);\n }\n return context;\n }\n\n /**\n * Checks if a specific tool is enabled for the given thread based on its config.\n * Loads the context first.\n * @param threadId The ID of the thread.\n * @param toolName The name of the tool.\n * @returns True if the tool is enabled, false otherwise.\n * @throws {Error} If the thread context cannot be loaded.\n */\n async isToolEnabled(threadId: string, toolName: string): Promise<boolean> {\n // loadThreadContext now throws if not found, simplifying checks here\n try {\n const context = await this.loadThreadContext(threadId);\n // If config or enabledTools is missing/null/undefined, it defaults to false\n return context.config?.enabledTools?.includes(toolName) ?? false;\n } catch (error) {\n // If context loading failed, treat as tool not enabled (or rethrow?)\n // For now, return false if context doesn't exist.\n console.warn(\n `StateManager: Could not check if tool '${toolName}' is enabled for thread '${threadId}' because context failed to load: ${error}`\n );\n return false;\n }\n }\n\n /**\n * Retrieves a specific configuration value for the thread.\n * Loads the context first. Supports only top-level keys.\n * @param threadId The ID of the thread.\n * @param key The configuration key (e.g., 'historyLimit', 'systemPrompt').\n * @returns The configuration value or undefined if not found.\n * @throws {Error} If the thread context cannot be loaded.\n */\n // Changed key type to string to match interface\n async getThreadConfigValue<T>(threadId: string, key: string): Promise<T | undefined> {\n // loadThreadContext now throws if not found\n const context = await this.loadThreadContext(threadId);\n\n if (!context.config) {\n return undefined; // No config part in the context\n }\n\n // Check if the key exists directly on the config object\n // Use 'key in obj' for safer property access check than hasOwnProperty for potential prototype issues\n if (key in context.config) {\n // Cast to T, assuming the caller knows the expected type.\n // Need to cast config to 'any' or use index signature to allow string key access.\n return (context.config as any)[key] as T | undefined;\n } else {\n return undefined; // Key doesn't exist on the config object\n }\n }\n\n /**\n * Saves the thread's state if it has been modified during execution.\n * NOTE: For v1.0, this is a placeholder (no-op). State must be saved explicitly.\n * @param threadId The ID of the thread.\n */\n async saveStateIfModified(threadId: string): Promise<void> {\n if (!threadId) {\n return Promise.reject(\n new Error('StateManager: threadId cannot be empty for saveStateIfModified.')\n );\n }\n // No-op in this v1.0 implementation.\n console.warn(\n `StateManager: saveStateIfModified called for thread ${threadId}, but state modification tracking/saving is not implemented in this version. State must be saved explicitly via repository methods.`\n );\n return Promise.resolve();\n }\n\n /**\n * Sets or updates the configuration for a specific thread.\n * Delegates the call to the state repository.\n * @param threadId The ID of the thread.\n * @param config The complete configuration object to set.\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 // Logger.debug(`StateManager: Setting thread config for ${threadId}`); // Assuming Logger is available\n // Assuming IStateRepository has a setThreadConfig method\n await this.repository.setThreadConfig(threadId, config);\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}\n","import {\n ObservationManager as ObservationManagerInterface,\n IObservationRepository,\n} 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\n\n/**\n * Manages the creation, retrieval, and notification of agent observations.\n * Implements the IObservationManager interface.\n */\nexport class ObservationManager implements ObservationManagerInterface {\n // Implement the imported interface\n private observationRepository: IObservationRepository;\n private observationSocket: ObservationSocket;\n\n /**\n * Creates an instance of ObservationManager.\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 * Records a new observation.\n * Generates an ID and timestamp, saves the observation using the repository,\n * and notifies listeners via the observation socket.\n * @param observationData - The data for the observation, excluding id, timestamp, and title.\n * @returns A promise that resolves when the observation is recorded and notified.\n */\n async record(observationData: Omit<Observation, 'id' | 'timestamp' | 'title'>): Promise<void> {\n // 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 this.observationSocket.notifyObservation(observation); // Use the specific method\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 observations for a specific thread, optionally filtered.\n * @param threadId - The ID of the thread to retrieve observations for.\n * @param filter - Optional filter criteria for observations.\n * @returns A promise that resolves with an array of matching observations.\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}\n","export enum LogLevel {\n DEBUG = 0,\n INFO = 1,\n WARN = 2,\n ERROR = 3,\n}\n\nexport interface LoggerConfig {\n level: LogLevel;\n prefix?: string;\n}\n\nexport class Logger {\n private static config: LoggerConfig = {\n level: LogLevel.INFO,\n };\n\n static configure(config: Partial<LoggerConfig>) {\n Logger.config = { ...Logger.config, ...config };\n }\n\n static debug(message: string, ...args: any[]) {\n if (Logger.config.level <= LogLevel.DEBUG) {\n console.debug(`${Logger.config.prefix || '[ART]'} ${message}`, ...args);\n }\n }\n\n static info(message: string, ...args: any[]) {\n if (Logger.config.level <= LogLevel.INFO) {\n console.info(`${Logger.config.prefix || '[ART]'} ${message}`, ...args);\n }\n }\n\n static warn(message: string, ...args: any[]) {\n if (Logger.config.level <= LogLevel.WARN) {\n console.warn(`${Logger.config.prefix || '[ART]'} ${message}`, ...args);\n }\n }\n\n static error(message: string, ...args: any[]) {\n if (Logger.config.level <= LogLevel.ERROR) {\n console.error(`${Logger.config.prefix || '[ART]'} ${message}`, ...args);\n }\n }\n}\n","// src/systems/tool/ToolRegistry.ts\nimport { ToolRegistry as IToolRegistry, IToolExecutor } from '../../core/interfaces';\nimport { ToolSchema } from '../../types';\nimport { Logger } from '../../utils/logger';\n\nexport class ToolRegistry implements IToolRegistry {\n private executors: Map<string, IToolExecutor> = new Map();\n\n /**\n * Registers a tool executor. Overwrites if a tool with the same name exists.\n * @param executor The tool executor instance.\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 tool executor by its name.\n * @param toolName The unique name of the tool.\n * @returns The executor instance or undefined if not found.\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 registered tools.\n * Note: The filter parameter is ignored in this basic in-memory implementation.\n * A more complex registry might use it (e.g., to check against StateManager).\n * @param filter Optional criteria (ignored in this implementation).\n * @returns An array of tool schemas.\n */\n async getAvailableTools(filter?: { enabledForThreadId?: string }): Promise<ToolSchema[]> {\n if (filter?.enabledForThreadId) {\n Logger.warn(\n 'ToolRegistry: Filtering by enabledForThreadId is not implemented in the basic ToolRegistry. Returning all tools.'\n );\n // In a real scenario, this might interact with StateManager\n }\n const schemas = Array.from(this.executors.values()).map((executor) => executor.schema);\n Logger.debug(`ToolRegistry: Returning ${schemas.length} available tool schemas.`);\n return schemas;\n }\n\n /**\n * Clears all registered tools. Useful for testing.\n */\n async clearAllTools(): Promise<void> {\n this.executors.clear();\n Logger.debug('ToolRegistry: Cleared all registered tools.');\n }\n}\n","// src/utils/validation.ts\nimport Ajv, { ValidateFunction } from 'ajv';\nimport { Logger } from './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 Ajv.\n * Caches compiled schemas for better performance.\n *\n * @param schema - The JSON schema object to validate against.\n * @param data - The data object to validate.\n * @returns An object containing:\n * - `isValid`: boolean indicating if the data is valid.\n * - `errors`: An array of Ajv validation errors if invalid, otherwise null.\n */\nexport function validateJsonSchema(\n schema: object,\n data: any\n): { isValid: boolean; errors: ValidateFunction['errors'] | 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 {\n keyword: 'compilation',\n instancePath: '',\n schemaPath: '',\n params: {},\n message: `Schema compilation failed: ${error.message}`,\n },\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// Optional: Function to clear the validator cache if needed (e.g., for testing)\nexport function clearJsonSchemaValidatorCache(): void {\n compiledValidators.clear();\n Logger.debug('Cleared JSON schema validator cache.');\n}\n","// src/systems/tool/ToolSystem.ts\nimport {\n ToolSystem as IToolSystem,\n ToolRegistry,\n StateManager,\n IToolExecutor,\n ObservationManager,\n} 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\nexport class ToolSystem implements IToolSystem {\n private toolRegistry: ToolRegistry;\n private stateManager: StateManager;\n private observationManager: ObservationManager; // Add when implementing observations\n\n constructor(\n toolRegistry: ToolRegistry,\n stateManager: StateManager,\n observationManager: ObservationManager // Add when implementing observations\n ) {\n if (!toolRegistry) throw new Error('ToolSystem requires a ToolRegistry.');\n if (!stateManager) throw new Error('ToolSystem requires a StateManager.');\n if (!observationManager) throw new Error('ToolSystem requires an ObservationManager.');\n\n this.toolRegistry = toolRegistry;\n this.stateManager = stateManager;\n this.observationManager = observationManager;\n Logger.info('ToolSystem initialized.');\n }\n\n /**\n * Executes a list of parsed tool calls sequentially.\n * @param toolCalls Array of tool calls requested by the LLM.\n * @param threadId The current thread ID for context and permissions.\n * @param traceId Optional trace ID for correlation.\n * @returns A promise resolving to an array of tool results.\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}`, {\n traceId,\n });\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 =\n validationResult.errors\n ?.map((e) => `${e.instancePath || 'input'} ${e.message}`)\n .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}\"`, {\n args: call.arguments,\n threadId,\n traceId,\n });\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`, {\n callId,\n result: result.output,\n threadId,\n traceId,\n });\n } catch (error: any) {\n Logger.error(\n `Tool \"${toolName}\" execution failed for callId \"${callId}\": ${error.message}`,\n { error, threadId, traceId }\n );\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) {\n // Ensure result is not null before recording\n this.observationManager\n .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 })\n .catch((err) =>\n Logger.error(\n `Failed to record TOOL_EXECUTION observation for callId ${call.callId}:`,\n err\n )\n );\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(\n `ToolSystem finished processing call ${call.callId} but result object was null.`\n );\n }\n }\n\n return results;\n }\n}\n","// src/systems/reasoning/PromptManager.ts\nimport {\n ConversationMessage,\n FormattedPrompt,\n MessageRole,\n // ParsedToolCall, // Removed unused import\n ThreadContext, // Added import\n ToolResult,\n ToolSchema,\n} from '../../types'; // Assuming types are exported from src/types/index.ts\nimport { PromptManager as PromptManagerInterface } from '../../core/interfaces'; // Use interface name\n\n// Basic templating function (can be replaced with a more robust library later)\nfunction simpleTemplate(template: string, data: Record<string, any>): string {\n return template.replace(/\\{\\{(\\w+)\\}\\}/g, (match, key) => {\n return data[key] !== undefined ? String(data[key]) : match;\n });\n}\n\nexport class PromptManager implements PromptManagerInterface {\n // Default prompts - these should likely be configurable via ThreadConfig\n private defaultSystemPrompt = 'You are a helpful AI assistant. Respond concisely and accurately.';\n private defaultPlanningPromptTemplate = `System Prompt:\n{{systemPrompt}}\n\nConversation History:\n{{history}}\n\nUser Query:\n{{query}}\n\nAvailable Tools:\n{{tools}}\n\nBased 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.\nRespond 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: [{\"callId\": \"call_1\", \"toolName\": \"tool_name\", \"arguments\": {\"arg1\": \"value1\"}}] or [] if no tools are needed. Do not add any other text in this section.]`;\n\n private defaultSynthesisPromptTemplate = `System Prompt:\n{{systemPrompt}}\n\nConversation History:\n{{history}}\n\nUser Query:\n{{query}}\n\nOriginal Intent:\n{{intent}}\n\nExecution Plan:\n{{plan}}\n\nTool Execution Results:\n{{toolResults}}\n\nBased 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\n async createPlanningPrompt(\n // Make async\n query: string,\n history: ConversationMessage[],\n systemPrompt: string | undefined, // Correct order and type\n availableTools: ToolSchema[], // Correct order\n _threadContext: ThreadContext // Add threadContext (prefixed with _ for unused)\n ): Promise<FormattedPrompt> {\n // Return Promise\n const historyString = history\n .map((msg) => `${msg.role === MessageRole.USER ? 'User' : 'AI'}: ${msg.content}`)\n .join('\\n');\n\n const toolsString =\n availableTools.length > 0\n ? availableTools\n .map(\n (tool) =>\n `- ${tool.name}: ${\n tool.description\n }\\n Input Schema: ${JSON.stringify(tool.inputSchema)}`\n )\n .join('\\n')\n : 'No tools available.';\n\n const promptData = {\n systemPrompt: systemPrompt || this.defaultSystemPrompt,\n history: historyString || 'No history yet.',\n query: query,\n tools: toolsString,\n };\n\n // For v1.0, we'll return a simple string. Adapters might format this further.\n // TODO: Potentially use _threadContext.config.systemPrompt if available\n return Promise.resolve(simpleTemplate(this.defaultPlanningPromptTemplate, promptData));\n }\n\n async createSynthesisPrompt(\n // Make async\n query: string,\n intent: string | undefined, // Correct order and type\n plan: string | undefined, // Correct order and type\n toolResults: ToolResult[], // Correct order\n history: ConversationMessage[], // Correct order\n systemPrompt: string | undefined, // Correct type\n _threadContext: ThreadContext // Add threadContext (prefixed with _ for unused)\n ): Promise<FormattedPrompt> {\n // Return Promise\n const historyString = history\n .map((msg) => `${msg.role === MessageRole.USER ? 'User' : 'AI'}: ${msg.content}`)\n .join('\\n');\n\n const toolResultsString =\n toolResults.length > 0\n ? toolResults\n .map((result) => {\n const output =\n result.status === 'success'\n ? `Output: ${JSON.stringify(result.output)}`\n : `Error: ${result.error}`;\n return `- Tool: ${result.toolName} (Call ID: ${result.callId})\\n Status: ${result.status}\\n ${output}`;\n })\n .join('\\n')\n : 'No tools were executed.';\n\n const promptData = {\n systemPrompt: systemPrompt || this.defaultSystemPrompt,\n history: historyString || 'No history yet.',\n query: query,\n intent: intent,\n plan: plan,\n toolResults: toolResultsString,\n };\n\n // For v1.0, we'll return a simple string. Adapters might format this further.\n // TODO: Potentially use _threadContext.config.systemPrompt if available\n return Promise.resolve(simpleTemplate(this.defaultSynthesisPromptTemplate, promptData)); // Wrap in Promise\n }\n}\n","// src/systems/reasoning/ReasoningEngine.ts\nimport { ReasoningEngine as IReasoningEngine, ProviderAdapter } from '../../core/interfaces';\nimport { FormattedPrompt, CallOptions } from '../../types';\nimport { Logger } from '../../utils/logger';\n\nexport class ReasoningEngine implements IReasoningEngine {\n private adapter: ProviderAdapter;\n\n /**\n * Creates an instance of ReasoningEngine.\n * @param adapter - The configured ProviderAdapter to use for LLM calls.\n */\n constructor(adapter: ProviderAdapter) {\n if (!adapter) {\n throw new Error('ReasoningEngine requires a valid ProviderAdapter.');\n }\n this.adapter = adapter;\n Logger.info(`ReasoningEngine initialized with adapter: ${adapter.providerName}`);\n }\n\n /**\n * Delegates the LLM call to the configured ProviderAdapter.\n * @param prompt - The formatted prompt.\n * @param options - Call options.\n * @returns The raw string response from the LLM adapter.\n */\n async call(prompt: FormattedPrompt, options: CallOptions): Promise<string> {\n Logger.debug(`ReasoningEngine delegating call to adapter: ${this.adapter.providerName}`, {\n threadId: options.threadId,\n traceId: options.traceId,\n });\n try {\n // Directly call the adapter's call method\n const result = await this.adapter.call(prompt, options);\n return result;\n } catch (error: any) {\n Logger.error(`ReasoningEngine encountered an error during adapter call: ${error.message}`, {\n error,\n threadId: options.threadId,\n traceId: options.traceId,\n });\n\n // TODO: Implement more nuanced error handling for adapter calls.\n // Currently, *any* error from the adapter.call (including network issues,\n // API errors, rate limits, etc.) is re-thrown, causing the Agent Core\n // (e.g., PESAgent) to potentially treat it as a fatal planning failure for the turn.\n // Consider:\n // 1. Differentiating error types (e.g., transient network vs. invalid API key vs. content filtering).\n // 2. For potentially recoverable errors (like temporary network glitches or maybe rate limits),\n // instead of re-throwing, formulate an 'OBSERVATION' message detailing the error.\n // This would allow the LLM/Agent to be aware of the issue and potentially retry or adjust its plan\n // in the next turn, rather than halting the current turn with a generic \"Planning phase failed\".\n // 3. Define which errors should still be considered fatal and re-thrown.\n\n // Re-throw the error to be handled by the Agent Core (current behavior)\n throw error;\n }\n }\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\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\nexport class OutputParser implements IOutputParser {\n /**\n * Parses the output of the planning LLM call.\n * Expects format like:\n * Intent: [intent description]\n * Plan: [plan steps]\n * Tool Calls: [JSON array of tool calls]\n * @param output Raw LLM output string.\n * @returns Structured planning data.\n */\n async parsePlanningOutput(output: string): Promise<{\n intent?: string;\n plan?: string;\n toolCalls?: ParsedToolCall[];\n }> {\n const result: {\n intent?: string;\n plan?: string;\n toolCalls?: ParsedToolCall[];\n } = {};\n\n // Robustly extract sections, handling potential variations in spacing/newlines\n const intentMatch = output.match(/Intent:\\s*([\\s\\S]*?)(Plan:|Tool Calls:|$)/i);\n result.intent = intentMatch?.[1]?.trim();\n\n const planMatch = output.match(/Plan:\\s*([\\s\\S]*?)(Tool Calls:|$)/i);\n result.plan = planMatch?.[1]?.trim();\n\n const toolCallsMatch = output.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]\n ? jsonMatch[1].trim()\n : jsonMatch[2]\n ? jsonMatch[2].trim()\n : null;\n } else {\n Logger.debug(\n `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(\n `OutputParser: Failed to parse extracted JSON array. Error: ${error}. Extracted Content: ${jsonArrayString}. Original Content: ${toolCallsString}`\n );\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(\n `OutputParser: Tool Calls JSON structure validation failed. Errors: ${validationResult.error.toString()}. Parsed Content: ${JSON.stringify(parsedJson)}`\n );\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\n if (!result.intent && !result.plan && !result.toolCalls) {\n // Fix logical AND operator\n Logger.warn(\n `OutputParser: Could not parse any structured data (Intent, Plan, Tool Calls) from planning output: ${output}`\n ); // Use static method\n // Consider returning the raw output as plan or intent if no structure found?\n // For now, return potentially empty fields.\n }\n\n return result;\n }\n\n /**\n * Parses the output of the synthesis LLM call.\n * For v1.0, assumes the entire output is the final response content.\n * @param output Raw LLM output string.\n * @returns The final synthesized response content.\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}\n","// src/adapters/reasoning/openai.ts\nimport { ProviderAdapter } from '../../core/interfaces'; // Import only ProviderAdapter from here\nimport { FormattedPrompt, CallOptions } from '../../types'; // Import CallOptions directly from types\nimport { Logger } from '../../utils/logger';\n\n// Define expected options for the OpenAI adapter constructor\nexport interface OpenAIAdapterOptions {\n apiKey: string;\n model?: string; // e.g., 'gpt-4', 'gpt-3.5-turbo'\n apiBaseUrl?: string; // Optional override for base URL (e.g., for proxies)\n}\n\n// Define the structure expected by the OpenAI Chat Completions API\ninterface OpenAIChatCompletionPayload {\n model: string;\n messages: { role: 'system' | 'user' | 'assistant'; content: string }[];\n temperature?: number;\n max_tokens?: number;\n // Add other OpenAI parameters as needed\n}\n\ninterface OpenAIChatCompletionResponse {\n id: string;\n object: string;\n created: number;\n model: string;\n choices: {\n index: number;\n message: {\n role: 'assistant';\n content: string;\n };\n finish_reason: string;\n }[];\n usage: {\n prompt_tokens: number;\n completion_tokens: number;\n total_tokens: number;\n };\n}\n\nexport class OpenAIAdapter implements ProviderAdapter {\n readonly providerName = 'openai';\n private apiKey: string;\n private model: string;\n private apiBaseUrl: string;\n\n constructor(options: OpenAIAdapterOptions) {\n if (!options.apiKey) {\n throw new Error('OpenAI API key is required.');\n }\n this.apiKey = options.apiKey;\n this.model = options.model || 'gpt-3.5-turbo'; // Default model\n this.apiBaseUrl = options.apiBaseUrl || 'https://api.openai.com/v1';\n Logger.debug(`OpenAIAdapter initialized with model: ${this.model}`);\n }\n\n /**\n * Calls the OpenAI Chat Completions API.\n * Note: This basic implementation assumes the FormattedPrompt is a string\n * representing the user's message or a pre-formatted structure.\n * It doesn't yet handle complex history formatting or system prompts\n * directly from the FormattedPrompt type itself.\n * The `onThought` callback is not implemented in this non-streaming version.\n * @param prompt - For this basic version, treated as the primary user message content.\n * A more robust version would parse a structured prompt object.\n * @param options - Call options, including threadId, traceId, and LLM parameters.\n * @returns The content string from the API response.\n */\n async call(prompt: FormattedPrompt, options: CallOptions): Promise<string> {\n // Basic assumption: prompt is the user message string.\n // TODO: Enhance prompt handling to support system prompts and history from FormattedPrompt if it becomes structured.\n if (typeof prompt !== 'string') {\n Logger.warn('OpenAIAdapter received non-string prompt. Treating as string.');\n prompt = String(prompt);\n }\n\n const apiUrl = `${this.apiBaseUrl}/chat/completions`;\n const payload: OpenAIChatCompletionPayload = {\n model: this.model,\n messages: [\n // TODO: Add system prompt handling based on options or thread config\n { role: 'user', content: prompt },\n // TODO: Add conversation history handling\n ],\n // Pass through relevant LLM parameters from CallOptions\n temperature: options.temperature,\n max_tokens: options.max_tokens,\n // top_p: options.top_p, // Example of another parameter\n };\n\n // Remove undefined parameters from payload\n Object.keys(payload).forEach(\n (key) =>\n payload[key as keyof OpenAIChatCompletionPayload] === undefined &&\n delete payload[key as keyof OpenAIChatCompletionPayload]\n );\n\n Logger.debug(`Calling OpenAI API: ${apiUrl} with model ${this.model}`, {\n threadId: options.threadId,\n traceId: options.traceId,\n });\n\n try {\n const response = await fetch(apiUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const errorBody = await response.text();\n Logger.error(`OpenAI API request failed with status ${response.status}: ${errorBody}`, {\n threadId: options.threadId,\n traceId: options.traceId,\n });\n throw new Error(\n `OpenAI API request failed: ${response.status} ${response.statusText} - ${errorBody}`\n );\n }\n\n const data = (await response.json()) as OpenAIChatCompletionResponse;\n\n if (!data.choices || data.choices.length === 0 || !data.choices[0].message?.content) {\n Logger.error('Invalid response structure from OpenAI API', {\n responseData: data,\n threadId: options.threadId,\n traceId: options.traceId,\n });\n throw new Error('Invalid response structure from OpenAI API: No content found.');\n }\n\n // TODO: Implement onThought callback if streaming is added later.\n // if (options.onThought) { options.onThought('Received response chunk...'); }\n\n const responseContent = data.choices[0].message.content.trim();\n Logger.debug(`OpenAI API call successful. Response length: ${responseContent.length}`, {\n threadId: options.threadId,\n traceId: options.traceId,\n });\n return responseContent;\n } catch (error: any) {\n Logger.error(`Error during OpenAI API call: ${error.message}`, {\n error,\n threadId: options.threadId,\n traceId: options.traceId,\n });\n // Re-throw or handle appropriately\n throw error;\n }\n }\n}\n","// src/adapters/reasoning/gemini.ts\nimport { ProviderAdapter } from '../../core/interfaces';\nimport { FormattedPrompt, CallOptions } from '../../types';\nimport { Logger } from '../../utils/logger';\n\n// Define expected options for the Gemini adapter constructor\nexport interface GeminiAdapterOptions {\n apiKey: string;\n model?: string; // e.g., 'gemini-1.5-flash', 'gemini-pro'\n apiBaseUrl?: string; // Optional override for base URL\n apiVersion?: string; // e.g., 'v1beta'\n}\n\n// Define the structure expected by the Gemini API (generateContent)\n// Based on https://ai.google.dev/api/rest/v1beta/models/generateContent\ninterface GeminiGenerateContentPayload {\n contents: {\n role?: 'user' | 'model'; // Optional, defaults to user if only one part\n parts: { text: string }[];\n }[];\n generationConfig?: {\n temperature?: number;\n maxOutputTokens?: number;\n topP?: number;\n topK?: number;\n stopSequences?: string[];\n // Add other Gemini generation parameters as needed\n };\n // safetySettings?: SafetySetting[]; // Add if needed\n // tools?: Tool[]; // Add if needed\n}\n\ninterface GeminiGenerateContentResponse {\n candidates?: {\n content?: {\n parts?: {\n text?: string;\n }[];\n role?: string;\n };\n finishReason?: string;\n // index?: number;\n // safetyRatings?: SafetyRating[];\n // citationMetadata?: CitationMetadata;\n }[];\n promptFeedback?: {\n // blockReason?: string;\n // safetyRatings?: SafetyRating[];\n };\n}\n\nexport class GeminiAdapter implements ProviderAdapter {\n readonly providerName = 'gemini';\n private apiKey: string;\n private model: string;\n private apiBaseUrl: string;\n private apiVersion: string;\n\n constructor(options: GeminiAdapterOptions) {\n if (!options.apiKey) {\n throw new Error('Gemini API key is required.');\n }\n this.apiKey = options.apiKey;\n this.model = options.model || 'gemini-1.5-flash'; // Default model\n this.apiVersion = options.apiVersion || 'v1beta';\n this.apiBaseUrl = options.apiBaseUrl || 'https://generativelanguage.googleapis.com';\n Logger.debug(\n `GeminiAdapter initialized with model: ${this.model}, version: ${this.apiVersion}`\n );\n }\n\n /**\n * Calls the Google Generative AI API (Gemini).\n * Note: Assumes prompt is a string for basic user input.\n * Does not yet handle complex history or system prompts.\n * `onThought` is not implemented (requires streaming API).\n * @param prompt - Treated as the user message content.\n * @param options - Call options including LLM parameters.\n * @returns The content string from the API response.\n */\n async call(prompt: FormattedPrompt, options: CallOptions): Promise<string> {\n if (typeof prompt !== 'string') {\n Logger.warn('GeminiAdapter received non-string prompt. Treating as string.');\n prompt = String(prompt);\n }\n\n const apiUrl = `${this.apiBaseUrl}/${this.apiVersion}/models/${this.model}:generateContent?key=${this.apiKey}`;\n\n const payload: GeminiGenerateContentPayload = {\n contents: [\n // TODO: Add system prompt/history handling by mapping to Gemini's contents structure\n { parts: [{ text: prompt }] }, // Simple user prompt\n ],\n generationConfig: {\n // Map relevant parameters from CallOptions\n temperature: options.temperature,\n maxOutputTokens: options.max_tokens || options.maxOutputTokens, // Allow both names\n topP: options.top_p || options.topP,\n topK: options.top_k || options.topK,\n stopSequences: options.stop || options.stop_sequences || options.stopSequences,\n },\n };\n\n // Remove undefined generationConfig parameters\n if (payload.generationConfig) {\n Object.keys(payload.generationConfig).forEach(\n (key) =>\n payload.generationConfig![\n key as keyof GeminiGenerateContentPayload['generationConfig']\n ] === undefined &&\n delete payload.generationConfig![\n key as keyof GeminiGenerateContentPayload['generationConfig']\n ]\n );\n // If generationConfig becomes empty, remove it entirely\n if (Object.keys(payload.generationConfig).length === 0) {\n delete payload.generationConfig;\n }\n }\n\n Logger.debug(`Calling Gemini API: ${apiUrl.split('?')[0]} with model ${this.model}`, {\n threadId: options.threadId,\n traceId: options.traceId,\n });\n\n try {\n const response = await fetch(apiUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const errorBody = await response.text();\n Logger.error(`Gemini API request failed with status ${response.status}: ${errorBody}`, {\n threadId: options.threadId,\n traceId: options.traceId,\n });\n throw new Error(\n `Gemini API request failed: ${response.status} ${response.statusText} - ${errorBody}`\n );\n }\n\n const data = (await response.json()) as GeminiGenerateContentResponse;\n\n // Extract text from the first candidate's content parts\n const responseText = data.candidates?.[0]?.content?.parts?.map((part) => part.text).join('');\n\n if (responseText === undefined || responseText === null) {\n // Check for prompt feedback indicating blocking\n if (data.promptFeedback) {\n Logger.error('Gemini API call blocked or failed to generate content.', {\n responseData: data,\n threadId: options.threadId,\n traceId: options.traceId,\n });\n throw new Error(\n 'Gemini API call blocked or failed to generate content. Check prompt feedback in logs or API documentation.'\n );\n }\n Logger.error('Invalid response structure from Gemini API: No text content found', {\n responseData: data,\n threadId: options.threadId,\n traceId: options.traceId,\n });\n throw new Error('Invalid response structure from Gemini API: No text content found.');\n }\n\n // TODO: Implement onThought callback if streaming is added later.\n\n const responseContent = responseText.trim();\n Logger.debug(`Gemini API call successful. Response length: ${responseContent.length}`, {\n threadId: options.threadId,\n traceId: options.traceId,\n });\n return responseContent;\n } catch (error: any) {\n Logger.error(`Error during Gemini API call: ${error.message}`, {\n error,\n threadId: options.threadId,\n traceId: options.traceId,\n });\n throw error;\n }\n }\n}\n","// src/adapters/reasoning/anthropic.ts\nimport { ProviderAdapter } from '../../core/interfaces';\nimport { FormattedPrompt, CallOptions } from '../../types';\nimport { Logger } from '../../utils/logger';\n\n// Define expected options for the Anthropic adapter constructor\nexport interface AnthropicAdapterOptions {\n apiKey: string;\n model?: string; // e.g., 'claude-3-opus-20240229', 'claude-3-sonnet-20240229'\n apiVersion?: string; // e.g., '2023-06-01'\n apiBaseUrl?: string; // Optional override\n}\n\n// Define the structure expected by the Anthropic Messages API\n// Based on https://docs.anthropic.com/claude/reference/messages_post\ninterface AnthropicMessagesPayload {\n model: string;\n messages: { role: 'user' | 'assistant'; content: string | object[] }[]; // Content can be complex\n system?: string; // Optional system prompt\n max_tokens: number; // Required by Anthropic\n temperature?: number;\n top_p?: number;\n top_k?: number;\n stop_sequences?: string[];\n // stream?: boolean; // For streaming later\n // Add other Anthropic parameters as needed\n}\n\ninterface AnthropicMessagesResponse {\n id: string;\n type: 'message';\n role: 'assistant';\n model: string;\n content: { type: 'text'; text: string }[]; // Assuming text content for now\n stop_reason: 'end_turn' | 'max_tokens' | 'stop_sequence' | null;\n stop_sequence: string | null;\n usage: {\n input_tokens: number;\n output_tokens: number;\n };\n}\n\nexport class AnthropicAdapter implements ProviderAdapter {\n readonly providerName = 'anthropic';\n private apiKey: string;\n private model: string;\n private apiVersion: string;\n private apiBaseUrl: string;\n\n // Default max tokens if not provided in options, as Anthropic requires it\n private defaultMaxTokens = 1024;\n\n constructor(options: AnthropicAdapterOptions) {\n if (!options.apiKey) {\n throw new Error('Anthropic API key is required.');\n }\n this.apiKey = options.apiKey;\n // Common default model, user should override if needed\n this.model = options.model || 'claude-3-haiku-20240307';\n this.apiVersion = options.apiVersion || '2023-06-01';\n this.apiBaseUrl = options.apiBaseUrl || 'https://api.anthropic.com/v1';\n Logger.debug(\n `AnthropicAdapter initialized with model: ${this.model}, version: ${this.apiVersion}`\n );\n }\n\n /**\n * Calls the Anthropic Messages API.\n * Note: Assumes prompt is a string for basic user input.\n * Does not yet handle complex history or system prompts robustly.\n * `onThought` is not implemented (requires streaming API).\n * @param prompt - Treated as the user message content.\n * @param options - Call options including LLM parameters. Requires max_tokens/maxOutputTokens.\n * @returns The content string from the API response.\n */\n async call(prompt: FormattedPrompt, options: CallOptions): Promise<string> {\n if (typeof prompt !== 'string') {\n Logger.warn('AnthropicAdapter received non-string prompt. Treating as string.');\n prompt = String(prompt);\n }\n\n const apiUrl = `${this.apiBaseUrl}/messages`;\n const maxTokens =\n options.max_tokens ||\n options.maxOutputTokens ||\n options.max_tokens_to_sample ||\n this.defaultMaxTokens;\n\n const payload: AnthropicMessagesPayload = {\n model: this.model,\n messages: [\n // TODO: Add system prompt/history handling by mapping to Anthropic's messages structure\n { role: 'user', content: prompt }, // Simple user prompt\n ],\n system: options.system_prompt || options.system, // Allow system prompt via options\n max_tokens: maxTokens, // Use mapped or default value\n // Map relevant parameters from CallOptions\n temperature: options.temperature,\n top_p: options.top_p || options.topP,\n top_k: options.top_k || options.topK,\n stop_sequences: options.stop || options.stop_sequences || options.stopSequences,\n };\n\n // Remove undefined parameters from payload (excluding max_tokens which is required)\n Object.keys(payload).forEach((key) => {\n const K = key as keyof AnthropicMessagesPayload;\n if (K !== 'max_tokens' && payload[K] === undefined) {\n delete payload[K];\n }\n });\n\n Logger.debug(`Calling Anthropic API: ${apiUrl} with model ${this.model}`, {\n threadId: options.threadId,\n traceId: options.traceId,\n });\n\n try {\n const response = await fetch(apiUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-api-key': this.apiKey,\n 'anthropic-version': this.apiVersion,\n // 'anthropic-beta': 'messages-2023-12-15', // Might be needed for certain features\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const errorBody = await response.text();\n Logger.error(`Anthropic API request failed with status ${response.status}: ${errorBody}`, {\n threadId: options.threadId,\n traceId: options.traceId,\n });\n // Attempt to parse error body for better message\n let errorMessage = errorBody;\n try {\n const parsedError = JSON.parse(errorBody);\n if (parsedError?.error?.message) {\n errorMessage = parsedError.error.message;\n }\n } catch (e) {\n /* Ignore parsing error */\n }\n throw new Error(\n `Anthropic API request failed: ${response.status} ${response.statusText} - ${errorMessage}`\n );\n }\n\n const data = (await response.json()) as AnthropicMessagesResponse;\n\n // Extract text content - assumes simple text response for now\n const responseText = data.content?.find((c) => c.type === 'text')?.text;\n\n if (responseText === undefined || responseText === null) {\n Logger.error('Invalid response structure from Anthropic API: No text content found', {\n responseData: data,\n threadId: options.threadId,\n traceId: options.traceId,\n });\n throw new Error('Invalid response structure from Anthropic API: No text content found.');\n }\n\n // TODO: Implement onThought callback if streaming is added later.\n\n const responseContent = responseText.trim();\n Logger.debug(`Anthropic API call successful. Response length: ${responseContent.length}`, {\n threadId: options.threadId,\n traceId: options.traceId,\n });\n return responseContent;\n } catch (error: any) {\n Logger.error(`Error during Anthropic API call: ${error.message}`, {\n error,\n threadId: options.threadId,\n traceId: options.traceId,\n });\n throw error;\n }\n }\n}\n","// src/adapters/reasoning/openrouter.ts\nimport { ProviderAdapter } from '../../core/interfaces';\nimport { FormattedPrompt, CallOptions } from '../../types';\nimport { Logger } from '../../utils/logger';\n\n// Define expected options for the OpenRouter adapter constructor\nexport interface OpenRouterAdapterOptions {\n apiKey: string;\n model: string; // Required: OpenRouter model identifier (e.g., 'google/gemini-pro', 'anthropic/claude-3-haiku')\n apiBaseUrl?: string; // Optional override\n siteUrl?: string; // Optional: Recommended header 'HTTP-Referer'\n appName?: string; // Optional: Recommended header 'X-Title'\n}\n\n// Re-use OpenAI-compatible structures (assuming OpenRouter adheres closely)\ninterface OpenAIChatCompletionPayload {\n model: string;\n messages: { role: 'system' | 'user' | 'assistant'; content: string }[];\n temperature?: number;\n max_tokens?: number;\n top_p?: number;\n top_k?: number;\n stop?: string | string[];\n // Add other compatible parameters as needed\n}\n\ninterface OpenAIChatCompletionResponse {\n id: string;\n object: string;\n created: number;\n model: string; // The specific model used by OpenRouter\n choices: {\n index: number;\n message: {\n role: 'assistant';\n content: string;\n };\n finish_reason: string;\n }[];\n usage?: {\n // Usage might be optional or structured differently\n prompt_tokens?: number;\n completion_tokens?: number;\n total_tokens?: number;\n // OpenRouter might add cost info here\n };\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('OpenRouter API key is required.');\n }\n if (!options.model) {\n // Model is required for OpenRouter as it specifies the underlying provider/model\n throw new Error('OpenRouter model identifier is required (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 /**\n * Calls the OpenRouter Chat Completions API (OpenAI compatible).\n * Note: Assumes prompt is a string for basic user input.\n * Does not yet handle complex history or system prompts robustly.\n * `onThought` is not implemented (requires streaming API).\n * @param prompt - Treated as the user message content.\n * @param options - Call options including LLM parameters.\n * @returns The content string from the API response.\n */\n async call(prompt: FormattedPrompt, options: CallOptions): Promise<string> {\n if (typeof prompt !== 'string') {\n Logger.warn('OpenRouterAdapter received non-string prompt. Treating as string.');\n prompt = String(prompt);\n }\n\n const apiUrl = `${this.apiBaseUrl}/chat/completions`;\n\n // Map relevant parameters from CallOptions, allowing provider-specific names\n const stopSequences = options.stop || options.stop_sequences || options.stopSequences;\n\n const payload: OpenAIChatCompletionPayload = {\n model: this.model, // Use the specific model provided in options\n messages: [\n // TODO: Add system prompt/history handling\n { role: 'user', content: prompt },\n ],\n temperature: options.temperature,\n max_tokens: options.max_tokens || options.maxOutputTokens,\n top_p: options.top_p || options.topP,\n top_k: options.top_k || options.topK,\n stop: stopSequences,\n // Add other parameters compatible with OpenAI/OpenRouter spec\n };\n\n // Remove undefined parameters from payload\n Object.keys(payload).forEach(\n (key) =>\n payload[key as keyof OpenAIChatCompletionPayload] === undefined &&\n delete payload[key as keyof OpenAIChatCompletionPayload]\n );\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n };\n // Add recommended OpenRouter headers if provided\n if (this.siteUrl) {\n headers['HTTP-Referer'] = this.siteUrl;\n }\n if (this.appName) {\n headers['X-Title'] = this.appName;\n }\n\n Logger.debug(`Calling OpenRouter API: ${apiUrl} with model ${this.model}`, {\n threadId: options.threadId,\n traceId: options.traceId,\n });\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 Logger.error(`OpenRouter API request failed with status ${response.status}: ${errorBody}`, {\n threadId: options.threadId,\n traceId: options.traceId,\n });\n // Attempt to parse error for better message\n let errorMessage = errorBody;\n try {\n const parsedError = JSON.parse(errorBody);\n if (parsedError?.error?.message) {\n errorMessage = parsedError.error.message;\n }\n } catch (e) {\n /* Ignore parsing error */\n }\n throw new Error(\n `OpenRouter API request failed: ${response.status} ${response.statusText} - ${errorMessage}`\n );\n }\n\n const data = (await response.json()) as OpenAIChatCompletionResponse;\n\n if (!data.choices || data.choices.length === 0 || !data.choices[0].message?.content) {\n Logger.error('Invalid response structure from OpenRouter API', {\n responseData: data,\n threadId: options.threadId,\n traceId: options.traceId,\n });\n throw new Error('Invalid response structure from OpenRouter API: No content found.');\n }\n\n // TODO: Implement onThought callback if streaming is added later.\n\n const responseContent = data.choices[0].message.content.trim();\n Logger.debug(`OpenRouter API call successful. Response length: ${responseContent.length}`, {\n threadId: options.threadId,\n traceId: options.traceId,\n });\n return responseContent;\n } catch (error: any) {\n Logger.error(`Error during OpenRouter API call: ${error.message}`, {\n error,\n threadId: options.threadId,\n traceId: options.traceId,\n });\n throw error;\n }\n }\n}\n","// src/adapters/reasoning/deepseek.ts\nimport { ProviderAdapter } from '../../core/interfaces';\nimport { FormattedPrompt, CallOptions } from '../../types';\nimport { Logger } from '../../utils/logger';\n\n// Define expected options for the DeepSeek adapter constructor\nexport interface DeepSeekAdapterOptions {\n apiKey: string;\n model?: string; // e.g., 'deepseek-chat', 'deepseek-coder'\n apiBaseUrl?: string; // Optional override\n}\n\n// Re-use OpenAI-compatible structures\ninterface OpenAIChatCompletionPayload {\n model: string;\n messages: { role: 'system' | 'user' | 'assistant'; content: string }[];\n temperature?: number;\n max_tokens?: number;\n top_p?: number;\n stop?: string | string[];\n // Add other compatible parameters as needed\n}\n\ninterface OpenAIChatCompletionResponse {\n id: string;\n object: string;\n created: number;\n model: string;\n choices: {\n index: number;\n message: {\n role: 'assistant';\n content: string;\n };\n finish_reason: string;\n }[];\n usage: {\n // Note: DeepSeek usage structure matches OpenAI\n prompt_tokens: number;\n completion_tokens: number;\n total_tokens: number;\n };\n}\n\nexport class DeepSeekAdapter implements ProviderAdapter {\n readonly providerName = 'deepseek';\n private apiKey: string;\n private model: string;\n private apiBaseUrl: string;\n\n constructor(options: DeepSeekAdapterOptions) {\n if (!options.apiKey) {\n throw new Error('DeepSeek API key is required.');\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 * Calls the DeepSeek Chat Completions API (OpenAI compatible).\n * Note: Assumes prompt is a string for basic user input.\n * Does not yet handle complex history or system prompts robustly.\n * `onThought` is not implemented (requires streaming API).\n * @param prompt - Treated as the user message content.\n * @param options - Call options including LLM parameters.\n * @returns The content string from the API response.\n */\n async call(prompt: FormattedPrompt, options: CallOptions): Promise<string> {\n if (typeof prompt !== 'string') {\n Logger.warn('DeepSeekAdapter received non-string prompt. Treating as string.');\n prompt = String(prompt);\n }\n\n const apiUrl = `${this.apiBaseUrl}/chat/completions`;\n\n // Map relevant parameters from CallOptions\n const stopSequences = options.stop || options.stop_sequences || options.stopSequences;\n\n const payload: OpenAIChatCompletionPayload = {\n model: this.model,\n messages: [\n // TODO: Add system prompt/history handling\n { role: 'user', content: prompt },\n ],\n temperature: options.temperature,\n max_tokens: options.max_tokens || options.maxOutputTokens,\n top_p: options.top_p || options.topP,\n stop: stopSequences,\n // Add other parameters compatible with DeepSeek spec if needed\n };\n\n // Remove undefined parameters from payload\n Object.keys(payload).forEach(\n (key) =>\n payload[key as keyof OpenAIChatCompletionPayload] === undefined &&\n delete payload[key as keyof OpenAIChatCompletionPayload]\n );\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: ${apiUrl} with model ${this.model}`, {\n threadId: options.threadId,\n traceId: options.traceId,\n });\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 Logger.error(`DeepSeek API request failed with status ${response.status}: ${errorBody}`, {\n threadId: options.threadId,\n traceId: options.traceId,\n });\n // Attempt to parse error for better message\n let errorMessage = errorBody;\n try {\n const parsedError = JSON.parse(errorBody);\n if (parsedError?.error?.message) {\n errorMessage = parsedError.error.message;\n }\n } catch (e) {\n /* Ignore parsing error */\n }\n throw new Error(\n `DeepSeek API request failed: ${response.status} ${response.statusText} - ${errorMessage}`\n );\n }\n\n const data = (await response.json()) as OpenAIChatCompletionResponse;\n\n if (!data.choices || data.choices.length === 0 || !data.choices[0].message?.content) {\n Logger.error('Invalid response structure from DeepSeek API', {\n responseData: data,\n threadId: options.threadId,\n traceId: options.traceId,\n });\n throw new Error('Invalid response structure from DeepSeek API: No content found.');\n }\n\n // TODO: Implement onThought callback if streaming is added later.\n\n const responseContent = data.choices[0].message.content.trim();\n Logger.debug(`DeepSeek API call successful. Response length: ${responseContent.length}`, {\n threadId: options.threadId,\n traceId: options.traceId,\n });\n return responseContent;\n } catch (error: any) {\n Logger.error(`Error during DeepSeek API call: ${error.message}`, {\n error,\n threadId: options.threadId,\n traceId: options.traceId,\n });\n throw error;\n }\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(\n `New subscription added: ${id}, Filter: ${JSON.stringify(filter)}, Options: ${JSON.stringify(options)}`\n ); // 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 Logger.debug(\n `Notifying ${this.subscriptions.size} subscribers. Data: ${JSON.stringify(data).substring(0, 100)}..., Options: ${JSON.stringify(options)}`\n ); // 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 (\n sub.options?.threadId &&\n options?.targetThreadId &&\n sub.options.threadId !== options.targetThreadId\n ) {\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 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?(\n _filter?: FilterType,\n _options?: { threadId?: string; limit?: number }\n ): Promise<DataType[]> {\n // 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}\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<\n Observation,\n ObservationType | ObservationType[]\n> {\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(\n `Notifying Observation: ${observation.id} (${observation.type}) for thread ${observation.threadId}`\n );\n super.notify(observation, { targetThreadId: observation.threadId }, (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 * 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(\n `Getting history for ObservationSocket: Thread ${options.threadId}, Filter: ${JSON.stringify(filter)}, Limit: ${options.limit}`\n );\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(\n `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(\n `Error fetching observation history for thread ${options.threadId} with filter ${JSON.stringify(observationFilter)}:`,\n error\n );\n return [];\n }\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<\n ConversationMessage,\n MessageRole | MessageRole[]\n> {\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(\n `Notifying Message: ${message.messageId} (${message.role}) for thread ${message.threadId}`\n );\n super.notify(message, { targetThreadId: message.threadId }, (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 * 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(\n 'Cannot getHistory for ConversationSocket: ConversationRepository not configured.'\n );\n return [];\n }\n if (!options?.threadId) {\n Logger.warn('Cannot getHistory for ConversationSocket: threadId is required.');\n return [];\n }\n\n Logger.debug(\n `Getting history for ConversationSocket: Thread ${options.threadId}, Filter: ${JSON.stringify(filter)}, Limit: ${options.limit}`\n );\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(\n `Role filtering requested for ConversationSocket.getHistory, but not directly supported by IConversationRepository.getMessages. Fetching all roles up to limit.`\n );\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}\n","// src/systems/ui/ui-system.ts\nimport {\n UISystem as IUISystem,\n IObservationRepository,\n IConversationRepository,\n} from '../../core/interfaces';\nimport { ObservationSocket } from './observation-socket';\nimport { ConversationSocket } from './conversation-socket';\nimport { Logger } from '../../utils/logger';\n\n/**\n * Provides access to the UI communication sockets (Observation and Conversation).\n * Instantiates the sockets with their required repository dependencies.\n */\nexport class UISystem implements IUISystem {\n private observationSocketInstance: ObservationSocket;\n private conversationSocketInstance: ConversationSocket;\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 */\n constructor(\n observationRepository: IObservationRepository,\n conversationRepository: IConversationRepository\n ) {\n this.observationSocketInstance = new ObservationSocket(observationRepository);\n this.conversationSocketInstance = new ConversationSocket(conversationRepository);\n Logger.debug('UISystem initialized with Observation and Conversation 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","// src/core/agent-factory.ts\nimport {\n IAgentCore,\n StorageAdapter,\n IConversationRepository,\n IObservationRepository,\n IStateRepository,\n ConversationManager,\n StateManager,\n ObservationManager,\n ToolRegistry,\n IToolExecutor,\n PromptManager,\n ProviderAdapter,\n ReasoningEngine,\n OutputParser,\n ToolSystem,\n UISystem,\n // Removed ObservationSocket, ConversationSocket interface imports\n} from './interfaces';\nimport { PESAgent } from './agents/pes-agent';\n\n// Import concrete implementations (assuming paths)\n// Storage Adapters\nimport { InMemoryStorageAdapter } from '../adapters/storage/inMemory'; // Corrected path\nimport { IndexedDBStorageAdapter } from '../adapters/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\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 { ReasoningEngine as ReasoningEngineImpl } from '../systems/reasoning/ReasoningEngine'; // Correct path\nimport { OutputParser as OutputParserImpl } from '../systems/reasoning/OutputParser'; // Correct path\n// Provider Adapters (Examples - Assuming correct paths/exports)\nimport { OpenAIAdapter } from '../adapters/reasoning/openai';\nimport { GeminiAdapter } from '../adapters/reasoning/gemini';\nimport { AnthropicAdapter } from '../adapters/reasoning/anthropic';\nimport { OpenRouterAdapter } from '../adapters/reasoning/openrouter';\nimport { DeepSeekAdapter } from '../adapters/reasoning/deepseek';\n// UI System\nimport { UISystem as UISystemImpl } from '../systems/ui/ui-system'; // Correct path\n// Removed direct imports of concrete socket classes - they will be accessed via UISystem instance\n// Removed unused type imports: Observation, ConversationMessage, ObservationType, MessageRole\n\n// Configuration Interfaces\nexport interface StorageConfig {\n type: 'memory' | 'indexedDB';\n dbName?: string; // For IndexedDB\n // other adapter-specific config\n}\n\nexport interface ReasoningConfig {\n provider: 'openai' | 'gemini' | 'anthropic' | 'openrouter' | 'deepseek'; // Add others as implemented\n apiKey: string; // Sensitive, handle appropriately\n // provider-specific options (model, baseURL, etc.)\n model?: string;\n baseURL?: string;\n}\n\nexport interface AgentFactoryConfig {\n storage: StorageConfig;\n reasoning: ReasoningConfig;\n tools?: IToolExecutor[]; // Optional list of tools to register initially\n agentCore?: new (dependencies: any) => IAgentCore; // Optional: Specify Agent Core implementation (defaults to PESAgent)\n // Add other configurations (e.g., default prompts, UI options)\n}\n\n/**\n * Factory class responsible for creating and configuring agent instances\n * with all their dependencies.\n */\nexport class AgentFactory {\n private config: AgentFactoryConfig;\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 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;\n private reasoningEngine: ReasoningEngine | null = null;\n private promptManager: PromptManager | null = null;\n private outputParser: OutputParser | null = null;\n private toolSystem: ToolSystem | null = null;\n\n constructor(config: AgentFactoryConfig) {\n this.config = config;\n // Basic validation\n if (!config.storage) throw new Error('Storage configuration is required.');\n if (!config.reasoning) throw new Error('Reasoning configuration is required.');\n }\n\n /**\n * Initializes shared components like storage and UI system.\n * Should be called once before creating agents.\n */\n async initialize(): Promise<void> {\n // --- Initialize Storage ---\n switch (this.config.storage.type) {\n case 'indexedDB':\n // Assuming constructor expects { dbName: string, objectStores: string[] }\n this.storageAdapter = new IndexedDBStorageAdapter({\n dbName: this.config.storage.dbName || 'ARTDB',\n objectStores: ['conversations', 'observations', 'state'], // Define required stores\n });\n break;\n case 'memory':\n default:\n this.storageAdapter = new InMemoryStorageAdapter();\n break;\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\n // --- Initialize UI System ---\n // UISystem constructor expects repositories, not sockets\n this.uiSystem = new UISystemImpl(this.observationRepository!, this.conversationRepository!); // Pass repositories\n\n // --- Initialize Managers ---\n // Pass the actual socket instances obtained from the initialized uiSystem\n this.conversationManager = new ConversationManagerImpl(\n this.conversationRepository!,\n this.uiSystem.getConversationSocket()\n );\n this.stateManager = new StateManagerImpl(this.stateRepository!);\n this.observationManager = new ObservationManagerImpl(\n this.observationRepository!,\n this.uiSystem.getObservationSocket()\n );\n\n // --- Initialize Tool Registry & Register Tools ---\n this.toolRegistry = new ToolRegistryImpl();\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 Reasoning Provider ---\n // --- Initialize Reasoning Provider ---\n const reasoningConfig = this.config.reasoning;\n switch (reasoningConfig.provider) {\n case 'openai':\n this.providerAdapter = new OpenAIAdapter({\n apiKey: reasoningConfig.apiKey,\n model: reasoningConfig.model,\n });\n break;\n case 'gemini':\n this.providerAdapter = new GeminiAdapter({\n apiKey: reasoningConfig.apiKey,\n model: reasoningConfig.model,\n });\n break;\n case 'anthropic':\n this.providerAdapter = new AnthropicAdapter({\n apiKey: reasoningConfig.apiKey,\n model: reasoningConfig.model,\n });\n break;\n case 'openrouter':\n this.providerAdapter = new OpenRouterAdapter({\n apiKey: reasoningConfig.apiKey,\n model: reasoningConfig.model!,\n }); // Model is required for OpenRouter\n break;\n case 'deepseek':\n this.providerAdapter = new DeepSeekAdapter({\n apiKey: reasoningConfig.apiKey,\n model: reasoningConfig.model,\n });\n break;\n default:\n throw new Error(`Unsupported reasoning provider: ${reasoningConfig.provider}`);\n }\n\n // --- Initialize Reasoning Components ---\n this.reasoningEngine = new ReasoningEngineImpl(this.providerAdapter!); // Add non-null assertion\n this.promptManager = new PromptManagerImpl(); // Basic implementation for now\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(\n this.toolRegistry!,\n this.stateManager!,\n this.observationManager!\n ); // Added observationManager\n }\n\n /**\n * Creates a new agent instance (currently PESAgent) with injected dependencies.\n * Requires initialize() to have been called first.\n * @returns An IAgentCore instance.\n * @returns An IAgentCore instance.\n * @returns An IAgentCore instance.\n * @throws Error if initialize() was not called or failed.\n */\n createAgent(): IAgentCore {\n // Check for all required components after initialization\n if (\n !this.stateManager ||\n !this.conversationManager ||\n !this.toolRegistry ||\n !this.promptManager ||\n !this.reasoningEngine ||\n !this.outputParser ||\n !this.observationManager ||\n !this.toolSystem ||\n !this.providerAdapter\n ) {\n // Added providerAdapter check\n throw new Error(\n 'AgentFactory not fully initialized. Call initialize() before creating an agent.'\n );\n }\n\n // Pass dependencies to the agent constructor\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 // 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 // --- Optional: Getters for accessing initialized components if needed externally ---\n getStorageAdapter(): StorageAdapter | null {\n return this.storageAdapter;\n }\n getUISystem(): UISystem | null {\n return this.uiSystem;\n }\n getToolRegistry(): ToolRegistry | null {\n return this.toolRegistry;\n }\n getStateManager(): StateManager | null {\n return this.stateManager;\n }\n getConversationManager(): ConversationManager | null {\n return this.conversationManager;\n }\n getObservationManager(): ObservationManager | null {\n return this.observationManager;\n }\n // ... add others as needed\n}\n\n// --- Convenience Factory Function ---\nimport { ArtInstance } from './interfaces'; // Import the new interface\n\n/**\n * Creates and initializes an ART instance with the specified configuration.\n * This is the recommended way to get started with the ART framework.\n * @param config The configuration for the ART instance.\n * @returns A promise resolving to the initialized ArtInstance.\n */\nexport async function createArtInstance(config: AgentFactoryConfig): Promise<ArtInstance> {\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\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 };\n}\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// Define the allowed functions from mathjs\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 // Constants (implicitly allowed via evaluate, but good to be aware)\n // pi: math.pi,\n // e: math.e,\n};\n\nexport class CalculatorTool implements IToolExecutor {\n public static readonly toolName = 'calculator';\n\n readonly schema: ToolSchema = {\n name: CalculatorTool.toolName,\n description: `Evaluates mathematical expressions using a sandboxed mathjs environment. IMPORTANT LIMITATIONS: Each expression is evaluated independently; there is no memory of previous results (e.g., no 'ans' variable). Only a specific list of functions is supported.\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.`,\n inputSchema: {\n type: 'object',\n properties: {\n expression: {\n type: 'string',\n description:\n 'The mathematical expression to evaluate (e.g., \"2 + 2\", \"sqrt(a)\", \"a * b\", \"sqrt(-4)\").',\n },\n scope: {\n type: 'object',\n description:\n '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 // Removed outputSchema due to type conflicts with 'oneOf'. Output is { result: number | string }.\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 {\n input: { expression: 'sqrt(16)' },\n output: { result: 4 },\n description: 'Square root function',\n },\n {\n input: { expression: 'a + b', scope: { a: 7, b: 3 } },\n output: { result: 10 },\n description: 'Expression with variables',\n },\n {\n input: { expression: 'result % 13', scope: { result: 347 } },\n output: { result: 9 },\n description: 'Modulo with variable',\n },\n {\n input: { expression: 'sqrt(-4)' },\n output: { result: '2i' },\n description: 'Square root of negative (complex result)',\n },\n {\n input: { expression: 'pow(i, 2)' },\n output: { result: -1 },\n description: 'Complex number calculation (i^2)',\n },\n {\n input: { expression: 'log(10)' },\n output: { result: 2.302585092994046 },\n description: 'Natural logarithm',\n },\n // Example of a disallowed function (if factorial '!' were disallowed)\n // { input: { expression: \"5!\" }, error: \"Failed to evaluate expression: Function factorial is not allowed\" },\n ],\n };\n\n // TODO: Enhance CalculatorTool:\n // 1. Implement state management to allow referencing previous results within a single execution sequence (e.g., using 'ans' or similar).\n // 2. Expand the library of allowed functions (e.g., add 'digits', factorial '!', statistical functions, etc.). Consider security implications.\n async execute(input: any, context: ExecutionContext): Promise<ToolResult> {\n const expression = input.expression as string;\n // Combine user scope with allowed functions. User scope takes precedence if names clash.\n const executionScope = { ...allowedFunctions, ...(input.scope || {}) };\n const callId = context.traceId || 'calculator-call';\n\n Logger.debug(\n `CalculatorTool executing with expression: \"${expression}\" and combined scope keys: ${Object.keys(executionScope).join(', ')}`,\n { callId, context }\n );\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 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(\n `CalculatorTool failed to evaluate expression \"${expression}\": ${error.message}`,\n { callId, error }\n );\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}\n","// --- Core Factory ---\nexport { createArtInstance } from './core/agent-factory';\n\n// --- Agent Core Implementations ---\nexport { PESAgent } from './core/agents/pes-agent';\n// export { ReActAgent } from './core/agents/react-agent'; // Example for future\n\n// --- Storage Adapters ---\nexport { InMemoryStorageAdapter } from './adapters/storage/inMemory';\nexport { IndexedDBStorageAdapter } from './adapters/storage/indexedDB';\n\n// --- Reasoning Adapters ---\nexport { GeminiAdapter } from './adapters/reasoning/gemini';\nexport { OpenAIAdapter } from './adapters/reasoning/openai';\nexport { AnthropicAdapter } from './adapters/reasoning/anthropic';\nexport { OpenRouterAdapter } from './adapters/reasoning/openrouter';\nexport { DeepSeekAdapter } from './adapters/reasoning/deepseek';\n\n// --- Tools ---\nexport { CalculatorTool } from './tools/CalculatorTool';\n// export { WebSearchTool } from './tools/WebSearchTool'; // Example for future\n\n// --- Core Types & Interfaces ---\nexport * from './types'; // Export all types from the central types file\nexport * from './core/interfaces'; // Export all core interfaces\n\n// --- Utilities ---\nexport { Logger, LogLevel } from './utils/logger';\nexport { generateUUID } from './utils/uuid';\n\n// --- Framework Version ---\nexport const VERSION = '0.2.4';\n"]}
|