{
  "version": 3,
  "sources": ["../src/index.js", "../src/orchestration/daitanOrchestrator.js", "../src/intelligence/core/llmOrchestrator.js", "../src/intelligence/core/promptBuilder.js", "../src/intelligence/core/expertModels.js", "../src/intelligence/core/llmPricing.js", "../src/intelligence/core/tokenUtils.js", "../src/services/llmService.js", "../src/intelligence/index.js", "../src/intelligence/core/embeddingGenerator.js", "../src/intelligence/core/toolFactory.js", "../src/intelligence/rag/index.js", "../src/intelligence/rag/retrieval.js", "../src/intelligence/rag/vectorStoreFactory.js", "../src/intelligence/rag/chromaVectorStoreAdapter.js", "../src/intelligence/rag/chromaClient.js", "../src/intelligence/rag/memoryVectorStoreAdapter.js", "../src/intelligence/rag/chatMemory.js", "../src/intelligence/rag/chat.js", "../src/intelligence/rag/embed.js", "../src/intelligence/rag/documentLoader.js", "../src/intelligence/metadata/parse.js", "../src/intelligence/metadata/index.js", "../src/intelligence/rag/printStats.js", "../src/intelligence/search/specializedSearch.js", "../src/intelligence/tools/tool-registries.js", "../src/intelligence/tools/calculatorTool.js", "../src/intelligence/tools/wikipediaSearchTool.js", "../src/intelligence/tools/cliTool.js", "../src/intelligence/tools/webSearchTool.js", "../src/intelligence/tools/userManagementTool.js", "../src/intelligence/tools/csvQueryTool.js", "../src/intelligence/tools/createPaymentIntentTool.js", "../src/intelligence/tools/youtubeSearchTool.js", "../src/intelligence/tools/processYoutubeAudioTool.js", "../src/intelligence/tools/imageGenerationTool.js", "../src/intelligence/tools/gmailTools.js", "../src/intelligence/tools/calendarTool.js", "../src/intelligence/tools/googleDriveTools.js", "../src/intelligence/tools/ragTool.js", "../src/intelligence/tools/baseTool.js", "../src/intelligence/agents/agentRunner.js", "../src/intelligence/workflows/graphRunner.js", "../src/intelligence/workflows/planAndExecuteAgentGraph.js", "../src/intelligence/workflows/langGraphManager.js", "../src/intelligence/workflows/reactWithReflectionAgentGraph.js", "../src/intelligence/agents/agentExecutor.js", "../src/intelligence/agents/prompts/generalAgentPrompt.js", "../src/memory/inMemoryChatHistoryStore.js", "../src/intelligence/agents/baseAgent.js", "../src/intelligence/agents/chat/index.js", "../src/intelligence/agents/chat/choreographerAgent.js", "../src/intelligence/agents/chat/coachAgent.js", "../src/intelligence/agents/chat/openingPhraseAgent.js", "../src/intelligence/agents/chat/participantAgent.js", "../src/intelligence/workflows/index.js", "../src/intelligence/workflows/presets/deepResearchAgent.js", "../src/intelligence/workflows/presets/searchAndUnderstand.js", "../src/intelligence/workflows/presets/automatedResearchAgent.js", "../src/intelligence/core/ollamaUtils.js", "../src/caching/cacheManager.js", "../src/language/index.js"],
  "sourcesContent": ["// src/index.js\n/**\n * @file Main public entry point for the @daitanjs/intelligence package.\n * @module @daitanjs/intelligence\n */\nimport { getLogger } from '@daitanjs/development';\n\nconst mainIndexLogger = getLogger('daitan-intelligence-main-index');\n\nmainIndexLogger.debug(\n  'Initializing DaitanJS Intelligence main package exports...'\n);\n\n// --- Core Abstractions & Services ---\nexport { DaitanOrchestrator } from './orchestration/daitanOrchestrator.js';\nexport { LLMService } from './services/llmService.js';\n\n// --- Configuration Management ---\nexport {\n  getConfigManager,\n  initializeConfigManager,\n  DaitanConfigManagerClass,\n} from '@daitanjs/config';\n\n// --- Core Intelligence & Utilities ---\nexport {\n  generateIntelligence,\n  generateEmbedding,\n  askWithRetrieval,\n  createRagChatInstance,\n  loadAndEmbedFile,\n  printStoreStats,\n  getVectorStore,\n  vectorStoreCollectionExists,\n  checkChromaConnection,\n  runToolCallingAgent,\n  runGraphAgent,\n  runDeepResearchAgent,\n  runAutomatedResearchWorkflow,\n  searchAndUnderstand,\n  // --- New Export for Specialized Search ---\n  searchNews,\n  searchGeneralWeb,\n  searchAcademic,\n  BaseAgent,\n  ChoreographerAgent,\n  CoachAgent,\n  OpeningPhraseAgent,\n  ParticipantAgent,\n  createDaitanTool,\n  getDefaultTools,\n  getDaitanPlatformTools,\n  BaseTool,\n  DaitanLangGraph,\n  createGraphRunner,\n  estimateLlmCost,\n  countTokens,\n  countTokensForMessages,\n  checkOllamaStatus,\n} from './intelligence/index.js';\n\n// --- Caching ---\nexport {\n  getCache,\n  generateCacheKey,\n  clearCache,\n} from './caching/cacheManager.js';\n\n// --- Memory Management ---\nexport { InMemoryChatMessageHistoryStore } from './memory/inMemoryChatHistoryStore.js';\n\n// --- Language Services ---\nexport { translate } from './language/index.js';\n\nmainIndexLogger.info(\n  'DaitanJS Intelligence package main exports configured and ready.'\n);\n", "// intelligence/src/orchestration/daitanOrchestrator.js\n/**\n * @file High-level orchestrator facade for the DaitanJS Intelligence library.\n * @module @daitanjs/orchestration/daitanOrchestrator\n *\n * @description\n * The DaitanOrchestrator provides a simplified, unified interface to the most common\n * and powerful functionalities of the @daitanjs/intelligence package. It is designed\n * to be the primary entry point for developers, abstracting away the underlying\n * complexity of service instantiation, graph compilation, and state management.\n * It now includes direct access to the most powerful research agent.\n */\nimport { getLogger } from '@daitanjs/development';\nimport { getConfigManager } from '@daitanjs/config';\nimport { LLMService } from '../services/llmService.js';\nimport {\n  askWithRetrieval,\n  loadAndEmbedFile,\n  printStoreStats,\n  runToolCallingAgent,\n  runDeepResearchAgent, // NEW: Direct import of the best research agent\n  getDefaultTools,\n  createGraphRunner,\n  createPlanAndExecuteAgentGraph,\n  createReActAgentGraph,\n  runAutomatedResearchWorkflow,\n  InMemoryChatMessageHistoryStore,\n} from '../intelligence/index.js'; // Use the main barrel file\nimport { HumanMessage } from '@langchain/core/messages';\n\nconst logger = getLogger('daitan-orchestrator');\n\n/**\n * @typedef {import('../services/llmService.js').LLMServiceConfig} LLMServiceConfig\n * @typedef {import('../intelligence/rag/interfaces.js').AskWithRetrievalOptions} AskWithRetrievalOptions\n * @typedef {import('../intelligence/rag/interfaces.js').LoadAndEmbedOptions} LoadAndEmbedOptions\n * @typedef {import('../intelligence/agents/agentExecutor.js').RunDaitanAgentParams} RunToolCallingAgentParams\n * @typedef {import('../intelligence/workflows/planAndExecuteAgentGraph.js').PlanAndExecuteAgentState} PlanAndExecuteAgentState\n * @typedef {import('../intelligence/workflows/reactWithReflectionAgentGraph.js').ReActAgentState} ReActAgentState\n * @typedef {import('../intelligence/workflows/presets/automatedResearchAgent.js').ResearchState} AutomatedResearchState\n * @typedef {import('../intelligence/workflows/graphRunner.js').CreateGraphRunnerOptions} CreateGraphRunnerOptions\n */\n\nexport class DaitanOrchestrator {\n  /**\n   * @param {Object} [orchestratorConfig={}]\n   * @param {LLMServiceConfig} [orchestratorConfig.llmServiceConfig] - Configuration for the internal LLMService.\n   * @param {LLMService} [orchestratorConfig.llmServiceInstance] - An existing LLMService instance.\n   * @param {boolean} [orchestratorConfig.verboseGlobal] - Global verbosity for orchestrator operations.\n   */\n  constructor(orchestratorConfig = {}) {\n    const configManager = getConfigManager();\n    this.verbose =\n      orchestratorConfig.verboseGlobal ??\n      (configManager.get('DEBUG_ORCHESTRATOR', false) ||\n        configManager.get('DEBUG_INTELLIGENCE', false));\n\n    this.llmService =\n      orchestratorConfig.llmServiceInstance instanceof LLMService\n        ? orchestratorConfig.llmServiceInstance\n        : new LLMService({\n            ...orchestratorConfig.llmServiceConfig,\n            verbose: this.verbose,\n          });\n\n    this.compiledGraphs = {};\n    this.defaultHistoryStore = new InMemoryChatMessageHistoryStore();\n\n    logger.info('DaitanOrchestrator fully initialized.');\n  }\n\n  /**\n   * Direct call to the underlying LLM service.\n   * @param {import('../services/llmService.js').GenerateIntelligenceParams} params\n   * @returns {Promise<import('../intelligence/core/llmOrchestrator.js').GenerateIntelligenceResult<any>>}\n   */\n  async llmCall(params) {\n    if (this.verbose) {\n      logger.info('Orchestrator: Initiating direct LLM call.', {\n        summary: params.metadata?.summary,\n      });\n    }\n    // The LLMService's generate method handles merging defaults correctly.\n    return this.llmService.generate(params);\n  }\n\n  /**\n   * Performs a RAG query with advanced options.\n   * @param {string} query - The user's query.\n   * @param {AskWithRetrievalOptions} [ragOptions] - Options for askWithRetrieval.\n   * @returns {Promise<import('../intelligence/rag/retrieval.js').RetrievalResult>}\n   */\n  async ragQuery(query, ragOptions = {}) {\n    if (this.verbose)\n      logger.info(\n        `Orchestrator: Initiating RAG query for: \"${query.substring(\n          0,\n          50\n        )}...\"`,\n        { collection: ragOptions.collectionName }\n      );\n    return askWithRetrieval(query, {\n      localVerbose: this.verbose,\n      ...ragOptions,\n    });\n  }\n\n  /**\n   * Loads and embeds a file into the vector store.\n   * @param {string} filePath - Path to the file.\n   * @param {Object} [customMetadata={}] - Custom metadata to add.\n   * @param {LoadAndEmbedOptions} [embedOptions={}] - Options for loadAndEmbedFile.\n   * @returns {Promise<object>} An object indicating success and embedding stats.\n   */\n  async embedFile(filePath, customMetadata = {}, embedOptions = {}) {\n    if (this.verbose)\n      logger.info(\n        `Orchestrator: Initiating file embedding for: \"${filePath}\"`,\n        { collection: embedOptions.collectionName }\n      );\n    return loadAndEmbedFile({\n      filePath,\n      customMetadata,\n      options: { localVerbose: this.verbose, ...embedOptions },\n    });\n  }\n\n  /**\n   * Prints statistics for a RAG collection.\n   * @param {string} [collectionName] - Name of the collection.\n   * @returns {Promise<void>}\n   */\n  async getRagStats(collectionName) {\n    if (this.verbose)\n      logger.info(\n        `Orchestrator: Requesting RAG stats for collection: \"${\n          collectionName || 'default'\n        }\"`\n      );\n    return printStoreStats({ collectionName, localVerbose: this.verbose });\n  }\n\n  /**\n   * Runs the most advanced, multi-step research agent to answer a complex query.\n   * @param {string} query - The complex question or research topic.\n   * @param {import('../intelligence/workflows/presets/deepResearchAgent.js').runDeepResearchAgent} options - Options for the deep research agent, including `thinkingLevel`, `collectionName`, `onProgress`, and `chatHistory`.\n   * @returns {Promise<{finalAnswer: string, sources: string[], plan: any[]}>} The comprehensive answer and its sources.\n   */\n  async research(query, options) {\n    if (this.verbose) {\n      logger.info(\n        `Orchestrator: Initiating deep research for topic: \"${query}\"`\n      );\n    }\n    // Directly call the powerful, imported research agent\n    return runDeepResearchAgent(query, options);\n  }\n\n  /**\n   * Runs a general-purpose tool-using agent.\n   * @param {RunToolCallingAgentParams} params - The parameters for the agent run.\n   * @returns {Promise<Object>}\n   */\n  async runToolAgent(params) {\n    if (this.verbose)\n      logger.info(`Orchestrator: Running tool-calling Agent.`, {\n        input: params.input.substring(0, 50) + '...',\n        sessionId: params.sessionId,\n      });\n\n    return runToolCallingAgent({\n      historyStore: this.defaultHistoryStore,\n      verbose: this.verbose,\n      ...params,\n    });\n  }\n\n  // The more granular agent runners below are kept for advanced use cases or backward compatibility.\n  // The top-level `research` method is now the recommended entry point for research tasks.\n\n  /**\n   * Runs the Plan-and-Execute agent graph.\n   * @param {string} query - The user's original query.\n   * @param {object} [options={}] - Options for the run.\n   * @returns {Promise<PlanAndExecuteAgentState>}\n   */\n  async runPlanAndExecuteAgent(query, options = {}) {\n    const { tools, initialState = {}, sessionId, onStateUpdate } = options;\n    const effectiveSessionId = sessionId || `plan-exec-${Date.now()}`;\n    if (this.verbose)\n      logger.info(\n        `Orchestrator: Running Plan-and-Execute Agent for query: \"${query.substring(\n          0,\n          50\n        )}...\"`,\n        { sessionId: effectiveSessionId }\n      );\n\n    if (!this.compiledGraphs.planAndExecute) {\n      this.compiledGraphs.planAndExecute = await createPlanAndExecuteAgentGraph(\n        this.llmService,\n        tools || getDefaultTools()\n      );\n      logger.info('Compiled Plan-and-Execute graph for the first time.');\n    }\n\n    const runner = createGraphRunner(this.compiledGraphs.planAndExecute, {\n      verbose: this.verbose,\n      onStateUpdate,\n    });\n    const effectiveTools = tools || getDefaultTools();\n\n    const finalInitialState = {\n      originalQuery: query,\n      inputMessage: new HumanMessage(query),\n      llmServiceInstance: this.llmService,\n      toolsMap: effectiveTools.reduce(\n        (map, tool) => ({ ...map, [tool.name]: tool }),\n        {}\n      ),\n      verbose: this.verbose,\n      ...initialState,\n    };\n    return runner(finalInitialState, {\n      configurable: { thread_id: effectiveSessionId },\n    });\n  }\n}\n", "// intelligence/src/intelligence/core/llmOrchestrator.js\n/**\n * @file The final, stable, and feature-complete LLM orchestrator.\n * @module @daitanjs/intelligence/core/llmOrchestrator\n *\n * @description\n * This file contains the fully restored logic for the intelligence orchestrator.\n * It is built on a proven stable core and safely integrates multi-provider support,\n * expert profile resolution, configuration, and robust error handling.\n * For architectural guidance, see the README.md in this directory.\n */\nimport { ChatOpenAI } from '@langchain/openai';\nimport { ChatAnthropic } from '@langchain/anthropic';\nimport { ChatGroq } from '@langchain/groq';\nimport {\n  StringOutputParser,\n  JsonOutputParser,\n} from '@langchain/core/output_parsers';\nimport { getConfigManager } from '@daitanjs/config';\nimport { DaitanApiError, DaitanConfigurationError } from '@daitanjs/error';\nimport { buildLlmMessages } from './promptBuilder.js';\nimport { getExpertModelDefinition } from './expertModels.js';\nimport { estimateLlmCost } from './llmPricing.js';\nimport { countTokensForMessages, countTokens } from './tokenUtils.js';\nimport { getLogger } from '@daitanjs/development';\n\nconst logger = getLogger('daitan-llm-orchestrator');\n\n/**\n * Extracts a JSON object from a string, especially if it's wrapped in markdown code fences.\n * @param {string} text - The input string which might contain a JSON object.\n * @returns {string} - The extracted JSON string or the original text if no JSON is found.\n */\nfunction extractJsonFromString(text) {\n  if (typeof text !== 'string') return text;\n\n  // This regex finds JSON within ```json ... ``` or just the first valid { ... } or [ ... ]\n  const jsonRegex = /```(?:json)?\\s*([\\s\\S]+?)\\s*```|({[\\s\\S]*}|\\[[\\s\\S]*\\])/m;\n  const match = text.match(jsonRegex);\n\n  // If a match is found, return the captured group (either from the code block or the raw object/array).\n  // Otherwise, return the original text to let the parser try.\n  return match ? match[1] || match[2] || text : text;\n}\n\nexport const generateIntelligence = async ({\n  prompt = {},\n  config = {},\n  callbacks,\n  metadata = {}, // Add metadata to destructuring\n}) => {\n  const {\n    llm: llmConfig = {},\n    response: responseConfig = {},\n    ...otherConfigs\n  } = config;\n\n  if (!prompt.user && (!prompt.shots || prompt.shots.length === 0)) {\n    throw new DaitanConfigurationError(\n      'A `prompt.user` message or messages in `prompt.shots` are required.'\n    );\n  }\n\n  let llm;\n  let providerName;\n  let modelName;\n  let temperature;\n\n  try {\n    const configManager = getConfigManager();\n    const rawTarget =\n      llmConfig.target ||\n      configManager.get('DEFAULT_EXPERT_PROFILE') ||\n      configManager.get('LLM_PROVIDER') ||\n      'FAST_TASKER';\n\n    const expertDef = getExpertModelDefinition(rawTarget);\n    if (expertDef) {\n      providerName = expertDef.provider.toLowerCase();\n      modelName = expertDef.model;\n      temperature = expertDef.temperature;\n    } else {\n      const [p, m] = rawTarget.split('|');\n      providerName = p ? p.toLowerCase() : 'openai';\n      modelName = m;\n    }\n\n    const commonConfig = {\n      temperature: temperature ?? llmConfig.temperature ?? 0.7,\n      maxRetries: config.retry?.maxAttempts ?? 2,\n      timeout: llmConfig.requestTimeout,\n      modelName: modelName,\n    };\n\n    switch (providerName) {\n      case 'openai': {\n        const apiKey = llmConfig.apiKey || configManager.get('OPENAI_API_KEY');\n        if (!apiKey)\n          throw new DaitanConfigurationError('OPENAI_API_KEY not found.');\n        llm = new ChatOpenAI({ ...commonConfig, apiKey });\n        break;\n      }\n      case 'anthropic': {\n        const apiKey =\n          llmConfig.apiKey || configManager.get('ANTHROPIC_API_KEY');\n        if (!apiKey)\n          throw new DaitanConfigurationError('ANTHROPIC_API_KEY not found.');\n        llm = new ChatAnthropic({ ...commonConfig, apiKey });\n        break;\n      }\n      case 'groq': {\n        const apiKey = llmConfig.apiKey || configManager.get('GROQ_API_KEY');\n        if (!apiKey)\n          throw new DaitanConfigurationError('GROQ_API_KEY not found.');\n        llm = new ChatGroq({ ...commonConfig, apiKey });\n        break;\n      }\n      default:\n        throw new DaitanConfigurationError(\n          `Unsupported provider in orchestrator: '${providerName}'`\n        );\n    }\n\n    // --- DEFINITIVE FIX: Use the new `buildLlmMessages` which correctly parses the structured prompt object ---\n    const messages = buildLlmMessages(prompt);\n    // --- END OF FIX ---\n\n    const result = await llm.invoke(messages, { callbacks });\n    const rawContent = result.content ?? '';\n\n    let contentToParse = rawContent;\n    if (responseConfig.format === 'json') {\n      contentToParse = extractJsonFromString(rawContent);\n    }\n\n    const parser =\n      responseConfig.format === 'json'\n        ? new JsonOutputParser()\n        : new StringOutputParser();\n\n    const finalResponse = await parser.parse(contentToParse);\n\n    const usageMetadata = result.usage_metadata ?? {};\n    const usage = {\n      inputTokens:\n        usageMetadata.inputTokens ??\n        (await countTokensForMessages(messages, modelName, providerName)),\n      outputTokens:\n        usageMetadata.outputTokens ??\n        (await countTokens(\n          typeof finalResponse === 'string'\n            ? finalResponse\n            : JSON.stringify(finalResponse ?? ''),\n          modelName,\n          providerName\n        )),\n    };\n    usage.totalTokens = (usage.inputTokens || 0) + (usage.outputTokens || 0);\n    const cost = estimateLlmCost(\n      providerName,\n      modelName,\n      usage.inputTokens,\n      usage.outputTokens\n    );\n\n    return {\n      response: finalResponse,\n      usage: { ...usage, ...cost },\n      rawResponse: rawContent,\n    };\n  } catch (error) {\n    logger.error(\n      `LLM Interaction Failed. Summary: ${\n        metadata.summary || 'N/A'\n      }. Provider: ${providerName}, Model: ${modelName}. Error: ${\n        error.message\n      }`,\n      { errorStack: error.stack }\n    );\n\n    throw new DaitanApiError(\n      `An unrecoverable error occurred during the LLM interaction with provider '${\n        providerName || 'unknown'\n      }'.`,\n      providerName || 'unknown',\n      error?.status,\n      { model: modelName, summary: metadata.summary },\n      error\n    );\n  }\n};\n", "// intelligence/src/intelligence/core/promptBuilder.js\n/**\n * @file Contains helpers for building and constructing prompt message arrays for LLMs.\n * @module @daitanjs/intelligence/core/promptBuilder\n *\n * @description\n * This module centralizes the logic for creating the list of messages that will be sent\n * to a large language model. It handles the assembly of system messages, few-shot examples\n * (`shots`), and the final user prompt into a structured format compatible with\n * LangChain's chat models.\n */\n\nimport {\n  HumanMessage,\n  SystemMessage,\n  AIMessage,\n  BaseMessage,\n} from '@langchain/core/messages';\nimport { getLogger } from '@daitanjs/development';\n\nconst promptBuilderLogger = getLogger('daitan-prompt-builder');\n\n/**\n * Converts an array of DaitanJS-style message objects into LangChain `BaseMessage` instances.\n * @private\n * @param {Array<Object>} messages - Array of message objects (e.g., `{role: 'user', content: '...'}`).\n * @returns {BaseMessage[]} An array of LangChain message instances.\n */\nfunction convertToLangChainMessages(messages) {\n  if (!Array.isArray(messages)) {\n    return [];\n  }\n  return messages.reduce((acc, msg) => {\n    if (msg instanceof BaseMessage) {\n      acc.push(msg);\n    } else if (\n      typeof msg === 'object' &&\n      msg !== null &&\n      typeof msg.role === 'string' &&\n      (typeof msg.content === 'string' ||\n        Array.isArray(msg.content) ||\n        typeof msg.content === 'object') // Allow object for JSON few-shot\n    ) {\n      const role = msg.role.toLowerCase();\n      try {\n        if (role === 'system')\n          acc.push(new SystemMessage({ content: msg.content }));\n        else if (role === 'user' || role === 'human')\n          acc.push(new HumanMessage({ content: msg.content }));\n        else if (role === 'assistant' || role === 'ai')\n          acc.push(new AIMessage({ content: msg.content }));\n        else {\n          promptBuilderLogger.warn(\n            `Unknown message role \"${msg.role}\". Treating as human.`\n          );\n          acc.push(new HumanMessage({ content: msg.content }));\n        }\n      } catch (e) {\n        promptBuilderLogger.error(\n          'Failed to create LangChain message from object.',\n          { messageObject: msg, error: e.message }\n        );\n        // ignore malformed message\n      }\n    }\n    return acc;\n  }, []);\n}\n\n/**\n * Builds the final array of message objects to be sent to the LLM from a structured prompt object.\n *\n * @param {Object} prompt - The structured prompt object.\n * @param {Object} [prompt.system] - An object containing parts of the system message (e.g., persona, task).\n * @param {string | object} [prompt.user] - The final user query.\n * @param {Array} [prompt.shots=[]] - Few-shot examples in `{role, content}` format.\n * @returns {BaseMessage[]} An array of LangChain `BaseMessage` objects ready for an LLM.\n */\nexport const buildLlmMessages = (prompt = {}) => {\n  const systemConfig = prompt.system || {};\n  const userContent = prompt.user;\n  const fewShotExamples = prompt.shots || [];\n\n  // This order defines the structure of the system prompt.\n  const systemInstructionParts = [\n    systemConfig.persona,\n    systemConfig.whoYouAre, // Legacy support\n    systemConfig.task,\n    systemConfig.whatYouDo, // Legacy support\n    systemConfig.guidelines,\n    systemConfig.vitals,\n    systemConfig.scoring,\n    systemConfig.writingStyle,\n    systemConfig.outputFormat,\n    systemConfig.outputFormatDescription, // Legacy support\n    systemConfig.promptingTips,\n    systemConfig.reiteration,\n  ];\n\n  const systemInstructionContent = systemInstructionParts\n    .filter(Boolean)\n    .join('\\n\\n');\n\n  let messages = [];\n  if (systemInstructionContent) {\n    messages.push({ role: 'system', content: systemInstructionContent });\n  }\n\n  if (Array.isArray(fewShotExamples) && fewShotExamples.length > 0) {\n    messages.push(\n      ...fewShotExamples.filter(\n        (s) =>\n          s &&\n          typeof s.role === 'string' &&\n          (typeof s.content === 'string' ||\n            Array.isArray(s.content) ||\n            typeof s.content === 'object')\n      )\n    );\n  }\n\n  if (\n    userContent &&\n    (typeof userContent === 'string' || typeof userContent === 'object')\n  ) {\n    messages.push({ role: 'user', content: userContent });\n  }\n\n  return convertToLangChainMessages(messages);\n};\n", "// intelligence/src/intelligence/core/expertModels.js\nimport { getEnvVariable } from '@daitanjs/development';\n\nexport const DEFAULT_EXPERT_PROFILE_NAME = getEnvVariable(\n  'DEFAULT_EXPERT_PROFILE',\n  'FAST_TASKER'\n);\n\nconst getExpertConfig = (envVarKey, defaultValue) => {\n  const combinedValue = getEnvVariable(envVarKey, defaultValue);\n  const parts = combinedValue.split('|');\n  const provider = parts[0]?.trim();\n  const model = parts[1]?.trim();\n  if (!provider || !model) {\n    const [defaultProvider, defaultModel] = defaultValue.split('|');\n    return { provider: defaultProvider.trim(), model: defaultModel.trim() };\n  }\n  return { provider, model };\n};\n\nexport const EXPERT_MODELS = {\n  MASTER_COMMUNICATOR: {\n    ...getExpertConfig('LLM_EXPERT_MASTER_COMMUNICATOR', 'openai|gpt-4o-mini'),\n    description: 'Expert in clear, concise, and engaging communication.',\n    temperature: 0.7,\n  },\n  CREATIVE_WRITER: {\n    ...getExpertConfig('LLM_EXPERT_CREATIVE_WRITER', 'openai|gpt-4-turbo'),\n    description: 'Expert in creative writing, storytelling, and brainstorming.',\n    temperature: 0.9,\n  },\n  FAST_TASKER: {\n    ...getExpertConfig('LLM_EXPERT_FAST_TASKER', 'openai|gpt-4o-mini'),\n    description: 'Optimized for speed on less complex tasks.',\n    temperature: 0.5,\n  },\n  LOCAL_DEFAULT: {\n    ...getExpertConfig('LLM_EXPERT_LOCAL_DEFAULT', 'ollama|llama3:instruct'),\n    description: 'A general-purpose model running locally via Ollama.',\n    temperature: 0.7,\n  },\n  MASTER_CODER: {\n    ...getExpertConfig(\n      'LLM_EXPERT_MASTER_CODER',\n      'anthropic|claude-3-opus-20240229'\n    ),\n    description: 'Expert in code generation, debugging, and explanation.',\n    temperature: 0.3,\n  },\n  CODING_STUDENT: {\n    ...getExpertConfig('LLM_EXPERT_CODING_STUDENT', 'openai|gpt-4o-mini'),\n    description: 'Capable, cost-effective coding assistant for simpler tasks.',\n    temperature: 0.5,\n  },\n  SENTIMENT_WIZARD: {\n    ...getExpertConfig('LLM_EXPERT_SENTIMENT_WIZARD', 'openai|gpt-3.5-turbo'),\n    description:\n      'Specialized in sentiment analysis and understanding nuanced text.',\n    temperature: 0.2,\n  },\n  TRANSLATION_MULTILINGUAL: {\n    ...getExpertConfig(\n      'LLM_EXPERT_TRANSLATION_MULTILINGUAL',\n      'openai|gpt-4o-mini'\n    ),\n    description: 'Expert in multilingual translation.',\n    temperature: 0.1,\n  },\n  DATA_ANALYSIS_EXPERT: {\n    ...getExpertConfig('LLM_EXPERT_DATA_ANALYSIS', 'openai|gpt-4-turbo'),\n    description: 'Expert in interpreting data and generating insights.',\n    temperature: 0.4,\n  },\n  RESEARCH_ASSISTANT: {\n    ...getExpertConfig('LLM_EXPERT_RESEARCH_ASSISTANT', 'openai|gpt-4-turbo'),\n    description:\n      'Specialized in synthesizing information and research queries.',\n    temperature: 0.5,\n  },\n};\n\nexport const getExpertModelDefinition = (expertName) => {\n  if (typeof expertName !== 'string' || !expertName.trim()) return undefined;\n  return EXPERT_MODELS[expertName.toUpperCase()];\n};\n\nexport const getDefaultExpertProfile = () => {\n  return getExpertModelDefinition(DEFAULT_EXPERT_PROFILE_NAME);\n};\n", "// intelligence/src/intelligence/core/llmPricing.js\n// This is the full, original code for this file.\n\nimport { getLogger } from '@daitanjs/development';\n\nconst logger = getLogger('llm-pricing');\n\nexport const PROVIDER_MODEL_PRICING = {\n  openai: {\n    'gpt-4o': { inputCostPer1MTokens: 5.0, outputCostPer1MTokens: 15.0 },\n    'gpt-4o-mini': { inputCostPer1MTokens: 0.15, outputCostPer1MTokens: 0.6 },\n    'gpt-4-turbo': { inputCostPer1MTokens: 10.0, outputCostPer1MTokens: 30.0 },\n    'gpt-4': { inputCostPer1MTokens: 30.0, outputCostPer1MTokens: 60.0 },\n    'gpt-3.5-turbo': { inputCostPer1MTokens: 0.5, outputCostPer1MTokens: 1.5 },\n    'text-embedding-3-large': {\n      inputCostPer1MTokens: 0.13,\n      outputCostPer1MTokens: 0.0,\n    },\n    'text-embedding-3-small': {\n      inputCostPer1MTokens: 0.02,\n      outputCostPer1MTokens: 0.0,\n    },\n    'text-embedding-ada-002': {\n      inputCostPer1MTokens: 0.1,\n      outputCostPer1MTokens: 0.0,\n    },\n  },\n  anthropic: {\n    'claude-3-opus-20240229': {\n      inputCostPer1MTokens: 15.0,\n      outputCostPer1MTokens: 75.0,\n    },\n    'claude-3-sonnet-20240229': {\n      inputCostPer1MTokens: 3.0,\n      outputCostPer1MTokens: 15.0,\n    },\n    'claude-3-haiku-20240307': {\n      inputCostPer1MTokens: 0.25,\n      outputCostPer1MTokens: 1.25,\n    },\n  },\n  groq: {\n    'llama3-8b-8192': {\n      inputCostPer1MTokens: 0.05,\n      outputCostPer1MTokens: 0.1,\n    },\n    'llama3-70b-8192': {\n      inputCostPer1MTokens: 0.59,\n      outputCostPer1MTokens: 0.79,\n    },\n    'mixtral-8x7b-32768': {\n      inputCostPer1MTokens: 0.27,\n      outputCostPer1MTokens: 0.27,\n    },\n  },\n  ollama: {\n    'llama3:instruct': {\n      inputCostPer1MTokens: 0,\n      outputCostPer1MTokens: 0,\n      details: 'Local model, no cost.',\n    },\n    'nomic-embed-text': {\n      inputCostPer1MTokens: 0,\n      outputCostPer1MTokens: 0,\n      details: 'Local model, no cost.',\n    },\n  },\n};\n\nexport const estimateLlmCost = (\n  provider,\n  model,\n  inputTokens = 0,\n  outputTokens = 0\n) => {\n  const providerKey = provider?.toLowerCase();\n  const modelKey = model?.toLowerCase();\n  const result = {\n    estimatedCostUSD: null,\n    currency: 'USD',\n    details: 'No pricing information available.',\n  };\n\n  if (!providerKey || !modelKey) {\n    logger.debug('Provider or model key missing for cost estimation.');\n    return result;\n  }\n\n  const providerPricing = PROVIDER_MODEL_PRICING[providerKey];\n  if (!providerPricing) {\n    result.details = `No pricing for provider '${providerKey}'.`;\n    return result;\n  }\n\n  // Find a matching model, allowing for variants like 'gpt-4-turbo-2024-04-09' to match 'gpt-4-turbo'\n  const baseModelKey = Object.keys(providerPricing).find((key) =>\n    modelKey.startsWith(key)\n  );\n\n  if (!baseModelKey) {\n    result.details = `No pricing for model '${modelKey}' under provider '${providerKey}'.`;\n    return result;\n  }\n\n  const modelPricing = providerPricing[baseModelKey];\n\n  if (\n    modelPricing.inputCostPer1MTokens === 0 &&\n    modelPricing.outputCostPer1MTokens === 0\n  ) {\n    result.estimatedCostUSD = 0;\n    result.details = modelPricing.details || 'Model is free or local.';\n    return result;\n  }\n\n  const inputCost =\n    (inputTokens / 1_000_000) * (modelPricing.inputCostPer1MTokens || 0);\n  const outputCost =\n    (outputTokens / 1_000_000) * (modelPricing.outputCostPer1MTokens || 0);\n\n  result.estimatedCostUSD = inputCost + outputCost;\n  result.details = `Cost calculated for ${providerKey}/${baseModelKey}.`;\n\n  return result;\n};\n", "// intelligence/src/intelligence/core/tokenUtils.js\n// This is the full, original code for this file.\n\nimport { get_encoding } from 'tiktoken';\nimport { getLogger } from '@daitanjs/development';\n\nconst logger = getLogger('token-utils');\nconst DEFAULT_CHAR_TO_TOKEN_RATIO = 4;\nconst tiktokenCache = new Map();\n\nconst getTiktokenForModel = (modelNameInput) => {\n  const modelName = String(modelNameInput || '');\n  if (tiktokenCache.has(modelName)) {\n    return tiktokenCache.get(modelName);\n  }\n\n  let encodingName;\n  if (\n    modelName.startsWith('gpt-4') ||\n    modelName.startsWith('gpt-3.5-turbo') ||\n    modelName.startsWith('text-embedding-3') ||\n    modelName.startsWith('gpt-4o')\n  ) {\n    encodingName = 'cl100k_base';\n  } else if (modelName.includes('text-embedding-ada-002')) {\n    encodingName = 'p50k_base';\n  } else {\n    logger.debug(\n      `No specific tiktoken encoding for model \"${modelName}\". Defaulting to cl100k_base.`\n    );\n    encodingName = 'cl100k_base';\n  }\n\n  try {\n    const encoding = get_encoding(encodingName);\n    tiktokenCache.set(modelName, encoding);\n    return encoding;\n  } catch (error) {\n    logger.warn(\n      `Could not initialize tiktoken for model \"${modelName}\" (encoding: ${encodingName}): ${error.message}.`\n    );\n    return null;\n  }\n};\n\nexport const countTokens = (text, modelName, providerName = 'openai') => {\n  if (typeof text !== 'string' || text === '') return 0;\n\n  const openaiCompatibleProviders = [\n    'openai',\n    'groq',\n    'openrouter',\n    'anthropic',\n  ];\n  if (openaiCompatibleProviders.includes(providerName?.toLowerCase() || '')) {\n    const tiktokenInstance = getTiktokenForModel(modelName);\n    if (tiktokenInstance) {\n      try {\n        return tiktokenInstance.encode(text).length;\n      } catch (error) {\n        logger.warn(\n          `Tiktoken encoding failed for model \"${modelName}\". Falling back to char count.`\n        );\n      }\n    }\n  }\n\n  const estimatedTokens = Math.ceil(text.length / DEFAULT_CHAR_TO_TOKEN_RATIO);\n  logger.debug(\n    `Using char-based token approximation for model \"${modelName}\" (provider: ${providerName}). Chars: ${text.length}, Approx Tokens: ${estimatedTokens}`\n  );\n  return estimatedTokens;\n};\n\nexport const countTokensForMessages = (\n  messages,\n  modelName,\n  providerName = 'openai'\n) => {\n  if (!Array.isArray(messages) || messages.length === 0) return 0;\n\n  const tiktokenInstance = getTiktokenForModel(modelName);\n  if (!tiktokenInstance) {\n    let totalChars = 0;\n    messages.forEach((msg) => {\n      if (typeof msg.content === 'string') {\n        totalChars += msg.content.length;\n      }\n    });\n    return (\n      Math.ceil(totalChars / DEFAULT_CHAR_TO_TOKEN_RATIO) + messages.length * 2\n    );\n  }\n\n  let tokensPerMessage = 3;\n  let tokensPerName = 1;\n\n  let numTokens = 0;\n  messages.forEach((message) => {\n    numTokens += tokensPerMessage;\n    for (const key in message) {\n      // Note: LangChain message objects have content as a direct property.\n      if (key === 'content' && typeof message.content === 'string') {\n        numTokens += tiktokenInstance.encode(message.content).length;\n      } else if (key === 'name' && message[key]) {\n        numTokens += tokensPerName;\n      }\n    }\n  });\n\n  numTokens += 3; // every reply is primed with <|start|>assistant<|message|>\n  return numTokens;\n};\n", "// intelligence/src/services/llmService.js\n/**\n * @file Provides a service class for simplified and consistent interaction with LLMs.\n * @module @daitanjs/intelligence/services/llmService\n */\nimport { generateIntelligence } from '../intelligence/core/llmOrchestrator.js';\nimport { getLogger } from '@daitanjs/development';\nimport { getConfigManager } from '@daitanjs/config';\nimport { DaitanInvalidInputError } from '@daitanjs/error';\n\nconst logger = getLogger('daitan-llm-service');\n\n/**\n * @typedef {import('../intelligence/core/llmOrchestrator.js').LLMUsageInfo} LLMUsageInfo\n * @typedef {import('../intelligence/core/llmOrchestrator.js').LLMCallbacks} LLMCallbacks\n * @typedef {import('../intelligence/core/llmOrchestrator.js').GenerateIntelligenceParams} GenerateIntelligenceParams\n */\n\n/**\n * @typedef {Object} LLMServiceConfig\n * @property {string} [target] - Default LLM target, as an expert profile name (e.g., 'FAST_TASKER') or a 'provider|model' string.\n * @property {string} [apiKey] - Default API key (overrides configManager).\n * @property {string} [baseURL] - Default base URL (overrides configManager).\n * @property {number} [temperature] - Default temperature.\n * @property {number} [maxTokens] - Default max_tokens.\n * @property {boolean} [verbose] - Default verbosity for LLM calls.\n * @property {boolean} [trace] - Default LangSmith tracing enablement.\n * @property {boolean} [trackUsage] - Default for tracking token usage.\n * @property {number} [requestTimeout] - Default request timeout for LLM calls.\n * @property {number} [maxRetries] - Default max retries for LLM calls.\n * @property {number} [initialDelayMs] - Default initial retry delay.\n */\n\nexport class LLMService {\n  /**\n   * @param {LLMServiceConfig} [defaultConfig={}] - Default configuration for this service instance.\n   */\n\n  constructor(defaultConfig = {}) {\n    const configManager = getConfigManager();\n    this.defaultConfig = {\n      target: configManager.get('LLM_PROVIDER', 'openai'), // Default to provider if no specific target\n      temperature: 0.7,\n      maxTokens: 2000,\n      verbose: configManager.get('DEBUG_INTELLIGENCE', false),\n      trackUsage: configManager.get('LLM_TRACK_USAGE', true),\n      ...defaultConfig,\n    };\n    this.logger = logger; // Make logger available to instances\n    logger.info('LLMService initialized.');\n    logger.debug('LLMService default configuration:', this.defaultConfig);\n  }\n\n  /**\n   * Makes a generic call to `generateIntelligence`, merging service defaults with call-specific options.\n   * @param {GenerateIntelligenceParams} options - Options for generateIntelligence, including prompt, config, metadata, and callbacks.\n   * @returns {Promise<import('../intelligence/core/llmOrchestrator.js').GenerateIntelligenceResult<any>>}\n   */\n  async generate(options) {\n    const {\n      prompt = {},\n      config: callConfig = {},\n      metadata = {},\n      callbacks,\n    } = options;\n\n    if (!prompt?.user && !(prompt?.shots && prompt.shots.length > 0)) {\n      throw new DaitanInvalidInputError(\n        'LLMService.generate: A `prompt.user` message or messages in `prompt.shots` are required.'\n      );\n    }\n\n    const {\n      llm: callLlm = {},\n      response: callResponse = {},\n      retry: callRetry = {},\n      ...callRootConfig\n    } = callConfig;\n\n    const finalConfig = {\n      verbose: this.defaultConfig.verbose,\n      trackUsage: this.defaultConfig.trackUsage,\n      ...callRootConfig,\n      llm: {\n        target: this.defaultConfig.target,\n        temperature: this.defaultConfig.temperature,\n        maxTokens: this.defaultConfig.maxTokens,\n        apiKey: this.defaultConfig.apiKey,\n        baseURL: this.defaultConfig.baseURL,\n        ...callLlm,\n      },\n      response: { ...callResponse },\n      retry: {\n        maxAttempts: this.defaultConfig.maxRetries,\n        ...callRetry,\n      },\n    };\n\n    const finalParams = {\n      prompt,\n      config: finalConfig,\n      metadata,\n      callbacks,\n    };\n\n    const summary = metadata?.summary || 'Untitled LLMService Call';\n    this.logger.info(`LLMService.generate called for summary: \"${summary}\"`);\n\n    try {\n      const result = await generateIntelligence(finalParams);\n      this.logger.info(`LLMService.generate successful for: \"${summary}\"`);\n      if (result.usage) {\n        this.logger.debug('LLM Usage:', result.usage);\n      }\n      return result;\n    } catch (error) {\n      this.logger.error(\n        `LLMService.generate failed for \"${summary}\": ${error.message}`,\n        { error }\n      );\n      throw error;\n    }\n  }\n\n  /**\n   * Generates a JSON response from the LLM.\n   * @param {Object} params\n   * @returns {Promise<{response: Object, usage: LLMUsageInfo | null}>}\n   */\n  async generateJson({\n    userPrompt,\n    whoYouAre,\n    whatYouDo,\n    summary = 'JSON Generation',\n    shots,\n    ...overrideConfig\n  }) {\n    const { target, temperature, maxTokens, apiKey, baseURL, ...rootConfig } =\n      overrideConfig;\n\n    const params = {\n      prompt: {\n        system: { persona: whoYouAre, task: whatYouDo },\n        user: userPrompt,\n        shots,\n      },\n      config: {\n        ...rootConfig,\n        response: { format: 'json' },\n        llm: { target, temperature, maxTokens, apiKey, baseURL },\n      },\n      metadata: { summary },\n    };\n    return this.generate(params);\n  }\n\n  /**\n   * Generates a text response from the LLM.\n   * @param {Object} params\n   * @returns {Promise<{response: string, usage: LLMUsageInfo | null}>}\n   */\n  async generateText({\n    userPrompt,\n    whoYouAre,\n    whatYouDo,\n    summary = 'Text Generation',\n    shots,\n    ...overrideConfig\n  }) {\n    const { target, temperature, maxTokens, apiKey, baseURL, ...rootConfig } =\n      overrideConfig;\n\n    const params = {\n      prompt: {\n        system: { persona: whoYouAre, task: whatYouDo },\n        user: userPrompt,\n        shots,\n      },\n      config: {\n        ...rootConfig,\n        response: { format: 'text' },\n        llm: { target, temperature, maxTokens, apiKey, baseURL },\n      },\n      metadata: { summary },\n    };\n    return this.generate(params);\n  }\n\n  /**\n   * Streams a text response from the LLM.\n   * @param {Object} params\n   * @returns {Promise<{response: string | undefined, usage: LLMUsageInfo | null}>}\n   */\n  async streamText({\n    userPrompt,\n    whoYouAre,\n    whatYouDo,\n    summary = 'Text Streaming',\n    shots,\n    callbacks,\n    returnFullResponseAfterStream = true,\n    ...overrideConfig\n  }) {\n    if (!callbacks || typeof callbacks.onTokenStream !== 'function') {\n      throw new DaitanInvalidInputError(\n        'LLMService.streamText: `callbacks.onTokenStream` is required for streaming.'\n      );\n    }\n    const { target, temperature, maxTokens, apiKey, baseURL, ...rootConfig } =\n      overrideConfig;\n\n    const params = {\n      prompt: {\n        system: { persona: whoYouAre, task: whatYouDo },\n        user: userPrompt,\n        shots,\n      },\n      config: {\n        ...rootConfig,\n        response: { format: 'text', returnFullResponseAfterStream },\n        llm: { target, temperature, maxTokens, apiKey, baseURL },\n      },\n      metadata: { summary },\n      callbacks,\n    };\n    return this.generate(params);\n  }\n}\n", "// intelligence/src/intelligence/index.js\n/**\n * @file Main entry point for core AI/LLM functionalities in the @daitanjs/intelligence package.\n * @module @daitanjs/intelligence\n */\nimport { getLogger } from '@daitanjs/development';\n\nconst intelligenceIndexLogger = getLogger('daitan-intelligence-index');\n\nintelligenceIndexLogger.debug(\n  'Initializing DaitanJS Intelligence module exports...'\n);\n\n// --- Core LLM, Embedding, and Factory Exports ---\nexport { generateIntelligence } from './core/llmOrchestrator.js';\nexport { generateEmbedding } from './core/embeddingGenerator.js';\nexport { createDaitanTool } from './core/toolFactory.js';\n\n// --- Prompt Management ---\nexport * from './prompts/index.js';\n\n// --- RAG (Retrieval Augmented Generation) ---\nexport * from './rag/index.js';\n\n// --- Metadata Extraction ---\nexport * from './metadata/index.js';\n\n// --- Specialized Search (New Export) ---\nexport {\n  searchNews,\n  searchGeneralWeb,\n  searchAcademic,\n} from './search/specializedSearch.js';\n\n// --- Tool Exports ---\nexport {\n  getDefaultTools,\n  getDaitanPlatformTools,\n} from './tools/tool-registries.js';\nexport { BaseTool } from './tools/baseTool.js';\nexport { calculatorTool } from './tools/calculatorTool.js';\nexport { wikipediaSearchTool } from './tools/wikipediaSearchTool.js';\nexport { cliTool } from './tools/cliTool.js';\nexport { webSearchTool } from './tools/webSearchTool.js';\nexport { ragTool } from './tools/ragTool.js';\nexport { userManagementTool } from './tools/userManagementTool.js';\nexport { csvQueryTool } from './tools/csvQueryTool.js';\nexport { createPaymentIntentTool } from './tools/createPaymentIntentTool.js';\nexport { youtubeSearchTool } from './tools/youtubeSearchTool.js';\nexport { processYoutubeAudioTool } from './tools/processYoutubeAudioTool.js';\nexport { imageGenerationTool } from './tools/imageGenerationTool.js';\nexport {\n  searchGmailTool,\n  readEmailContentTool,\n  createGmailDraftTool,\n} from './tools/gmailTools.js';\nexport { calendarTool } from './tools/calendarTool.js';\nexport {\n  createGoogleDocTool,\n  createGoogleSheetTool,\n} from './tools/googleDriveTools.js';\n\n// --- Agent Exports ---\nexport { runGraphAgent } from './agents/agentRunner.js';\nexport { runToolCallingAgent } from './agents/agentExecutor.js';\nexport { BaseAgent } from './agents/baseAgent.js';\nexport * from './agents/prompts/index.js';\nexport * from './agents/chat/index.js';\n\n// --- Workflow Exports ---\nexport * from './workflows/index.js';\n\n// --- Memory Management ---\nexport { InMemoryChatMessageHistoryStore } from '../memory/inMemoryChatHistoryStore.js';\n\n// --- Core Utilities (re-exported for convenience) ---\nexport { estimateLlmCost } from './core/llmPricing.js';\nexport { countTokens, countTokensForMessages } from './core/tokenUtils.js';\nexport { checkOllamaStatus } from './core/ollamaUtils.js';\nexport {\n  EXPERT_MODELS,\n  getExpertModelDefinition,\n  getDefaultExpertProfile,\n} from './core/expertModels.js';\n\nintelligenceIndexLogger.info(\n  'DaitanJS Intelligence module main exports configured and ready.'\n);\n", "// intelligence/src/intelligence/core/embeddingGenerator.js\n/**\n * @file Re-exports embedding generation functionalities from the canonical @daitanjs/embeddings package.\n * @module @daitanjs/intelligence/core/embeddingGenerator\n *\n * @description\n * This module ensures that embedding generation capabilities are accessible through the\n * `@daitanjs/intelligence` package's core interface while maintaining a single source of truth.\n * The actual implementation of `generateEmbedding` and related utilities resides in the\n * `@daitanjs/embeddings` package.\n *\n * This re-export approach prevents code duplication and enforces the DaitanJS architectural\n * principle of specialized, reusable packages.\n *\n * For detailed documentation on the exported functions, please refer to the `@daitanjs/embeddings` package.\n */\nimport { getLogger } from '@daitanjs/development';\n\nconst embeddingGeneratorLogger = getLogger('daitan-embedding-generator');\n\nembeddingGeneratorLogger.info(\n  'Embedding generator module is a re-export layer. All embedding functionalities are canonical in @daitanjs/embeddings.'\n);\n\n// Re-exporting the canonical embedding generation functions from the @daitanjs/embeddings package.\n// This assumes that @daitanjs/embeddings is a dependency of @daitanjs/intelligence.\nexport {\n  generateEmbedding,\n  generateBatchEmbeddings, // This function is deprecated in the source but exported for compatibility\n} from '@daitanjs/embeddings';\n", "// intelligence/src/intelligence/core/toolFactory.js\n/**\n * @file Contains the factory function for creating DaitanJS tools.\n * @module @daitanjs/intelligence/core/toolFactory\n * @private\n */\nimport { DynamicTool } from '@langchain/core/tools';\nimport { getLogger } from '@daitanjs/development';\nimport {\n  DaitanInvalidInputError,\n  DaitanValidationError,\n  DaitanOperationError,\n} from '@daitanjs/error';\nimport { ZodError } from 'zod';\n\nconst toolFactoryLogger = getLogger('daitan-tool-factory');\n\n/**\n * Creates a LangChain-compatible custom tool (`DynamicTool`) from an asynchronous function.\n * This factory wraps the provided function with robust input parsing, validation, logging, and error handling.\n *\n * @public\n * @param {string} name - The unique, snake_case name of the tool.\n * @param {string} description - A detailed description for the LLM.\n * @param {(input: any, callId?: string) => Promise<string | any>} func - The async function that implements the tool's logic.\n * @param {import('zod').ZodSchema} [argsSchema] - Optional Zod schema for input validation.\n * @returns {DynamicTool} A LangChain DynamicTool instance.\n */\nexport const createDaitanTool = (\n  name,\n  description,\n  func,\n  argsSchema = undefined\n) => {\n  if (!name || typeof name !== 'string' || !name.trim()) {\n    throw new DaitanInvalidInputError(\n      'Tool `name` must be a non-empty string.'\n    );\n  }\n  if (!description || typeof description !== 'string' || !description.trim()) {\n    throw new DaitanInvalidInputError(\n      'Tool `description` must be a non-empty string.'\n    );\n  }\n  if (typeof func !== 'function') {\n    throw new DaitanInvalidInputError(\n      'Tool `func` must be a callable function.'\n    );\n  }\n\n  const daitanToolWrapperFunc = async (rawInput) => {\n    const callId = `tool-run-${name}-${Date.now().toString(36)}`;\n    const logger = getLogger(`daitan-tool-${name}`);\n    logger.info(`Tool \"${name}\" execution: START`, { callId, rawInput });\n\n    let inputForRun = rawInput;\n    try {\n      if (typeof rawInput === 'string') {\n        try {\n          inputForRun = JSON.parse(rawInput);\n        } catch (e) {\n          // Ignore if not a valid JSON string.\n        }\n      }\n\n      if (argsSchema) {\n        inputForRun = argsSchema.parse(inputForRun);\n      }\n\n      const result = await func(inputForRun, callId);\n      const outputString =\n        typeof result === 'string' ? result : JSON.stringify(result, null, 2);\n\n      logger.info(`Tool \"${name}\" execution: SUCCESS`, {\n        callId,\n        outputPreview: outputString.substring(0, 150) + '...',\n      });\n      return outputString;\n    } catch (error) {\n      logger.error(`Execution error in tool \"${name}\": ${error.message}`, {\n        callId,\n        errorName: error.name,\n      });\n\n      if (error instanceof ZodError) {\n        const validationErrorMessage =\n          'Invalid input. ' +\n          error.errors\n            .map((e) => `${e.path.join('.')}: ${e.message}`)\n            .join('; ');\n        return `Error: ${validationErrorMessage}`;\n      }\n      if (\n        error instanceof DaitanValidationError ||\n        error instanceof DaitanOperationError\n      ) {\n        return `Error: ${error.message}`;\n      }\n      return `Error executing tool \"${name}\": An unexpected error occurred. ${error.message}`;\n    }\n  };\n\n  const toolConfig = {\n    name: name.trim(),\n    description: description.trim(),\n    func: daitanToolWrapperFunc,\n    schema: argsSchema,\n  };\n\n  return new DynamicTool(toolConfig);\n};\n", "// intelligence/src/intelligence/rag/index.js\n/**\n * @file Main entry point for RAG (Retrieval Augmented Generation) functionalities.\n * @module @daitanjs/intelligence/rag\n *\n * @description\n * This module aggregates and exports all public-facing components of the DaitanJS RAG system.\n * It provides a comprehensive toolkit for building applications that can answer questions\n * or generate content based on information retrieved from a knowledge base (vector store).\n */\nimport { getLogger } from '@daitanjs/development';\n\nconst ragIndexLogger = getLogger('daitan-rag-index');\nragIndexLogger.debug('Exporting DaitanJS RAG functionalities...');\n\n// --- High-level RAG Querying & Chat ---\nexport { askWithRetrieval } from './retrieval.js';\nexport { createRagChatInstance } from './chat.js';\n\n// --- Document Ingestion Pipeline ---\nexport { loadAndEmbedFile } from './embed.js';\nexport {\n  loadDocumentsFromFile,\n  extractRawTextForMetadata,\n} from './documentLoader.js';\nexport { embedChunks } from './vectorStoreFactory.js';\n\n// --- Vector Store Management ---\nexport {\n  getVectorStore,\n  vectorStoreCollectionExists,\n  DEFAULT_COLLECTION_NAME,\n  setRagMemoryVerbose,\n} from './vectorStoreFactory.js';\nexport { ChromaVectorStoreAdapter } from './chromaVectorStoreAdapter.js';\nexport { MemoryVectorStoreAdapter } from './memoryVectorStoreAdapter.js';\n\n// --- Conversational Session Memory ---\nexport {\n  resetSessionMemory,\n  getSessionMemoryHistory,\n  saveSessionContext,\n} from './chatMemory.js';\n\n// --- Direct DB Client & Admin ---\nexport {\n  CHROMA_PATH,\n  COLLECTION as CHROMA_CLIENT_DEFAULT_COLLECTION,\n  getChromaHost,\n  getChromaPort,\n  getChromaTenant,\n  getChromaDatabase,\n  getDefaultCollectionName,\n  addToChromaDirectly,\n  checkChromaConnection,\n  getOrInitializeChromaClient,\n} from './chromaClient.js';\nexport { printStoreStats } from './printStats.js';\n\n// --- Type Definitions ---\nexport * from './interfaces.js';\nexport * from './vectorStoreAdapterInterface.js';\n\nragIndexLogger.info('DaitanJS RAG module exports ready.');\n", "// intelligence/src/intelligence/rag/retrieval.js\n/**\n * @file Contains the core RAG (Retrieval-Augmented Generation) pipeline logic.\n * @module @daitanjs/intelligence/rag/retrieval\n *\n * @description\n * This is the central function for querying the RAG system. It orchestrates a\n * multi-step process that can include query transformation (HyDE), initial\n * document retrieval from a vector store, relevance re-ranking with an LLM,\n * and final answer synthesis. It also manages chat history for stateful conversations.\n */\nimport path from 'path';\nimport { getVectorStore } from './vectorStoreFactory.js';\nimport { getSessionMemoryHistory, saveSessionContext } from './chatMemory.js';\nimport { generateIntelligence } from '../core/llmOrchestrator.js';\nimport { getLogger } from '@daitanjs/development';\nimport { getConfigManager } from '@daitanjs/config';\nimport {\n  DaitanApiError,\n  DaitanError,\n  DaitanInvalidInputError,\n} from '@daitanjs/error';\n\nconst retrievalLogger = getLogger('daitan-rag-retrieval');\n\n/**\n * Generates a hypothetical document to improve retrieval accuracy (HyDE).\n * @private\n */\nasync function generateHydeDocumentInternal(query, options, logger) {\n  const { hydeLlmConfig = {}, localVerbose: verbose, trackUsage } = options;\n  try {\n    const { response: hypotheticalDocument, usage: hydeUsage } =\n      await generateIntelligence({\n        prompt: {\n          system: {\n            persona: 'You are an expert assistant that writes documents.',\n            task: \"Generate a full, detailed, hypothetical document that perfectly answers the user's question. This document will be used to improve semantic search; it should not be shown to the user.\",\n          },\n          user: `The user is asking: \"${query}\"`,\n        },\n        config: {\n          response: { format: 'text' },\n          llm: {\n            target: hydeLlmConfig.target || 'FAST_TASKER',\n            temperature: hydeLlmConfig.temperature ?? 0.3,\n            maxTokens: hydeLlmConfig.maxTokens ?? 500,\n          },\n          verbose,\n          trackUsage,\n        },\n        metadata: { summary: 'RAG HyDE Generation' },\n      });\n    return {\n      document: String(hypotheticalDocument || query),\n      usage: hydeUsage,\n    };\n  } catch (error) {\n    logger.error(\n      `HyDE: Error generating hypothetical document: ${error.message}`\n    );\n    // Fallback to the original query if HyDE fails\n    return { document: query, usage: null };\n  }\n}\n\n/**\n * Re-ranks retrieved documents using an LLM for better relevance.\n * @private\n */\nasync function reRankDocsWithLlm(query, documents, options, logger) {\n  if (!documents || documents.length === 0) return { docs: [], usage: null };\n  const { reRankerLlmConfig = {}, localVerbose: verbose, trackUsage } = options;\n  const docsWithContent = documents.filter(\n    (doc) => doc.pageContent && doc.pageContent.trim()\n  );\n\n  const snippetsForReranking = docsWithContent\n    .map(\n      (doc, i) =>\n        `DOCUMENT ${i}:\\n${doc.pageContent.substring(0, 1500)}...\\n---`\n    )\n    .join('\\n');\n\n  try {\n    const { response, usage } = await generateIntelligence({\n      prompt: {\n        system: {\n          persona: 'You are an expert relevance-ranking assistant.',\n          task: 'Analyze the provided documents and score their relevance to the user query on a scale of 0 to 100 (0=irrelevant, 100=perfect match).',\n          outputFormat:\n            'You MUST respond with a single JSON object. Keys are document indices (e.g., \"0\", \"1\"), values are relevance scores (e.g., 85). Example: {\"0\": 95, \"1\": 20, \"2\": 80}',\n        },\n        user: `User Query: \"${query}\"\\n\\nDocuments to rank:\\n${snippetsForReranking}`,\n      },\n      config: {\n        response: { format: 'json' },\n        llm: {\n          target: reRankerLlmConfig.target || 'FAST_TASKER', // FAST_TASKER is fine for this\n          temperature: reRankerLlmConfig.temperature ?? 0.0,\n          maxTokens: reRankerLlmConfig.maxTokens ?? 500,\n        },\n        verbose,\n        trackUsage,\n      },\n      metadata: { summary: 'RAG Re-ranking' },\n    });\n\n    if (typeof response !== 'object' || response === null) {\n      logger.warn(\n        'LLM Re-ranker returned non-object response. Skipping re-ranking.'\n      );\n      return { docs: docsWithContent, usage };\n    }\n\n    docsWithContent.forEach((doc, i) => {\n      doc.relevanceScore =\n        typeof response[String(i)] === 'number' ? response[String(i)] : 0;\n    });\n\n    const rerankedDocs = docsWithContent.sort(\n      (a, b) => (b.relevanceScore ?? 0) - (a.relevanceScore ?? 0)\n    );\n\n    return { docs: rerankedDocs, usage };\n  } catch (error) {\n    logger.error(\n      `LLM Re-ranker failed: ${error.message}. Returning original order.`\n    );\n    return { docs: docsWithContent, usage: null };\n  }\n}\n\n/**\n * The main RAG pipeline function.\n * @param {string} query The user's question.\n * @param {import('./interfaces.js').AskWithRetrievalOptions} [options={}]\n * @returns {Promise<import('./interfaces.js').RetrievalResult>}\n */\nexport const askWithRetrieval = async (query, options = {}) => {\n  const configManager = getConfigManager();\n  if (!query)\n    throw new DaitanInvalidInputError(\"A valid 'query' string is required.\");\n\n  const {\n    topK = 5,\n    useHyDE = false,\n    useLlmReRanker = false,\n    synthesisLlmConfig = {},\n    callbacks,\n    sessionId,\n    useAnalysisPrompt = false,\n    allowGeneralKnowledge = false,\n    ...adapterOptions\n  } = options;\n  const currentCallVerbose =\n    adapterOptions.localVerbose ??\n    configManager.get('RAG_RETRIEVAL_VERBOSE', false);\n  const trackUsageOverall =\n    adapterOptions.trackUsage ?? configManager.get('LLM_TRACK_USAGE', true);\n\n  let queryForRetrieval = query;\n  let hydeUsageInfo = null;\n  if (useHyDE) {\n    /* ... */\n  }\n\n  let retrievedDocs = [];\n  try {\n    retrievalLogger.info(\n      `RAG Step: Retrieving documents for query: \"${queryForRetrieval.substring(\n        0,\n        70\n      )}...\"`\n    );\n    const adapter = await getVectorStore(adapterOptions);\n    const initialK = useLlmReRanker ? Math.max(10, topK * 2) : topK;\n    const vectorDocs = await adapter.similaritySearchWithScore(\n      queryForRetrieval,\n      initialK,\n      adapterOptions.filter\n    );\n    retrievedDocs = vectorDocs.map(([doc, score]) => ({\n      ...doc,\n      score,\n      retrieverType: 'vector_store_adapter',\n    }));\n  } catch (error) {\n    retrievalLogger.warn(\n      `askWithRetrieval: Vector search failed. Error: ${error.message}. Proceeding without retrieved docs.`\n    );\n  }\n\n  let reRankerUsageInfo = null;\n  if (useLlmReRanker && retrievedDocs.length > 0) {\n    /* ... */\n  }\n\n  const finalDocsForLLM = retrievedDocs.slice(0, topK);\n\n  retrievalLogger.info(\n    `RAG Step: Synthesizing answer from ${finalDocsForLLM.length} documents...`\n  );\n  const snippets =\n    finalDocsForLLM.length > 0\n      ? finalDocsForLLM\n          .map(\n            (doc, i) =>\n              `Snippet ${i + 1} (Source: ${\n                doc.metadata.source_filename ||\n                path.basename(String(doc.metadata.source || ''))\n              }):\\n${doc.pageContent}`\n          )\n          .join('\\n\\n---\\n\\n')\n      : 'No relevant snippets found in the knowledge base.';\n\n  const memoryHistory = sessionId\n    ? await getSessionMemoryHistory(sessionId)\n    : [];\n  const historyText = memoryHistory\n    .map((m) => `${m._getType()}: ${String(m.content).substring(0, 150)}...`)\n    .join('\\n');\n\n  let systemPrompt, userPrompt;\n\n  // --- THE DEFINITIVE FIX: A SMARTER SYNTHESIS PROMPT ---\n  if (useAnalysisPrompt) {\n    systemPrompt = {\n      persona: 'You are a meticulous data analyst and research assistant.',\n      task: 'Carefully read all provided \"Context Snippets\" and provide a detailed, factual analysis that directly answers the user\\'s request. Synthesize information from multiple snippets if necessary, and present it clearly, for example in a list or table.',\n      guidelines: [\n        'Base your entire analysis STRICTLY on the provided snippets.',\n        'If the snippets do not contain the answer, state that clearly.',\n      ],\n    };\n    userPrompt = `CONTEXT SNIPPETS:\\n---\\n${snippets}\\n---\\nUSER'S ANALYTICAL REQUEST:\\n${query}\\n\\nANALYSIS RESULT:`;\n  } else {\n    // This is the new, more intelligent default prompt.\n    systemPrompt = {\n      persona:\n        'You are a helpful AI assistant that answers questions by reasoning over the provided context.',\n      // It now encourages synthesis and reasoning, not just strict extraction.\n      task: `Answer the user's question by synthesizing and reasoning over the provided \"Context Snippets\". Connect information from multiple snippets if necessary to form a complete answer. If the information is not in the snippets, you MUST state that clearly.`,\n      guidelines: [\n        'Be concise and directly answer the question.',\n        'When you use information from a snippet, cite its source (e.g., \"[Source: doc1.pdf]\").',\n      ],\n    };\n    userPrompt = `CONTEXT SNIPPETS:\\n---\\n${snippets}\\n---\\nCHAT HISTORY:\\n---\\n${\n      historyText || 'No previous conversation history.'\n    }\\n---\\nQUESTION:\\n${query}\\n\\nANSWER:`;\n  }\n\n  try {\n    const { response: answerText, usage: synthesisUsageInfo } =\n      await generateIntelligence({\n        prompt: { system: systemPrompt, user: userPrompt },\n        config: {\n          response: { format: 'text' },\n          llm: {\n            target:\n              synthesisLlmConfig.target ||\n              (useAnalysisPrompt\n                ? 'openai|gpt-4-turbo'\n                : 'MASTER_COMMUNICATOR'),\n            temperature: synthesisLlmConfig.temperature ?? 0.01,\n            maxTokens: synthesisLlmConfig.maxTokens ?? 1500,\n          },\n          verbose: currentCallVerbose,\n          trackUsage: trackUsageOverall,\n        },\n        callbacks,\n      });\n\n    if (sessionId) {\n      await saveSessionContext(\n        sessionId,\n        { input: query },\n        { output: String(answerText || '') }\n      );\n    }\n\n    return {\n      text: String(answerText || ''),\n      retrievedDocs: finalDocsForLLM,\n      originalQuery: query,\n      hydeUsage: trackUsageOverall ? hydeUsageInfo : null,\n      reRankerUsage: trackUsageOverall ? reRankerUsageInfo : null,\n      synthesisUsage: trackUsageOverall ? synthesisUsageInfo : null,\n    };\n  } catch (llmError) {\n    throw llmError instanceof DaitanError\n      ? llmError\n      : new DaitanApiError(\n          `Error during RAG synthesis: ${llmError.message}`,\n          'SynthesisLLM',\n          llmError.status,\n          {},\n          llmError\n        );\n  }\n};\n", "// intelligence/src/intelligence/rag/vectorStoreFactory.js\n/**\n * @file Factory and management functions for vector store instances.\n * @module @daitanjs/intelligence/rag/vectorStoreFactory\n */\nimport { getLogger } from '@daitanjs/development';\nimport { getConfigManager } from '@daitanjs/config';\nimport {\n  DaitanConfigurationError,\n  DaitanOperationError,\n  DaitanInvalidInputError,\n} from '@daitanjs/error';\nimport { ChromaVectorStoreAdapter } from './chromaVectorStoreAdapter.js';\nimport { MemoryVectorStoreAdapter } from './memoryVectorStoreAdapter.js';\nimport { getDefaultCollectionName as getClientDefaultCollection } from './chromaClient.js';\n\nconst vectorStoreLogger = getLogger('daitan-rag-vectorstore');\n\nconst FALLBACK_DEFAULT_COLLECTION_NAME = 'daitan_rag_default_store';\n\n// --- CORRECTED: Convert constant to a function to defer config access ---\nexport const DEFAULT_COLLECTION_NAME = () => {\n  const configManager = getConfigManager();\n  return (\n    configManager.get('RAG_DEFAULT_COLLECTION_NAME') ||\n    getClientDefaultCollection() ||\n    FALLBACK_DEFAULT_COLLECTION_NAME\n  );\n};\n\nlet currentModuleVerbose = false; // Will be set on first getVectorStore call\nlet vectorStoreAdapterSingleton = null;\n\nexport const setRagMemoryVerbose = (isVerbose) => {\n  currentModuleVerbose = !!isVerbose;\n};\n\nexport const getVectorStore = async ({\n  persistent,\n  collectionName,\n  forceRecreateCollection = false,\n  embeddingsInstance,\n  chromaUrl,\n  localVerbose,\n} = {}) => {\n  const configManager = getConfigManager();\n  const usePersistentStore =\n    persistent ?? configManager.get('RAG_PERSISTENT_STORE', true);\n  const effectiveCollectionName = collectionName || DEFAULT_COLLECTION_NAME();\n\n  currentModuleVerbose =\n    localVerbose ?? configManager.get('RAG_MEMORY_VERBOSE', false);\n\n  const requestedStoreType = usePersistentStore ? 'Chroma' : 'Memory';\n  let currentStoreType = vectorStoreAdapterSingleton\n    ? vectorStoreAdapterSingleton instanceof ChromaVectorStoreAdapter\n      ? 'Chroma'\n      : 'Memory'\n    : null;\n\n  let needsRecreation =\n    !vectorStoreAdapterSingleton ||\n    forceRecreateCollection ||\n    requestedStoreType !== currentStoreType ||\n    (vectorStoreAdapterSingleton.collectionName && // Check if collectionName exists before comparing\n      vectorStoreAdapterSingleton.collectionName !== effectiveCollectionName);\n\n  if (\n    usePersistentStore &&\n    vectorStoreAdapterSingleton instanceof ChromaVectorStoreAdapter &&\n    chromaUrl &&\n    vectorStoreAdapterSingleton.url !== chromaUrl\n  ) {\n    needsRecreation = true;\n  }\n\n  if (!needsRecreation) {\n    if (currentModuleVerbose)\n      vectorStoreLogger.debug(\n        `Returning existing VectorStoreAdapter for \"${effectiveCollectionName}\".`\n      );\n    return vectorStoreAdapterSingleton;\n  }\n\n  if (currentModuleVerbose)\n    vectorStoreLogger.info(\n      `Re-initializing VectorStoreAdapter. Type: ${requestedStoreType}, Collection: \"${effectiveCollectionName}\"`\n    );\n\n  if (forceRecreateCollection && usePersistentStore) {\n    try {\n      const tempAdapter = new ChromaVectorStoreAdapter({\n        collectionName: effectiveCollectionName,\n        url: chromaUrl,\n        embeddings: embeddingsInstance,\n      });\n      await tempAdapter.deleteCollection();\n    } catch (e) {\n      vectorStoreLogger.warn(\n        `Error during pre-emptive deletion of collection \"${effectiveCollectionName}\": ${e.message}.`\n      );\n    }\n  }\n\n  try {\n    vectorStoreAdapterSingleton = usePersistentStore\n      ? new ChromaVectorStoreAdapter({\n          collectionName: effectiveCollectionName,\n          url: chromaUrl,\n          embeddings: embeddingsInstance,\n          verbose: currentModuleVerbose,\n        })\n      : new MemoryVectorStoreAdapter({\n          embeddings: embeddingsInstance,\n          verbose: currentModuleVerbose,\n        });\n    return vectorStoreAdapterSingleton;\n  } catch (error) {\n    vectorStoreAdapterSingleton = null;\n    throw new DaitanOperationError(\n      `Failed to initialize ${requestedStoreType}VectorStoreAdapter for \"${effectiveCollectionName}\"`,\n      {},\n      error\n    );\n  }\n};\n\nexport const vectorStoreCollectionExists = async (collectionName) => {\n  const configManager = getConfigManager();\n  const usePersistentStore = configManager.get('RAG_PERSISTENT_STORE', true);\n  if (!usePersistentStore) return true; // In-memory always \"exists\" once requested\n\n  const effectiveCollectionName = collectionName || DEFAULT_COLLECTION_NAME();\n  try {\n    const tempAdapter = new ChromaVectorStoreAdapter({\n      collectionName: effectiveCollectionName,\n    });\n    return await tempAdapter.collectionExists();\n  } catch (error) {\n    vectorStoreLogger.error(\n      `Error checking existence for collection \"${effectiveCollectionName}\": ${error.message}`\n    );\n    return false;\n  }\n};\n\nexport const embedChunks = async (chunks, options = {}) => {\n  const effectiveCollectionName =\n    options.collectionName || DEFAULT_COLLECTION_NAME();\n  if (!Array.isArray(chunks) || chunks.length === 0) return;\n  const adapter = await getVectorStore({\n    ...options,\n    collectionName: effectiveCollectionName,\n  });\n  return adapter.addDocuments(chunks, {\n    ids: options.ids,\n    batchSize: options.batchSize,\n  });\n};\n", "// intelligence/src/intelligence/rag/chromaVectorStoreAdapter.js\n/**\n * @file Adapter for interacting with a ChromaDB vector store using LangChain.\n * @module @daitanjs/intelligence/rag/chromaVectorStoreAdapter\n */\nimport { Chroma } from '@langchain/community/vectorstores/chroma';\nimport { OpenAIEmbeddings } from '@langchain/openai';\nimport { getLogger } from '@daitanjs/development';\nimport { getConfigManager } from '@daitanjs/config';\nimport {\n  DaitanConfigurationError,\n  DaitanOperationError,\n} from '@daitanjs/error';\nimport { getOrInitializeChromaClient } from './chromaClient.js';\n\nconst adapterLogger = getLogger('daitan-chroma-adapter');\n\n/**\n * @implements {import('./vectorStoreAdapterInterface.js').IVectorStoreAdapter}\n */\nexport class ChromaVectorStoreAdapter {\n  constructor({ collectionName, url, embeddings, verbose }) {\n    if (!collectionName) {\n      throw new DaitanConfigurationError(\n        'ChromaVectorStoreAdapter: collectionName is required.'\n      );\n    }\n    this.collectionName = collectionName;\n    this.initialConfig = { url, embeddings, verbose };\n    this.isInitialized = false;\n    this.directClient = null;\n    this.langchainStoreInstance = null;\n  }\n\n  /**\n   * Initializes the adapter on its first use. This lazy initialization\n   * prevents unnecessary connections and configuration lookups.\n   * @private\n   */\n  async _lazyInitialize() {\n    if (this.isInitialized) return;\n\n    const configManager = getConfigManager();\n    this.verbose =\n      this.initialConfig.verbose ??\n      configManager.get('CHROMA_ADAPTER_VERBOSE', false);\n    this.url =\n      this.initialConfig.url ||\n      `http://${configManager.get(\n        'CHROMA_HOST',\n        'localhost'\n      )}:${configManager.get('CHROMA_PORT', '8000')}`;\n    this.embeddings =\n      this.initialConfig.embeddings ||\n      this._resolveDefaultEmbeddings(configManager);\n\n    if (!this.embeddings) {\n      throw new DaitanConfigurationError(\n        'Embeddings must be provided or OpenAI default must be configurable (OPENAI_API_KEY is missing).'\n      );\n    }\n\n    // Use the factory to get a pre-initialized and tested direct client\n    this.directClient = await getOrInitializeChromaClient();\n\n    // The LangChain Chroma class can now be instantiated. It will use the\n    // same underlying connection pool as the directClient if configured correctly.\n    this.langchainStoreInstance = new Chroma(this.embeddings, {\n      collectionName: this.collectionName,\n      url: this.url,\n    });\n\n    this.isInitialized = true;\n    adapterLogger.info(\n      `ChromaVectorStoreAdapter for \"${this.collectionName}\" has been initialized on first use.`\n    );\n  }\n\n  /**\n   * Creates a default OpenAI embeddings instance if none is provided.\n   * @private\n   */\n  _resolveDefaultEmbeddings(configManager) {\n    const apiKey = configManager.get('OPENAI_API_KEY');\n    if (!apiKey) {\n      adapterLogger.warn(\n        'Cannot create default OpenAIEmbeddings: OPENAI_API_KEY is not configured.'\n      );\n      return null;\n    }\n\n    const ragEmbeddingModel = configManager.get(\n      'RAG_EMBEDDING_MODEL_OPENAI',\n      'text-embedding-3-small'\n    );\n    // LangChain's OpenAIEmbeddings constructor correctly uses 'model'\n    return new OpenAIEmbeddings({\n      apiKey,\n      model: ragEmbeddingModel,\n    });\n  }\n\n  async addDocuments(documents, options = {}) {\n    await this._lazyInitialize();\n    try {\n      return await this.langchainStoreInstance.addDocuments(\n        documents,\n        options.ids ? { ids: options.ids } : undefined\n      );\n    } catch (error) {\n      throw new DaitanOperationError(\n        `Failed to add documents to collection \"${this.collectionName}\": ${error.message}`,\n        { collectionName: this.collectionName },\n        error\n      );\n    }\n  }\n\n  async similaritySearchWithScore(query, k = 4, filter) {\n    await this._lazyInitialize();\n    try {\n      return await this.langchainStoreInstance.similaritySearchWithScore(\n        query,\n        k,\n        filter\n      );\n    } catch (error) {\n      throw new DaitanOperationError(\n        `Failed to perform similarity search in collection \"${this.collectionName}\": ${error.message}`,\n        { collectionName: this.collectionName, query, k },\n        error\n      );\n    }\n  }\n\n  async collectionExists() {\n    await this._lazyInitialize();\n    try {\n      // Use the direct client for administrative tasks like checking existence.\n      await this.directClient.getCollection({ name: this.collectionName });\n      return true;\n    } catch (error) {\n      const errorMessage = String(error.message).toLowerCase();\n      // ChromaDB's error message for non-existent collections can vary slightly.\n      if (\n        errorMessage.includes('not found') ||\n        errorMessage.includes('does not exist')\n      ) {\n        return false;\n      }\n      // Re-throw other errors (e.g., connection issues)\n      throw new DaitanOperationError(\n        `Failed to check for collection \"${this.collectionName}\": ${error.message}`,\n        { host: this.url, collectionName: this.collectionName },\n        error\n      );\n    }\n  }\n\n  async deleteCollection() {\n    await this._lazyInitialize();\n    try {\n      await this.directClient.deleteCollection({ name: this.collectionName });\n      // Reset the adapter state after successful deletion\n      this.isInitialized = false;\n      this.langchainStoreInstance = null;\n      adapterLogger.info(\n        `Collection \"${this.collectionName}\" deleted successfully.`\n      );\n    } catch (error) {\n      const errorMessage = String(error.message).toLowerCase();\n      if (\n        !errorMessage.includes('not found') &&\n        !errorMessage.includes('does not exist')\n      ) {\n        throw new DaitanOperationError(\n          `Failed to delete Chroma collection \"${this.collectionName}\": ${error.message}`,\n          { collectionName: this.collectionName },\n          error\n        );\n      }\n      // If collection doesn't exist, it's a success from the user's perspective.\n      adapterLogger.info(\n        `Collection \"${this.collectionName}\" was already deleted or doesn't exist.`\n      );\n    }\n  }\n\n  async getCollectionInfo() {\n    await this._lazyInitialize();\n    try {\n      const collection = await this.directClient.getCollection({\n        name: this.collectionName,\n      });\n      const count = await collection.count();\n      return {\n        name: collection.name,\n        id: collection.id,\n        count,\n        metadata: collection.metadata,\n      };\n    } catch (error) {\n      throw new DaitanOperationError(\n        `Failed to get collection info for \"${this.collectionName}\": ${error.message}`,\n        { collectionName: this.collectionName },\n        error\n      );\n    }\n  }\n\n  async clearCollection() {\n    await this._lazyInitialize();\n    try {\n      const collection = await this.directClient.getCollection({\n        name: this.collectionName,\n      });\n      // Get all IDs from the collection to delete them.\n      const result = await collection.get();\n      if (result.ids && result.ids.length > 0) {\n        await collection.delete({ ids: result.ids });\n        adapterLogger.info(\n          `Cleared ${result.ids.length} documents from collection \"${this.collectionName}\".`\n        );\n      } else {\n        adapterLogger.info(\n          `Collection \"${this.collectionName}\" is already empty.`\n        );\n      }\n    } catch (error) {\n      throw new DaitanOperationError(\n        `Failed to clear collection \"${this.collectionName}\": ${error.message}`,\n        { collectionName: this.collectionName },\n        error\n      );\n    }\n  }\n\n  async getLangchainStore() {\n    await this._lazyInitialize();\n    return this.langchainStoreInstance;\n  }\n}\n", "// intelligence/src/intelligence/rag/chromaClient.js\n/**\n * @file Manages the singleton connection and client for ChromaDB.\n * @module @daitanjs/intelligence/rag/chromaClient\n */\nimport { ChromaClient } from 'chromadb';\nimport { getLogger } from '@daitanjs/development';\nimport { getConfigManager } from '@daitanjs/config';\nimport { DaitanOperationError, DaitanInvalidInputError } from '@daitanjs/error';\n\nconst logger = getLogger('daitan-rag-chroma-client');\n\n// --- Configuration Accessors (Restored Exports) ---\nexport const getChromaHost = () =>\n  getConfigManager().get('CHROMA_HOST', 'localhost');\nexport const getChromaPort = () => getConfigManager().get('CHROMA_PORT', 8000);\nexport const getChromaTenant = () =>\n  getConfigManager().get('CHROMA_TENANT', 'default_tenant');\nexport const getChromaDatabase = () =>\n  getConfigManager().get('CHROMA_DATABASE', 'default_database');\nexport const getDefaultCollectionName = () =>\n  getConfigManager().get(\n    'RAG_DEFAULT_COLLECTION_NAME',\n    'daitan_rag_default_store'\n  );\n\n// --- Constants (Restored Exports) ---\nexport const CHROMA_PATH = './.vectorstore';\nexport const COLLECTION = () => getDefaultCollectionName(); // Maintained as function to defer config access\n\n// The singleton client instance.\nlet chromaClientInstance = null;\n\n// The global fetch patch has been permanently removed as it was the root cause of the bug.\n\n/**\n * Checks if the ChromaDB server is responsive.\n * @public\n */\nexport const checkChromaConnection = async (timeoutMs = 3000) => {\n  const host = getChromaHost();\n  const port = getChromaPort();\n  const endpointsToTry = [\n    `http://${host}:${port}/api/v2/heartbeat`,\n    `http://${host}:${port}/api/v1/heartbeat`,\n  ];\n\n  for (const url of endpointsToTry) {\n    try {\n      const controller = new AbortController();\n      const timeoutId = setTimeout(() => controller.abort(), timeoutMs);\n      const response = await fetch(url, { signal: controller.signal });\n      clearTimeout(timeoutId);\n      if (response.ok) {\n        logger.info(`ChromaDB connection successful on endpoint: ${url}`);\n        return true;\n      }\n    } catch (error) {\n      // This is expected if an endpoint doesn't exist.\n    }\n  }\n  logger.error(`ChromaDB connection check failed on all attempted endpoints.`);\n  return false;\n};\n\nexport async function getOrInitializeChromaClient() {\n  if (chromaClientInstance) {\n    try {\n      await chromaClientInstance.heartbeat();\n      return chromaClientInstance;\n    } catch (error) {\n      logger.warn(\n        'Existing ChromaDB client connection is stale, re-initializing...'\n      );\n      chromaClientInstance = null;\n    }\n  }\n\n  const host = getChromaHost();\n  const port = getChromaPort();\n  const baseUrl = `http://${host}:${port}`;\n\n  try {\n    if (!(await checkChromaConnection())) {\n      throw new DaitanOperationError(\n        `Could not connect to ChromaDB server at ${baseUrl}.`\n      );\n    }\n    chromaClientInstance = new ChromaClient({ path: baseUrl });\n    await chromaClientInstance.heartbeat();\n    logger.info(`ChromaDB client initialized and connection confirmed.`);\n  } catch (error) {\n    chromaClientInstance = null;\n    throw new DaitanOperationError(\n      `Failed to initialize ChromaDB client: ${error.message}`,\n      { host, port },\n      error\n    );\n  }\n  return chromaClientInstance;\n}\n\nexport async function addToChromaDirectly(\n  embeddings,\n  metadatas,\n  ids,\n  documents\n) {\n  if (!Array.isArray(embeddings) || embeddings.length === 0) {\n    throw new DaitanInvalidInputError(\n      'Embeddings array is required and cannot be empty.'\n    );\n  }\n\n  try {\n    const client = await getOrInitializeChromaClient();\n    const collectionName = getDefaultCollectionName();\n    const collection = await client.getOrCreateCollection({\n      name: collectionName,\n      metadata: { 'hnsw:space': 'cosine' },\n    });\n\n    const cleanMetadatas = metadatas.map((meta) => {\n      if (typeof meta !== 'object' || meta === null) return {};\n      return Object.fromEntries(\n        Object.entries(meta).filter(\n          ([, value]) => value != null && value !== ''\n        )\n      );\n    });\n\n    await collection.add({\n      ids,\n      embeddings,\n      metadatas: cleanMetadatas,\n      documents,\n    });\n    return { success: true, count: embeddings.length, collectionName };\n  } catch (error) {\n    throw new DaitanOperationError(\n      `Failed to add documents to ChromaDB: ${error.message}`,\n      { documentCount: embeddings.length },\n      error\n    );\n  }\n}\n", "// intelligence/src/intelligence/rag/memoryVectorStoreAdapter.js\nimport { MemoryVectorStore } from 'langchain/vectorstores/memory';\nimport { OpenAIEmbeddings } from '@langchain/openai'; // Default embeddings\nimport { getLogger } from '@daitanjs/development';\nimport { getConfigManager } from '@daitanjs/config';\nimport {\n  DaitanConfigurationError,\n  DaitanOperationError,\n} from '@daitanjs/error';\nimport { Document as LangchainDocument } from '@langchain/core/documents'; // For type hints\n\nconst memoryAdapterLogger = getLogger('daitan-memory-vstore-adapter'); // Service-specific logger\n\n/**\n * Adapter for LangChain's in-memory vector store.\n * @implements {import('./vectorStoreAdapterInterface.js').IVectorStoreAdapter}\n */\nexport class MemoryVectorStoreAdapter {\n  /**\n   * @param {Object} [config={}]\n   * @param {import('@langchain/core/embeddings').Embeddings} [config.embeddings] - LangChain embeddings instance.\n   * @param {LangchainDocument[]} [config.initialDocuments=[]] - Optional documents to initialize with.\n   * @param {boolean} [config.verbose] - Verbose logging for this instance. Defaults from ConfigManager.\n   * @throws {DaitanConfigurationError} If embeddings cannot be configured.\n   */\n  constructor({\n    embeddings, // Renamed from embeddingsInstance\n    initialDocuments = [],\n    verbose,\n  } = {}) {\n    const configManager = getConfigManager(); // Lazy-load\n    this.verbose =\n      verbose !== undefined\n        ? verbose\n        : configManager.get('MEMORY_ADAPTER_VERBOSE', false) ||\n          configManager.get('DEBUG_INTELLIGENCE', false);\n\n    this.embeddings = embeddings || this._resolveDefaultEmbeddings();\n\n    if (!this.embeddings) {\n      const errMsg =\n        'MemoryVectorStoreAdapter: Embeddings must be provided, or OpenAI default embeddings must be configurable (requires OPENAI_API_KEY via ConfigManager).';\n      memoryAdapterLogger.error(errMsg);\n      throw new DaitanConfigurationError(errMsg);\n    }\n\n    /** @type {MemoryVectorStore | null} */\n    this.store = null; // Lazy initialized or initialized with initialDocuments\n\n    if (this.verbose) {\n      memoryAdapterLogger.info(\n        `MemoryVectorStoreAdapter initialized. Verbose: ${this.verbose}. Embeddings: ${this.embeddings.constructor.name}`\n      );\n    }\n\n    if (initialDocuments && initialDocuments.length > 0) {\n      // Fire-and-forget initialization with documents.\n      // Methods using `this.store` will await `_ensureStoreIsInitialized`.\n      this._initializeWithDocuments(initialDocuments).catch((err) => {\n        memoryAdapterLogger.error(\n          `MemoryVectorStoreAdapter: Background initialization with documents failed: ${err.message}`\n        );\n        // Store might remain null, subsequent operations will attempt to re-initialize an empty store.\n      });\n    }\n  }\n\n  /**\n   * Sets the verbosity for this adapter instance.\n   * @param {boolean} isVerbose\n   */\n  setVerbose(isVerbose) {\n    this.verbose = isVerbose;\n    memoryAdapterLogger.info(\n      `MemoryVectorStoreAdapter verbosity set to: ${this.verbose}`\n    );\n  }\n\n  _resolveDefaultEmbeddings() {\n    const configManager = getConfigManager(); // Lazy-load\n    const apiKey = configManager.get('OPENAI_API_KEY'); // Changed from getApiKeyForProvider\n    if (!apiKey) {\n      memoryAdapterLogger.warn(\n        'MemoryVectorStoreAdapter: OPENAI_API_KEY not found via ConfigManager for default OpenAIEmbeddings.'\n      );\n      return null;\n    }\n    try {\n      const ragEmbeddingModel = configManager.get('RAG_EMBEDDING_MODEL_OPENAI'); // Allow override\n      const embeddingsConfig = { apiKey };\n      if (ragEmbeddingModel) {\n        embeddingsConfig.modelName = ragEmbeddingModel;\n      }\n      if (this.verbose)\n        memoryAdapterLogger.debug(\n          `Using OpenAIEmbeddings with model: ${\n            ragEmbeddingModel || 'default (text-embedding-ada-002 or similar)'\n          }`\n        );\n      return new OpenAIEmbeddings(embeddingsConfig);\n    } catch (e) {\n      memoryAdapterLogger.error(\n        `Failed to instantiate default OpenAIEmbeddings: ${e.message}`\n      );\n      return null;\n    }\n  }\n\n  async _initializeWithDocuments(documents) {\n    // This method is typically called from constructor, which is not async.\n    // However, MemoryVectorStore.fromDocuments IS async.\n    // This means the constructor can't truly \"wait\" for this.\n    // Operations relying on store must call _ensureStoreIsInitialized.\n    if (this.store) {\n      if (this.verbose)\n        memoryAdapterLogger.debug(\n          'MemoryVectorStore already initialized, skipping re-initialization with documents.'\n        );\n      return;\n    }\n    try {\n      if (this.verbose)\n        memoryAdapterLogger.debug(\n          `MemoryVectorStore: Initializing via fromDocuments with ${documents.length} documents.`\n        );\n      this.store = await MemoryVectorStore.fromDocuments(\n        documents,\n        this.embeddings\n      );\n      if (this.verbose)\n        memoryAdapterLogger.debug(\n          `MemoryVectorStore initialized successfully with ${documents.length} documents.`\n        );\n    } catch (error) {\n      memoryAdapterLogger.error(\n        `MemoryVectorStoreAdapter: Error during fromDocuments initialization: ${error.message}`,\n        { error_stack: error.stack?.substring(0, 300) }\n      );\n      // Don't throw here as it's background init from constructor; store remains null.\n      // throw new DaitanOperationError('Failed to initialize MemoryVectorStore with documents', {}, error);\n    }\n  }\n\n  async _ensureStoreIsInitialized() {\n    if (!this.store) {\n      if (this.verbose)\n        memoryAdapterLogger.debug(\n          'MemoryVectorStoreAdapter: Store not yet initialized. Lazily creating empty store now.'\n        );\n      try {\n        // If _initializeWithDocuments failed or wasn't called, create an empty store.\n        // MemoryVectorStore constructor is synchronous.\n        this.store = new MemoryVectorStore(this.embeddings);\n        if (this.verbose)\n          memoryAdapterLogger.debug(\n            'MemoryVectorStoreAdapter: Empty store created successfully.'\n          );\n      } catch (error) {\n        memoryAdapterLogger.error(\n          `MemoryVectorStoreAdapter: Error creating empty MemoryVectorStore instance: ${error.message}`,\n          { error_stack: error.stack?.substring(0, 300) }\n        );\n        throw new DaitanOperationError(\n          'Failed to create empty MemoryVectorStore',\n          {},\n          error\n        );\n      }\n    }\n  }\n\n  async addDocuments(documents, options = {}) {\n    if (!Array.isArray(documents) || documents.length === 0) {\n      if (this.verbose)\n        memoryAdapterLogger.info(\n          'MemoryAdapter: No documents provided to add.'\n        );\n      return;\n    }\n    await this._ensureStoreIsInitialized(); // Ensures `this.store` is not null\n    if (this.verbose)\n      memoryAdapterLogger.info(\n        `MemoryAdapter: Adding ${documents.length} documents.`\n      );\n\n    try {\n      await this.store.addDocuments(\n        documents,\n        options.ids ? { ids: options.ids } : undefined\n      );\n      if (this.verbose)\n        memoryAdapterLogger.debug(\n          `MemoryAdapter: Successfully added ${documents.length} documents.`\n        );\n    } catch (error) {\n      memoryAdapterLogger.error(\n        `MemoryAdapter: Error adding documents: ${error.message}`,\n        {\n          numDocs: documents.length,\n          error_stack: error.stack?.substring(0, 300),\n        }\n      );\n      throw new DaitanOperationError(\n        'Failed to add documents to MemoryVectorStore',\n        {},\n        error\n      );\n    }\n  }\n\n  async similaritySearchWithScore(query, k, filter) {\n    await this._ensureStoreIsInitialized();\n    const logContext = {\n      queryPreview: String(query).substring(0, 70) + '...',\n      k,\n    };\n\n    if (this.verbose) {\n      memoryAdapterLogger.debug('MemoryAdapter: Similarity search started.', {\n        ...logContext,\n        filter: filter\n          ? typeof filter === 'function'\n            ? 'Function filter'\n            : filter\n          : 'None',\n      });\n    }\n\n    let adaptedFilter = filter;\n    if (\n      filter &&\n      typeof filter === 'object' &&\n      !Array.isArray(filter) &&\n      typeof filter !== 'function'\n    ) {\n      // Convert simple metadata object filter to a function for MemoryVectorStore\n      adaptedFilter = (doc) => {\n        for (const key in filter) {\n          if (!doc.metadata || doc.metadata[key] !== filter[key]) return false;\n        }\n        return true;\n      };\n      if (this.verbose)\n        memoryAdapterLogger.debug(\n          'MemoryAdapter: Adapted object metadata filter to function for similaritySearch.'\n        );\n    } else if (typeof filter !== 'function' && filter !== undefined) {\n      memoryAdapterLogger.warn(\n        'MemoryAdapter: Filter provided is not a metadata object or function. It will be ignored by MemoryVectorStore for similaritySearchWithScore.',\n        { filterType: typeof filter }\n      );\n      adaptedFilter = undefined;\n    }\n\n    try {\n      const results = await this.store.similaritySearchWithScore(\n        query,\n        k,\n        adaptedFilter\n      );\n      if (this.verbose)\n        memoryAdapterLogger.debug(\n          `MemoryAdapter: Similarity search returned ${results.length} results.`\n        );\n      return results; // Results are [Document, number][]\n    } catch (error) {\n      memoryAdapterLogger.error(\n        `MemoryAdapter: Similarity search error: ${error.message}`,\n        { ...logContext, error_stack: error.stack?.substring(0, 300) }\n      );\n      throw new DaitanOperationError(\n        'Similarity search failed in MemoryVectorStore',\n        logContext,\n        error\n      );\n    }\n  }\n\n  async collectionExists(collectionNameIgnored) {\n    // For MemoryVectorStore, the \"collection\" is the store instance itself.\n    // If the store is initialized (even if empty), it \"exists\".\n    // `collectionNameIgnored` because MemoryVectorStore doesn't have named collections.\n    await this._ensureStoreIsInitialized(); // Ensure store is attempted to be created\n    if (this.verbose)\n      memoryAdapterLogger.debug(\n        `MemoryAdapter: \"collectionExists\" check - returning ${!!this.store}.`\n      );\n    return !!this.store;\n  }\n\n  async ensureCollection(collectionNameIgnored, options = {}) {\n    // For MemoryVectorStore, this just means ensuring the store is initialized.\n    await this._ensureStoreIsInitialized();\n    if (this.verbose)\n      memoryAdapterLogger.debug(\n        'MemoryAdapter: \"ensureCollection\" called. Store is ready or will be created.'\n      );\n  }\n\n  async deleteCollection(collectionNameIgnored) {\n    if (this.verbose)\n      memoryAdapterLogger.info(\n        'MemoryAdapter: \"Deleting collection\" - re-initializing to an empty store.'\n      );\n    try {\n      this.store = new MemoryVectorStore(this.embeddings); // Create a new, empty instance\n      if (this.verbose)\n        memoryAdapterLogger.debug(\n          'MemoryAdapter: Store re-initialized (effectively cleared).'\n        );\n    } catch (error) {\n      memoryAdapterLogger.error(\n        `MemoryAdapter: Error re-initializing store during deleteCollection: ${error.message}`,\n        { error_stack: error.stack?.substring(0, 300) }\n      );\n      throw new DaitanOperationError(\n        'Failed to clear/re-initialize MemoryVectorStore',\n        {},\n        error\n      );\n    }\n  }\n\n  async getLangchainStore() {\n    await this._ensureStoreIsInitialized();\n    return this.store;\n  }\n}\n", "// intelligence/src/intelligence/rag/chatMemory.js\n/**\n * @file Manages conversational session memory for RAG chat interactions.\n * @module @daitanjs/intelligence/rag/chatMemory\n *\n * @description\n * This module provides a robust, session-based memory management system. It uses a\n * private, in-memory store (a Map) to hold separate conversation histories for\n * different session IDs. This ensures that concurrent conversations do not interfere\n * with each other, a critical requirement for multi-user or concurrent applications.\n */\nimport { BufferMemory } from 'langchain/memory';\nimport { getLogger } from '@daitanjs/development';\n\nconst chatMemoryLogger = getLogger('daitan-rag-chat-memory');\n\n/**\n * A map to hold different session memories, keyed by sessionId.\n * This is kept private to the module to enforce access via exported functions.\n * @private\n * @type {Map<string, BufferMemory>}\n */\nconst sessionMemoryStore = new Map();\n\n/**\n * Creates or retrieves a BufferMemory instance for a given session ID.\n * This is the core function for managing session-specific memory objects.\n * @private\n * @param {string} sessionId - The unique identifier for the conversation session.\n * @returns {BufferMemory | null} The memory instance for the session, or null if sessionId is invalid.\n */\nconst getSessionMemory = (sessionId) => {\n  if (!sessionId || typeof sessionId !== 'string') {\n    chatMemoryLogger.warn(\n      'A valid sessionId is required to get session memory.'\n    );\n    return null;\n  }\n\n  if (!sessionMemoryStore.has(sessionId)) {\n    chatMemoryLogger.info(\n      `Creating new BufferMemory for session: ${sessionId}`\n    );\n    const newMemory = new BufferMemory({\n      returnMessages: true,\n      memoryKey: 'history', // LangChain's key for chat history in memory\n      inputKey: 'input', // LangChain's key for the user's input\n    });\n    sessionMemoryStore.set(sessionId, newMemory);\n  }\n  return sessionMemoryStore.get(sessionId);\n};\n\n/**\n * Clears the message history for a specific session.\n * @public\n * @param {string} sessionId - The unique identifier of the session to clear.\n */\nexport const resetSessionMemory = (sessionId) => {\n  const memory = getSessionMemory(sessionId);\n  if (memory) {\n    memory.chatHistory.clear();\n    chatMemoryLogger.info(`Cleared memory for session: ${sessionId}`);\n  }\n};\n\n/**\n * Retrieves the message history for a specific session.\n * @public\n * @async\n * @param {string} sessionId - The unique identifier for the session.\n * @returns {Promise<import('@langchain/core/messages').BaseMessage[]>} A promise that resolves to an array of LangChain message objects.\n */\nexport const getSessionMemoryHistory = async (sessionId) => {\n  const memory = getSessionMemory(sessionId);\n  if (!memory) {\n    return [];\n  }\n  const memoryVariables = await memory.loadMemoryVariables({});\n  return memoryVariables.history || [];\n};\n\n/**\n * Saves the context (input and output) for a specific session.\n * @public\n * @async\n * @param {string} sessionId - The unique identifier for the session.\n * @param {object} inputValues - The input object, e.g., `{ input: \"user query\" }`.\n * @param {object} outputValues - The output object, e.g., `{ output: \"ai response\" }`.\n */\nexport const saveSessionContext = async (\n  sessionId,\n  inputValues,\n  outputValues\n) => {\n  const memory = getSessionMemory(sessionId);\n  if (memory) {\n    await memory.saveContext(inputValues, outputValues);\n  }\n};\n", "// intelligence/src/intelligence/rag/chat.js\n/**\n * @file Provides a high-level, stateful chat interface for the RAG system.\n * @module @daitanjs/intelligence/rag/chat\n *\n * @description\n * This module exports `createRagChatInstance`, a factory function that creates\n * a self-contained, stateful chat object. Each instance is assigned a unique\n * session ID, ensuring that its conversational history is completely isolated\n * from other instances. This is a critical feature for building robust,\n * multi-user applications.\n */\nimport { getLogger } from '@daitanjs/development';\nimport { getConfigManager } from '@daitanjs/config';\nimport { DaitanOperationError } from '@daitanjs/error';\nimport { askWithRetrieval } from './retrieval.js';\nimport { getVectorStore } from './vectorStoreFactory.js';\nimport { getSessionMemoryHistory, resetSessionMemory } from './chatMemory.js';\n\nconst ragChatLogger = getLogger('daitan-rag-chat');\n\n/**\n * @typedef {import('./interfaces.js').RagChatInstance} RagChatInstance\n * @typedef {import('./interfaces.js').AskWithRetrievalOptions} AskWithRetrievalOptions\n */\n\n/**\n * Creates a new, isolated RAG chat instance with its own session memory.\n *\n * @public\n * @async\n * @param {Object} [options={}] - Configuration options for the chat instance.\n * @param {string} [options.collectionName] - The RAG collection to chat with.\n * @param {boolean} [options.localVerbose] - Verbosity override for this instance.\n * @param {boolean} [options.persistent] - Whether to use a persistent vector store.\n * @returns {Promise<RagChatInstance>} A stateful RAG chat instance.\n */\nexport const createRagChatInstance = async (options = {}) => {\n  const configManager = getConfigManager();\n  // Each chat instance gets a unique, private session ID to ensure conversational isolation.\n  const sessionId = `rag-chat-session-${Date.now().toString(36)}-${Math.random()\n    .toString(36)\n    .substring(2, 8)}`;\n\n  const effectiveVerbose =\n    options.localVerbose !== undefined\n      ? options.localVerbose\n      : configManager.get('RAG_VERBOSE', false);\n  const logContext = { sessionId, collection: options.collectionName };\n\n  if (effectiveVerbose) {\n    ragChatLogger.info(`Creating new RAG chat instance.`, logContext);\n  }\n\n  // Initialize the vector store adapter for this instance.\n  let vectorStoreAdapter;\n  try {\n    vectorStoreAdapter = await getVectorStore({\n      ...options,\n      localVerbose: effectiveVerbose,\n    });\n  } catch (error) {\n    throw new DaitanOperationError(\n      `Could not create RAG chat instance: vector store initialization failed.`,\n      logContext,\n      error\n    );\n  }\n\n  // The returned object's methods have access to the `sessionId` via closure.\n  const ragChatInstance = {\n    /**\n     * Asks a question within the context of this chat instance's session.\n     * @param {Object} params - The parameters for asking a question.\n     * @param {string} params.question - The question to ask.\n     * @param {AskWithRetrievalOptions} [params.options={}] - Call-specific options.\n     * @returns {Promise<import('./retrieval.js').RetrievalResult>}\n     */\n    async ask({ question, options: askOptions = {} }) {\n      const askLogContext = {\n        ...logContext,\n        questionPreview: question.substring(0, 50),\n      };\n      if (effectiveVerbose) {\n        ragChatLogger.info(`RAG chat instance: .ask() called.`, askLogContext);\n      }\n\n      // Combine instance-level and call-level options, ensuring the instance's\n      // session ID is always used.\n      const combinedOptions = {\n        ...options,\n        ...askOptions,\n        sessionId, // Pass the instance's unique session ID to every call.\n        callbacks: askOptions.callbacks,\n        localVerbose:\n          askOptions.localVerbose !== undefined\n            ? askOptions.localVerbose\n            : effectiveVerbose,\n      };\n\n      return askWithRetrieval(question, combinedOptions);\n    },\n\n    /**\n     * Retrieves the message history for this specific chat instance.\n     * @returns {Promise<import('@langchain/core/messages').BaseMessage[]>}\n     */\n    async getHistory() {\n      if (effectiveVerbose) {\n        ragChatLogger.info(\n          `RAG chat instance: .getHistory() called.`,\n          logContext\n        );\n      }\n      // Get history for this specific session.\n      return getSessionMemoryHistory(sessionId);\n    },\n\n    /**\n     * Clears the message history for this specific chat instance.\n     * @returns {void}\n     */\n    resetHistory() {\n      if (effectiveVerbose) {\n        ragChatLogger.info(\n          `RAG chat instance: .resetHistory() called.`,\n          logContext\n        );\n      }\n      // Reset history for this specific session.\n      resetSessionMemory(sessionId);\n    },\n\n    /**\n     * Returns the underlying vector store adapter for this instance.\n     * @returns {import('./vectorStoreAdapterInterface.js').IVectorStoreAdapter}\n     */\n    getVectorStoreAdapter() {\n      return vectorStoreAdapter;\n    },\n  };\n\n  if (effectiveVerbose) {\n    ragChatLogger.info(`RAG chat instance created and ready.`, logContext);\n  }\n  return ragChatInstance;\n};\n", "// intelligence/src/intelligence/rag/embed.js\n/**\n * @file Provides the high-level loadAndEmbedFile function for the RAG system.\n * @module @daitanjs/intelligence/rag/embed\n */\nimport { getLogger } from '@daitanjs/development';\nimport { getConfigManager } from '@daitanjs/config';\nimport { loadDocumentsFromFile } from './documentLoader.js';\nimport { embedChunks } from './vectorStoreFactory.js';\nimport { autoTagDocument } from '../metadata/index.js';\nimport { RecursiveCharacterTextSplitter } from 'langchain/text_splitter';\nimport { DaitanInvalidInputError, DaitanOperationError } from '@daitanjs/error';\nimport { generateIntelligence } from '../core/llmOrchestrator.js';\n\nconst embedLogger = getLogger('daitan-rag-embed');\n\n/**\n * Generates multiple query representations for a single text chunk to improve retrieval.\n * @private\n */\nasync function generateMultiVectorRepresentations(chunkText, verbose) {\n  if (!chunkText || chunkText.trim().length < 50) { // Avoid processing tiny chunks\n    return { summary: null, hypothetical_questions: [] };\n  }\n\n  try {\n    const { response, usage } = await generateIntelligence({\n      prompt: {\n        system: {\n          persona:\n            'You are an expert at distilling information for retrieval systems.',\n          task: 'For the given text, create a very concise one-sentence summary and generate 2-3 diverse, high-quality hypothetical questions that this text would be the perfect answer for. The questions should cover different aspects of the text.',\n          outputFormat:\n            'You MUST respond with a single JSON object with keys: \"summary\" (string) and \"hypothetical_questions\" (array of strings).',\n        },\n        user: `TEXT TO ANALYZE:\\n\"\"\"\\n${chunkText}\\n\"\"\"`,\n      },\n      config: {\n        response: { format: 'json' },\n        llm: { target: 'FAST_TASKER', temperature: 0.2, maxTokens: 600 },\n        verbose,\n        trackUsage: true,\n      },\n      metadata: { summary: 'Multi-vector representation generation' },\n    });\n    // Log usage if needed\n    if (verbose && usage) {\n      embedLogger.debug('Multi-vector LLM usage:', usage);\n    }\n    return {\n      summary: response?.summary || null,\n      hypothetical_questions: response?.hypothetical_questions || [],\n    };\n  } catch (error) {\n    embedLogger.warn(\n      `Could not generate multi-vector representations for chunk: ${error.message}`\n    );\n    return { summary: null, hypothetical_questions: [] };\n  }\n}\n\nexport const loadAndEmbedFile = async ({\n  filePath,\n  customMetadata = {},\n  options = {},\n}) => {\n  const configManager = getConfigManager();\n  const {\n    chunkSize = 1000,\n    chunkOverlap = 200,\n    generateAiMetadata = true,\n    useMultiVector = false,\n    localVerbose,\n    embedOptions = {},\n  } = options;\n  const collectionName =\n    options.collectionName || configManager.get('RAG_DEFAULT_COLLECTION_NAME');\n  const effectiveVerbose =\n    localVerbose ??\n    (configManager.get('RAG_EMBED_VERBOSE', false) ||\n    configManager.get('DEBUG_INTELLIGENCE', false));\n\n  if (!filePath || typeof filePath !== 'string' || !filePath.trim()) {\n    throw new DaitanInvalidInputError('A valid filePath string is required.');\n  }\n\n  embedLogger.info(`Starting loadAndEmbedFile for: \"${filePath}\"`, {\n    useMultiVector,\n    collectionName,\n  });\n\n  const docs = await loadDocumentsFromFile(filePath, {\n    localVerbose: effectiveVerbose,\n  });\n  if (!docs || docs.length === 0) {\n    embedLogger.warn(`No documents were loaded from \"${filePath}\". Aborting.`);\n    return {\n      success: false,\n      message: `No documents loaded from file: ${filePath}`,\n    };\n  }\n\n  let aiMetadata = {};\n  if (generateAiMetadata) {\n    embedLogger.info(`Generating AI metadata for \"${filePath}\"...`);\n    const rawTextForMetadata = docs.map((doc) => doc.pageContent).join('\\n\\n');\n    if (rawTextForMetadata) {\n      const { metadata, llmUsage } = await autoTagDocument(rawTextForMetadata, {\n        config: { verbose: effectiveVerbose, trackUsage: true },\n      });\n      aiMetadata = metadata;\n      if (effectiveVerbose && llmUsage) {\n        embedLogger.debug('AI metadata generation usage:', llmUsage);\n      }\n    }\n  }\n\n  const splitter = new RecursiveCharacterTextSplitter({\n    chunkSize,\n    chunkOverlap,\n  });\n  const chunks = await splitter.splitDocuments(docs);\n  embedLogger.info(\n    `Split file \"${filePath}\" into ${chunks.length} initial chunks.`\n  );\n\n  let finalDocsToEmbed = [];\n  if (useMultiVector) {\n    embedLogger.info(\n      `Generating multi-vector representations for ${chunks.length} chunks...`\n    );\n    // Use Promise.all for concurrency\n    const representationPromises = chunks.map(async (chunk, index) => {\n      // Add the raw chunk itself\n      chunk.metadata = { ...chunk.metadata, chunk_type: 'raw', original_chunk_index: index };\n      \n      const representations = await generateMultiVectorRepresentations(\n        chunk.pageContent,\n        effectiveVerbose\n      );\n\n      const generatedDocs = [];\n      // Add summary chunk\n      if (representations.summary) {\n        generatedDocs.push({\n          pageContent: representations.summary,\n          metadata: { ...chunk.metadata, chunk_type: 'summary' },\n        });\n      }\n      // Add hypothetical question chunks\n      if (representations.hypothetical_questions.length > 0) {\n        representations.hypothetical_questions.forEach((question) => {\n          generatedDocs.push({\n            pageContent: question,\n            metadata: { ...chunk.metadata, chunk_type: 'hypothetical_question' },\n          });\n        });\n      }\n      return [chunk, ...generatedDocs];\n    });\n\n    const nestedResults = await Promise.all(representationPromises);\n    finalDocsToEmbed = nestedResults.flat();\n    \n    embedLogger.info(\n      `Finished generating representations. Total items to embed: ${finalDocsToEmbed.length}`\n    );\n  } else {\n    finalDocsToEmbed = chunks;\n  }\n\n  // Add combined metadata to all chunks\n  finalDocsToEmbed.forEach((chunk) => {\n    chunk.metadata = { ...chunk.metadata, ...customMetadata, ...aiMetadata };\n  });\n  \n  if (finalDocsToEmbed.length === 0) {\n      throw new DaitanOperationError('No document chunks were produced for embedding.', {filePath});\n  }\n\n  await embedChunks(finalDocsToEmbed, {\n    collectionName,\n    localVerbose: effectiveVerbose,\n    ...embedOptions,\n  });\n  embedLogger.info(\n    `Successfully processed and embedded ${finalDocsToEmbed.length} items from \"${filePath}\" into \"${collectionName}\".`\n  );\n\n  return {\n    success: true,\n    message: `Successfully embedded ${finalDocsToEmbed.length} items.`,\n    initialChunks: chunks.length,\n    totalEmbeddings: finalDocsToEmbed.length,\n    collectionName,\n  };\n};", "// intelligence/src/intelligence/rag/documentLoader.js\n/**\n * @file Provides document loading and parsing capabilities from various file formats.\n * @module @daitanjs/intelligence/rag/documentLoader\n *\n * @description\n * This module is responsible for reading local files (PDF, DOCX, TXT, HTML, etc.) and\n * converting their content into a standardized format, specifically LangChain `Document` objects.\n * It also provides a helper to extract raw text content for preliminary analysis, such as\n * AI-driven metadata generation, before the full document is chunked and processed.\n */\nimport fs from 'fs-extra';\nimport path from 'path';\nimport mammoth from 'mammoth';\nimport { JSDOM } from 'jsdom';\nimport Papa from 'papaparse';\nimport { getLogger } from '@daitanjs/development';\nimport { getConfigManager } from '@daitanjs/config';\nimport {\n  DaitanConfigurationError,\n  DaitanFileOperationError,\n} from '@daitanjs/error';\nimport { PDFLoader } from '@langchain/community/document_loaders/fs/pdf';\nimport { Document as LangchainDocumentCore } from '@langchain/core/documents';\n\nconst loaderHelperLogger = getLogger('daitan-rag-loader-helper');\n\n/**\n * Loads documents from a local file path using appropriate loaders.\n * @public\n * @async\n * @param {string} filePath - The path to the file.\n * @param {object} [options={}] - Options for loading.\n * @returns {Promise<LangchainDocumentCore[]>} An array of LangChain Document objects.\n */\nexport const loadDocumentsFromFile = async (filePath, options = {}) => {\n  const configManager = getConfigManager(); // Lazy-load\n  const currentCallVerbose =\n    options.localVerbose ??\n    (configManager.get('RAG_LOADER_VERBOSE', false) ||\n      configManager.get('DEBUG_INTELLIGENCE', false));\n  const logContext = { filePath: path.basename(filePath) };\n\n  if (!filePath || typeof filePath !== 'string' || !filePath.trim()) {\n    throw new DaitanConfigurationError('filePath must be a non-empty string.');\n  }\n\n  const absoluteFilePath = path.resolve(filePath);\n  const fileExtension = path.extname(absoluteFilePath).toLowerCase();\n  logContext.fileExtension = fileExtension;\n\n  if (!(await fs.pathExists(absoluteFilePath))) {\n    throw new DaitanFileOperationError(`File not found: ${absoluteFilePath}`, {\n      path: absoluteFilePath,\n      operation: 'load',\n    });\n  }\n\n  try {\n    let documents = [];\n    const plainTextExtensions = [\n      '.txt',\n      '.md',\n      '.rtf',\n      '.js',\n      '.ts',\n      '.py',\n      '.java',\n      '.c',\n      '.cpp',\n      '.h',\n      '.hpp',\n      '.cs',\n      '.xml',\n      '.yaml',\n      '.yml',\n      '.log',\n      '.sh',\n      '.bash',\n      '.sql',\n      '.rb',\n      '.go',\n      '.php',\n      '.swift',\n      '.kt',\n    ];\n\n    if (plainTextExtensions.includes(fileExtension)) {\n      const textContent = await fs.readFile(absoluteFilePath, 'utf-8');\n      documents = [\n        new LangchainDocumentCore({\n          pageContent: textContent,\n          metadata: { source_type: fileExtension.substring(1) },\n        }),\n      ];\n    } else {\n      switch (fileExtension) {\n        case '.pdf':\n          const pdfLoader = new PDFLoader(absoluteFilePath, {\n            splitPages: options.pdfSplitPages !== false,\n          });\n          documents = await pdfLoader.load();\n          break;\n        case '.docx':\n          const docxBuffer = await fs.readFile(absoluteFilePath);\n          const docxResult = await mammoth.extractRawText({\n            buffer: docxBuffer,\n          });\n          documents = [\n            new LangchainDocumentCore({\n              pageContent: docxResult.value || '',\n              metadata: { source_type: 'docx' },\n            }),\n          ];\n          break;\n        case '.html':\n        case '.htm':\n          const htmlContent = await fs.readFile(absoluteFilePath, 'utf-8');\n          const dom = new JSDOM(htmlContent);\n          const selectors = [\n            'main',\n            'article',\n            '.main-content',\n            '.content',\n            '#main',\n            '#content',\n            '[role=\"main\"]',\n            'body',\n          ];\n          let extractedText = '';\n          for (const selector of selectors) {\n            const element = dom.window.document.querySelector(selector);\n            if (element) {\n              extractedText = element.textContent?.trim() || '';\n              if (extractedText) break;\n            }\n          }\n          const maxHtmlLength = options.maxHtmlContentLength || 500000;\n          extractedText = extractedText\n            .replace(/\\s\\s+/g, ' ')\n            .replace(/\\n\\s*\\n+/g, '\\n')\n            .trim()\n            .substring(0, maxHtmlLength);\n          documents = [\n            new LangchainDocumentCore({\n              pageContent: extractedText,\n              metadata: { source_type: 'html' },\n            }),\n          ];\n          break;\n        case '.json':\n          const jsonContent = await fs.readFile(absoluteFilePath, 'utf-8');\n          documents = [\n            new LangchainDocumentCore({\n              pageContent: JSON.stringify(JSON.parse(jsonContent), null, 2),\n              metadata: { source_type: 'json_object' },\n            }),\n          ];\n          break;\n        case '.csv':\n          const csvContent = await fs.readFile(absoluteFilePath, 'utf-8');\n          const parsedCsv = Papa.parse(csvContent, {\n            header: true,\n            skipEmptyLines: true,\n            dynamicTyping: true,\n          });\n          documents = parsedCsv.data.map(\n            (row, index) =>\n              new LangchainDocumentCore({\n                pageContent: Object.values(row).join('; '),\n                metadata: {\n                  source_type: 'csv_row',\n                  row_number: index + 1,\n                  ...row,\n                },\n              })\n          );\n          break;\n        default:\n          throw new DaitanConfigurationError(\n            `Unsupported file type: ${fileExtension}`\n          );\n      }\n    }\n\n    documents.forEach((doc) => {\n      doc.metadata = {\n        ...doc.metadata,\n        source: absoluteFilePath,\n        source_filename: path.basename(absoluteFilePath),\n      };\n    });\n\n    if (currentCallVerbose) {\n      loaderHelperLogger.debug(\n        `Loaded ${documents.length} document(s) from \"${absoluteFilePath}\".`\n      );\n    }\n    return documents;\n  } catch (error) {\n    throw new DaitanFileOperationError(\n      `Failed to load or parse file ${absoluteFilePath}: ${error.message}`,\n      { path: absoluteFilePath },\n      error\n    );\n  }\n};\n\n/**\n * Extracts raw text content from a file for metadata generation purposes.\n * @public\n * @async\n * @param {string} filePath\n * @param {object} [options={}]\n * @returns {Promise<string>}\n */\nexport const extractRawTextForMetadata = async (filePath, options = {}) => {\n  const docs = await loadDocumentsFromFile(filePath, options);\n  return docs.map((doc) => doc.pageContent).join('\\n\\n');\n};\n", "// intelligence/src/intelligence/metadata/parse.js\n\nimport { getLogger } from '@daitanjs/development';\nconst parseLogger = getLogger('daitan-metadata-parser');\n\n/**\n * Validates and normalizes raw metadata output from an LLM.\n * Ensures essential fields (tags, type, summary) exist and have expected basic types.\n *\n * @param {any} rawLLMOutput - The raw output from the LLM, expected to be an object after JSON parsing.\n * @returns {{tags: string[], type: string, summary: string, originalRaw?: any}}\n *          A normalized metadata object. `originalRaw` is included if parsing/validation changes structure.\n */\nexport const validateAndNormalizeMetadata = (rawLLMOutput) => {\n  const result = {\n    tags: [],\n    type: 'unknown',\n    summary: 'No summary available.',\n  };\n\n  if (typeof rawLLMOutput !== 'object' || rawLLMOutput === null) {\n    parseLogger.warn(\n      'Raw LLM output for metadata is not an object or is null. Returning default structure.',\n      { rawLLMOutput }\n    );\n    result.originalRaw = rawLLMOutput; // Store what was received if it's not an object\n    return result;\n  }\n\n  // Tags: should be an array of strings.\n  if (Array.isArray(rawLLMOutput.tags)) {\n    result.tags = rawLLMOutput.tags\n      .map((tag) => String(tag).trim().toLowerCase())\n      .filter(Boolean);\n  } else if (\n    typeof rawLLMOutput.tags === 'string' &&\n    rawLLMOutput.tags.trim()\n  ) {\n    // Handle case where LLM might return a comma-separated string for tags\n    result.tags = rawLLMOutput.tags\n      .split(',')\n      .map((tag) => tag.trim().toLowerCase())\n      .filter(Boolean);\n    parseLogger.debug('Converted string of tags to an array.', {\n      originalTags: rawLLMOutput.tags,\n      convertedTags: result.tags,\n    });\n  } else if (rawLLMOutput.tags) {\n    parseLogger.warn(\n      'Metadata \"tags\" field was present but not an array or valid string. Defaulting to empty array.',\n      { tagsReceived: rawLLMOutput.tags }\n    );\n  }\n\n  // Type: should be a string.\n  if (typeof rawLLMOutput.type === 'string' && rawLLMOutput.type.trim()) {\n    result.type = rawLLMOutput.type.trim().toLowerCase().replace(/\\s+/g, '_'); // Normalize type string\n  } else if (rawLLMOutput.type) {\n    parseLogger.warn(\n      'Metadata \"type\" field was present but not a string. Defaulting to \"unknown\".',\n      { typeReceived: rawLLMOutput.type }\n    );\n  }\n\n  // Summary: should be a string.\n  if (typeof rawLLMOutput.summary === 'string' && rawLLMOutput.summary.trim()) {\n    result.summary = rawLLMOutput.summary.trim();\n  } else if (rawLLMOutput.summary) {\n    parseLogger.warn(\n      'Metadata \"summary\" field was present but not a string. Defaulting to \"No summary available.\".',\n      { summaryReceived: rawLLMOutput.summary }\n    );\n  }\n\n  // If the validated structure is different from raw (e.g. due to normalization or missing fields),\n  // it might be useful to log or attach the original for debugging.\n  // For simplicity here, we just return the normalized structure.\n  // If rawLLMOutput itself was significantly different, one might add:\n  // if (JSON.stringify(result) !== JSON.stringify(rawLLMOutput)) { // Basic check for structural difference\n  //    result.originalRaw = rawLLMOutput;\n  // }\n\n  return result;\n};\n\n/**\n * @deprecated `tidyJsonString` is a simple heuristic and might not cover all cases.\n *             Prefer LLMs that reliably output valid JSON or use more robust JSON repair libraries if needed.\n *             `generateIntelligence` with `responseFormat: 'json'` should ideally handle JSON parsing robustly.\n * Simple attempt to clean common issues in LLM-generated JSON-like strings.\n * @param {string} str - The JSON-like string.\n * @returns {string} A potentially cleaner string.\n */\nexport const tidyJsonString = (str) => {\n  if (typeof str !== 'string') return str;\n  // This is a very basic attempt and might not be robust enough.\n  // LLMs (like OpenAI with JSON mode) should ideally return valid JSON.\n  return str\n    .replace(/([{,]\\s*)([A-Za-z0-9_]+)\\s*:/g, '$1\"$2\":') // Add quotes to keys\n    .replace(/[\u201C\u201D]/g, '\"') // Replace smart quotes with standard quotes\n    .replace(/'/g, '\"') // Replace single quotes with double quotes (can be risky if content has apostrophes)\n    .replace(/,\\s*([}\\]])/g, '$1') // Remove trailing commas before closing brace/bracket\n    .replace(/\\\\'/g, \"'\") // Unescape apostrophes that might have been wrongly escaped if we replaced all single quotes\n    .trim();\n};\n\n/**\n * Converts a value to a plain string, attempting to extract content if it's an object.\n * @param {any} value - The value to convert.\n * @returns {string} The string representation.\n */\nexport const toPlainString = (value) => {\n  if (typeof value === 'string') return value;\n  if (\n    value &&\n    typeof value === 'object' &&\n    value.content &&\n    typeof value.content === 'string'\n  ) {\n    return value.content; // Common pattern for LangChain message content\n  }\n  try {\n    return JSON.stringify(value);\n  } catch (e) {\n    return String(value); // Fallback\n  }\n};\n\n/**\n * @deprecated `generateIntelligence` with `responseFormat: 'json'` should directly return a parsed object.\n *             This function might be useful if dealing with LLM outputs that are strings needing parsing.\n * Safely parses a JSON string, attempting to clean it first.\n * @param {string | object} val - The value to parse. If already an object, returns it.\n * @returns {object} The parsed JSON object.\n * @throws {DaitanValidationError} If parsing fails.\n */\nexport const parseSafeJSON = (val) => {\n  if (typeof val === 'object' && val !== null && !Array.isArray(val)) {\n    // Already a plain object\n    return val;\n  }\n  if (typeof val !== 'string') {\n    parseLogger.error('parseSafeJSON: Input is not a string or object.', {\n      type: typeof val,\n    });\n    throw new DaitanValidationError(\n      'Invalid input for JSON parsing: not a string or object.'\n    );\n  }\n\n  try {\n    // First, try direct parsing\n    return JSON.parse(val);\n  } catch (directParseError) {\n    parseLogger.warn(\n      'Direct JSON.parse failed, attempting to tidy and re-parse.',\n      { error: directParseError.message, stringPreview: val.substring(0, 100) }\n    );\n    try {\n      const tidiedString = tidyJsonString(val);\n      return JSON.parse(tidiedString);\n    } catch (tidyParseError) {\n      parseLogger.error('JSON parsing failed even after tidying.', {\n        originalError: directParseError.message,\n        tidyError: tidyParseError.message,\n        stringPreview: val.substring(0, 200),\n      });\n      throw new DaitanValidationError(\n        `Failed to parse JSON string: ${tidyParseError.message}. Original error: ${directParseError.message}`,\n        { stringAttempted: val }\n      );\n    }\n  }\n};\n", "// intelligence/src/intelligence/metadata/index.js\n/**\n * @file Metadata generation and validation utilities for documents.\n * @module @daitanjs/intelligence/metadata\n *\n * @description\n * This module provides functions for automatically generating metadata (tags, document type, summary)\n * from text content using Large Language Models (LLMs). It also includes utilities for\n * validating and normalizing the structure of this AI-generated metadata.\n */\nimport { generateIntelligence } from '../core/llmOrchestrator.js';\nimport { validateAndNormalizeMetadata } from './parse.js';\nimport { getLogger } from '@daitanjs/development';\nimport { getConfigManager } from '@daitanjs/config';\nimport { DaitanOperationError, DaitanInvalidInputError } from '@daitanjs/error';\n\nconst metadataGeneratorLogger = getLogger('daitan-metadata-generator');\n\n/** @private */\nconst METADATA_GENERATION_SYSTEM_PROMPT_CONFIG = {\n  persona:\n    'You are an expert AI assistant specialized in analyzing documents and extracting relevant, structured metadata.',\n  task: 'Your primary task is to identify key tags or keywords, determine an appropriate document type or category, and create a concise, informative summary based on the provided text content.',\n  outputFormat:\n    'You MUST respond ONLY with a single, valid JSON object with keys: \"tags\", \"type\", \"summary\".',\n  guidelines: [\n    \"For 'tags', provide an array of 3-7 relevant lowercase strings representing key concepts or themes.\",\n    \"For 'type', provide a single, general classification string (e.g., 'news_article', 'technical_document').\",\n    \"For 'summary', create a brief, neutral overview of the document's main points, no more than 150 words.\",\n    'Verify your entire output is a single, valid JSON object before responding.',\n  ],\n};\n\n/**\n * @typedef {Object} GeneratedMetadata\n * @property {string[]} tags - Array of lowercase keyword tags.\n * @property {string} type - A normalized string representing the document type.\n * @property {string} summary - A concise summary of the document content.\n */\n\n/**\n * @typedef {Object} AutoTagResult\n * @property {GeneratedMetadata} metadata - The generated metadata.\n * @property {import('../core/llmOrchestrator.js').LLMUsageInfo | null} llmUsage - LLM token usage information.\n */\n\n/**\n * @typedef {import('../core/llmOrchestrator.js').GenerateIntelligenceParams['config']} LLMCallOptions\n */\n\n/**\n * Generates metadata (tags, document type, summary) for a given text using an LLM.\n *\n * @public\n * @async\n * @param {string} text - The input text content to analyze.\n * @param {LLMCallOptions} [llmCallOptions={}] - Options for the LLM call, conforming to the `generateIntelligence` config structure.\n * @returns {Promise<AutoTagResult>} An object containing `metadata` and `llmUsage`. On failure, returns a default error structure.\n * @throws {DaitanInvalidInputError} If `text` is not a non-empty string.\n */\nexport const autoTagDocument = async (text, llmCallOptions = {}) => {\n  const callId = `autoTag-${Date.now().toString(36)}`;\n  const configManager = getConfigManager();\n\n  const effectiveVerbose =\n    llmCallOptions.verbose ??\n    (configManager.get('RAG_METADATA_VERBOSE', false) ||\n      configManager.get('DEBUG_INTELLIGENCE', false));\n  const effectiveTrackUsage =\n    llmCallOptions.trackUsage ?? configManager.get('LLM_TRACK_USAGE', true);\n\n  if (!text || typeof text !== 'string' || !text.trim()) {\n    throw new DaitanInvalidInputError(\n      'Input text for autoTagDocument must be a non-empty string.'\n    );\n  }\n\n  const maxCharsForMetadata = parseInt(\n    configManager.get('RAG_METADATA_SAMPLE_CHARS', '12000'),\n    10\n  );\n  const textSample =\n    text.length > maxCharsForMetadata\n      ? text.substring(0, maxCharsForMetadata)\n      : text;\n\n  if (effectiveVerbose && text.length > maxCharsForMetadata) {\n    metadataGeneratorLogger.debug(\n      `[${callId}] Text sample for metadata generation truncated to ${maxCharsForMetadata} chars.`\n    );\n  }\n\n  try {\n    const callSummaryForLog = `AI Metadata generation for document snippet (length: ${textSample.length})`;\n\n    const { response: rawLLMParsedOutput, usage: llmUsageInfo } =\n      await generateIntelligence({\n        prompt: {\n          system: METADATA_GENERATION_SYSTEM_PROMPT_CONFIG,\n          user: `Analyze the following text content and generate structured metadata:\\n\\n---BEGIN CONTENT SAMPLE---\\n${textSample}\\n---END CONTENT SAMPLE---`,\n        },\n        config: {\n          response: { format: 'json' },\n          llm: {\n            target:\n              llmCallOptions.llm?.target ||\n              configManager.get('LLM_TARGET_METADATA') ||\n              'FAST_TASKER',\n            ...(llmCallOptions.llm || {}), // Allow overriding all LLM params\n          },\n          trackUsage: effectiveTrackUsage,\n          verbose: effectiveVerbose,\n          ...(llmCallOptions || {}), // Pass other top-level configs like retry, cache etc.\n        },\n        metadata: { summary: callSummaryForLog },\n      });\n\n    const normalizedMetadata = validateAndNormalizeMetadata(rawLLMParsedOutput);\n    metadataGeneratorLogger.info(\n      `[${callId}] Metadata successfully generated.`\n    );\n    return {\n      metadata: normalizedMetadata,\n      llmUsage: effectiveTrackUsage ? llmUsageInfo : null,\n    };\n  } catch (error) {\n    metadataGeneratorLogger.warn(\n      `[${callId}] autoTagDocument failed: ${error.message}. Returning default error metadata.`\n    );\n    return {\n      metadata: {\n        tags: ['error_metadata_generation_failed'],\n        type: 'metadata_generation_error',\n        summary: `Automated metadata generation failed. Reason: ${String(\n          error.message\n        ).substring(0, 100)}...`,\n      },\n      llmUsage: null,\n    };\n  }\n};\n\n/**\n * @deprecated As of v1.1.0, use `autoTagDocument` instead. It now returns a default error structure on failure.\n *\n * @param {string} text - The input text content to analyze.\n * @param {object} [llmOpts={}] - Deprecated: Simple options for the LLM call (e.g., target, temperature).\n * @returns {Promise<GeneratedMetadata>} The generated metadata or a default error structure.\n */\nexport const safeGenerateMetadata = async (text, llmOpts = {}) => {\n  metadataGeneratorLogger.warn(\n    '`safeGenerateMetadata` is deprecated and will be removed in a future version. Please use `autoTagDocument` instead, which provides a more flexible configuration and consistent error handling.'\n  );\n\n  // Adapt the old, flat `llmOpts` to the new structured `config` for `autoTagDocument`\n  const adaptedConfig = {\n    llm: {\n      target: llmOpts.target,\n      temperature: llmOpts.temperature,\n      maxTokens: llmOpts.maxTokens,\n      // Add any other direct mappings from the old llmOpts structure\n    },\n    // You can also map other deprecated options here if they existed\n    verbose: llmOpts.verbose,\n    trackUsage: llmOpts.trackUsage,\n  };\n\n  try {\n    const { metadata } = await autoTagDocument(text, adaptedConfig);\n    return metadata;\n  } catch (e) {\n    // autoTagDocument now throws DaitanInvalidInputError, which is more specific.\n    // However, it also has a fail-safe return, so this catch block might only\n    // catch the input error. The original intent was to prevent all throws.\n    // The new `autoTagDocument` handles operational errors internally by returning a default structure.\n    return {\n      tags: ['error_invalid_input_to_safe_generate'],\n      type: 'input_error',\n      summary: `Metadata generation failed due to invalid input: ${e.message.substring(\n        0,\n        100\n      )}...`,\n    };\n  }\n};\n\nexport { validateAndNormalizeMetadata } from './parse.js';\n", "// intelligence/src/intelligence/rag/printStats.js\n/**\n * @file Utility for printing statistics of a RAG vector store collection.\n * @module @daitanjs/intelligence/rag/printStats\n */\nimport path from 'path';\nimport { ChromaClient as DirectChromaClient } from 'chromadb';\nimport { getLogger } from '@daitanjs/development';\nimport { getConfigManager } from '@daitanjs/config';\nimport { DaitanOperationError } from '@daitanjs/error';\nimport { DEFAULT_COLLECTION_NAME } from './vectorStoreFactory.js';\n\nconst statsLogger = getLogger('daitan-rag-stats');\n\n/** @private */\nconst previewContent = (text, maxLength = 80) => {\n  if (typeof text !== 'string') return '<invalid_content>';\n  const cleaned = text.replace(/\\s+/g, ' ').trim();\n  if (cleaned.length <= maxLength) return cleaned;\n  return cleaned.slice(0, maxLength - 3) + '...';\n};\n\n/**\n * @typedef {Object} PrintStoreStatsOptions\n * @property {string} [collectionName]\n * @property {number} [sampleLimit=2]\n * @property {string} [chromaHost]\n * @property {number} [chromaPort]\n * @property {boolean} [localVerbose]\n */\n\n/**\n * Prints statistics and sample documents for a specified ChromaDB collection.\n *\n * @param {PrintStoreStatsOptions} [options={}] - Optional parameters.\n * @returns {Promise<void>}\n */\nexport const printStoreStats = async (options = {}) => {\n  const configManager = getConfigManager(); // Lazy-load\n  const {\n    collectionName: collectionNameInput,\n    sampleLimit = 2,\n    chromaHost = configManager.get('CHROMA_HOST', 'localhost'),\n    chromaPort = configManager.get('CHROMA_PORT', 8000),\n    localVerbose,\n  } = options;\n\n  const effectiveCollectionName =\n    collectionNameInput || DEFAULT_COLLECTION_NAME();\n  const logContext = {\n    collectionName: effectiveCollectionName,\n    host: chromaHost,\n    port: chromaPort,\n  };\n\n  statsLogger.info(\n    `\uD83D\uDCCA Printing stats for ChromaDB collection: \"${effectiveCollectionName}\"`\n  );\n\n  const chromaUrl = `http://${chromaHost}:${chromaPort}`;\n  try {\n    const client = new DirectChromaClient({ path: chromaUrl });\n    await client.heartbeat();\n    const collection = await client.getCollection({\n      name: effectiveCollectionName,\n    });\n    const count = await collection.count();\n    statsLogger.info(\n      `\uD83D\uDCE6 Collection \"${effectiveCollectionName}\" contains ${count} document chunks.`\n    );\n\n    if (count > 0 && sampleLimit > 0) {\n      const results = await collection.peek({\n        limit: Math.min(sampleLimit, count),\n      });\n      const ids = results.ids || [];\n      if (ids.length > 0) {\n        statsLogger.info(\n          `\uD83D\uDCCB Sample documents from \"${effectiveCollectionName}\":`\n        );\n        ids.forEach((id, i) => {\n          const metadata = results.metadatas[i] || {};\n          const source =\n            metadata.source_filename ||\n            (metadata.source\n              ? path.basename(String(metadata.source))\n              : 'unknown');\n          statsLogger.info(\n            `  #${i + 1} [ID: ${String(id).substring(\n              0,\n              10\n            )}...] Source: ${source} \u2192 \"${previewContent(\n              results.documents[i]\n            )}\"`\n          );\n        });\n      }\n    }\n  } catch (err) {\n    if (String(err.message).toLowerCase().includes('not found')) {\n      statsLogger.error(\n        `Collection \"${effectiveCollectionName}\" does not exist at ${chromaUrl}.`\n      );\n      return;\n    }\n    throw new DaitanOperationError(\n      `Error getting store stats: ${err.message}`,\n      logContext,\n      err\n    );\n  }\n};\n", "// intelligence/src/intelligence/search/specializedSearch.js\n/**\n * @file Implements specialized search agents for different source types (News, Academic, etc.).\n * @module @daitanjs/intelligence/search/specializedSearch\n */\nimport { getLogger } from '@daitanjs/development';\nimport { googleSearch, downloadAndExtract } from '@daitanjs/web';\nimport { generateIntelligence } from '../../intelligence/core/llmOrchestrator.js';\n\nconst logger = getLogger('daitan-specialized-search');\n\n/**\n * @typedef {import('@daitanjs/web').GoogleSearchResultItem} GoogleSearchResultItem\n */\n\n/**\n * @typedef {Object} SourcedContent\n * @property {string} url - The source URL.\n * @property {string} title - The title of the page or document.\n * @property {string} content - The extracted and cleaned text content.\n * @property {string} [publishedDate] - The publication date, if found.\n */\n\n/**\n * @typedef {Object} SearchAgentOptions\n * @property {(update: { source: string, status: 'scraping' | 'summarizing' | 'complete' | 'failed', data?: any }) => void} [onProgress]\n * @property {boolean} [verbose=false]\n */\n\n/**\n * A specialized research agent focused on finding recent news articles.\n * It uses date restrictions in its search queries and attempts to extract publication dates.\n *\n * @param {string} query - The search query.\n * @param {SearchAgentOptions} [options={}] - Options for the search agent.\n * @returns {Promise<SourcedContent[]>} A promise that resolves to an array of sourced content objects.\n */\nexport async function searchNews(query, options = {}) {\n  const callId = `news-search-${Date.now().toString(36)}`;\n  logger.info(`[${callId}] Starting news search for query: \"${query}\"`);\n\n  try {\n    // Step 1: Search Google with a date restriction to prioritize recent news.\n    const searchResults = await googleSearch({\n      query,\n      num: 5,\n      dateRestrict: 'm1', // Prioritize results from the last month\n    });\n\n    if (!searchResults || searchResults.length === 0) {\n      logger.info(`[${callId}] No recent news results found for query.`);\n      return [];\n    }\n\n    // Step 2: Scrape and process results in parallel.\n    const processingPromises = searchResults.map(async (result) => {\n      if (options.onProgress) {\n        options.onProgress({ source: result.link, status: 'scraping' });\n      }\n\n      try {\n        const content = await downloadAndExtract(result.link, {\n          outputFormat: 'cleanText',\n          strategy: 'robust',\n        });\n\n        if (!content || content.length < 100) {\n          throw new Error('Extracted content is too short to be useful.');\n        }\n\n        const dateMatch = content\n          .substring(0, 1500)\n          .match(\n            /(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\s+\\d{1,2},\\s+\\d{4}|(\\d{4}-\\d{2}-\\d{2})/\n          );\n\n        const sourcedContent = {\n          url: result.link,\n          title: result.title,\n          content: content,\n          publishedDate: dateMatch ? dateMatch[0] : undefined,\n        };\n\n        if (options.onProgress) {\n          options.onProgress({\n            source: result.link,\n            status: 'complete',\n            data: sourcedContent.title,\n          });\n        }\n        return sourcedContent;\n      } catch (error) {\n        logger.warn(\n          `[${callId}] Failed to process news source ${result.link}: ${error.message}`\n        );\n        if (options.onProgress) {\n          options.onProgress({\n            source: result.link,\n            status: 'failed',\n            data: error.message,\n          });\n        }\n        return null;\n      }\n    });\n\n    const allSourcedContent = (await Promise.all(processingPromises)).filter(\n      Boolean\n    );\n\n    logger.info(\n      `[${callId}] News search complete. Retrieved and processed ${allSourcedContent.length} sources.`\n    );\n    return allSourcedContent;\n  } catch (error) {\n    logger.error(\n      `[${callId}] A critical error occurred during the news search workflow: ${error.message}`\n    );\n    throw error;\n  }\n}\n\n/**\n * A specialized research agent for finding academic papers and scholarly articles.\n * (Placeholder for future implementation)\n */\nexport async function searchAcademic(query, options = {}) {\n  logger.info(\n    `[ACADEMIC-STUB] Academic search called for query: \"${query}\". This feature is not yet fully implemented.`\n  );\n  return Promise.resolve([]);\n}\n\n/**\n * A research agent for general web content.\n */\nexport async function searchGeneralWeb(query, options = {}) {\n  const callId = `general-search-${Date.now().toString(36)}`;\n  logger.info(`[${callId}] Starting general web search for query: \"${query}\"`);\n\n  try {\n    const searchResults = await googleSearch({ query, num: 3 });\n    if (!searchResults || searchResults.length === 0) return [];\n\n    const processingPromises = searchResults.map(async (result) => {\n      if (options.onProgress)\n        options.onProgress({ source: result.link, status: 'scraping' });\n      try {\n        const content = await downloadAndExtract(result.link, {\n          outputFormat: 'cleanText',\n        });\n        if (!content || content.length < 100) return null;\n\n        const sourcedContent = {\n          url: result.link,\n          title: result.title,\n          content,\n        };\n        if (options.onProgress)\n          options.onProgress({\n            source: result.link,\n            status: 'complete',\n            data: sourcedContent.title,\n          });\n        return sourcedContent;\n      } catch (error) {\n        logger.warn(\n          `[${callId}] Failed to process web source ${result.link}: ${error.message}`\n        );\n        if (options.onProgress)\n          options.onProgress({\n            source: result.link,\n            status: 'failed',\n            data: error.message,\n          });\n        return null;\n      }\n    });\n\n    const allSourcedContent = (await Promise.all(processingPromises)).filter(\n      Boolean\n    );\n    logger.info(\n      `[${callId}] General web search complete. Processed ${allSourcedContent.length} sources.`\n    );\n    return allSourcedContent;\n  } catch (error) {\n    logger.error(\n      `[${callId}] A critical error occurred during the general web search: ${error.message}`\n    );\n    throw error;\n  }\n}\n", "// intelligence/src/intelligence/tools/tool-registries.js\n/**\n * @file Defines tool registries and helper functions for retrieving tools.\n * @module @daitanjs/intelligence/tools/tool-registries\n *\n * @description This module is isolated to prevent circular dependencies. It imports\n * all tools to create registries and exports helper functions for accessing them.\n */\nimport { getLogger } from '@daitanjs/development';\n\n// Import all tools to populate registries\nimport { calculatorTool } from './calculatorTool.js';\nimport { wikipediaSearchTool } from './wikipediaSearchTool.js';\nimport { cliTool } from './cliTool.js';\nimport { webSearchTool } from './webSearchTool.js';\nimport { userManagementTool } from './userManagementTool.js';\nimport { csvQueryTool } from './csvQueryTool.js';\nimport { createPaymentIntentTool } from './createPaymentIntentTool.js';\nimport { youtubeSearchTool } from './youtubeSearchTool.js';\nimport { processYoutubeAudioTool } from './processYoutubeAudioTool.js';\nimport { imageGenerationTool } from './imageGenerationTool.js';\nimport {\n  searchGmailTool,\n  readEmailContentTool,\n  createGmailDraftTool,\n} from './gmailTools.js';\nimport { calendarTool } from './calendarTool.js';\nimport {\n  createGoogleDocTool,\n  createGoogleSheetTool,\n} from './googleDriveTools.js';\nimport { ragTool } from './ragTool.js';\n\nconst toolsRegistryLogger = getLogger('daitan-tools-registry');\n\nconst DEFAULT_TOOLS_REGISTRY = {\n  calculator: calculatorTool,\n  wikipedia_search: wikipediaSearchTool,\n  command_line_interface: cliTool,\n  web_search: webSearchTool,\n  knowledge_base_tool: ragTool,\n};\n\nconst DAITAN_PLATFORM_TOOLS_REGISTRY = {\n  user_management: userManagementTool,\n  csv_query_tool: csvQueryTool,\n  create_payment_intent: createPaymentIntentTool,\n  youtube_search: youtubeSearchTool,\n  process_youtube_audio: processYoutubeAudioTool,\n  generate_image: imageGenerationTool,\n  search_gmail: searchGmailTool,\n  read_email_content: readEmailContentTool,\n  create_gmail_draft: createGmailDraftTool,\n  google_calendar_tool: calendarTool,\n  create_google_doc: createGoogleDocTool,\n  create_google_sheet: createGoogleSheetTool,\n};\n\nfunction getToolsFromRegistry(toolNames, registry, registryName) {\n  if (!Array.isArray(toolNames) || toolNames.length === 0) {\n    return Object.values(registry);\n  }\n  const selectedTools = [];\n  for (const name of toolNames) {\n    if (registry[name]) {\n      selectedTools.push(registry[name]);\n    } else {\n      toolsRegistryLogger.warn(\n        `Tool \"${name}\" not found in ${registryName} registry.`\n      );\n    }\n  }\n  return selectedTools;\n}\n\nexport const getDefaultTools = (toolNames) =>\n  getToolsFromRegistry(toolNames, DEFAULT_TOOLS_REGISTRY, 'default');\n\nexport const getDaitanPlatformTools = (toolNames) =>\n  getToolsFromRegistry(\n    toolNames,\n    DAITAN_PLATFORM_TOOLS_REGISTRY,\n    'Daitan Platform'\n  );\n", "// intelligence/src/intelligence/tools/calculatorTool.js\nimport { getLogger } from '@daitanjs/development';\nimport { DaitanValidationError, DaitanOperationError } from '@daitanjs/error';\nimport { z } from 'zod'; // For input schema definition\nimport { createDaitanTool } from '../core/toolFactory.js'; // CORRECTED: Import from the new 'core' location\n\nconst calculatorLogger = getLogger('daitan-tool-calculator');\nconst TOOL_NAME = 'calculator';\nconst MAX_EXPRESSION_LENGTH = 150; // Increased slightly\n\n// Define Zod schema for input validation\nconst CalculatorInputSchema = z\n  .object({\n    expression: z\n      .string()\n      .min(1, 'Expression cannot be empty.')\n      .max(\n        MAX_EXPRESSION_LENGTH,\n        `Expression cannot exceed ${MAX_EXPRESSION_LENGTH} characters.`\n      )\n      .regex(\n        /^[0-9+\\-*/().\\s^%]+$/,\n        'Expression contains invalid characters. Only numbers, basic operators (+, -, *, /, %, ^), parentheses, and spaces are allowed.'\n      )\n      .refine((expr) => {\n        try {\n          // Basic safety: check for balanced parentheses\n          let open = 0;\n          for (const char of expr) {\n            if (char === '(') open++;\n            else if (char === ')') open--;\n            if (open < 0) return false; // Unbalanced closing parenthesis\n          }\n          return open === 0; // Ensure all opened are closed\n        } catch {\n          return false;\n        }\n      }, 'Expression has unbalanced parentheses.')\n      .refine((expr) => {\n        // Avoid sequences like `**` if `^` is for power, or `++` if not intended for increment\n        // This is a simple check; more complex validation might use a proper parser\n        if (\n          expr.includes('**') ||\n          expr.includes('//') ||\n          expr.includes('++') ||\n          expr.includes('--')\n        ) {\n          // Disallow Python-style power or C-style increments if not supported by new Function()\n          // If supporting `**` for exponentiation, remove it from this check\n          return false;\n        }\n        return true;\n      }, 'Expression contains disallowed operator sequences (e.g., **, //, ++, --). Use ^ for exponentiation if needed.'),\n  })\n  .strict(); // Ensure no extra properties are passed\n\n/**\n * A tool for performing mathematical calculations.\n * Leverages Zod for input schema definition and validation.\n */\nexport const calculatorTool = createDaitanTool(\n  TOOL_NAME,\n  `Useful for performing mathematical calculations when you need an exact numerical answer.\nInput must be an object with a single key \"expression\", which is a string representing a mathematical expression.\nExample input: {\"expression\": \"2 + 2 * (5-1)\"} or {\"expression\": \"100 / 4^2\"}.\nSupports basic arithmetic operators: +, -, *, /, %, and ^ (for exponentiation).\nParentheses can be used for grouping. Avoid overly complex or excessively long expressions.`,\n  async (input) => {\n    // LangChain DynamicTool func receives a string or an object\n    const callId = Math.random().toString(36).substring(2, 9); // Simple call ID for logging\n    const startTime = Date.now();\n    let validatedInput;\n    let expressionToEvaluate;\n\n    calculatorLogger.info(`Tool \"${TOOL_NAME}\" execution: START`, {\n      callId,\n      rawInput: input,\n    });\n\n    try {\n      // Handle if input is stringified JSON (common from LLMs) or direct object\n      if (typeof input === 'string') {\n        try {\n          const parsedInput = JSON.parse(input);\n          if (\n            typeof parsedInput === 'object' &&\n            parsedInput !== null &&\n            'expression' in parsedInput\n          ) {\n            validatedInput = CalculatorInputSchema.parse(parsedInput);\n          } else {\n            // Assume the string itself is the expression if it's not a JSON object with 'expression' key\n            validatedInput = CalculatorInputSchema.parse({ expression: input });\n          }\n        } catch (e) {\n          // If JSON.parse fails, try to validate as if the string itself is the expression\n          validatedInput = CalculatorInputSchema.parse({ expression: input });\n        }\n      } else if (\n        typeof input === 'object' &&\n        input !== null &&\n        'expression' in input\n      ) {\n        validatedInput = CalculatorInputSchema.parse(input);\n      } else if (\n        typeof input === 'object' &&\n        input !== null &&\n        Object.keys(input).length === 1 &&\n        typeof Object.values(input)[0] === 'string'\n      ) {\n        // Handle cases where LLM might send {\"query\": \"2+2\"} instead of {\"expression\": \"2+2\"}\n        calculatorLogger.warn(\n          `Received object with unexpected key, assuming value is the expression.`,\n          { inputKeys: Object.keys(input) }\n        );\n        validatedInput = CalculatorInputSchema.parse({\n          expression: Object.values(input)[0],\n        });\n      } else {\n        throw new DaitanValidationError(\n          'Input must be a string (expression or JSON stringified object with \"expression\" key) or an object with an \"expression\" key.',\n          { inputType: typeof input, inputValue: input }\n        );\n      }\n      expressionToEvaluate = validatedInput.expression;\n\n      // Replace ^ with ** for JavaScript's exponentiation operator, if not already handled by Function constructor\n      // Be cautious if the Function constructor environment is very restricted.\n      const safeExpression = expressionToEvaluate.replace(/\\^/g, '**');\n\n      // Evaluate the expression using Function constructor for safety (sandboxed compared to eval)\n      // Still, ensure input is heavily sanitized by Zod.\n      const result = new Function(\n        `\"use strict\"; return (${safeExpression});`\n      )();\n\n      if (typeof result !== 'number' || isNaN(result) || !isFinite(result)) {\n        calculatorLogger.warn(\n          'Calculation did not result in a valid finite number.',\n          { callId, expression: safeExpression, result }\n        );\n        throw new DaitanOperationError(\n          'Calculation resulted in an invalid or non-finite number.',\n          { expression: safeExpression, resultValue: result }\n        );\n      }\n\n      const duration = Date.now() - startTime;\n      const output = `Result: ${result}`;\n      calculatorLogger.info(`Tool \"${TOOL_NAME}\" execution: SUCCESS.`, {\n        callId,\n        expression: safeExpression,\n        output,\n        durationMs: duration,\n      });\n      return output;\n    } catch (error) {\n      const duration = Date.now() - startTime;\n      calculatorLogger.error(`Tool \"${TOOL_NAME}\" execution: FAILED.`, {\n        callId,\n        inputAttempted: expressionToEvaluate || input, // Log the expression if validation passed, else raw input\n        errorMessage: error.message,\n        errorName: error.name,\n        durationMs: duration,\n        // errorStack: error.stack // Potentially verbose\n      });\n\n      if (\n        error instanceof DaitanValidationError ||\n        error instanceof DaitanOperationError ||\n        error.name === 'ZodError'\n      ) {\n        // DaitanValidationError is more specific than ZodError here, but ZodError is what schema.parse throws\n        return `Error: Invalid input. ${\n          error.errors\n            ? error.errors.map((e) => e.message).join(', ')\n            : error.message\n        }`;\n      }\n      return `Error during calculation for expression \"${\n        expressionToEvaluate || input\n      }\": ${\n        error.message\n      }. Please ensure the expression is mathematically valid.`;\n    }\n  },\n  CalculatorInputSchema\n);\n", "// intelligence/src/intelligence/tools/wikipediaSearchTool.js\nimport { getLogger } from '@daitanjs/development';\nimport { DaitanValidationError, DaitanOperationError } from '@daitanjs/error';\nimport { z } from 'zod';\nimport { createDaitanTool } from '../core/toolFactory.js'; // CORRECTED: Import from the new 'core' location\n\nconst wikipediaLogger = getLogger('daitan-tool-wikipedia');\nconst TOOL_NAME = 'wikipedia_search';\nconst WIKIPEDIA_API_ENDPOINT = 'https://en.wikipedia.org/w/api.php'; // Default to English Wikipedia\n\n// Zod schema for the input\nconst WikipediaSearchInputSchema = z\n  .object({\n    query: z\n      .string()\n      .min(1, 'Search query cannot be empty.')\n      .max(150, 'Search query is too long for Wikipedia search.'),\n    // lang: z.string().length(2).optional().default('en'), // Optional: specify Wikipedia language (e.g., \"es\", \"de\")\n    num_results: z.number().int().min(1).max(3).optional().default(1), // Max 1-3 results usually enough for LLM\n  })\n  .strict();\n\nexport const wikipediaSearchTool = createDaitanTool(\n  TOOL_NAME,\n  `Searches Wikipedia for a given query string and returns a summary of the most relevant article(s).\nInput must be an object: {\"query\": \"your search term\", \"num_results\": 1 (optional, 1-3, default 1)}.\nUseful for finding factual information, definitions, or overviews on a wide range of topics, people, places, and events.\nProvides titles and concise summaries of Wikipedia articles.`,\n  async (input) => {\n    // input can be string or object\n    const callId = Math.random().toString(36).substring(2, 9);\n    const startTime = Date.now();\n    let validatedArgs;\n    let originalQueryForLog;\n\n    wikipediaLogger.info(`Tool \"${TOOL_NAME}\" execution: START`, {\n      callId,\n      rawInput: input,\n    });\n\n    try {\n      // Input normalization and validation\n      if (typeof input === 'string') {\n        try {\n          const parsedInput = JSON.parse(input);\n          if (typeof parsedInput === 'object' && parsedInput !== null) {\n            validatedArgs = WikipediaSearchInputSchema.parse(parsedInput);\n          } else {\n            // If parsed is not an object, assume string input is the query\n            validatedArgs = WikipediaSearchInputSchema.parse({ query: input });\n          }\n        } catch (e) {\n          // If JSON.parse fails, assume string input is the query\n          validatedArgs = WikipediaSearchInputSchema.parse({ query: input });\n        }\n      } else if (typeof input === 'object' && input !== null) {\n        validatedArgs = WikipediaSearchInputSchema.parse(input);\n      } else {\n        throw new DaitanValidationError(\n          'Input must be a string (search query or JSON stringified object) or an object with a \"query\" key.',\n          { inputType: typeof input }\n        );\n      }\n      originalQueryForLog = validatedArgs.query;\n\n      const searchUrl = new URL(WIKIPEDIA_API_ENDPOINT);\n      searchUrl.searchParams.append('action', 'query');\n      searchUrl.searchParams.append('list', 'search');\n      searchUrl.searchParams.append('srsearch', validatedArgs.query);\n      searchUrl.searchParams.append(\n        'srlimit',\n        String(validatedArgs.num_results)\n      );\n      searchUrl.searchParams.append('srprop', 'snippet|titlesnippet'); // Request snippet and title snippet\n      searchUrl.searchParams.append('format', 'json');\n      searchUrl.searchParams.append('origin', '*'); // For CORS, if ever called from browser contexts (though this tool is server-side)\n\n      wikipediaLogger.debug(`Fetching Wikipedia URL: ${searchUrl.toString()}`, {\n        callId,\n      });\n\n      const response = await fetch(searchUrl.toString(), {\n        headers: {\n          'User-Agent':\n            'DaitanJS-Intelligence-Library/1.1 (https://github.com/daitandojo/@daitanjs)',\n        },\n      });\n\n      if (!response.ok) {\n        const errorText = await response.text();\n        throw new DaitanOperationError(\n          `Wikipedia API request failed with status ${\n            response.status\n          }. Response: ${errorText.substring(0, 200)}`,\n          {\n            query: validatedArgs.query,\n            httpStatus: response.status,\n            apiResponse: errorText.substring(0, 200),\n          }\n        );\n      }\n\n      const data = await response.json();\n      const duration = Date.now() - startTime;\n\n      if (data.query?.search?.length > 0) {\n        const searchResults = data.query.search;\n        const formattedResults = searchResults\n          .map((item, index) => {\n            // Clean snippets (remove HTML tags)\n            const snippet = String(item.snippet || item.titlesnippet || '')\n              .replace(/<span class=\"searchmatch\">/gi, '')\n              .replace(/<\\/span>/gi, '')\n              .replace(/<\\/?\\w+[^>]*>/g, ' ') // Basic HTML tag removal\n              .replace(/\\s+/g, ' ')\n              .trim();\n            return `${index + 1}. Title: ${\n              item.title\n            }\\n   Summary Snippet: ${snippet}\\n   Wikipedia URL: https://en.wikipedia.org/wiki/${encodeURIComponent(\n              item.title.replace(/ /g, '_')\n            )}`;\n          })\n          .join('\\n\\n');\n\n        wikipediaLogger.info(`Tool \"${TOOL_NAME}\" execution: SUCCESS.`, {\n          callId,\n          query: validatedArgs.query,\n          resultsFound: searchResults.length,\n          durationMs: duration,\n        });\n        return `Wikipedia Search Results for \"${validatedArgs.query}\":\\n${formattedResults}`;\n      } else {\n        wikipediaLogger.info(\n          `Tool \"${TOOL_NAME}\" execution: SUCCESS (No Results).`,\n          { callId, query: validatedArgs.query, durationMs: duration }\n        );\n        return `No Wikipedia results found for query: \"${validatedArgs.query}\". Try a different or broader query.`;\n      }\n    } catch (error) {\n      const duration = Date.now() - startTime;\n      wikipediaLogger.error(`Tool \"${TOOL_NAME}\" execution: FAILED.`, {\n        callId,\n        queryAttempted:\n          originalQueryForLog ||\n          (typeof input === 'string' ? input : JSON.stringify(input)),\n        errorMessage: error.message,\n        errorName: error.name,\n        durationMs: duration,\n      });\n      if (error instanceof DaitanValidationError || error.name === 'ZodError') {\n        return `Error: Invalid input for Wikipedia search. ${\n          error.errors\n            ? error.errors.map((e) => e.message).join(', ')\n            : error.message\n        }`;\n      }\n      return `Error searching Wikipedia for \"${\n        originalQueryForLog || input\n      }\": ${error.message}.`;\n    }\n  },\n  WikipediaSearchInputSchema\n);\n", "// intelligence/src/intelligence/tools/cliTool.js\nimport { getLogger } from '@daitanjs/development';\nimport { DaitanValidationError, DaitanOperationError } from '@daitanjs/error';\nimport { exec } from 'child_process';\nimport util from 'util';\nimport { z } from 'zod';\nimport { createDaitanTool } from '../core/toolFactory.js'; // CORRECTED: Import from the new 'core' location\n\nconst cliLogger = getLogger('daitan-tool-cli');\nconst execPromise = util.promisify(exec);\nconst TOOL_NAME = 'command_line_interface';\n\nconst IS_WINDOWS = process.platform === 'win32';\nconst COMMAND_TIMEOUT_MS = 5000; // Default timeout for commands\n\n// --- Command Whitelist and Validation Configuration ---\n/**\n * @typedef {Object} AllowedCommandConfig\n * @property {string} command - The base command (e.g., 'ls', 'pwd').\n * @property {RegExp | null} allowedArgsRegex - Regex to validate arguments. Null means no args allowed.\n * @property {string} description - Description of what the command does (for tool's main description).\n * @property {boolean} [isSafeReadOnly=true] - Flag indicating if the command is generally read-only.\n */\nconst ALLOWED_COMMANDS_CONFIG = [\n  {\n    command: 'ls',\n    allowedArgsRegex: /^(?:\\s+(-[a-zA-Z]{1,10}))*(?:\\s+[\\w./~-]+)?$/,\n    description: 'List directory contents. Args like -l, -a, path are common.',\n    isSafeReadOnly: true,\n  },\n  {\n    command: 'pwd',\n    allowedArgsRegex: null,\n    description: 'Print working directory name. No arguments accepted.',\n    isSafeReadOnly: true,\n  },\n  {\n    command: 'date',\n    allowedArgsRegex: /^(?:\\s*\\+?[\\w%:\\s-]+)?$/,\n    description:\n      'Print the current date and time. Can take format string starting with +.',\n    isSafeReadOnly: true,\n  },\n  {\n    command: 'echo',\n    allowedArgsRegex: /^[\\s\\S]*$/,\n    description: 'Display a line of text. Input string will be echoed.',\n    isSafeReadOnly: true,\n  }, // More permissive but still subject to overall input sanitization\n  {\n    command: 'whoami',\n    allowedArgsRegex: null,\n    description: 'Print effective user ID. No arguments accepted.',\n    isSafeReadOnly: true,\n  },\n  {\n    command: 'uptime',\n    allowedArgsRegex: null,\n    description:\n      'Show how long the system has been running. No arguments accepted.',\n    isSafeReadOnly: true,\n  },\n  {\n    command: 'df',\n    allowedArgsRegex: /^(?:\\s+(-[a-zA-Z]{1,10}))*(?:\\s+[\\w./~-]+)*$/,\n    description:\n      'Report file system disk space usage. Args like -h, path are common.',\n    isSafeReadOnly: true,\n  },\n  {\n    command: 'free',\n    allowedArgsRegex: /^(?:\\s+(-[a-zA-Z]{1,5}))*$/,\n    description:\n      'Display amount of free and used memory. Args like -m, -g are common.',\n    isSafeReadOnly: true,\n  },\n  {\n    command: 'uname',\n    allowedArgsRegex: /^(?:\\s+(-[a-zA-Z]{1,5}))*$/,\n    description: 'Print system information. Args like -a, -s, -r are common.',\n    isSafeReadOnly: true,\n  },\n  // Add other safe, read-only commands as needed. Be extremely cautious.\n];\n\n// Characters/sequences generally unsafe in shell commands if not properly handled/escaped.\n// This validation is a first line of defense. Proper command construction is also key.\nconst FORBIDDEN_CHARS_REGEX = /[&|;<>$`(){}'\"!#\\\\]/; // Stricter: removed ' and \" as they might be needed for args, but rely on arg validation. Re-added for safety.\nconst FORBIDDEN_SEQUENCES_REGEX = /\\.\\.|\\/\\//; // Path traversal and protocol-like sequences\n\n// Zod schema for the input object\nconst CliInputSchema = z\n  .object({\n    command: z\n      .string()\n      .min(1, 'Command cannot be empty.')\n      .max(256, 'Full command string is too long.') // Limit overall length\n      .refine((cmdStr) => !FORBIDDEN_CHARS_REGEX.test(cmdStr), {\n        message:\n          'Command string contains forbidden characters (e.g., &, |, ;, <, >, $, `, (, ), {, }, \\\\, \\', \", !).',\n      })\n      .refine((cmdStr) => !FORBIDDEN_SEQUENCES_REGEX.test(cmdStr), {\n        message: 'Command string contains forbidden sequences (e.g., .., //).',\n      }),\n  })\n  .strict();\n\nconst validateAndParseCommand = (fullCommandString) => {\n  // Schema validation handles forbidden chars/sequences broadly.\n  // This function now focuses on whitelisting and arg validation.\n  const parts = fullCommandString.trim().split(/\\s+/);\n  const baseCommand = parts[0];\n  const argsString = parts.slice(1).join(' ');\n\n  const commandConfig = ALLOWED_COMMANDS_CONFIG.find(\n    (c) => c.command === baseCommand\n  );\n\n  if (!commandConfig) {\n    return {\n      isValid: false,\n      error: `Command \"${baseCommand}\" is not in the allowed list.`,\n    };\n  }\n\n  if (commandConfig.allowedArgsRegex === null) {\n    // Explicitly null means no arguments allowed\n    if (argsString.trim() !== '') {\n      return {\n        isValid: false,\n        error: `Command \"${baseCommand}\" does not accept any arguments. Received: \"${argsString}\"`,\n      };\n    }\n  } else if (commandConfig.allowedArgsRegex) {\n    // If a regex is provided for args\n    if (!commandConfig.allowedArgsRegex.test(argsString)) {\n      return {\n        isValid: false,\n        error: `Arguments \"${argsString}\" for command \"${baseCommand}\" are not allowed or incorrectly formatted.`,\n      };\n    }\n  }\n  // If allowedArgsRegex is undefined, it means any args are fine (already passed basic char validation by Zod) - useful for 'echo'.\n\n  if (!commandConfig.isSafeReadOnly) {\n    cliLogger.warn(\n      `Executing command \"${baseCommand}\" which is not marked as safe read-only. Ensure this is intended and secured.`,\n      { fullCommandString }\n    );\n  }\n\n  return { isValid: true, commandConfig, baseCommand, args: argsString };\n};\n\nexport const cliTool = createDaitanTool(\n  TOOL_NAME,\n  `Executes a strictly whitelisted and validated shell command and returns its standard output and standard error.\nInput must be an object with a single key \"command\", which is a string representing the full command to execute (e.g., {\"command\": \"ls -la /tmp\"}).\nOnly a pre-defined set of safe, primarily read-only commands are allowed.\nForbidden characters (like '&', '|', ';', '$') and sequences (like '..') in the command string are NOT allowed.\nAllowed commands include: ${ALLOWED_COMMANDS_CONFIG.map(\n    (c) => `${c.command} (${c.description.substring(0, 30)}...)`\n  ).join(', ')}.\nConsult the full descriptions of allowed commands if unsure about arguments. Misuse can be a security risk.`,\n  async (input) => {\n    const callId = Math.random().toString(36).substring(2, 9);\n    const startTime = Date.now();\n    let commandStringInput;\n    let logContext = { toolName: TOOL_NAME, callId };\n\n    cliLogger.info(`Tool \"${TOOL_NAME}\" execution: START`, {\n      callId,\n      rawInput: input,\n    });\n\n    try {\n      if (typeof input === 'string') {\n        try {\n          const parsed = JSON.parse(input);\n          if (\n            typeof parsed === 'object' &&\n            parsed !== null &&\n            typeof parsed.command === 'string'\n          ) {\n            commandStringInput = parsed.command;\n          } else {\n            // Assume the string itself is the command\n            commandStringInput = input;\n          }\n        } catch (e) {\n          // If JSON.parse fails, assume the string itself is the command\n          commandStringInput = input;\n        }\n      } else if (\n        typeof input === 'object' &&\n        input !== null &&\n        typeof input.command === 'string'\n      ) {\n        commandStringInput = input.command;\n      } else {\n        throw new DaitanValidationError(\n          'Input must be a string (the command or JSON stringified object with \"command\" key) or an object with a \"command\" key.',\n          { inputType: typeof input }\n        );\n      }\n\n      logContext.commandAttempted = String(commandStringInput).substring(\n        0,\n        200\n      );\n      CliInputSchema.parse({ command: commandStringInput }); // Validate against Zod schema first\n\n      const validationResult = validateAndParseCommand(commandStringInput);\n      if (!validationResult.isValid) {\n        throw new DaitanValidationError(validationResult.error, {\n          commandString: commandStringInput,\n        });\n      }\n\n      const { baseCommand, args } = validationResult;\n      const fullCommandToExecute = args\n        ? `${baseCommand} ${args}`\n        : baseCommand;\n      logContext.commandExecuted = fullCommandToExecute;\n\n      cliLogger.info(\n        `Attempting to execute validated command: \"${fullCommandToExecute}\"`,\n        { callId }\n      );\n\n      const executionOptions = {\n        timeout: COMMAND_TIMEOUT_MS,\n        shell: IS_WINDOWS ? 'cmd.exe' : '/bin/sh', // Or a more restricted shell if possible\n        windowsHide: true,\n        // Consider cwd if needed, but be very careful with allowing LLM to specify CWD.\n      };\n\n      const { stdout, stderr } = await execPromise(\n        fullCommandToExecute,\n        executionOptions\n      );\n      const duration = Date.now() - startTime;\n\n      let output = '';\n      if (stdout && stdout.trim()) output += `Stdout:\\n${stdout.trim()}\\n`;\n      if (stderr && stderr.trim()) output += `Stderr:\\n${stderr.trim()}\\n`; // Include stderr as it can be informative\n\n      const finalOutput =\n        output.trim() ||\n        '(Command executed successfully with no output to stdout or stderr)';\n      cliLogger.info(`Tool \"${TOOL_NAME}\" execution: SUCCESS.`, {\n        ...logContext,\n        outputPreview: finalOutput.substring(0, 100),\n        durationMs: duration,\n      });\n      return finalOutput;\n    } catch (error) {\n      const duration = Date.now() - startTime;\n      logContext.durationMs = duration;\n      logContext.errorMessage = error.message;\n      logContext.errorName = error.name;\n\n      if (error instanceof DaitanValidationError || error.name === 'ZodError') {\n        cliLogger.warn(\n          `Tool \"${TOOL_NAME}\" execution: FAILED (Validation).`,\n          logContext\n        );\n        return `Error: Command validation failed. ${\n          error.errors\n            ? error.errors.map((e) => e.message).join(', ')\n            : error.message\n        }`;\n      }\n\n      // Runtime error from execPromise\n      logContext.errorCode = error.code; // exit code\n      logContext.errorSignal = error.signal;\n      logContext.errorStderr = error.stderr?.trim() || null;\n      logContext.errorStdout = error.stdout?.trim() || null; // stdout might exist even on error\n\n      cliLogger.error(\n        `Tool \"${TOOL_NAME}\" execution: FAILED (Runtime).`,\n        logContext\n      );\n\n      let userMessage = `Error executing command \"${\n        logContext.commandExecuted || commandStringInput\n      }\": ${error.message}.`;\n      if (error.killed)\n        userMessage = `Error: Command timed out after ${\n          COMMAND_TIMEOUT_MS / 1000\n        }s or was killed.`;\n      else if (error.code) userMessage += ` Exit code: ${error.code}.`;\n      if (error.stderr) userMessage += ` Stderr: ${error.stderr.trim()}`;\n\n      // Return a DaitanOperationError or just the string for LangChain\n      return userMessage;\n    }\n  },\n  CliInputSchema\n);\n", "// intelligence/src/intelligence/tools/webSearchTool.js\n/**\n * @file A DaitanJS tool for performing web searches via the Google Search API.\n * @module @daitanjs/intelligence/tools/webSearchTool\n *\n * @description\n * This module exports `webSearchTool`, a LangChain-compatible `DynamicTool`. It\n * provides a structured interface for an AI agent to search the web by wrapping\n\n * the `googleSearch` function from `@daitanjs/web`. A key feature is its lazy\n * initialization, which defers loading the underlying search service until the\n * tool is first used, improving initial application load times.\n */\nimport { DynamicTool } from '@langchain/core/tools';\nimport { getLogger } from '@daitanjs/development';\nimport { DaitanConfigurationError } from '@daitanjs/error';\nimport { z } from 'zod';\n\nconst webSearchLogger = getLogger('daitan-tool-web-search');\nconst TOOL_NAME = 'web_search';\n\n// --- Lazy-loaded search function ---\nlet googleSearchFunction = null;\nlet googleSearchInitializationAttempted = false;\n\n// Zod schema for robust input validation.\nconst WebSearchInputSchema = z\n  .object({\n    // Use `query` to match the underlying service, simplifying the mapping.\n    query: z\n      .string()\n      .min(1, 'Search query cannot be empty.')\n      .max(200, 'Search query is too long.')\n      .describe('The string to search for on the web.'),\n    num_results: z\n      .number()\n      .int()\n      .min(1)\n      .max(10)\n      .optional()\n      .default(3) // A sensible default for most agent use cases.\n      .describe('The number of search results to return (1-10).'),\n  })\n  .strict(); // Disallow any other properties on the input object.\n\n/**\n * Lazily initializes the Google Search service from @daitanjs/web on first use.\n * This prevents a hard dependency and improves startup performance.\n * @private\n * @returns {Promise<Function|null>} The googleSearch function or null if initialization fails.\n */\nasync function initializeGoogleSearchService() {\n  if (googleSearchFunction) {\n    return googleSearchFunction;\n  }\n  if (googleSearchInitializationAttempted) {\n    return null; // Avoid re-attempting a failed import.\n  }\n\n  googleSearchInitializationAttempted = true;\n  try {\n    const webModule = await import('@daitanjs/web');\n    if (webModule && typeof webModule.googleSearch === 'function') {\n      googleSearchFunction = webModule.googleSearch;\n      webSearchLogger.info('Web search service initialized successfully.');\n    } else {\n      throw new DaitanConfigurationError(\n        'The @daitanjs/web package does not export a \"googleSearch\" function.'\n      );\n    }\n  } catch (e) {\n    webSearchLogger.error(\n      `Failed to load 'googleSearch' from '@daitanjs/web'. This tool will not function. Error: ${e.message}`\n    );\n    googleSearchFunction = null;\n  }\n  return googleSearchFunction;\n}\n\n/**\n * A LangChain-compatible tool for performing web searches.\n */\nexport const webSearchTool = new DynamicTool({\n  name: TOOL_NAME,\n  description: `Performs a web search for a given query.\nInput must be an object with the following keys:\n- \"query\" (string): The search query.\n- \"num_results\" (integer, optional): The number of results to return (1-10, default 3).\nReturns a formatted string containing the top search results with titles, links, and snippets.`,\n  schema: WebSearchInputSchema,\n  func: async (input) => {\n    try {\n      const searchService = await initializeGoogleSearchService();\n      if (!searchService) {\n        throw new DaitanConfigurationError(\n          'Web search service is not available. Check for initialization errors.'\n        );\n      }\n\n      // The input is already validated by the DynamicTool's schema.\n      // We map the validated `num_results` to the `num` parameter expected by the service.\n      const searchParams = {\n        query: input.query,\n        num: input.num_results,\n      };\n\n      const results = await searchService(searchParams);\n\n      if (!results || !Array.isArray(results) || results.length === 0) {\n        return `No web search results found for \"${input.query}\".`;\n      }\n\n      const formattedResults = results\n        .map(\n          (item, index) =>\n            `${index + 1}. Title: ${item.title}\\n   Link: ${\n              item.link\n            }\\n   Snippet: ${String(item.snippet || '').substring(0, 250)}...`\n        )\n        .join('\\n\\n');\n\n      return `Web Search Results for \"${input.query}\":\\n${formattedResults}`;\n    } catch (error) {\n      // The tool should return a string error message for the agent to process.\n      return `Error performing web search for \"${JSON.stringify(input)}\": ${\n        error.message\n      }.`;\n    }\n  },\n});\n", "// intelligence/src/intelligence/tools/userManagementTool.js\n/**\n * @file A DaitanJS tool for managing system users.\n * @module @daitanjs/intelligence/tools/userManagementTool\n */\nimport { z } from 'zod';\nimport { createDaitanTool } from '../core/toolFactory.js';\nimport { createUser, getUserByEmail, getUserById } from '@daitanjs/users';\nimport { DaitanNotFoundError, DaitanValidationError } from '@daitanjs/error';\n\n// --- SCHEMA DEFINITIONS ---\n// Define the individual action schemas as before.\nconst FindUserInputSchema = z\n  .object({\n    action: z.literal('find_user'),\n    email: z.string().email('A valid email address is required.').optional(),\n    userId: z.string().optional(),\n  })\n  .strict()\n  .refine((data) => data.email || data.userId, {\n    message:\n      \"To find a user, you must provide either the 'email' or the 'userId'.\",\n  });\n\nconst CreateUserInputSchema = z\n  .object({\n    action: z.literal('create_user'),\n    email: z.string().email('A valid email address is required for creation.'),\n    name: z\n      .string()\n      .min(2, 'Name must be at least 2 characters long.')\n      .optional(),\n    username: z.string().optional(),\n    firstName: z.string().optional(),\n    lastName: z.string().optional(),\n  })\n  .strict();\n\n// --- TOOL DEFINITION ---\n\nexport const userManagementTool = createDaitanTool(\n  'user_management',\n  `Manages users in the system. Can find a user by email or ID, or create a new user.\nInput must be an object specifying the 'action' and its corresponding parameters.\n- To find a user: {\"action\": \"find_user\", \"email\": \"user@example.com\"} OR {\"action\": \"find_user\", \"userId\": \"some-id\"}\n- To create a user: {\"action\": \"create_user\", \"email\": \"new@user.com\", \"name\": \"New User\"}`,\n  async (input) => {\n    // --- DEFINITIVE FIX: Manual Validation Logic ---\n    // Instead of a discriminated union, we manually check the action and validate.\n    // This is more robust against module initialization order issues.\n    if (!input || typeof input.action !== 'string') {\n      throw new DaitanValidationError(\n        \"Invalid input: \\\"action\\\" key must be a string ('find_user' or 'create_user').\"\n      );\n    }\n\n    let validatedInput;\n    if (input.action === 'find_user') {\n      validatedInput = FindUserInputSchema.parse(input);\n      let user;\n      if (validatedInput.email) {\n        user = await getUserByEmail(validatedInput.email);\n      } else {\n        user = await getUserById(validatedInput.userId);\n      }\n      if (!user) {\n        throw new DaitanNotFoundError(\n          `User not found with the provided criteria.`\n        );\n      }\n      const { hash, salt, ...publicUser } = user.toObject\n        ? user.toObject()\n        : user;\n      return `User found: ${JSON.stringify(publicUser, null, 2)}`;\n    } else if (input.action === 'create_user') {\n      validatedInput = CreateUserInputSchema.parse(input);\n      const { action, ...userData } = validatedInput;\n      const result = await createUser(userData);\n      return `User operation successful. Status: ${result.status}. User ID: ${result.document._id}`;\n    } else {\n      throw new DaitanValidationError(\n        `Unsupported action: \"${input.action}\". Must be 'find_user' or 'create_user'.`\n      );\n    }\n  }\n  // We remove the schema from the tool definition since we are handling validation manually inside.\n);\n", "// intelligence/src/intelligence/tools/csvQueryTool.js\n/**\n * @file A DaitanJS tool for querying local CSV files using a SQL-like interface.\n * @module @daitanjs/intelligence/tools/csvQueryTool\n *\n * @description\n * This module exports a LangChain-compatible tool that allows an AI agent to\n * execute simplified SQL queries against a directory of CSV files, where each\n * file is treated as a table. It wraps the `CSVSQL` class from the `@daitanjs/data` package.\n */\n\nimport { createDaitanTool } from '../core/toolFactory.js'; // CORRECTED: Import from the new 'core' location\nimport { z } from 'zod';\nimport { CSVSQL } from '@daitanjs/data';\n\nconst CsvQueryInputSchema = z\n  .object({\n    query: z\n      .string()\n      .min(10, 'Query string seems too short.')\n      .max(500, 'Query string is too long.'),\n    directoryPath: z\n      .string()\n      .optional()\n      .describe(\n        'Optional: A specific server directory path containing the CSV files to query.'\n      ),\n  })\n  .strict();\n\nexport const csvQueryTool = createDaitanTool(\n  'csv_query_tool',\n  `Executes a simplified SQL-like query on a collection of local CSV files.\nEach CSV file in the target directory is treated as a table (the table name is the filename without .csv).\nThe input must be an object with a \"query\" key containing the SQL-like query string.\nExample: {\"query\": \"SELECT name, age FROM people WHERE city = 'New York'\"}\nThe tool supports SELECT, INSERT, and DELETE operations on the CSV files. This is useful for analyzing data or retrieving structured information that has been saved locally.`,\n  async (input) => {\n    const validatedInput = CsvQueryInputSchema.parse(input);\n\n    const csvSql = new CSVSQL(validatedInput.directoryPath, { verbose: true });\n    await csvSql.initialize();\n\n    const queryResult = await csvSql.query(validatedInput.query);\n\n    if (Array.isArray(queryResult)) {\n      if (queryResult.length === 0) {\n        return 'Query executed successfully and returned no results.';\n      }\n      const summary = `Query returned ${queryResult.length} rows.`;\n      const resultsToShow = queryResult.slice(0, 20);\n      const resultString = JSON.stringify(resultsToShow, null, 2);\n\n      return `${summary}\\n\\nFirst ${resultsToShow.length} rows:\\n${resultString}`;\n    } else if (typeof queryResult === 'object' && queryResult !== null) {\n      return `Action query executed successfully. Result: ${JSON.stringify(\n        queryResult\n      )}`;\n    }\n\n    return 'Query executed, but the result format was unexpected. Please check the query syntax.';\n  },\n  CsvQueryInputSchema\n);\n", "// intelligence/src/intelligence/tools/createPaymentIntentTool.js\n/**\n * @file A DaitanJS tool for creating Stripe Payment Intents.\n * @module @daitanjs/intelligence/tools/createPaymentIntentTool\n *\n * @description\n * This module exports a LangChain-compatible tool that allows an AI agent to\n * initiate a payment process by creating a Stripe Payment Intent. It securely\n * wraps the `createPaymentIntent` function from the `@daitanjs/payments` package,\n * ensuring that sensitive operations remain on the server side. The tool uses\n * Zod for rigorous input validation.\n */\n\nimport { createDaitanTool } from '../core/toolFactory.js'; // CORRECTED: Import from the new 'core' location\nimport { z } from 'zod';\nimport { createPaymentIntent } from '@daitanjs/payments';\n\nconst CreatePaymentIntentInputSchema = z\n  .object({\n    amount: z\n      .number()\n      .int()\n      .positive(\n        'Amount must be a positive integer in the smallest currency unit (e.g., cents).'\n      ),\n    currency: z\n      .string()\n      .length(3, 'Currency must be a 3-letter ISO code.')\n      .toLowerCase(),\n    description: z\n      .string()\n      .optional()\n      .describe('An optional description for the payment.'),\n    metadata: z\n      .record(z.string())\n      .optional()\n      .describe('Optional key-value metadata for the payment.'),\n  })\n  .strict();\n\nexport const createPaymentIntentTool = createDaitanTool(\n  'create_payment_intent',\n  `Initiates a payment by creating a Stripe Payment Intent. This is the first step in processing a credit card payment.\nThe input must be an object with:\n- \"amount\" (integer): The amount in the smallest currency unit (e.g., 1000 for $10.00).\n- \"currency\" (string): The 3-letter ISO currency code (e.g., \"usd\").\n- \"description\" (string, optional): A description for the payment that may appear on the user's statement.\n- \"metadata\" (object, optional): Key-value pairs for internal tracking.\nThis tool returns a summary including the 'client_secret' which is essential for a front-end application to securely finalize the payment.`,\n  async (input) => {\n    const validatedInput = CreatePaymentIntentInputSchema.parse(input);\n\n    const paymentIntent = await createPaymentIntent({\n      amount: validatedInput.amount,\n      currency: validatedInput.currency,\n      description: validatedInput.description,\n      metadata: validatedInput.metadata,\n    });\n\n    // Only return the necessary client-side information to the LLM.\n    const result = {\n      paymentIntentId: paymentIntent.id,\n      clientSecret: paymentIntent.client_secret,\n      status: paymentIntent.status,\n      amount: paymentIntent.amount,\n      currency: paymentIntent.currency,\n    };\n\n    return `Payment Intent created successfully. The client_secret is available to pass to the front-end for payment confirmation. Details: ${JSON.stringify(\n      result\n    )}`;\n  },\n  CreatePaymentIntentInputSchema\n);\n", "// intelligence/src/intelligence/tools/youtubeSearchTool.js\n/**\n * @file A DaitanJS tool for searching YouTube videos.\n * @module @daitanjs/intelligence/tools/youtubeSearchTool\n *\n * @description\n * This module exports a LangChain-compatible tool that allows an AI agent to\n * search for videos on YouTube using the `searchVideos` function from the\n * `@daitanjs/media` package. It provides a structured way for the agent to\n * find video content based on a query.\n */\n\nimport { createDaitanTool } from '../core/toolFactory.js'; // CORRECTED: Import from the new 'core' location\nimport { z } from 'zod';\nimport { searchVideos } from '@daitanjs/media';\nimport { DaitanNotFoundError } from '@daitanjs/error';\n\nconst YoutubeSearchInputSchema = z\n  .object({\n    query: z\n      .string()\n      .min(1, 'Search query cannot be empty.')\n      .max(150, 'Search query is too long.'),\n    maxResults: z\n      .number()\n      .int()\n      .min(1)\n      .max(5)\n      .optional()\n      .default(3)\n      .describe('Number of search results to return, between 1 and 5.'),\n  })\n  .strict();\n\nexport const youtubeSearchTool = createDaitanTool(\n  'youtube_search',\n  `Searches YouTube for videos based on a query string.\nThe input must be an object with:\n- \"query\" (string): The search term or phrase.\n- \"maxResults\" (integer, optional, 1-5): The maximum number of video results to return. Defaults to 3.\nThis tool returns a list of videos, each with a title, video ID, and a link.`,\n  async (input) => {\n    const validatedInput = YoutubeSearchInputSchema.parse(input);\n\n    const searchResult = await searchVideos(validatedInput.query, {\n      maxResults: validatedInput.maxResults,\n    });\n\n    if (\n      !searchResult ||\n      !searchResult.items ||\n      searchResult.items.length === 0\n    ) {\n      throw new DaitanNotFoundError(\n        `No YouTube videos found for the query: \"${validatedInput.query}\"`\n      );\n    }\n\n    const formattedResults = searchResult.items.map((item) => ({\n      title: item.snippet?.title,\n      videoId: item.id?.videoId,\n      channelTitle: item.snippet?.channelTitle,\n      publishedAt: item.snippet?.publishedAt,\n      link: `https://www.youtube.com/watch?v=${item.id?.videoId}`,\n    }));\n\n    return `Found ${formattedResults.length} YouTube videos for \"${\n      validatedInput.query\n    }\":\\n${JSON.stringify(formattedResults, null, 2)}`;\n  },\n  YoutubeSearchInputSchema\n);\n", "// intelligence/src/intelligence/tools/processYoutubeAudioTool.js\n/**\n * @file A DaitanJS tool for downloading and transcribing YouTube video audio.\n * @module @daitanjs/intelligence/tools/processYoutubeAudioTool\n *\n * @description\n * This module exports a high-level, LangChain-compatible tool that allows an AI agent to\n * orchestrate the download and transcription of a YouTube video in a single step. It wraps\n * the `transcribeYoutubeVideo` function from the `@daitanjs/media` package.\n */\n\nimport { createDaitanTool } from '../core/toolFactory.js'; // CORRECTED: Import from the new 'core' location\nimport { z } from 'zod';\nimport { transcribeYoutubeVideo } from '@daitanjs/media';\nimport { DaitanNotFoundError } from '@daitanjs/error';\n\n// Zod schema for validating the input to the tool\nconst ProcessYoutubeAudioInputSchema = z\n  .object({\n    url: z\n      .string()\n      .url('A valid YouTube video URL is required.')\n      .refine(\n        (val) => val.includes('youtube.com') || val.includes('youtu.be'),\n        'The URL must be a valid YouTube video link.'\n      ),\n    transcriptionConfig: z\n      .object({\n        language: z\n          .string()\n          .optional()\n          .describe(\n            'Optional: The ISO-639-1 language code of the audio (e.g., \"en\", \"es\").'\n          ),\n        prompt: z\n          .string()\n          .optional()\n          .describe(\n            'Optional: A prompt to guide the transcription model or provide context.'\n          ),\n      })\n      .optional()\n      .describe(\n        'Optional configuration for the speech-to-text transcription process.'\n      ),\n  })\n  .strict();\n\n/**\n * A DaitanJS tool that downloads the audio from a YouTube URL,\n * transcribes it to text using OpenAI Whisper, and returns the transcription.\n */\nexport const processYoutubeAudioTool = createDaitanTool(\n  'process_youtube_audio',\n  `Downloads the audio from a given YouTube video URL and transcribes it into text.\nThe input must be an object with a \"url\" key containing the full YouTube video URL.\nIt can optionally include a \"transcriptionConfig\" object with a \"language\" (ISO-639-1 code) or \"prompt\" to improve accuracy.\nThis tool is very powerful for extracting spoken content from videos for analysis, summarization, or answering questions.`,\n  async (input) => {\n    // Validate the input against the Zod schema\n    const validatedInput = ProcessYoutubeAudioInputSchema.parse(input);\n\n    // Call the underlying service from @daitanjs/media\n    const transcriptionResult = await transcribeYoutubeVideo({\n      url: validatedInput.url,\n      config: validatedInput.transcriptionConfig,\n    });\n\n    if (!transcriptionResult || !transcriptionResult.text) {\n      throw new DaitanNotFoundError(\n        `Could not obtain a valid transcription for the video at ${validatedInput.url}.`\n      );\n    }\n\n    const fullText = transcriptionResult.text;\n    const summary = `Successfully transcribed video. Length: ${\n      fullText.length\n    } characters. Preview: \"${fullText.substring(0, 150)}...\"`;\n\n    return summary;\n  },\n  ProcessYoutubeAudioInputSchema\n);\n", "// intelligence/src/intelligence/tools/imageGenerationTool.js\n/**\n * @file A DaitanJS tool for generating images using DALL-E.\n * @module @daitanjs/intelligence/tools/imageGenerationTool\n *\n * @description\n * This module exports a LangChain-compatible tool that allows an AI agent to\n * generate images from a text prompt by wrapping the `generateImage` function\n * from the `@daitanjs/senses` package. It provides a structured interface\n * for the agent to specify the prompt, model, size, and other parameters.\n */\n\nimport { createDaitanTool } from '../core/toolFactory.js'; // CORRECTED: Import from the new 'core' location\nimport { z } from 'zod';\nimport { generateImage } from '@daitanjs/senses';\n\nconst ImageGenerationInputSchema = z\n  .object({\n    prompt: z\n      .string()\n      .min(1, 'A descriptive prompt is required.')\n      .max(4000, 'The prompt for DALL-E 3 cannot exceed 4000 characters.'),\n    outputPath: z\n      .string()\n      .optional()\n      .describe(\n        \"Optional: A local server path to save the image (e.g., './output/image.png'). If not provided, a public URL will be returned instead.\"\n      ),\n    model: z.enum(['dall-e-3', 'dall-e-2']).optional().default('dall-e-3'),\n    size: z\n      .enum(['1024x1024', '1792x1024', '1024x1792', '512x512', '256x256'])\n      .optional()\n      .default('1024x1024'),\n    quality: z\n      .enum(['standard', 'hd'])\n      .optional()\n      .default('standard')\n      .describe('For DALL-E 3 only.'),\n    style: z\n      .enum(['vivid', 'natural'])\n      .optional()\n      .default('vivid')\n      .describe('For DALL-E 3 only.'),\n  })\n  .strict();\n\nexport const imageGenerationTool = createDaitanTool(\n  'generate_image',\n  `Generates an image from a text prompt using the DALL-E model.\nThe input must be an object with:\n- \"prompt\" (string): A detailed description of the image to generate.\n- \"outputPath\" (string, optional): A local server file path (including extension, e.g., './images/my_cat.png') to save the image to. If you use this, the tool will return the path.\n- \"model\" (string, optional): \"dall-e-3\" (default) or \"dall-e-2\".\n- \"size\" (string, optional): The image dimensions. For DALL-E 3, valid sizes are \"1024x1024\", \"1792x1024\", or \"1024x1792\". For DALL-E 2, valid sizes are \"256x256\", \"512x512\", or \"1024x1024\". Defaults to \"1024x1024\".\n- \"quality\" (string, optional): For DALL-E 3 only. \"standard\" or \"hd\". Defaults to \"standard\".\n- \"style\" (string, optional): For DALL-E 3 only. \"vivid\" or \"natural\". Defaults to \"vivid\".\nIf 'outputPath' is not provided, the tool returns a public URL to the generated image.`,\n  async (input) => {\n    const validatedInput = ImageGenerationInputSchema.parse(input);\n\n    const response_format = validatedInput.outputPath ? 'b64_json' : 'url';\n\n    const result = await generateImage({\n      ...validatedInput,\n      response_format: response_format,\n    });\n\n    if (response_format === 'url') {\n      const url = Array.isArray(result.urls) ? result.urls[0] : result.urls;\n      return `Image generated successfully. It is available at the following URL: ${url}`;\n    } else {\n      return `Image generated and saved successfully to the server path: ${result.outputPath}`;\n    }\n  },\n  ImageGenerationInputSchema\n);\n", "// intelligence/src/intelligence/tools/gmailTools.js\n/**\n * @file A suite of DaitanJS tools for interacting with the Gmail API.\n * @module @daitanjs/intelligence/tools/gmailTools\n *\n * @description\n * This module provides a set of granular, focused tools for an AI agent to\n * read, search, and draft emails in a user's Gmail account. This modular\n * approach is more effective for LLM reasoning than a single monolithic tool.\n * All tools require an authenticated Google OAuth2 client with the appropriate\n * Gmail scopes (e.g., 'https://www.googleapis.com/auth/gmail.readonly',\n * 'https://www.googleapis.com/auth/gmail.compose').\n */\n\nimport { google } from 'googleapis';\nimport { createDaitanTool } from '../core/toolFactory.js'; // CORRECTED: Import from the new 'core' location\nimport { getGoogleAuthClient, getLogger } from '@daitanjs/development';\nimport {\n  DaitanConfigurationError,\n  DaitanOperationError,\n} from '@daitanjs/error';\nimport { z } from 'zod';\nimport { Buffer } from 'buffer';\n\n/**\n * Gets an authenticated Gmail API client.\n * @private\n */\nconst getGmailClient = () => {\n  const oauth2Client = getGoogleAuthClient();\n  if (!oauth2Client.credentials.access_token) {\n    throw new DaitanConfigurationError(\n      'Gmail tools require an authenticated OAuth2 client with an access token.'\n    );\n  }\n  return google.gmail({ version: 'v1', auth: oauth2Client });\n};\n\n// --- Tool 1: Search Gmail ---\nconst SearchGmailInputSchema = z\n  .object({\n    query: z\n      .string()\n      .min(1, 'A search query is required.')\n      .describe(\n        'A Gmail search query string, similar to the web interface (e.g., \\'from:elon@x.com is:unread subject:\"Launch Plans\"\\').'\n      ),\n    maxResults: z.number().int().min(1).max(20).optional().default(5),\n  })\n  .strict();\n\nexport const searchGmailTool = createDaitanTool(\n  'search_gmail',\n  `Searches for emails in the user's Gmail account using a standard Gmail query string.\nReturns a list of email summaries (ID, Subject, From, Snippet) that match the query.\nUse this to find specific emails before deciding to read one in full.`,\n  async (input) => {\n    const validatedInput = SearchGmailInputSchema.parse(input);\n    const gmail = getGmailClient();\n\n    const res = await gmail.users.messages.list({\n      userId: 'me',\n      q: validatedInput.query,\n      maxResults: validatedInput.maxResults,\n    });\n\n    if (!res.data.messages || res.data.messages.length === 0) {\n      return `No emails found matching query: \"${validatedInput.query}\".`;\n    }\n\n    // Fetch snippets for each found message\n    const summaries = await Promise.all(\n      res.data.messages.map(async (msg) => {\n        const message = await gmail.users.messages.get({\n          userId: 'me',\n          id: msg.id,\n          format: 'metadata',\n          metadataHeaders: ['Subject', 'From', 'Date'],\n        });\n        const headers = message.data.payload.headers;\n        return {\n          id: msg.id,\n          threadId: msg.threadId,\n          subject:\n            headers.find((h) => h.name === 'Subject')?.value || 'No Subject',\n          from:\n            headers.find((h) => h.name === 'From')?.value || 'Unknown Sender',\n          date: headers.find((h) => h.name === 'Date')?.value || 'Unknown Date',\n          snippet: message.data.snippet,\n        };\n      })\n    );\n    return `Found ${summaries.length} email(s):\\n${JSON.stringify(\n      summaries,\n      null,\n      2\n    )}`;\n  },\n  SearchGmailInputSchema\n);\n\n// --- Tool 2: Read Email Content ---\nconst ReadEmailInputSchema = z\n  .object({\n    messageId: z.string().min(1, 'A message ID is required to read an email.'),\n  })\n  .strict();\n\nexport const readEmailContentTool = createDaitanTool(\n  'read_email_content',\n  `Retrieves the full plain-text body of a specific email using its message ID.\nUse this tool after 'search_gmail' to get the full content of an email you want to analyze or respond to.\nThe input must be an object with a \"messageId\" key.`,\n  async (input) => {\n    const validatedInput = ReadEmailInputSchema.parse(input);\n    const gmail = getGmailClient();\n\n    const message = await gmail.users.messages.get({\n      userId: 'me',\n      id: validatedInput.messageId,\n      format: 'full', // Get the full message payload\n    });\n\n    if (!message.data || !message.data.payload) {\n      return 'Error: Could not retrieve email payload.';\n    }\n\n    let body = '';\n    const findBodyPart = (parts) => {\n      for (const part of parts) {\n        if (part.mimeType === 'text/plain' && part.body?.data) {\n          return part.body.data;\n        }\n        if (part.parts) {\n          const nestedBody = findBodyPart(part.parts);\n          if (nestedBody) return nestedBody;\n        }\n      }\n      // Fallback for simple, non-multipart emails\n      if (\n        message.data.payload.mimeType === 'text/plain' &&\n        message.data.payload.body?.data\n      ) {\n        return message.data.payload.body.data;\n      }\n      return null;\n    };\n\n    const bodyData = message.data.payload.parts\n      ? findBodyPart(message.data.payload.parts)\n      : findBodyPart([message.data.payload]);\n\n    if (bodyData) {\n      body = Buffer.from(bodyData, 'base64').toString('utf-8');\n    } else {\n      body =\n        'Could not find a plain text body in this email. It might be HTML only or an attachment.';\n    }\n\n    const subject =\n      message.data.payload.headers.find((h) => h.name === 'Subject')?.value ||\n      'No Subject';\n    return `Subject: ${subject}\\n\\nBody:\\n${body}`;\n  },\n  ReadEmailInputSchema\n);\n\n// --- Tool 3: Create Email Draft ---\nconst CreateDraftInputSchema = z\n  .object({\n    to: z.string().email('A valid recipient email address is required.'),\n    subject: z.string().min(1, 'Subject cannot be empty.'),\n    body: z.string().min(1, 'Body content cannot be empty.'),\n    inReplyTo: z\n      .string()\n      .optional()\n      .describe(\n        \"Optional: The 'Message-ID' header of the email being replied to, to create a threaded reply.\"\n      ),\n    threadId: z\n      .string()\n      .optional()\n      .describe('Optional: The ID of the thread to reply to.'),\n  })\n  .strict();\n\nexport const createGmailDraftTool = createDaitanTool(\n  'create_gmail_draft',\n  `Creates a new draft email in the user's Gmail account. This tool does NOT send the email.\nThe input is an object with \"to\", \"subject\", and \"body\".\nOptionally include \"inReplyTo\" (the Message-ID of a previous email) and \"threadId\" to create a reply within a conversation thread.`,\n  async (input) => {\n    const validatedInput = CreateDraftInputSchema.parse(input);\n    const gmail = getGmailClient();\n\n    const emailLines = [\n      `To: ${validatedInput.to}`,\n      `Subject: ${validatedInput.subject}`,\n    ];\n\n    if (validatedInput.inReplyTo) {\n      emailLines.push(`In-Reply-To: ${validatedInput.inReplyTo}`);\n      emailLines.push(`References: ${validatedInput.inReplyTo}`);\n    }\n\n    emailLines.push('Content-Type: text/plain; charset=\"UTF-8\"');\n    emailLines.push('');\n    emailLines.push(validatedInput.body);\n\n    const rawEmail = emailLines.join('\\n');\n    const encodedMessage = Buffer.from(rawEmail).toString('base64url');\n\n    const draftRequestBody = {\n      message: {\n        raw: encodedMessage,\n      },\n    };\n\n    if (validatedInput.threadId) {\n      draftRequestBody.message.threadId = validatedInput.threadId;\n    }\n\n    const res = await gmail.users.drafts.create({\n      userId: 'me',\n      requestBody: draftRequestBody,\n    });\n\n    if (res.data.id) {\n      return `Email draft created successfully. Draft ID: ${res.data.id}. The user must review and send it manually.`;\n    } else {\n      throw new DaitanOperationError(\n        'Gmail API created a draft but did not return an ID.'\n      );\n    }\n  },\n  CreateDraftInputSchema\n);\n", "// intelligence/src/intelligence/tools/calendarTool.js\n/**\n * @file A tool for interacting with the Google Calendar API.\n * @module @daitanjs/intelligence/tools/calendarTool\n *\n * @description\n * This module provides the `calendarTool`, a DaitanJS tool that allows AI agents\n * to interact with a user's Google Calendar.\n */\nimport { google } from 'googleapis';\nimport { createDaitanTool } from '../core/toolFactory.js';\nimport { getGoogleAuthClient, getLogger } from '@daitanjs/development';\nimport {\n  DaitanConfigurationError,\n  DaitanOperationError,\n} from '@daitanjs/error';\nimport { z } from 'zod';\n\nconst calendarLogger = getLogger('daitan-tool-calendar');\nconst TOOL_NAME = 'google_calendar_tool';\n\n// --- SCHEMA DEFINITIONS (Moved directly into this file) ---\n// This co-location of schemas with their usage in `discriminatedUnion`\n// is the definitive fix for the build-time initialization error.\n\nconst CheckEventsSchema = z.object({\n  action: z.literal('check_events'),\n  timeMin: z\n    .string()\n    .datetime({ message: 'timeMin must be a valid ISO 8601 datetime string.' })\n    .optional(),\n  timeMax: z\n    .string()\n    .datetime({ message: 'timeMax must be a valid ISO 8601 datetime string.' })\n    .optional(),\n  maxResults: z.number().int().min(1).max(25).optional().default(10),\n  calendarId: z.string().optional().default('primary'),\n});\n\nconst CreateEventSchema = z.object({\n  action: z.literal('create_event'),\n  title: z.string().min(1, 'Event title cannot be empty.'),\n  startTime: z.string().datetime({\n    message: 'startTime must be a valid ISO 8601 datetime string.',\n  }),\n  endTime: z\n    .string()\n    .datetime({ message: 'endTime must be a valid ISO 8601 datetime string.' }),\n  attendees: z\n    .array(z.string().email())\n    .optional()\n    .describe('An array of attendee email addresses.'),\n  description: z\n    .string()\n    .optional()\n    .describe('A description or notes for the event.'),\n  location: z.string().optional().describe('The location of the event.'),\n  calendarId: z.string().optional().default('primary'),\n});\n\nconst CalendarToolInputSchema = z.discriminatedUnion('action', [\n  CheckEventsSchema,\n  CreateEventSchema,\n]);\n\n// --- Tool Implementation ---\n\nconst getCalendarClient = () => {\n  const oauth2Client = getGoogleAuthClient();\n  if (!oauth2Client.credentials.access_token) {\n    throw new DaitanConfigurationError(\n      'Google Calendar tool requires an authenticated OAuth2 client with an access token.'\n    );\n  }\n  return google.calendar({ version: 'v3', auth: oauth2Client });\n};\n\nexport const calendarTool = createDaitanTool(\n  TOOL_NAME,\n  `A tool to interact with Google Calendar. It can check for events or create new ones.\nInput must be an object specifying the 'action'.\n- For \"check_events\": {\"action\": \"check_events\", \"timeMin\": \"ISO_DATETIME\", \"timeMax\": \"ISO_DATETIME\" (optional)}.\n- For \"create_event\": {\"action\": \"create_event\", \"title\": \"Meeting Title\", \"startTime\": \"ISO_DATETIME\", \"endTime\": \"ISO_DATETIME\"}.`,\n  async (input) => {\n    // The wrapper in toolFactory handles parsing and the Zod schema below handles validation\n    const validatedInput = CalendarToolInputSchema.parse(input);\n\n    const calendar = getCalendarClient();\n\n    switch (validatedInput.action) {\n      case 'check_events':\n        const timeMin = validatedInput.timeMin || new Date().toISOString();\n        const timeMax =\n          validatedInput.timeMax ||\n          new Date(\n            new Date().getTime() + 7 * 24 * 60 * 60 * 1000\n          ).toISOString();\n\n        const res = await calendar.events.list({\n          calendarId: validatedInput.calendarId,\n          timeMin,\n          timeMax,\n          maxResults: validatedInput.maxResults,\n          singleEvents: true,\n          orderBy: 'startTime',\n        });\n\n        const events = res.data.items;\n        if (!events || events.length === 0) {\n          return `No upcoming events found between ${timeMin} and ${timeMax}.`;\n        }\n\n        return `Found ${events.length} event(s):\\n${JSON.stringify(\n          events.map((e) => ({\n            summary: e.summary,\n            start: e.start.dateTime || e.start.date,\n          }))\n        )}`;\n\n      case 'create_event':\n        const eventResource = {\n          summary: validatedInput.title,\n          location: validatedInput.location,\n          description: validatedInput.description,\n          start: { dateTime: validatedInput.startTime },\n          end: { dateTime: validatedInput.endTime },\n          attendees: validatedInput.attendees?.map((email) => ({ email })),\n        };\n\n        const createResponse = await calendar.events.insert({\n          calendarId: validatedInput.calendarId,\n          requestBody: eventResource,\n          sendNotifications: true,\n        });\n\n        if (createResponse.data.htmlLink) {\n          return `Event \"${validatedInput.title}\" created successfully. Link: ${createResponse.data.htmlLink}`;\n        }\n        throw new DaitanOperationError(\n          'Google Calendar created the event but did not return a link.'\n        );\n    }\n  },\n  CalendarToolInputSchema\n);\n", "// intelligence/src/intelligence/tools/googleDriveTools.js\n/**\n * @file A suite of DaitanJS tools for interacting with Google Drive (Docs, Sheets).\n * @module @daitanjs/intelligence/tools/googleDriveTools\n *\n * @description\n * This module provides tools for an AI agent to create Google Docs and Sheets\n * in a user's Google Drive. This requires an authenticated Google OAuth2 client\n * with the necessary Drive and Sheets API scopes.\n *\n * Required Scopes:\n * - 'https://www.googleapis.com/auth/drive.file' (to create files)\n * - 'https://www.googleapis.com/auth/spreadsheets' (to create and write to Sheets)\n */\n\nimport { google } from 'googleapis';\nimport { createDaitanTool } from '../core/toolFactory.js'; // CORRECTED: Import from the new 'core' location\nimport { getGoogleAuthClient, getLogger } from '@daitanjs/development';\n\nimport {\n  DaitanConfigurationError,\n  DaitanOperationError,\n} from '@daitanjs/error';\nimport { z } from 'zod';\n\nconst driveLogger = getLogger('daitan-tool-drive');\n\n/**\n * Gets an authenticated Google APIs client for a specific service.\n * @private\n */\nconst getGoogleApiClient = (service) => {\n  const oauth2Client = getGoogleAuthClient();\n  if (!oauth2Client.credentials.access_token) {\n    throw new DaitanConfigurationError(\n      `Google Drive/Sheets tools require an authenticated OAuth2 client with an access token.`\n    );\n  }\n  if (service === 'drive') {\n    return google.drive({ version: 'v3', auth: oauth2Client });\n  }\n  if (service === 'sheets') {\n    return google.sheets({ version: 'v4', auth: oauth2Client });\n  }\n  throw new DaitanConfigurationError(\n    `Unsupported Google service requested: ${service}`\n  );\n};\n\n// --- Tool 1: Create Google Doc ---\nconst CreateGoogleDocInputSchema = z\n  .object({\n    title: z.string().min(1, 'Document title cannot be empty.'),\n    content: z\n      .string()\n      .describe('The plain text content to be placed in the document.'),\n  })\n  .strict();\n\nexport const createGoogleDocTool = createDaitanTool(\n  'create_google_doc',\n  `Creates a new Google Doc in the user's Google Drive with the provided title and content.\nThe input is an object with \"title\" and \"content\" string keys.\nReturns the URL of the newly created document.`,\n  async (input) => {\n    const validatedInput = CreateGoogleDocInputSchema.parse(input);\n    const drive = getGoogleApiClient('drive');\n\n    driveLogger.debug(`Creating Google Doc titled: \"${validatedInput.title}\"`);\n\n    // The Drive API can create a Google Doc by uploading plain text and specifying the MIME type.\n    const fileMetadata = {\n      name: validatedInput.title,\n      mimeType: 'application/vnd.google-apps.document',\n    };\n    const media = {\n      mimeType: 'text/plain',\n      body: validatedInput.content,\n    };\n\n    const res = await drive.files.create({\n      resource: fileMetadata,\n      media: media,\n      fields: 'webViewLink, id', // Request the web link and file ID in the response\n    });\n\n    if (res.data.webViewLink) {\n      return `Google Doc \"${validatedInput.title}\" created successfully. Link: ${res.data.webViewLink}`;\n    } else {\n      throw new DaitanOperationError(\n        'Google Drive API created the document but did not return a link.'\n      );\n    }\n  },\n  CreateGoogleDocInputSchema\n);\n\n// --- Tool 2: Create Google Sheet ---\nconst CreateGoogleSheetInputSchema = z\n  .object({\n    title: z.string().min(1, 'Spreadsheet title cannot be empty.'),\n    data: z\n      .array(z.array(z.union([z.string(), z.number(), z.boolean(), z.null()])))\n      .describe(\n        'A 2D array of data representing rows and cells to populate the sheet. The first inner array is typically the headers.'\n      ),\n  })\n  .strict();\n\nexport const createGoogleSheetTool = createDaitanTool(\n  'create_google_sheet',\n  `Creates a new Google Sheet in the user's Google Drive and populates it with the provided data.\nThe input is an object with \"title\" (string) and \"data\" (a 2D array of strings/numbers/booleans).\nThe first row of the data array will be treated as the header row.\nReturns the URL of the newly created spreadsheet.`,\n  async (input) => {\n    const validatedInput = CreateGoogleSheetInputSchema.parse(input);\n    const sheets = getGoogleApiClient('sheets');\n    driveLogger.debug(\n      `Creating Google Sheet titled: \"${validatedInput.title}\"`\n    );\n\n    // Step 1: Create an empty spreadsheet\n    const createResponse = await sheets.spreadsheets.create({\n      resource: {\n        properties: {\n          title: validatedInput.title,\n        },\n      },\n    });\n\n    const spreadsheetId = createResponse.data.spreadsheetId;\n    if (!spreadsheetId) {\n      throw new DaitanOperationError(\n        'Google Sheets API failed to create a new spreadsheet.'\n      );\n    }\n\n    // Step 2: Populate the spreadsheet with data\n    if (validatedInput.data.length > 0) {\n      await sheets.spreadsheets.values.update({\n        spreadsheetId: spreadsheetId,\n        range: 'Sheet1!A1', // Start from the top-left cell of the first sheet\n        valueInputOption: 'USER_ENTERED', // This allows Google to parse dates, numbers, etc., correctly\n        resource: {\n          values: validatedInput.data,\n        },\n      });\n    }\n\n    const spreadsheetUrl = createResponse.data.spreadsheetUrl;\n    if (spreadsheetUrl) {\n      return `Google Sheet \"${validatedInput.title}\" created and populated successfully. Link: ${spreadsheetUrl}`;\n    } else {\n      // This case is unlikely if creation succeeded, but as a fallback\n      return `Google Sheet created with ID: ${spreadsheetId}, but the URL was not returned.`;\n    }\n  },\n  CreateGoogleSheetInputSchema\n);\n", "// intelligence/src/intelligence/tools/ragTool.js\nimport { createDaitanTool } from '../core/toolFactory.js'; // CORRECTED: Import from the new 'core' location\nimport { z } from 'zod';\nimport { askWithRetrieval } from '../rag/retrieval.js';\nimport { DaitanNotFoundError } from '@daitanjs/error';\n\nconst RagToolInputSchema = z\n  .string()\n  .describe(\n    \"The user's question or the specific sub-query to research within the document.\"\n  );\n\nexport const ragTool = createDaitanTool(\n  'knowledge_base_tool',\n  `Queries the internal knowledge base (a specific PDF document) to answer questions. \nThis is the primary tool for finding information contained within the document.\nThe input is the direct question string to search for. \nThe tool can perform two types of queries: a 'simple' query for direct questions, and an 'analytical' query for complex questions that require summarizing or analyzing data across the document. \nIt can also optionally blend its findings with general knowledge.`,\n  async (input) => {\n    // The input is a string, which is always valid if it exists\n    const query = input;\n\n    const analyticalKeywords = [\n      'how many',\n      'count',\n      'list all',\n      'what are the',\n      'categorize',\n    ];\n    const useAnalysisPrompt = analyticalKeywords.some((keyword) =>\n      query.toLowerCase().includes(keyword)\n    );\n\n    const result = await askWithRetrieval(query, {\n      useAnalysisPrompt: useAnalysisPrompt,\n      topK: 7,\n    });\n\n    if (\n      !result.text ||\n      result.text.toLowerCase().includes(\"i don't have enough information\")\n    ) {\n      return `The knowledge base did not contain a definitive answer for the query: \"${query}\". Try rephrasing or using a web search.`;\n    }\n\n    return `Result from knowledge base: ${result.text}`;\n  },\n  RagToolInputSchema\n);\n", "// intelligence/src/intelligence/tools/baseTool.js\n/**\n * @file Abstract base class for creating tools compatible with DaitanJS and LangChain.\n * @module @daitanjs/intelligence/tools/baseTool\n *\n * @description\n * This class provides a common structure and robust execution wrapper for custom tools.\n * It integrates Zod schema validation, standardized logging, and error handling.\n *\n * NOTE: While this class is functional, the recommended modern approach is to use the\n * `createDaitanTool` factory function from `./toolFactory.js`. The factory provides\n * the same benefits with less boilerplate and is the primary pattern used throughout\n * the library. This class is maintained for compatibility or specific inheritance needs.\n */\nimport { getLogger } from '@daitanjs/development';\nimport {\n  DaitanValidationError,\n  DaitanOperationError,\n  DaitanConfigurationError,\n} from '@daitanjs/error';\nimport { DynamicTool } from '@langchain/core/tools';\nimport { ZodError } from 'zod';\n\n/**\n * @typedef {import('./toolInterface.js').ToolInputWrapper} ToolInputWrapper\n * @typedef {import('./toolInterface.js').ToolInputData} ToolInputData\n * @typedef {import('./toolInterface.js').ToolResponse} ToolResponse\n * @typedef {import('zod').ZodSchema} ZodSchemaType\n */\n\n/**\n * Abstract base class for DaitanJS tools.\n */\nexport class BaseTool {\n  /** @type {string} */\n  name;\n  /** @type {string} */\n  description;\n  /** @type {ZodSchemaType | undefined} */\n  schema;\n  /** @type {import('winston').Logger} */\n  logger;\n\n  constructor(name, description, argsSchema = undefined) {\n    if (!name || typeof name !== 'string' || !name.trim()) {\n      throw new DaitanConfigurationError(\n        'Tool name must be a non-empty string.'\n      );\n    }\n    if (\n      !description ||\n      typeof description !== 'string' ||\n      !description.trim()\n    ) {\n      throw new DaitanConfigurationError(\n        'Tool description must be a non-empty string.'\n      );\n    }\n    this.name = name;\n    this.description = description;\n    this.schema = argsSchema;\n    this.logger = getLogger(`daitan-tool-${this.name}`);\n    this.logger.info(`Tool \"${this.name}\" initialized.`);\n  }\n\n  /**\n   * The core logic of the tool. Subclasses MUST implement this method.\n   * @protected\n   * @abstract\n   * @param {any} processedInput - The validated and processed input for the tool.\n   * @param {string} [callId] - A unique ID for logging and tracing this specific call.\n   * @returns {Promise<string | any>} The result of the tool's execution.\n   */\n  async _run(processedInput, callId) {\n    throw new DaitanOperationError(\n      'Method \"_run()\" not implemented by subclass.',\n      { toolName: this.name }\n    );\n  }\n\n  /**\n   * Public execution method that wraps the core logic with validation and error handling.\n   * @param {any} rawInput - The raw input from the agent or caller.\n   * @returns {Promise<string>} The result formatted as a string for the agent.\n   */\n  async run(rawInput) {\n    const callId =\n      (typeof rawInput === 'object' && rawInput?.callId) ||\n      `tool-run-${this.name}-${Date.now().toString(36)}`;\n    let inputForRun = rawInput;\n\n    this.logger.info(`Tool \"${this.name}\" execution: START`, { callId });\n\n    try {\n      // Handle cases where input is a stringified JSON\n      if (typeof rawInput === 'string') {\n        try {\n          inputForRun = JSON.parse(rawInput);\n        } catch (e) {\n          // Not a JSON string, proceed with the raw string.\n          // This is fine if the schema expects a string.\n        }\n      }\n\n      // If a Zod schema is provided, parse and validate the input.\n      if (this.schema) {\n        inputForRun = this.schema.parse(inputForRun);\n      }\n\n      // Execute the core tool logic with the (potentially validated) input.\n      const result = await this._run(inputForRun, callId);\n\n      // Format the output to be a string, as expected by LangChain's agent observation.\n      const outputString =\n        typeof result === 'string' ? result : JSON.stringify(result, null, 2);\n\n      this.logger.info(`Tool \"${this.name}\" execution: SUCCESS`, {\n        callId,\n        outputPreview: outputString.substring(0, 150) + '...',\n      });\n\n      return outputString;\n    } catch (error) {\n      this.logger.error(\n        `Execution error in tool \"${this.name}\": ${error.message}`,\n        {\n          callId,\n          errorName: error.name,\n        }\n      );\n\n      // Format a user-friendly error message for the agent.\n      if (error instanceof ZodError) {\n        return `Error: Invalid input. ${error.errors\n          .map((e) => `${e.path.join('.')}: ${e.message}`)\n          .join('; ')}`;\n      }\n      if (\n        error instanceof DaitanValidationError ||\n        error instanceof DaitanOperationError\n      ) {\n        return `Error: ${error.message}`;\n      }\n      return `Error executing tool \"${this.name}\": An unexpected error occurred. ${error.message}`;\n    }\n  }\n\n  /**\n   * Synchronously gets a LangChain-compatible `DynamicTool` instance.\n   * This getter is now synchronous, making it safe to use when initializing agents.\n   * @returns {DynamicTool}\n   */\n  get lcTool() {\n    return new DynamicTool({\n      name: this.name,\n      description: this.description,\n      // The `func` property can be async, which is the correct pattern.\n      func: (input) => this.run(input),\n      // Pass the schema to the DynamicTool for structured input handling.\n      schema: this.schema,\n    });\n  }\n}\n", "// intelligence/src/intelligence/agents/agentRunner.js\n/**\n * @file Provides a simplified, high-level function to run complex, graph-based agents.\n * @module @daitanjs/intelligence/agents/agentRunner\n *\n * @description\n * This module exports the `runGraphAgent` function, which acts as a user-friendly \"one-shot\"\n * interface for executing complex agentic workflows like Plan-and-Execute or ReAct.\n * It abstracts away the boilerplate of instantiating the LLMService, creating the agent graph,\n * managing the graph runner, and constructing the initial state.\n */\nimport { HumanMessage } from '@langchain/core/messages';\nimport { getLogger } from '@daitanjs/development';\nimport { LLMService } from '../../services/llmService.js';\n// CORRECTED: Import getDefaultTools from its new, isolated location\nimport { getDefaultTools } from '../tools/tool-registries.js';\nimport { createGraphRunner } from '../workflows/graphRunner.js';\nimport { createPlanAndExecuteAgentGraph } from '../workflows/planAndExecuteAgentGraph.js';\nimport { createReActAgentGraph } from '../workflows/reactWithReflectionAgentGraph.js';\nimport { DaitanInvalidInputError } from '@daitanjs/error';\n\nconst agentRunnerLogger = getLogger('daitan-agent-runner');\n\n/**\n * @typedef {import('@langchain/core/tools').BaseTool} BaseTool\n */\n\n/**\n * @typedef {Object} RunGraphAgentParams\n * @property {string} query - The user's query or task for the agent.\n * @property {'default' | 'research' | 'react'} [agentType='default'] - The type of agent workflow.\n * @property {BaseTool[]} [tools] - An array of tools for the agent. Defaults to `getDefaultTools()`.\n * @property {string} [llmTarget] - Optional LLM target for the agent's LLMService.\n * @property {string} [sessionId] - Optional session ID for stateful conversations.\n * @property {boolean} [verbose=false] - Enable verbose logging for the entire agent run.\n */\n\n/**\n * @typedef {Object} AgentRunResult\n * @property {string | null} finalAnswer - The final answer produced by the agent.\n * @property {object} finalState - The complete final state object of the LangGraph execution.\n */\n\nconst compiledGraphCache = new Map();\n\n/**\n * A simplified, high-level function to run a complex, graph-based agentic workflow.\n *\n * @public\n * @async\n * @param {RunGraphAgentParams} params - The parameters for the agent run.\n * @returns {Promise<AgentRunResult>} The result of the agent's execution.\n */\nexport const runGraphAgent = async ({\n  query,\n  agentType = 'default',\n  tools,\n  llmTarget,\n  sessionId,\n  verbose = false,\n}) => {\n  const callId = `runGraphAgent-${agentType}-${Date.now().toString(36)}`;\n  agentRunnerLogger.info(\n    `[${callId}] runGraphAgent: Initiating agent workflow.`,\n    {\n      query: query.substring(0, 70),\n      agentType,\n      sessionId,\n    }\n  );\n\n  if (!query || typeof query !== 'string' || !query.trim()) {\n    throw new DaitanInvalidInputError(\n      'A non-empty `query` string is required to run an agent.'\n    );\n  }\n\n  const llmService = new LLMService({ target: llmTarget, verbose });\n  const effectiveTools = tools || getDefaultTools();\n\n  const toolsMap = effectiveTools.reduce((map, tool) => {\n    if (tool?.name) map[tool.name] = tool;\n    return map;\n  }, {});\n\n  const effectiveSessionId =\n    sessionId || `agent-session-${Date.now().toString(36)}`;\n  let compiledGraph;\n  let initialState;\n\n  if (compiledGraphCache.has(agentType)) {\n    compiledGraph = compiledGraphCache.get(agentType);\n    if (verbose)\n      agentRunnerLogger.debug(\n        `[${callId}] Using cached compiled graph for agent type: \"${agentType}\"`\n      );\n  } else {\n    agentRunnerLogger.info(\n      `[${callId}] Compiling new graph for agent type: \"${agentType}\"`\n    );\n    if (agentType === 'react') {\n      compiledGraph = await createReActAgentGraph(llmService, effectiveTools);\n    } else {\n      compiledGraph = await createPlanAndExecuteAgentGraph(\n        llmService,\n        effectiveTools\n      );\n    }\n    compiledGraphCache.set(agentType, compiledGraph);\n  }\n\n  const graphRunner = createGraphRunner(compiledGraph, { verbose });\n\n  if (agentType === 'react') {\n    initialState = {\n      inputMessage: new HumanMessage(query),\n      llmServiceInstance: llmService,\n      toolsMap: toolsMap,\n      verbose: verbose,\n    };\n  } else {\n    initialState = {\n      inputMessage: new HumanMessage(query),\n      originalQuery: query,\n      llmServiceInstance: llmService,\n      toolsMap: toolsMap,\n      verbose: verbose,\n    };\n  }\n\n  agentRunnerLogger.info(`[${callId}] Invoking agent graph runner...`);\n  const finalState = await graphRunner(initialState, {\n    configurable: { thread_id: effectiveSessionId },\n  });\n\n  agentRunnerLogger.info(`[${callId}] Agent workflow completed.`);\n  return {\n    finalAnswer: finalState.finalAnswer || null,\n    finalState: finalState,\n  };\n};\n", "// intelligence/src/intelligence/workflows/graphRunner.js\n/**\n * @file Contains the factory function for creating DaitanJS graph runners.\n * @module @daitanjs/intelligence/workflows/graphRunner\n *\n * @description\n * This module provides `createGraphRunner`, a factory for executing compiled LangGraphs.\n * The runner handles invocation, advanced streaming of state updates with structured\n * event types, detailed logging, and robust error handling, making it a cornerstone\n * for building observable and debuggable agentic workflows.\n */\nimport { getLogger } from '@daitanjs/development';\nimport { getConfigManager } from '@daitanjs/config';\nimport {\n  DaitanOperationError,\n  DaitanConfigurationError,\n} from '@daitanjs/error';\n\n/**\n * @typedef {import('@langchain/langgraph').CompiledGraph} CompiledGraph\n * @typedef {import('@langchain/core/callbacks/manager').Callbacks} Callbacks\n * @typedef {{ configurable?: Record<string, any>, callbacks?: Callbacks, recursionLimit?: number, [key: string]: any }} LangGraphRuntimeConfig\n */\n\n/**\n * @typedef {'node_start' | 'node_finish' | 'stream_end' | 'error'} GraphStreamEventType\n */\n\n/**\n * @typedef {Object} GraphStreamEvent\n * @property {GraphStreamEventType} event - The type of the streaming event.\n * @property {string} node - The name of the node the event relates to.\n * @property {any} [data] - The data payload of the event (e.g., state changes).\n * @property {object} [state] - A snapshot of the accumulated graph state.\n */\n\n/**\n * @typedef {Object} CreateGraphRunnerOptions\n * @property {(event: GraphStreamEvent) => void | Promise<void>} [onStateUpdate] - Callback for each streamed state event.\n * @property {boolean} [verbose] - Verbosity for this specific runner instance. Overrides ConfigManager settings.\n * @property {import('winston').Logger} [loggerInstance] - Optional logger instance for the runner.\n */\n\n/**\n * Creates a runner function for a pre-compiled LangGraph.\n *\n * @param {CompiledGraph} compiledGraph - The compiled LangGraph instance.\n * @param {CreateGraphRunnerOptions} [options={}] - Options for the runner.\n * @returns {(initialInputs: object, runtimeConfig?: LangGraphRuntimeConfig) => Promise<object>} An async function that executes the graph.\n */\nexport const createGraphRunner = (compiledGraph, options = {}) => {\n  if (\n    !compiledGraph ||\n    typeof compiledGraph.invoke !== 'function' ||\n    typeof compiledGraph.stream !== 'function'\n  ) {\n    throw new DaitanConfigurationError(\n      'Invalid compiledGraph provided. Must be a LangGraph compiled graph instance.'\n    );\n  }\n\n  const {\n    onStateUpdate,\n    verbose: runnerSpecificVerbose,\n    loggerInstance,\n  } = options;\n\n  const currentLogger = loggerInstance || getLogger('daitan-graph-runner');\n  const configManager = getConfigManager();\n  const effectiveVerbose =\n    runnerSpecificVerbose !== undefined\n      ? runnerSpecificVerbose\n      : configManager.get('DEBUG_LANGGRAPH', false) ||\n        configManager.get('DEBUG_INTELLIGENCE', false);\n\n  const enableStreaming = typeof onStateUpdate === 'function';\n\n  /**\n   * Executes the compiled LangGraph.\n   * @param {object} initialInputs - The initial state for the graph.\n   * @param {LangGraphRuntimeConfig} [runtimeConfig={}] - LangGraph runtime configuration.\n   * @returns {Promise<object>} The final state of the graph.\n   */\n  return async (initialInputs, runtimeConfig = {}) => {\n    const graphId =\n      compiledGraph?.graph?.id || compiledGraph?.id || 'UnnamedGraph';\n    const threadId =\n      runtimeConfig?.configurable?.thread_id || `default-thread-${Date.now()}`;\n    const runIdentifier = `${graphId}-run-${String(threadId).substring(0, 12)}`;\n\n    const logContext = { graphId, threadId, runIdentifier };\n    const overallStartTime = Date.now();\n\n    currentLogger.info(`Graph run: START for \"${runIdentifier}\"`, {\n      ...logContext,\n      initialInputKeys: Object.keys(initialInputs || {}),\n      streaming: enableStreaming,\n    });\n\n    try {\n      if (enableStreaming) {\n        let accumulatedState = { ...(initialInputs || {}) };\n\n        const stream = await compiledGraph.stream(initialInputs, runtimeConfig);\n        let lastNode = null;\n\n        for await (const chunk of stream) {\n          const nodeName = Object.keys(chunk || {})[0];\n          if (nodeName && nodeName !== lastNode) {\n            if (lastNode) {\n              await onStateUpdate({\n                event: 'node_finish',\n                node: lastNode,\n                state: accumulatedState,\n              });\n            }\n            await onStateUpdate({\n              event: 'node_start',\n              node: nodeName,\n              state: accumulatedState,\n            });\n            lastNode = nodeName;\n          }\n\n          if (typeof chunk === 'object' && chunk !== null && chunk[nodeName]) {\n            accumulatedState = { ...accumulatedState, ...chunk[nodeName] };\n          }\n\n          if (effectiveVerbose) {\n            currentLogger.debug(`Graph stream chunk for \"${runIdentifier}\":`, {\n              ...logContext,\n              node: nodeName,\n              data: chunk[nodeName],\n            });\n          }\n        }\n\n        await onStateUpdate({\n          event: 'stream_end',\n          node: 'END',\n          state: accumulatedState,\n        });\n\n        currentLogger.info(`Graph stream: COMPLETED for \"${runIdentifier}\".`, {\n          ...logContext,\n          durationMs: Date.now() - overallStartTime,\n        });\n\n        // Invoke is still needed to get the absolute final, merged state reliably.\n        return await compiledGraph.invoke(initialInputs, runtimeConfig);\n      } else {\n        // Non-streaming execution\n        const finalOutputState = await compiledGraph.invoke(\n          initialInputs,\n          runtimeConfig\n        );\n        currentLogger.info(`Graph run: SUCCESS for \"${runIdentifier}\".`, {\n          ...logContext,\n          durationMs: Date.now() - overallStartTime,\n        });\n        return finalOutputState;\n      }\n    } catch (error) {\n      currentLogger.error(\n        `Graph run: FAILED for \"${runIdentifier}\". Error: ${error.message}`,\n        {\n          ...logContext,\n          durationMs: Date.now() - overallStartTime,\n          errorName: error.name,\n          errorStack: effectiveVerbose ? error.stack : undefined,\n        }\n      );\n      if (enableStreaming) {\n        await onStateUpdate({\n          event: 'error',\n          node: 'ERROR',\n          data: { message: error.message, name: error.name },\n          state: {},\n        });\n      }\n      throw new DaitanOperationError(\n        `Graph run for \"${runIdentifier}\" failed: ${error.message}`,\n        logContext,\n        error\n      );\n    }\n  };\n};\n", "// intelligence/src/intelligence/workflows/planAndExecuteAgentGraph.js\nimport { END } from '@langchain/langgraph';\nimport { HumanMessage } from '@langchain/core/messages';\nimport { getLogger } from '@daitanjs/development';\nimport { DaitanLangGraph } from './langGraphManager.js';\nimport { LLMService } from '../../services/llmService.js';\nimport {\n  DaitanConfigurationError,\n  DaitanOperationError,\n} from '@daitanjs/error';\n\nconst planAndExecuteLogger = getLogger('daitan-plan-execute-graph');\n\n/**\n * @typedef {import('../../services/llmService.js').LLMUsageInfo} LLMUsageInfo\n * @typedef {import('@langchain/core/tools').BaseTool} LangChainBaseTool\n * @typedef {Object} PlanStep\n * @property {number} step @property {string} task @property {string | null} [toolToUse] @property {any} [toolInput] @property {string} [expectedOutput] @property {\"pending\" | \"completed\" | \"failed\"} [status] @property {any} [result] @property {string} [error]\n * @typedef {Object} PlanAndExecuteAgentState\n * @property {HumanMessage} inputMessage @property {string} originalQuery @property {PlanStep[]} plan @property {number} currentStepIndex @property {Array<{step: number, task: string, result: any, error?: string}>} intermediateStepResults @property {string | null} finalAnswer @property {string | null} currentPipelineError @property {LLMService} llmServiceInstance @property {Record<string, LangChainBaseTool>} toolsMap @property {import('../../services/llmService.js').LLMServiceConfig} [plannerLlmConfig] @property {import('../../services/llmService.js').LLMServiceConfig} [executorLlmConfig] @property {import('../../services/llmService.js').LLMServiceConfig} [synthesizerLlmConfig] @property {LLMUsageInfo[]} llmUsages @property {boolean} verbose\n */\nexport const planAndExecuteAgentStateSchema = {\n  inputMessage: { value: (x, y) => y ?? x, default: () => null },\n  originalQuery: { value: (x, y) => y ?? x, default: () => '' },\n  plan: { value: (x, y) => y ?? x, default: () => [] },\n  currentStepIndex: { value: (x, y) => y ?? x, default: () => 0 },\n  intermediateStepResults: {\n    value: (x, y) => (x || []).concat(y || []),\n    default: () => [],\n  },\n  finalAnswer: { value: (x, y) => y ?? x, default: () => null },\n  currentPipelineError: { value: (x, y) => y ?? x, default: () => null },\n  llmServiceInstance: { value: (x, y) => y ?? x, default: () => null },\n  toolsMap: { value: (x, y) => y ?? x, default: () => ({}) },\n  plannerLlmConfig: { value: (x, y) => y ?? x, default: () => ({}) },\n  executorLlmConfig: { value: (x, y) => y ?? x, default: () => ({}) },\n  synthesizerLlmConfig: { value: (x, y) => y ?? x, default: () => ({}) },\n  llmUsages: { value: (x, y) => (x || []).concat(y || []), default: () => [] },\n  verbose: { value: (x, y) => y ?? x, default: () => false },\n};\n\n// --- Node Definitions ---\n\nconst plannerNode = async (state) => {\n  const {\n    originalQuery,\n    llmServiceInstance,\n    toolsMap,\n    plannerLlmConfig,\n    llmUsages,\n    verbose,\n  } = state;\n  const toolDescriptions = Object.values(toolsMap)\n    .map((t) => `- ${t.name}: ${t.description.split('\\n')[0]}`)\n    .join('\\n');\n  const plannerUserPrompt = `User Query: \"${originalQuery}\"\\n\\nAvailable tools:\\n${\n    toolDescriptions || 'No tools available.'\n  }\\n\\nBased on the query, create a step-by-step plan as a JSON array of objects.`;\n  const plannerSystemPrompt = {\n    persona: 'You are an expert planner.',\n    task: \"Create a step-by-step plan to answer the user's query.\",\n    outputFormat:\n      'Respond ONLY with a valid JSON array of objects. Each object must have keys: \"step\", \"task\", \"toolToUse\", \"toolInput\", and \"expectedOutput\". The final step should be for synthesis.',\n  };\n\n  try {\n    const { response: planArray, usage } = await llmServiceInstance.generate({\n      prompt: { system: plannerSystemPrompt, user: plannerUserPrompt },\n      config: {\n        response: { format: 'json' },\n        llm: {\n          target: plannerLlmConfig?.target || 'MASTER_COMMUNICATOR',\n          temperature: plannerLlmConfig?.temperature ?? 0.1,\n        },\n        verbose,\n      },\n    });\n    if (usage) llmUsages.push({ step: 'planner', ...usage });\n    if (\n      !Array.isArray(planArray) ||\n      planArray.some((step) => !step.task || typeof step.step !== 'number')\n    )\n      throw new DaitanOperationError(\n        'Planner failed to generate a valid plan.'\n      );\n    return {\n      plan: planArray.map((step) => ({ ...step, status: 'pending' })),\n      currentStepIndex: 0,\n      llmUsages,\n    };\n  } catch (error) {\n    return {\n      currentPipelineError: `Planner error: ${error.message}`,\n      plan: [],\n      llmUsages,\n    };\n  }\n};\n\nconst executorNode = async (state) => {\n  const {\n    plan,\n    currentStepIndex,\n    llmServiceInstance,\n    toolsMap,\n    executorLlmConfig,\n    intermediateStepResults,\n    originalQuery,\n    llmUsages,\n    verbose,\n  } = state;\n  if (currentStepIndex >= plan.length)\n    return { currentPipelineError: 'Execution attempted beyond plan length.' };\n  const stepToExecute = { ...plan[currentStepIndex], status: 'in_progress' };\n\n  let stepOutput,\n    stepError = null;\n  try {\n    if (stepToExecute.toolToUse && toolsMap[stepToExecute.toolToUse]) {\n      stepOutput = await toolsMap[stepToExecute.toolToUse].call(\n        stepToExecute.toolInput\n      );\n    } else if (stepToExecute.toolToUse) {\n      stepError = `Tool \"${stepToExecute.toolToUse}\" not found.`;\n    } else {\n      const prevResultsText = intermediateStepResults\n        .map(\n          (res) =>\n            `Result from Step ${res.step}: ${String(res.result).substring(\n              0,\n              150\n            )}...`\n        )\n        .join('\\n');\n      const { response, usage } = await llmServiceInstance.generate({\n        prompt: {\n          user: `Original Query: \"${originalQuery}\"\\nCurrent Task: \"${\n            stepToExecute.task\n          }\"\\nPrevious results:\\n${\n            prevResultsText || 'None'\n          }\\n\\nProvide the result for THIS STEP ONLY.`,\n        },\n        config: {\n          response: { format: 'text' },\n          llm: {\n            target: executorLlmConfig?.target || 'FAST_TASKER',\n            temperature: executorLlmConfig?.temperature ?? 0.3,\n          },\n          verbose,\n        },\n      });\n      stepOutput = response;\n      if (usage)\n        llmUsages.push({\n          step: `executor_llm_step_${stepToExecute.step}`,\n          ...usage,\n        });\n    }\n    stepToExecute.result = stepOutput ?? stepError;\n    stepToExecute.status = stepError ? 'failed' : 'completed';\n  } catch (error) {\n    stepError = `Error during step ${stepToExecute.step}: ${error.message}`;\n    stepToExecute.result = stepError;\n    stepToExecute.status = 'failed';\n  }\n  const updatedPlan = [...plan];\n  updatedPlan[currentStepIndex] = stepToExecute;\n  return {\n    plan: updatedPlan,\n    intermediateStepResults: [\n      ...intermediateStepResults,\n      {\n        step: stepToExecute.step,\n        task: stepToExecute.task,\n        result: stepToExecute.result,\n        error: stepError,\n      },\n    ],\n    currentStepIndex: currentStepIndex + 1,\n    currentPipelineError: stepError,\n    llmUsages,\n  };\n};\n\nconst synthesizerNode = async (state) => {\n  const {\n    originalQuery,\n    plan,\n    llmServiceInstance,\n    synthesizerLlmConfig,\n    llmUsages,\n    verbose,\n  } = state;\n  const planSummary = plan\n    .map(\n      (s) =>\n        `Step ${s.step} (${s.status}): ${s.task}\\n  Output: ${String(\n          s.result\n        ).substring(0, 200)}...${s.error ? `\\n  Error: ${s.error}` : ''}`\n    )\n    .join('\\n---\\n');\n\n  try {\n    const { response: finalAnswer, usage } = await llmServiceInstance.generate({\n      prompt: {\n        system: {\n          persona:\n            'You are an expert AI assistant tasked with synthesizing a final answer from a series of planned steps.',\n        },\n        user: `Based ONLY on the information from the executed steps below, provide a comprehensive answer to the original query: \"${originalQuery}\".\\n\\n--- PLAN EXECUTION SUMMARY ---\\n${planSummary}\\n--- END SUMMARY ---\\n\\nFinal Answer:`,\n      },\n      config: {\n        response: { format: 'text' },\n        llm: {\n          target: synthesizerLlmConfig?.target || 'MASTER_COMMUNICATOR',\n          temperature: synthesizerLlmConfig?.temperature ?? 0.1,\n        },\n        verbose,\n      },\n    });\n    if (usage) llmUsages.push({ step: 'synthesizer', ...usage });\n    return { finalAnswer: String(finalAnswer), llmUsages };\n  } catch (error) {\n    return {\n      finalAnswer: `Error synthesizing answer: ${error.message}`,\n      currentPipelineError: `Synthesizer error: ${error.message}`,\n      llmUsages,\n    };\n  }\n};\n\nconst routeAfterPlannerLogic = (state) =>\n  state.currentPipelineError || !state.plan || state.plan.length === 0\n    ? 'error_handler'\n    : 'executor';\nconst routeAfterStepExecutionLogic = (state) =>\n  state.currentPipelineError\n    ? 'error_handler'\n    : state.currentStepIndex < state.plan.length\n    ? 'executor'\n    : 'synthesizer';\n\nexport const createPlanAndExecuteAgentGraph = async (\n  llmServiceInstance,\n  tools,\n  checkpointerConfig\n) => {\n  if (!(llmServiceInstance instanceof LLMService))\n    throw new DaitanConfigurationError(\n      'An instance of LLMService is required.'\n    );\n\n  const workflow = new DaitanLangGraph(planAndExecuteAgentStateSchema, {\n    loggerInstance: planAndExecuteLogger,\n  });\n  workflow.addNode({ name: 'planner', action: plannerNode });\n  workflow.addNode({ name: 'executor', action: executorNode });\n  workflow.addNode({ name: 'synthesizer', action: synthesizerNode });\n  workflow.addNode({\n    name: 'error_handler',\n    action: async (state) => ({\n      finalAnswer: `Execution failed: ${\n        state.currentPipelineError || 'Unknown error.'\n      }`,\n    }),\n  });\n\n  workflow.setEntryPoint('planner');\n  workflow.addConditionalEdge({\n    sourceNode: 'planner',\n    condition: routeAfterPlannerLogic,\n    pathMap: { executor: 'executor', error_handler: 'error_handler' },\n  });\n  workflow.addConditionalEdge({\n    sourceNode: 'executor',\n    condition: routeAfterStepExecutionLogic,\n    pathMap: {\n      executor: 'executor',\n      synthesizer: 'synthesizer',\n      error_handler: 'error_handler',\n    },\n  });\n  workflow.addEdge({ sourceNode: 'synthesizer', targetNode: END });\n  workflow.addEdge({ sourceNode: 'error_handler', targetNode: END });\n\n  if (checkpointerConfig) await workflow.withPersistence(checkpointerConfig);\n  return workflow.compile();\n};\n", "// intelligence/src/intelligence/workflows/langGraphManager.js\nimport { StateGraph, END } from '@langchain/langgraph';\nimport { BaseMessage } from '@langchain/core/messages'; // For type hints if needed in state\nimport { getLogger } from '@daitanjs/development';\nimport { getConfigManager } from '@daitanjs/config';\nimport {\n  DaitanConfigurationError,\n  DaitanOperationError,\n} from '@daitanjs/error';\n\n// Checkpointer imports are dynamically handled or assumed available if specific types are used.\n// Example:\n// import { SqliteSaver } from '@langchain/langgraph/checkpoint/sqlite';\n// import { RedisSaver } from '@langchain/redis';\n// import { PostgresSaver } from '@langchain/langgraph/checkpoint/postgres';\n\nconst langGraphManagerLogger = getLogger('daitan-langgraph-manager');\n\n/**\n * @typedef {import('@langchain/core/callbacks/manager').Callbacks} Callbacks\n * @typedef {{ configurable?: Record<string, any>, callbacks?: Callbacks, recursionLimit?: number, [key: string]: any }} LangGraphRuntimeConfig\n * @typedef {import('@langchain/langgraph/checkpoint/base').BaseCheckpointSaver} BaseCheckpointSaver\n */\n\n/**\n * @template TState - The type of the graph's state object.\n * @typedef {Object} DaitanLangGraphNode\n * @property {string} name - Unique name of the node.\n * @property {(state: TState, config?: LangGraphRuntimeConfig) => Promise<Partial<TState> | typeof END | string | void | { [key:string]: any }>} action -\n *           The async function to execute for this node.\n *           It receives the current state and runtime config.\n *           It can return:\n *           - A partial state object to update the graph's state.\n *           - `END` to terminate this path of the graph.\n *           - A string value, typically used by conditional edges for routing.\n *           - `void` or `undefined` if the node only has side effects and doesn't update state directly.\n *           - An object with arbitrary keys that will be merged into the state (common pattern).\n */\n\n/**\n * @template TState - The type of the graph's state object.\n * @typedef {Object} DaitanLangGraphConditionalEdge\n * @property {string} sourceNode - Name of the source node from which this conditional edge originates.\n * @property {(state: TState) => string | Promise<string>} condition - An async function that receives the current state\n *           and must return a string. This string is then used as a key in the `pathMap`.\n * @property {Record<string, string | typeof END>} pathMap - An object mapping the string results from the `condition`\n *           function to the name of the next node or to `END`.\n */\n\n/**\n * @typedef {Object} DaitanLangGraphEdge\n * @property {string} sourceNode - Name of the source node.\n * @property {string | typeof END} targetNode - Name of the target node, or `END` to terminate the path.\n */\n\nexport class DaitanLangGraph {\n  /**\n   * @param {Object} stateSchema - An object defining the shape and update mechanism for the graph's state channels.\n   *                               This schema is passed directly to LangGraph's `StateGraph`.\n   *                               Example: `{ messages: { value: (x, y) => x.concat(y), default: () => [] } }`\n   * @param {object} [options={}]\n   * @param {import('winston').Logger} [options.loggerInstance] - Optional logger.\n   */\n  constructor(stateSchema, options = {}) {\n    this.logger = options.loggerInstance || langGraphManagerLogger;\n\n    if (\n      !stateSchema ||\n      typeof stateSchema !== 'object' ||\n      Object.keys(stateSchema).length === 0\n    ) {\n      this.logger.error(\n        'stateSchema must be a non-empty object defining the graph state structure.'\n      );\n      throw new DaitanConfigurationError(\n        'stateSchema is required for DaitanLangGraph.'\n      );\n    }\n    // LangGraph StateGraph will validate the schema structure.\n    this.graph = new StateGraph({ channels: stateSchema });\n    this.nodes = new Map();\n    this.compiledGraph = null;\n    /** @type {BaseCheckpointSaver | null} */\n    this.checkpointer = null;\n\n    this.logger.info('DaitanLangGraph initialized.');\n    this.logger.debug('State schema channels:', Object.keys(stateSchema));\n  }\n\n  /**\n   * Adds a node to the graph.\n   * @template TState\n   * @param {DaitanLangGraphNode<TState>} nodeConfig - Configuration for the node.\n   * @returns {this}\n   */\n  addNode(nodeConfig) {\n    if (\n      !nodeConfig ||\n      !nodeConfig.name ||\n      typeof nodeConfig.action !== 'function'\n    ) {\n      throw new DaitanConfigurationError(\n        'Invalid node configuration: name and action function are required.',\n        { name: nodeConfig?.name }\n      );\n    }\n    if (this.nodes.has(nodeConfig.name)) {\n      throw new DaitanConfigurationError(\n        `Node with name \"${nodeConfig.name}\" already exists.`\n      );\n    }\n\n    const wrappedAction = async (state, config) => {\n      const nodeStartTime = Date.now();\n      this.logger.debug(`Graph Node EXECUTING: \"${nodeConfig.name}\"`, {\n        threadId: config?.configurable?.thread_id,\n        stateKeys: Object.keys(state),\n      });\n      try {\n        const output = await nodeConfig.action(state, config);\n        const duration = Date.now() - nodeStartTime;\n        this.logger.debug(`Graph Node COMPLETED: \"${nodeConfig.name}\"`, {\n          threadId: config?.configurable?.thread_id,\n          outputPreview:\n            typeof output === 'string' || output === END\n              ? output\n              : output\n              ? Object.keys(output)\n              : 'void',\n          durationMs: duration,\n        });\n        return output;\n      } catch (error) {\n        const duration = Date.now() - nodeStartTime;\n        this.logger.error(\n          `Graph Node ERROR in \"${nodeConfig.name}\": ${error.message}`,\n          {\n            threadId: config?.configurable?.thread_id,\n            stateKeys: Object.keys(state),\n            // stack: error.stack, // Log full stack for dev/debug\n            durationMs: duration,\n          },\n          error\n        ); // Pass full error object to logger\n        // Propagate error to be handled by LangGraph or runtime\n        throw new DaitanOperationError(\n          `Error in graph node \"${nodeConfig.name}\": ${error.message}`,\n          { nodeName: nodeConfig.name },\n          error\n        );\n      }\n    };\n\n    this.graph.addNode(nodeConfig.name, wrappedAction);\n    this.nodes.set(nodeConfig.name, nodeConfig);\n    this.logger.debug(`Node \"${nodeConfig.name}\" added to graph definition.`);\n    return this;\n  }\n\n  setEntryPoint(nodeName) {\n    if (!this.nodes.has(nodeName)) {\n      throw new DaitanConfigurationError(\n        `Entry point node \"${nodeName}\" not found in added nodes.`\n      );\n    }\n    this.graph.setEntryPoint(nodeName);\n    this.logger.debug(`Graph entry point set to \"${nodeName}\".`);\n    return this;\n  }\n\n  setFinishPoint(nodeName) {\n    if (!this.nodes.has(nodeName)) {\n      throw new DaitanConfigurationError(\n        `Finish point node \"${nodeName}\" not found in added nodes.`\n      );\n    }\n    this.graph.addEdge(nodeName, END); // LangGraph's END sentinel\n    this.logger.debug(\n      `Node \"${nodeName}\" designated as a finish point (edge to END added).`\n    );\n    return this;\n  }\n\n  /**\n   * Adds a conditional edge to the graph.\n   * @template TState\n   * @param {DaitanLangGraphConditionalEdge<TState>} edgeConfig - Configuration for the conditional edge.\n   * @returns {this}\n   */\n  addConditionalEdge(edgeConfig) {\n    const { sourceNode, condition, pathMap } = edgeConfig;\n    if (\n      !sourceNode ||\n      typeof condition !== 'function' ||\n      typeof pathMap !== 'object' ||\n      Object.keys(pathMap).length === 0\n    ) {\n      throw new DaitanConfigurationError(\n        'Invalid conditional edge: sourceNode, condition function, and a non-empty pathMap object are required.',\n        { sourceNode }\n      );\n    }\n    if (!this.nodes.has(sourceNode)) {\n      throw new DaitanConfigurationError(\n        `Source node \"${sourceNode}\" for conditional edge not found.`\n      );\n    }\n    Object.entries(pathMap).forEach(([pathKey, targetNodeName]) => {\n      if (targetNodeName !== END && !this.nodes.has(targetNodeName)) {\n        throw new DaitanConfigurationError(\n          `Target node \"${targetNodeName}\" in pathMap (key: \"${pathKey}\") from \"${sourceNode}\" not found.`\n        );\n      }\n    });\n\n    const wrappedCondition = async (state, config) => {\n      // LangGraph passes config to conditional edges too\n      this.logger.debug(\n        `Graph Edge CONDITION EVALUATING: from \"${sourceNode}\"`,\n        {\n          threadId: config?.configurable?.thread_id,\n          stateKeys: Object.keys(state),\n        }\n      );\n      try {\n        const routeKey = await condition(state); // User's condition function\n        if (\n          typeof routeKey !== 'string' ||\n          !Object.prototype.hasOwnProperty.call(pathMap, routeKey)\n        ) {\n          this.logger.error(\n            `Conditional edge from \"${sourceNode}\" resolved to unknown route key: \"${routeKey}\". Valid keys: ${Object.keys(\n              pathMap\n            ).join(', ')}.`\n          );\n          throw new DaitanOperationError(\n            `Conditional logic from node \"${sourceNode}\" returned unmappable route: \"${routeKey}\".`\n          );\n        }\n        this.logger.debug(\n          `Graph Edge ROUTE from \"${sourceNode}\" determined: \"${routeKey}\" -> \"${\n            pathMap[routeKey] || 'END'\n          }\"`,\n          { threadId: config?.configurable?.thread_id }\n        );\n        return routeKey;\n      } catch (error) {\n        this.logger.error(\n          `Error in conditional edge logic from \"${sourceNode}\": ${error.message}`,\n          { threadId: config?.configurable?.thread_id },\n          error\n        );\n        throw new DaitanOperationError(\n          `Error in conditional edge from \"${sourceNode}\": ${error.message}`,\n          { sourceNode },\n          error\n        );\n      }\n    };\n\n    this.graph.addConditionalEdges(sourceNode, wrappedCondition, pathMap);\n    this.logger.debug(\n      `Conditional edge added from \"${sourceNode}\". PathMap keys: ${Object.keys(\n        pathMap\n      ).join(', ')}`\n    );\n    return this;\n  }\n\n  /**\n   * Adds a direct edge from a source node to a target node or to END.\n   * @param {DaitanLangGraphEdge} edgeConfig - Configuration for the edge.\n   * @returns {this}\n   */\n  addEdge(edgeConfig) {\n    const { sourceNode, targetNode } = edgeConfig;\n    if (!sourceNode || !targetNode) {\n      throw new DaitanConfigurationError(\n        'Invalid edge: sourceNode and targetNode are required.'\n      );\n    }\n    if (!this.nodes.has(sourceNode)) {\n      throw new DaitanConfigurationError(\n        `Source node \"${sourceNode}\" for edge not found.`\n      );\n    }\n    if (targetNode !== END && !this.nodes.has(targetNode)) {\n      throw new DaitanConfigurationError(\n        `Target node \"${targetNode}\" for edge not found.`\n      );\n    }\n    this.graph.addEdge(sourceNode, targetNode);\n    this.logger.debug(\n      `Edge added from \"${sourceNode}\" to \"${\n        targetNode === END ? 'END' : targetNode\n      }\".`\n    );\n    return this;\n  }\n\n  /**\n   * Configures a checkpointer for graph state persistence.\n   * @param {'memory' | BaseCheckpointSaver | { type: 'sqlite', dbPath?: string } | { type: 'redis', client: any, config?: Object } | { type: 'postgres', dbConnection: any, config?: Object } | null} checkpointerConfig\n   *        - `'memory'`: Uses an in-memory SqliteSaver (requires `sqlite3` to be installed).\n   *        - `BaseCheckpointSaver instance`: A pre-configured LangChain checkpointer.\n   *        - `Object with type`: Specifies type of checkpointer:\n   *          - `sqlite`: `dbPath` (e.g., './daitan_graph.sqlite' or ':memory:'). Requires `sqlite3`.\n   *          - `redis`: `client` (ioredis instance), `config` (RedisSaver options). Requires `@langchain/redis` & `ioredis`.\n   *          - `postgres`: `dbConnection` (pg Pool/Client), `config` (PostgresSaver options). Requires `@langchain/langgraph/checkpoint/postgres` & `pg`.\n   *        - `null`: Explicitly disables persistence.\n   * @returns {Promise<this>}\n   */\n  async withPersistence(checkpointerConfig) {\n    if (checkpointerConfig === null) {\n      this.checkpointer = null;\n      this.logger.info(\n        'Graph persistence explicitly disabled (checkpointer set to null).'\n      );\n      return this;\n    }\n    if (!checkpointerConfig) {\n      // undefined or empty object\n      this.logger.info(\n        'No checkpointer configuration provided; graph will not have persistence unless set later.'\n      );\n      this.checkpointer = null;\n      return this;\n    }\n\n    let checkpointerInstance = null;\n\n    if (\n      typeof checkpointerConfig === 'object' &&\n      checkpointerConfig.get &&\n      checkpointerConfig.put\n    ) {\n      // Duck-typing for BaseCheckpointSaver\n      checkpointerInstance = checkpointerConfig;\n      this.logger.info('Using pre-configured external checkpointer instance.');\n    } else if (\n      checkpointerConfig === 'memory' ||\n      (typeof checkpointerConfig === 'object' &&\n        checkpointerConfig.type === 'sqlite')\n    ) {\n      try {\n        const { SqliteSaver } = await import(\n          '@langchain/langgraph/checkpoint/sqlite'\n        );\n        const dbPath =\n          typeof checkpointerConfig === 'object' && checkpointerConfig.dbPath\n            ? checkpointerConfig.dbPath\n            : ':memory:';\n        checkpointerInstance = SqliteSaver.fromConnString(dbPath);\n        this.logger.info(\n          `Configured SqliteSaver checkpointer (path: \"${dbPath}\"). Ensure 'sqlite3' is installed.`\n        );\n      } catch (err) {\n        this.logger.error(\n          `Failed to initialize SqliteSaver. Ensure @langchain/langgraph and sqlite3 are installed. Error: ${err.message}`,\n          err\n        );\n        throw new DaitanConfigurationError(\n          `Failed to set up SqliteSaver: ${err.message}`,\n          { type: 'sqlite' },\n          err\n        );\n      }\n    } else if (\n      typeof checkpointerConfig === 'object' &&\n      checkpointerConfig.type === 'redis'\n    ) {\n      try {\n        const { RedisSaver } = await import('@langchain/redis');\n        if (!checkpointerConfig.client)\n          throw new Error(\n            'Redis client instance (`client`) is required for RedisSaver.'\n          );\n        checkpointerInstance = new RedisSaver({\n          client: checkpointerConfig.client,\n          ...(checkpointerConfig.config || {}),\n        });\n        this.logger.info(\n          \"Configured RedisSaver checkpointer. Ensure '@langchain/redis' and 'ioredis' are installed.\"\n        );\n      } catch (err) {\n        this.logger.error(\n          `Failed to initialize RedisSaver. Ensure @langchain/redis and ioredis are installed, and a valid client is provided. Error: ${err.message}`,\n          err\n        );\n        throw new DaitanConfigurationError(\n          `Failed to set up RedisSaver: ${err.message}`,\n          { type: 'redis' },\n          err\n        );\n      }\n    } else if (\n      typeof checkpointerConfig === 'object' &&\n      checkpointerConfig.type === 'postgres'\n    ) {\n      try {\n        const { PostgresSaver } = await import(\n          '@langchain/langgraph/checkpoint/postgres'\n        );\n        if (!checkpointerConfig.dbConnection)\n          throw new Error(\n            'PostgreSQL connection (`dbConnection` as pg.Pool or pg.Client) is required for PostgresSaver.'\n          );\n        checkpointerInstance = new PostgresSaver({\n          dbConnection: checkpointerConfig.dbConnection,\n          ...(checkpointerConfig.config || {}),\n        });\n        this.logger.info(\n          \"Configured PostgresSaver checkpointer. Ensure '@langchain/langgraph/checkpoint/postgres' and 'pg' are installed.\"\n        );\n      } catch (err) {\n        this.logger.error(\n          `Failed to initialize PostgresSaver. Ensure a pg Pool/Client is provided and 'pg' package is installed. Error: ${err.message}`,\n          err\n        );\n        throw new DaitanConfigurationError(\n          `Failed to set up PostgresSaver: ${err.message}`,\n          { type: 'postgres' },\n          err\n        );\n      }\n    } else {\n      this.logger.error(\n        'Invalid or unsupported checkpointer configuration provided.',\n        { checkpointerConfig }\n      );\n      throw new DaitanConfigurationError('Invalid checkpointer configuration.');\n    }\n\n    this.checkpointer = checkpointerInstance;\n    return this;\n  }\n\n  compile(compileOptions = {}) {\n    const configManager = getConfigManager(); // Lazy-load\n    const { debug: compileDebug, interruptions } = compileOptions;\n    const effectiveDebug =\n      compileDebug !== undefined\n        ? compileDebug\n        : configManager.get('DEBUG_LANGGRAPH_COMPILE', false);\n\n    const compileArgs = {};\n    if (this.checkpointer) {\n      compileArgs.checkpointer = this.checkpointer;\n      this.logger.info('Compiling graph with persistence enabled.');\n    } else {\n      this.logger.warn(\n        'Compiling graph without a checkpointer. State will not persist across runs for the same thread_id.'\n      );\n    }\n\n    if (\n      interruptions &&\n      Array.isArray(interruptions) &&\n      interruptions.length > 0\n    ) {\n      const interruptBefore = [];\n      const interruptAfter = [];\n      interruptions.forEach((intr) => {\n        if (typeof intr === 'string') interruptBefore.push(intr);\n        // Default to interruptBefore if just a string\n        else if (typeof intr === 'object' && intr.before)\n          interruptBefore.push(intr.before);\n        else if (typeof intr === 'object' && intr.after)\n          interruptAfter.push(intr.after);\n      });\n      if (interruptBefore.length > 0)\n        compileArgs.interruptBefore = interruptBefore;\n      if (interruptAfter.length > 0)\n        compileArgs.interruptAfter = interruptAfter;\n      if (interruptBefore.length > 0 || interruptAfter.length > 0) {\n        this.logger.info('Graph compilation will include interruptions:', {\n          before: interruptBefore,\n          after: interruptAfter,\n        });\n      }\n    }\n    // LangSmith tracing for compiled graphs is typically enabled via environment variables (LANGCHAIN_TRACING_V2, etc.)\n    // or by wrapping the invoke/stream calls with `traceable` from `langsmith/traceable`.\n\n    try {\n      this.compiledGraph = this.graph.compile(compileArgs);\n      this.logger.info('DaitanLangGraph compiled successfully.');\n      if (effectiveDebug) {\n        this.logger.debug('Graph compilation arguments used:', compileArgs);\n        this.logger.debug(\n          'Nodes defined in graph:',\n          Array.from(this.nodes.keys())\n        );\n        // For more detailed graph structure, one might inspect this.graph.nodes, this.graph.edges, etc.\n        // but the compiled graph itself is opaque. `getGraph().printMermaid()` is useful on the StateGraph instance.\n      }\n    } catch (compileError) {\n      this.logger.error(\n        'DaitanLangGraph compilation FAILED.',\n        {\n          error: compileError.message,\n          // stack: compileError.stack, // Log full stack for dev/debug\n          compileArgs,\n        },\n        compileError\n      );\n      throw new DaitanOperationError(\n        `Graph compilation failed: ${compileError.message}`,\n        { compileArgs },\n        compileError\n      );\n    }\n    return this.compiledGraph;\n  }\n\n  getCompiledGraph() {\n    if (!this.compiledGraph) {\n      this.logger.error(\n        'Graph has not been compiled yet. Call .compile() method first.'\n      );\n      throw new DaitanOperationError(\n        'Graph not compiled. Call .compile() first.'\n      );\n    }\n    return this.compiledGraph;\n  }\n\n  /**\n   * Prints a Mermaid diagram representation of the defined graph structure (before compilation).\n   * Useful for visualizing the graph.\n   * @returns {string} Mermaid diagram string.\n   */\n  getMermaidDiagram() {\n    if (this.graph && typeof this.graph.getGraph === 'function') {\n      // getGraph().printMermaid() is a method on the underlying Graph representation\n      // It might require access to the internal graph structure of StateGraph or a similar utility.\n      // LangGraph's StateGraph itself has a .drawMermaid() method.\n      try {\n        return this.graph.drawMermaid();\n      } catch (e) {\n        this.logger.warn(\n          `Could not generate Mermaid diagram: ${e.message}. This feature might depend on specific LangGraph version capabilities.`\n        );\n        return 'Error generating Mermaid diagram.';\n      }\n    }\n    this.logger.warn(\n      'Graph instance not available or getGraph method missing for Mermaid diagram generation.'\n    );\n    return 'Mermaid diagram not available.';\n  }\n}\n\n/**\n * Helper function to create a basic state schema suitable for many chat agent graphs.\n * Includes channels for 'messages' (accumulates), 'input' (takes last), and 'errors' (accumulates).\n * @returns {Object} A state schema object for `DaitanLangGraph` or `StateGraph`.\n */\nexport const createChatAgentState = () => ({\n  messages: {\n    value: (x, y) => (x || []).concat(y || []), // Append new messages\n    default: () => [], // Default to an empty array\n  },\n  input: {\n    // To store the latest user input or intermediate inputs\n    value: (x, y) => y, // Always take the last written value\n    default: () => null,\n  },\n  errors: {\n    // For nodes to report non-fatal errors or warnings\n    value: (x, y) => {\n      const currentErrors = x || [];\n      if (Array.isArray(y))\n        return currentErrors.concat(y.map((e) => String(e)));\n      if (y) return [...currentErrors, String(y)];\n      return currentErrors;\n    },\n    default: () => [],\n  },\n  // Example of other common state fields for agents:\n  // agent_scratchpad: {\n  //   value: (x, y) => typeof y === 'string' ? (x || \"\") + \"\\n\" + y : x, // Append strings, good for thoughts\n  //   default: () => \"\",\n  // },\n  // current_tool_calls: {\n  //    value: (x,y) => y, // Stores tool calls from LLM for the tool execution node\n  //    default: () => [],\n  // }\n});\n", "// intelligence/src/intelligence/workflows/reactWithReflectionAgentGraph.js\nimport { END } from '@langchain/langgraph';\nimport { HumanMessage, AIMessage, ToolMessage } from '@langchain/core/messages';\nimport { getLogger } from '@daitanjs/development';\nimport { DaitanLangGraph } from './langGraphManager.js';\nimport { LLMService } from '../../services/llmService.js';\nimport {\n  DaitanConfigurationError,\n  DaitanOperationError,\n} from '@daitanjs/error';\n\nconst reactGraphLogger = getLogger('daitan-react-reflection-graph');\n\n/**\n * @typedef {import('../../services/llmService.js').LLMUsageInfo} LLMUsageInfo\n * @typedef {import('@langchain/core/tools').BaseTool} LangChainBaseTool\n * @typedef {import('@langchain/core/messages').BaseMessage} BaseMessage\n * @typedef {Object} AgentGraphAction @property {string} tool @property {any} toolInput @property {string} log @property {string} [actionId]\n * @typedef {Object} ReActAgentState @property {HumanMessage | null} inputMessage @property {string} originalQuery @property {BaseMessage[]} messages @property {string} currentThought @property {AgentGraphAction | null} lastAction @property {string | null} lastObservation @property {string | null} lastReflection @property {number} iterationCount @property {string | null} finalAnswer @property {string | null} currentPipelineError @property {LLMService} llmServiceInstance @property {Record<string, LangChainBaseTool>} toolsMap @property {import('../../services/llmService.js').LLMServiceConfig} [reasonerLlmConfig] @property {import('../../services/llmService.js').LLMServiceConfig} [reflectorLlmConfig] @property {LLMUsageInfo[]} llmUsages @property {number} maxIterations @property {boolean} verbose\n */\nexport const reactAgentStateSchema = {\n  inputMessage: { value: (x, y) => y ?? x, default: () => null },\n  originalQuery: { value: (x, y) => y ?? x, default: () => '' },\n  messages: { value: (x, y) => (x || []).concat(y || []), default: () => [] },\n  currentThought: { value: (x, y) => y ?? x, default: () => '' },\n  lastAction: { value: (x, y) => y ?? x, default: () => null },\n  lastObservation: { value: (x, y) => y ?? x, default: () => null },\n  lastReflection: { value: (x, y) => y ?? x, default: () => null },\n  iterationCount: { value: (x, y) => y ?? x, default: () => 0 },\n  finalAnswer: { value: (x, y) => y ?? x, default: () => null },\n  currentPipelineError: { value: (x, y) => y ?? x, default: () => null },\n  llmServiceInstance: { value: (x, y) => y ?? x, default: () => null },\n  toolsMap: { value: (x, y) => y ?? x, default: () => ({}) },\n  reasonerLlmConfig: { value: (x, y) => y ?? x, default: () => ({}) },\n  reflectorLlmConfig: { value: (x, y) => y ?? x, default: () => ({}) },\n  llmUsages: { value: (x, y) => (x || []).concat(y || []), default: () => [] },\n  maxIterations: { value: (x, y) => y ?? x, default: () => 10 },\n  verbose: { value: (x, y) => y ?? x, default: () => false },\n};\n\n// --- Node Definitions ---\n\nconst reasonerNode = async (state) => {\n  const {\n    messages,\n    llmServiceInstance,\n    toolsMap,\n    reasonerLlmConfig,\n    originalQuery,\n    iterationCount,\n    lastObservation,\n    lastReflection,\n    llmUsages,\n    verbose,\n  } = state;\n\n  const toolDescriptions = Object.values(toolsMap)\n    .map((t) => `- ${t.name}: ${String(t.description).split('\\n')[0]}`)\n    .join('\\n');\n  let reactHistoryContext = '';\n  if (state.lastAction)\n    reactHistoryContext += `Previous Action: Tool: ${\n      state.lastAction.tool\n    }, Input: ${JSON.stringify(state.lastAction.toolInput)}\\n`;\n  if (lastObservation)\n    reactHistoryContext += `Previous Observation: ${String(\n      lastObservation\n    ).substring(0, 500)}...\\n`;\n  if (lastReflection)\n    reactHistoryContext += `Previous Reflection: ${lastReflection}\\n`;\n\n  const systemPrompt = {\n    persona: `You are a ReAct-style AI assistant trying to answer: \"${originalQuery}\". You are in the THOUGHT and ACTION phase.`,\n    task: `Based on the history and reflection, decide your next step. Your response MUST be a valid JSON object with ONE of two structures: 1. To use a tool: {\"thought\": \"reasoning\", \"action\": { \"tool\": \"tool_name\", \"toolInput\": \"input\" }} 2. To answer: {\"thought\": \"reasoning\", \"finalAnswer\": \"your answer\"}`,\n  };\n  const userPrompt = `Available tools:\\n${\n    toolDescriptions || 'No tools.'\n  }\\n\\n${reactHistoryContext}Current Conversation History:\\n${messages\n    .slice(-6)\n    .map((m) => `${m._getType()}: ${String(m.content).substring(0, 200)}...`)\n    .join('\\n')}\\n\\nProvide your decision as a JSON object.`;\n\n  try {\n    const { response: decision, usage } = await llmServiceInstance.generate({\n      prompt: { system: systemPrompt, user: userPrompt },\n      config: {\n        response: { format: 'json' },\n        llm: {\n          target: reasonerLlmConfig?.target || 'MASTER_COMMUNICATOR',\n          temperature: reasonerLlmConfig?.temperature ?? 0.0,\n        },\n        verbose,\n      },\n    });\n    const newLlmUsages = usage\n      ? llmUsages.concat({ step: `reasoner_iter_${iterationCount}`, ...usage })\n      : llmUsages;\n    if (decision.finalAnswer) {\n      return {\n        finalAnswer: decision.finalAnswer,\n        currentThought: decision.thought,\n        lastAction: null,\n        messages: messages.concat(\n          new AIMessage({\n            content: `Thought: ${decision.thought}\\nFinal Answer: ${decision.finalAnswer}`,\n          })\n        ),\n        llmUsages: newLlmUsages,\n      };\n    } else if (decision.action?.tool) {\n      return {\n        currentThought: decision.thought,\n        lastAction: {\n          ...decision.action,\n          actionId: `tool_call_${iterationCount}`,\n        },\n        messages: messages.concat(\n          new AIMessage({ content: `Thought: ${decision.thought}` })\n        ),\n        llmUsages: newLlmUsages,\n      };\n    }\n    return {\n      currentPipelineError:\n        'Reasoner did not produce a valid action or final answer.',\n      llmUsages: newLlmUsages,\n    };\n  } catch (error) {\n    return {\n      currentPipelineError: `Reasoner error: ${error.message}`,\n      llmUsages,\n    };\n  }\n};\n\nconst actionExecutorNode = async (state) => {\n  const { lastAction, toolsMap, messages } = state;\n  if (!lastAction?.tool)\n    return {\n      lastObservation: 'Error: No action specified.',\n      messages,\n      currentPipelineError: 'No action specified.',\n    };\n  const toolToUse = toolsMap[lastAction.tool];\n  if (!toolToUse) {\n    const errorMsg = `Tool \"${lastAction.tool}\" not found.`;\n    return {\n      lastObservation: `Error: ${errorMsg}`,\n      messages: messages.concat(\n        new ToolMessage({\n          tool_call_id: lastAction.actionId,\n          content: `Error: ${errorMsg}`,\n        })\n      ),\n      currentPipelineError: errorMsg,\n    };\n  }\n  try {\n    const toolOutput = await toolToUse.call(lastAction.toolInput);\n    return {\n      lastObservation: String(toolOutput),\n      messages: messages.concat(\n        new ToolMessage({\n          tool_call_id: lastAction.actionId,\n          content: String(toolOutput),\n        })\n      ),\n    };\n  } catch (error) {\n    const errorMsg = `Error executing tool ${lastAction.tool}: ${error.message}`;\n    return {\n      lastObservation: errorMsg,\n      messages: messages.concat(\n        new ToolMessage({\n          tool_call_id: lastAction.actionId,\n          content: errorMsg,\n        })\n      ),\n      currentPipelineError: errorMsg,\n    };\n  }\n};\n\nconst reflectorNode = async (state) => {\n  const {\n    messages,\n    llmServiceInstance,\n    originalQuery,\n    currentThought,\n    lastAction,\n    lastObservation,\n    iterationCount,\n    reflectorLlmConfig,\n    llmUsages,\n    verbose,\n  } = state;\n  const userPrompt = `Query: \"${originalQuery}\"\\nThought: \"${\n    currentThought || 'N/A'\n  }\"\\nAction: Tool \"${lastAction?.tool}\", Input: ${JSON.stringify(\n    lastAction?.toolInput\n  )}\\nObservation: \"${String(lastObservation).substring(\n    0,\n    1000\n  )}...\"\\n\\nCritique this process and suggest a change for the next step if needed. If all is well, say \"Proceeding.\"`;\n\n  try {\n    const { response: reflection, usage } = await llmServiceInstance.generate({\n      prompt: {\n        system: { persona: 'You are a self-critiquing AI assistant.' },\n        user: userPrompt,\n      },\n      config: {\n        response: { format: 'text' },\n        llm: {\n          target: reflectorLlmConfig?.target || 'FAST_TASKER',\n          temperature: reflectorLlmConfig?.temperature ?? 0.1,\n        },\n        verbose,\n      },\n    });\n    const newLlmUsages = usage\n      ? llmUsages.concat({ step: `reflector_iter_${iterationCount}`, ...usage })\n      : llmUsages;\n    return {\n      lastReflection: String(reflection),\n      messages: messages.concat(\n        new AIMessage({ content: `Reflection: ${reflection}` })\n      ),\n      llmUsages: newLlmUsages,\n      iterationCount: iterationCount + 1,\n    };\n  } catch (error) {\n    const errorMsg = `Reflection error: ${error.message}`;\n    return {\n      lastReflection: errorMsg,\n      messages: messages.concat(new AIMessage({ content: errorMsg })),\n      llmUsages,\n      iterationCount: iterationCount + 1,\n    };\n  }\n};\n\nconst routeAfterReasonerLogic = (state) =>\n  state.currentPipelineError\n    ? 'error_handler'\n    : state.finalAnswer\n    ? END\n    : 'action_executor';\nconst routeAfterReflectionLogic = (state) =>\n  state.iterationCount >= state.maxIterations ? 'error_handler' : 'reasoner';\n\nexport const createReActAgentGraph = async (\n  llmServiceInstance,\n  tools,\n  checkpointerConfig\n) => {\n  if (!(llmServiceInstance instanceof LLMService))\n    throw new DaitanConfigurationError(\n      'An instance of LLMService is required.'\n    );\n\n  const workflow = new DaitanLangGraph(reactAgentStateSchema, {\n    loggerInstance: reactGraphLogger,\n  });\n  workflow.addNode({ name: 'reasoner', action: reasonerNode });\n  workflow.addNode({ name: 'action_executor', action: actionExecutorNode });\n  workflow.addNode({ name: 'reflector', action: reflectorNode });\n  workflow.addNode({\n    name: 'error_handler',\n    action: async (state) => ({\n      finalAnswer: `Execution failed: ${\n        state.currentPipelineError || `Max iterations reached.`\n      }`,\n    }),\n  });\n\n  workflow.setEntryPoint('reasoner');\n  workflow.addConditionalEdge({\n    sourceNode: 'reasoner',\n    condition: routeAfterReasonerLogic,\n    pathMap: {\n      action_executor: 'action_executor',\n      error_handler: 'error_handler',\n      [END]: END,\n    },\n  });\n  workflow.addEdge({ sourceNode: 'action_executor', targetNode: 'reflector' });\n  workflow.addConditionalEdge({\n    sourceNode: 'reflector',\n    condition: routeAfterReflectionLogic,\n    pathMap: { reasoner: 'reasoner', error_handler: 'error_handler' },\n  });\n  workflow.addEdge({ sourceNode: 'error_handler', targetNode: END });\n\n  if (checkpointerConfig) await workflow.withPersistence(checkpointerConfig);\n  return workflow.compile();\n};\n", "// intelligence/src/intelligence/agents/agentExecutor.js\n/**\n * @file Provides a wrapper for running LangChain's AgentExecutor.\n * @module @daitanjs/intelligence/agents/agentExecutor\n */\nimport { AgentExecutor, createOpenAIToolsAgent } from 'langchain/agents';\nimport {\n  ChatPromptTemplate,\n  MessagesPlaceholder,\n} from '@langchain/core/prompts';\nimport { RunnableWithMessageHistory } from '@langchain/core/runnables';\nimport { BaseTool } from '../tools/baseTool.js';\n// --- DEFINITIVE FIX: REMOVE a dependency on the broken providerConfigs.js ---\n// import { resolveProviderConfig } from '../core/providerConfigs.js';\nimport { getLogger } from '@daitanjs/development';\nimport { getConfigManager } from '@daitanjs/config';\nimport { OPENAI_TOOLS_AGENT_SYSTEM_MESSAGE } from './prompts/index.js';\nimport { InMemoryChatMessageHistoryStore } from '../../memory/inMemoryChatHistoryStore.js';\nimport {\n  DaitanConfigurationError,\n  DaitanOperationError,\n} from '@daitanjs/error';\nimport { BaseCallbackHandler } from '@langchain/core/callbacks/base';\nimport chalk from 'chalk';\n// --- DEFINITIVE FIX: Import LLM classes directly ---\nimport { ChatOpenAI } from '@langchain/openai';\nimport { getExpertModelDefinition } from '../core/expertModels.js';\n\nconst agentExecutorLogger = getLogger('daitan-agent-executor');\n\nclass ConciseAgentLogHandler extends BaseCallbackHandler {\n  name = 'ConciseAgentLogHandler';\n\n  handleToolStart(tool, input) {\n    const toolInput = typeof input === 'string' ? input : JSON.stringify(input);\n    console.log(\n      chalk.gray(\n        `  \u27A1\uFE0F  Agent decided to use Tool: ${chalk.bold(\n          tool.name\n        )} with input \"${toolInput}\"`\n      )\n    );\n  }\n\n  handleToolEnd(output) {\n    const preview =\n      output.length > 250 ? `${output.substring(0, 250)}...` : output;\n    console.log(chalk.gray(`  \u2B05\uFE0F  Tool returned: \"${preview}\"`));\n  }\n}\n\n// A default, singleton in-memory store for convenience if no store is provided.\nconst defaultHistoryStore = new InMemoryChatMessageHistoryStore();\n\nexport const runToolCallingAgent = async ({\n  input,\n  tools,\n  agentSystemMessage = OPENAI_TOOLS_AGENT_SYSTEM_MESSAGE,\n  llmProviderOrExpert,\n  sessionId,\n  historyStore = defaultHistoryStore, // Use the singleton default\n  verbose: callSpecificVerbose,\n  customHandlers,\n  trace: callSpecificTrace,\n  maxIterations: callSpecificMaxIterations,\n  returnIntermediateSteps: callSpecificReturnIntermediateSteps,\n  llmConfig = {},\n  requestTimeout,\n}) => {\n  const configManager = getConfigManager();\n  const effectiveSessionId = sessionId || `daitan-agent-session-${Date.now()}`;\n  const effectiveVerbose =\n    callSpecificVerbose ?? configManager.get('DEBUG_AGENT', false);\n  const effectiveMaxIterations =\n    callSpecificMaxIterations ?? configManager.get('AGENT_MAX_ITERATIONS', 15);\n  const effectiveReturnIntermediateSteps =\n    callSpecificReturnIntermediateSteps ?? effectiveVerbose;\n\n  if (\n    !historyStore ||\n    typeof historyStore.getHistory !== 'function' ||\n    typeof historyStore.clear !== 'function'\n  ) {\n    throw new DaitanConfigurationError(\n      'The provided `historyStore` does not adhere to the IChatMessageHistoryStore interface (missing getHistory or clear methods).'\n    );\n  }\n\n  // --- DEFINITIVE FIX: Replace resolveProviderConfig with direct instantiation ---\n  let llm;\n  try {\n    const target =\n      llmProviderOrExpert ||\n      configManager.get('LLM_PROVIDER_AGENT') ||\n      'FAST_TASKER';\n    const expertDef = getExpertModelDefinition(target);\n\n    let provider, model, temperature;\n\n    if (expertDef) {\n      provider = expertDef.provider;\n      model = expertDef.model;\n      temperature = expertDef.temperature;\n    } else {\n      const [p, m] = target.split('|');\n      provider = p;\n      model = m;\n    }\n\n    if (provider.toLowerCase() !== 'openai') {\n      throw new DaitanConfigurationError(\n        `runToolCallingAgent currently only supports the 'openai' provider for its LLM.`\n      );\n    }\n\n    const apiKey = configManager.get('OPENAI_API_KEY');\n    if (!apiKey) {\n      throw new DaitanConfigurationError(\n        'runToolCallingAgent requires OPENAI_API_KEY to be set.'\n      );\n    }\n\n    llm = new ChatOpenAI({\n      apiKey,\n      modelName: model || 'gpt-4o-mini',\n      temperature: temperature ?? llmConfig.temperature ?? 0.7,\n      maxRetries: 2,\n      timeout: requestTimeout,\n    });\n  } catch (e) {\n    throw new DaitanConfigurationError(\n      `Failed to configure LLM for agent: ${e.message}`,\n      {},\n      e\n    );\n  }\n  // --- End of new logic ---\n\n  const llmWithTools = llm.bindTools(tools);\n\n  const prompt = ChatPromptTemplate.fromMessages([\n    ['system', agentSystemMessage],\n    new MessagesPlaceholder('chat_history'),\n    ['human', '{input}'],\n    new MessagesPlaceholder('agent_scratchpad'),\n  ]);\n\n  const agent = await createOpenAIToolsAgent({\n    llm: llmWithTools,\n    tools,\n    prompt,\n  });\n\n  const agentExecutor = new AgentExecutor({\n    agent,\n    tools,\n    verbose: false,\n    returnIntermediateSteps: effectiveReturnIntermediateSteps,\n    maxIterations: effectiveMaxIterations,\n  });\n\n  const agentWithHistory = new RunnableWithMessageHistory({\n    runnable: agentExecutor,\n    getMessageHistory: (sessionId) => historyStore.getHistory(sessionId),\n    inputMessagesKey: 'input',\n    historyMessagesKey: 'chat_history',\n  });\n\n  try {\n    agentExecutorLogger.info(\n      `Starting agent run for session ${effectiveSessionId}`\n    );\n\n    const handlers = customHandlers ? [customHandlers] : [];\n    if (effectiveVerbose) {\n      handlers.push(new ConciseAgentLogHandler());\n    }\n\n    const result = await agentWithHistory.invoke(\n      { input: input },\n      {\n        configurable: { sessionId: effectiveSessionId },\n        callbacks: handlers.length > 0 ? handlers : undefined,\n      }\n    );\n\n    agentExecutorLogger.info(\n      `Agent run SUCCEEDED for session ${effectiveSessionId}.`\n    );\n    return result;\n  } catch (error) {\n    agentExecutorLogger.error(\n      `Agent run FAILED for session ${effectiveSessionId}: ${error.message}`,\n      { error: error.stack }\n    );\n    throw new DaitanOperationError(\n      `Agent execution failed: ${error.message}`,\n      { sessionId: effectiveSessionId },\n      error\n    );\n  }\n};\n", "// File: src/intelligence/agents/prompts/generalAgentPrompt.js\nimport { PromptTemplate } from '@langchain/core/prompts';\n\n// This prompt is a starting point and inspired by common LangChain agent prompts.\n// It needs to instruct the LLM on how to use tools and format its thoughts/actions.\n// The exact format depends on the agent type LangChain will use (e.g., ReAct, OpenAI Functions).\n// For OpenAI Functions/Tools agent, the \"tool_names\" and \"tools\" might be handled differently\n// (the model itself lists the tools it can call).\n// For ReAct, it's more explicit.\n\n// This is a simplified ReAct-style prompt template.\n// You might need to adjust this based on the specific LangChain agent type you build.\nexport const GENERAL_AGENT_SYSTEM_PROMPT_TEMPLATE = `\nYou are a helpful and intelligent assistant. Your goal is to assist the user with their tasks by reasoning, planning, and using available tools when necessary.\n\nTOOLS:\n------\nYou have access to the following tools:\n\n{tools}\n\nTo use a tool, you MUST use the following format in your thought process:\n\nThought: Do I need to use a tool? Yes\nAction: The action to take. Must be one of [{tool_names}].\nAction Input: The input to the tool.\nObservation: [Wait for the result of the Action]\n\nWhen you have the result from the Observation, you can continue with another Thought, Action, Action Input, Observation cycle, or if you have enough information to answer the user's request, respond directly.\n\nIf you can answer the user's request without using a tool, or after using tools you have the final answer, respond in the following format:\n\nThought: Do I need to use a tool? No\nFinal Answer: [Your comprehensive answer to the user's original request]\n\nBegin!\n\nPREVIOUS CONVERSATION HISTORY (if any):\n{chat_history}\n\nNEW USER INPUT:\n{input}\n\nYOUR THOUGHT PROCESS AND FINAL ANSWER:\n{agent_scratchpad}\n`;\n\nexport const generalAgentPromptTemplate = PromptTemplate.fromTemplate(\n  GENERAL_AGENT_SYSTEM_PROMPT_TEMPLATE\n);\n\n// Note: For OpenAI Functions/Tools agents, the prompt is simpler as the model handles tool invocation format.\n// Example for OpenAI Tools Agent (conceptual, would be used with `createOpenAIToolsAgent`):\nexport const OPENAI_TOOLS_AGENT_SYSTEM_MESSAGE = `\nYou are a helpful assistant. You have access to the following tools.\nOnly use a tool if you cannot answer the user's request directly with your existing knowledge.\nWhen you have a final answer, provide it directly.\n`;\n", "// src/memory/inMemoryChatHistoryStore.js\n/**\n * @file In-memory implementation of the chat message history store.\n * @module @daitanjs/intelligence/memory/inMemoryChatHistoryStore\n *\n * @description\n * This module provides an in-memory chat history store, which is suitable for\n * development, testing, or single-process applications. It holds session histories\n * in a simple JavaScript Map.\n *\n * NOTE: This implementation is not suitable for production environments that are\n * stateless (e.g., serverless functions) or run on multiple instances (e.g.,\n * load-balanced servers), as each instance would have its own separate memory.\n * For production, a persistent store like Redis or a database should be used.\n * @implements {import('./iChatMessageHistoryStore.js').IChatMessageHistoryStore}\n */\nimport { ChatMessageHistory } from 'langchain/memory';\nimport { getLogger } from '@daitanjs/development';\n\nconst logger = getLogger('daitan-in-memory-history');\n\nexport class InMemoryChatMessageHistoryStore {\n  constructor() {\n    /**\n     * @private\n     * @type {Map<string, ChatMessageHistory>}\n     */\n    this.histories = new Map();\n    logger.info('InMemoryChatMessageHistoryStore initialized.');\n  }\n\n  /**\n   * Retrieves the LangChain chat history object for a given session ID.\n   * If a history for the session does not exist, it is created.\n   *\n   * @param {string} sessionId - The unique identifier for the conversation session.\n   * @returns {Promise<ChatMessageHistory>} A promise that resolves to a `ChatMessageHistory` instance.\n   */\n  async getHistory(sessionId) {\n    if (!this.histories.has(sessionId)) {\n      logger.debug(\n        `Creating new in-memory ChatMessageHistory for session: ${sessionId}`\n      );\n      this.histories.set(sessionId, new ChatMessageHistory());\n    }\n    return this.histories.get(sessionId);\n  }\n\n  /**\n   * Clears the chat history for a specific session.\n   *\n   * @param {string} sessionId - The unique identifier for the session to clear.\n   * @returns {Promise<void>}\n   */\n  async clear(sessionId) {\n    if (this.histories.has(sessionId)) {\n      this.histories.delete(sessionId);\n      logger.info(`Cleared in-memory history for session: ${sessionId}`);\n    } else {\n      logger.debug(\n        `Attempted to clear non-existent in-memory history for session: ${sessionId}`\n      );\n    }\n  }\n\n  /**\n   * Clears all chat histories managed by the store.\n   * @returns {Promise<void>}\n   */\n  async clearAll() {\n    const sessionCount = this.histories.size;\n    this.histories.clear();\n    logger.info(`Cleared all ${sessionCount} in-memory session histories.`);\n  }\n\n  /**\n   * A convenience method for development to see all session IDs currently in memory.\n   * @returns {string[]} An array of session IDs.\n   */\n  getAllSessionIds() {\n    return Array.from(this.histories.keys());\n  }\n}\n", "// intelligence/src/intelligence/agents/baseAgent.js\nimport { getLogger } from '@daitanjs/development';\nimport { LLMService } from '../../services/llmService.js';\nimport {\n  DaitanConfigurationError,\n  DaitanOperationError,\n} from '@daitanjs/error';\n\nconst baseAgentLogger = getLogger('daitan-base-agent');\n\n/**\n * @typedef {import('../../services/llmService.js').LLMUsageInfo} LLMUsageInfo\n * @typedef {import('../tools/toolInterface.js').ITool} DaitanITool\n * @typedef {import('@langchain/core/tools').Tool} LangChainTool\n */\n\n/**\n * @typedef {Object} AgentContext\n * Provides context for a DaitanJS custom agent's operation.\n * This is a generic context; specific agent implementations may extend it.\n *\n * @property {LLMService} llmService - An instance of LLMService for the agent to use.\n * @property {any} [payload] - Any primary input data or payload for the agent's task.\n * @property {Record<string, DaitanITool | LangChainTool>} [tools] - Available tools for the agent, keyed by name.\n * @property {object} [config] - Agent-specific runtime configuration options.\n * @property {string} [callId] - An optional unique identifier for the agent's current run/invocation.\n */\n\n/**\n * @typedef {Object} AgentResponse\n * Represents the output of a DaitanJS custom agent's action.\n *\n * @property {any} output - The primary output of the agent (e.g., a string, a JSON object, structured data).\n * @property {string} [summary] - A brief summary of the agent's action or decision.\n * @property {LLMUsageInfo | null} [llmUsage] - LLM usage information if the agent directly used an LLM.\n * @property {any} [rawLLMResponse] - The raw response from the LLM, if applicable and needed for debugging.\n * @property {string | null} [error] - Error message string if the agent encountered an issue.\n * @property {boolean} success - True if the agent completed its task successfully, false otherwise.\n * @property {object} [nextStateChanges] - Suggested changes to a larger state or context, if applicable (e.g., for workflow integration).\n */\n\n/**\n * Abstract base class for custom DaitanJS agents.\n * This class provides a common structure for agents that might not use\n * LangChain's AgentExecutor or LangGraph directly, but still require access\n * to LLM services and tools.\n */\nexport class BaseAgent {\n  /**\n   * The unique name of the agent.\n   * @type {string}\n   */\n  name;\n\n  /**\n   * A brief description of what the agent does.\n   * @type {string}\n   */\n  description;\n\n  /**\n   * An instance of LLMService.\n   * @type {LLMService}\n   * @protected\n   */\n  llmService;\n\n  /**\n   * Available tools for the agent.\n   * @type {Record<string, DaitanITool | LangChainTool>}\n   * @protected\n   */\n  tools;\n\n  /**\n   * Logger instance for this agent.\n   * @type {import('winston').Logger}\n   * @protected\n   */\n  logger;\n\n  /**\n   * @param {string} name - The unique name of the agent.\n   * @param {string} description - A brief description of what the agent does.\n   * @param {LLMService} llmServiceInstance - An instance of LLMService.\n   * @param {Record<string, DaitanITool | LangChainTool>} [toolsMap={}] - Available tools, keyed by name.\n   * @throws {DaitanConfigurationError} If name, description, or llmServiceInstance is invalid.\n   */\n  constructor(name, description, llmServiceInstance, toolsMap = {}) {\n    if (!name || typeof name !== 'string' || !name.trim()) {\n      throw new DaitanConfigurationError(\n        'Agent name must be a non-empty string.'\n      );\n    }\n    if (\n      !description ||\n      typeof description !== 'string' ||\n      !description.trim()\n    ) {\n      throw new DaitanConfigurationError(\n        'Agent description must be a non-empty string.'\n      );\n    }\n    if (!(llmServiceInstance instanceof LLMService)) {\n      throw new DaitanConfigurationError(\n        'An instance of LLMService must be provided to BaseAgent.'\n      );\n    }\n\n    this.name = name;\n    this.description = description;\n    this.llmService = llmServiceInstance;\n    this.tools = toolsMap;\n    this.logger = getLogger(`daitan-agent-${this.name}`); // Agent-specific logger\n\n    this.logger.info(`Agent \"${this.name}\" initialized.`);\n    if (Object.keys(this.tools).length > 0) {\n      this.logger.debug(\n        `Agent \"${this.name}\" initialized with tools:`,\n        Object.keys(this.tools)\n      );\n    }\n  }\n\n  /**\n   * The main method for an agent to perform its action based on the given context.\n   * This method MUST be implemented by subclasses.\n   *\n   * @abstract\n   * @param {AgentContext} context - The context for the agent's operation.\n   * @returns {Promise<AgentResponse>} The result of the agent's action.\n   */\n  async run(context) {\n    this.logger.error(\n      `Agent \"${this.name}\": run(context) method not implemented. Subclasses must override this method.`,\n      { contextPayloadKeys: Object.keys(context?.payload || {}) }\n    );\n    throw new DaitanOperationError(\n      'Method \"run(context)\" not implemented by agent subclass.',\n      { agentName: this.name }\n    );\n  }\n\n  /**\n   * Utility to create a standard success response for this agent.\n   * @param {any} output - The primary output of the agent.\n   * @param {string} [summary] - Summary of the action.\n   * @param {LLMUsageInfo | null} [llmUsage=null] - LLM usage details, if any.\n   * @param {any} [rawLLMResponse] - Raw LLM response, if applicable.\n   * @param {object} [nextStateChanges] - Suggested state changes.\n   * @returns {AgentResponse}\n   */\n  createSuccessResponse(\n    output,\n    summary,\n    llmUsage = null,\n    rawLLMResponse = undefined,\n    nextStateChanges = undefined\n  ) {\n    return {\n      output,\n      summary:\n        summary || `Agent \"${this.name}\" completed its task successfully.`,\n      llmUsage,\n      rawLLMResponse,\n      error: null,\n      success: true,\n      nextStateChanges,\n    };\n  }\n\n  /**\n   * Utility to create a standard error response for this agent.\n   * @param {string} errorMessage - The error message.\n   * @param {string} [summary] - Summary of the error situation.\n   * @param {any} [output=null] - Any partial output that might still be relevant.\n   * @returns {AgentResponse}\n   */\n  createErrorResponse(errorMessage, summary, output = null) {\n    return {\n      output,\n      summary: summary || `Agent \"${this.name}\" encountered an error.`,\n      llmUsage: null,\n      rawLLMResponse: undefined,\n      error: errorMessage,\n      success: false,\n    };\n  }\n\n  /**\n   * Gets a tool by its name from the agent's toolset.\n   * @param {string} toolName\n   * @returns {DaitanITool | LangChainTool | undefined} The tool instance, or undefined if not found.\n   */\n  getTool(toolName) {\n    const tool = this.tools[toolName];\n    if (!tool) {\n      this.logger.warn(\n        `Tool \"${toolName}\" not found for agent \"${\n          this.name\n        }\". Available tools: ${Object.keys(this.tools).join(', ')}`\n      );\n    }\n    return tool;\n  }\n\n  /**\n   * Helper to execute a tool safely within an agent.\n   * @param {string} toolName - The name of the tool to execute.\n   * @param {any} toolInput - The input for the tool.\n   * @param {string} [callId] - Optional call ID for tracing.\n   * @returns {Promise<{output: string | null, error: string | null}>}\n   */\n  async safeExecuteTool(toolName, toolInput, callId) {\n    const tool = this.getTool(toolName);\n    if (!tool) {\n      const errorMsg = `Tool \"${toolName}\" not found or not configured for agent \"${this.name}\".`;\n      this.logger.error(errorMsg, { callId });\n      return { output: null, error: errorMsg };\n    }\n\n    this.logger.debug(`Executing tool \"${toolName}\" via safeExecuteTool.`, {\n      callId,\n      toolInput,\n    });\n    try {\n      let output;\n      if (typeof tool.call === 'function') {\n        output = await tool.call(toolInput);\n      } else if (typeof tool.run === 'function') {\n        output = await tool.run(toolInput);\n      } else {\n        throw new DaitanConfigurationError(\n          `Tool \"${toolName}\" is not callable (missing call/run method).`\n        );\n      }\n      this.logger.debug(`Tool \"${toolName}\" execution successful.`, {\n        callId,\n        outputPreview: String(output).substring(0, 100),\n      });\n      return { output: String(output), error: null };\n    } catch (error) {\n      this.logger.error(\n        `Error executing tool \"${toolName}\" via safeExecuteTool: ${error.message}`,\n        { callId, toolInput, errorName: error.name },\n        error\n      );\n      return {\n        output: null,\n        error: `Tool \"${toolName}\" execution failed: ${error.message}`,\n      };\n    }\n  }\n}\n", "// intelligence/src/intelligence/agents/chat/index.js\n/**\n * @file Main entry point for chat-specific AI agents in @daitanjs/intelligence.\n * @module @daitanjs/intelligence/agents/chat\n *\n * @description\n * This module aggregates and exports various specialized AI agents designed for\n * participating in or managing simulated chat conversations. These agents typically\n * extend the `BaseAgent` class and leverage the `LLMService` for their operations.\n *\n * Exported Chat Agents:\n * - **`ChoreographerAgent`**: Responsible for setting up the initial scene of a\n *   multi-participant conversation, including topic, setting, and participant profiles.\n *   (from `./choreographerAgent.js`)\n * - **`CoachAgent`**: Analyzes ongoing conversation dynamics and provides\n *   Robert Greene-inspired coaching hints or psychological insights to participants.\n *   (from `./coachAgent.js`)\n * - **`OpeningPhraseAgent`**: Generates engaging opening lines or conversation starters\n *   for a designated participant based on the scene context.\n *   (from `./openingPhraseAgent.js`)\n * - **`ParticipantAgent`**: A simpler, non-iterative agent that represents a single\n *   participant in a conversation, generating one turn of speech, thoughts, and actions.\n *   This is distinct from the more complex graph-based participant workflows.\n *   (from `./participantAgent.js`)\n *\n * These agents can be orchestrated together, for example, by using the `ChoreographerAgent`\n * to define a scene, then using `ParticipantAgent` instances (potentially guided by a `CoachAgent`)\n * to simulate the conversation turn by turn.\n *\n * For more complex, stateful, and iterative agent behaviors, consider using the\n * LangGraph-based workflows available in `@daitanjs/intelligence/workflows`, which\n * might internally use or adapt the logic from these chat agents as nodes in a graph.\n */\nimport { getLogger } from '@daitanjs/development';\n\nconst chatAgentIndexLogger = getLogger('daitan-chat-agents-index');\n\nchatAgentIndexLogger.debug('Exporting DaitanJS Chat Agents...');\n\n// --- Specialized Chat Agent Classes ---\n// JSDoc for each class is in its respective source file.\n\nexport { ChoreographerAgent } from './choreographerAgent.js';\nexport { CoachAgent } from './coachAgent.js';\nexport { OpeningPhraseAgent } from './openingPhraseAgent.js';\nexport { ParticipantAgent } from './participantAgent.js'; // Simple, single-turn participant\n\n// Note: More complex, graph-based participant agents (like `createParticipantAgentGraph`)\n// are typically exported from the `intelligence/workflows/index.js` module, as they\n// represent entire workflow structures rather than standalone agent classes.\n\nchatAgentIndexLogger.info('DaitanJS Chat Agents module exports ready.');\n", "// intelligence/src/intelligence/agents/chat/choreographerAgent.js\n/**\n * @file Defines the ChoreographerAgent for setting up multi-participant conversation scenes.\n * @module @daitanjs/intelligence/agents/chat/choreographerAgent\n */\nimport { BaseAgent } from '../baseAgent.js';\nimport {\n  DaitanConfigurationError,\n  DaitanOperationError,\n  DaitanInvalidInputError,\n  DaitanError,\n} from '@daitanjs/error';\nimport { getConfigManager } from '@daitanjs/config';\n\n/**\n * @typedef {import('../baseAgent.js').AgentContext} AgentContext\n * @typedef {import('../baseAgent.js').AgentResponse} AgentResponse\n * @typedef {import('../../../services/llmService.js').LLMUsageInfo} LLMUsageInfo\n * @typedef {import('../../../services/llmService.js').LLMServiceConfig} LLMServiceConfig\n */\n\n/**\n * @typedef {Object} ChoreographerAgentPayload\n * @property {string} theme\n * @property {number} [numParticipants=3]\n * @property {string} [language=\"en\"]\n * @property {string[]} [potentialPersonalities]\n * @property {string[]} [potentialObjectives]\n * @property {string[]} [potentialSettings]\n * @property {LLMServiceConfig} [llmConfig]\n * @property {LLMServiceConfig} [llmConfigForParticipants]\n */\n\n/** @typedef {AgentContext & { payload: ChoreographerAgentPayload }} ChoreographerAgentContext */\n\n/**\n * @typedef {Object} ChoreographedParticipant\n * @property {string} name\n * @property {string} role\n * @property {string} personality\n * @property {string} objective\n * @property {string} speakingStyle\n * @property {number} temperature\n * @property {string[]} innerWorld\n * @property {string | null} hintFromOutside\n */\n\n/**\n * @typedef {Object} ChoreographyResult\n * @property {string} topic\n * @property {string} setting\n * @property {string} language\n * @property {string} mood\n * @property {string} observedAs\n * @property {ChoreographedParticipant[]} participants\n * @property {string[]} [stageProps]\n * @property {string | null} [firstSpeakerName]\n * @property {LLMServiceConfig} [llmConfig]\n * @property {string[]} conversationHistory\n * @property {string[]} nonVerbalActionsHistory\n */\n\n/** @typedef {AgentResponse & { output: ChoreographyResult | null }} ChoreographerAgentResponse */\n\n/**\n * ChoreographerAgent sets the stage for a multi-participant conversation.\n */\nexport class ChoreographerAgent extends BaseAgent {\n  /**\n   * @param {import('../../../services/llmService.js').LLMService} llmServiceInstance\n   */\n  constructor(llmServiceInstance) {\n    super(\n      'ChoreographerAgent',\n      'Sets up a multi-participant conversation scene including topic, setting, participant profiles, and initial dynamics.',\n      llmServiceInstance\n    );\n  }\n\n  /** @private */\n  _createSceneSetupPrompts(payload) {\n    const {\n      theme,\n      numParticipants = 3,\n      language = 'en',\n      potentialPersonalities,\n      potentialObjectives,\n      potentialSettings,\n    } = payload;\n\n    const personalityGuidance =\n      Array.isArray(potentialPersonalities) && potentialPersonalities.length > 0\n        ? `personalities, potentially drawing inspiration from (but not strictly limited to): ${potentialPersonalities.join(\n            ', '\n          )}. Ensure they are distinct.`\n        : 'diverse and engaging personalities that fit the theme.';\n    const objectiveGuidance =\n      Array.isArray(potentialObjectives) && potentialObjectives.length > 0\n        ? `objectives, possibly inspired by these examples: ${potentialObjectives.join(\n            ', '\n          )}. Ensure each participant's objective is specific to THIS conversation scene.`\n        : 'distinct and clear objectives that will drive the conversation.';\n    const settingGuidance =\n      Array.isArray(potentialSettings) && potentialSettings.length > 0\n        ? `a setting, perhaps similar to one of these examples: ${potentialSettings.join(\n            ', '\n          )}, or create a new one appropriate for the theme.`\n        : 'a compelling and contextually relevant setting for the conversation.';\n\n    const systemPrompt = {\n      persona:\n        'You are an expert scene choreographer and creative storyteller for simulations.',\n      task: 'Your task is to design a complete and detailed setup for a conversation scene.',\n      outputFormat:\n        'You MUST respond ONLY with a single, valid JSON object with keys: \"topic\", \"setting\", \"language\", \"mood\", \"observedAs\", \"participants\", and optionally \"stageProps\" and \"firstSpeakerName\".',\n      guidelines: [\n        `\"topic\": A specific, engaging conversation topic derived from the theme.`,\n        `\"setting\": A vivid description of the environment. ${settingGuidance}`,\n        `\"language\": Confirm the language by providing its ISO 639-1 code.`,\n        `\"mood\": The initial overall mood or atmosphere of the scene.`,\n        `\"observedAs\": A brief description of how an impartial observer might describe the scene.`,\n        `\"participants\": An array of exactly ${numParticipants} participant objects. Each must include: \"name\", \"role\", \"personality\", \"objective\", \"speakingStyle\", \"temperature\". Participant personalities should be ${personalityGuidance}. Participant objectives should be ${objectiveGuidance}.`,\n        `\"stageProps\": Optional array of 0-3 strings describing key physical objects.`,\n        `\"firstSpeakerName\": Optional string with the name of the participant who should speak first.`,\n      ],\n    };\n\n    const userPrompt = `\nYour task is to act as an expert scene choreographer and design a detailed setup for a conversation scene.\n\nTheme: \"${theme}\"\nNumber of Participants: ${numParticipants}\nLanguage: ${language}\n\nYour response must be a single, valid JSON object with the specific keys and structure detailed in the system prompt.\n`.trim();\n\n    return { system: systemPrompt, user: userPrompt };\n  }\n\n  /**\n   * @public\n   * @async\n   * @param {ChoreographerAgentContext} context\n   * @returns {Promise<ChoreographerAgentResponse>}\n   */\n  async run(context) {\n    const configManager = getConfigManager(); // Lazy-load\n    const callId =\n      context.callId || `choreo-${this.name}-${Date.now().toString(36)}`;\n    this.logger.info(`[${callId}] ChoreographerAgent run triggered.`, {\n      theme: context.payload?.theme,\n    });\n\n    if (\n      !context.payload ||\n      typeof context.payload.theme !== 'string' ||\n      !context.payload.theme.trim()\n    ) {\n      throw new DaitanInvalidInputError(\n        'A non-empty `theme` is required in the payload for the ChoreographerAgent.'\n      );\n    }\n    const numParticipants = context.payload.numParticipants || 3;\n    if (\n      !Number.isInteger(numParticipants) ||\n      numParticipants < 1 ||\n      numParticipants > 10\n    ) {\n      throw new DaitanInvalidInputError(\n        '`numParticipants` must be an integer between 1 and 10.'\n      );\n    }\n\n    const { llmConfig = {}, llmConfigForParticipants = {} } = context.payload;\n    const prompts = this._createSceneSetupPrompts(context.payload);\n\n    try {\n      const { response: sceneSetupJson, usage: llmUsageInfo } =\n        await this.llmService.generate({\n          prompt: prompts,\n          config: {\n            response: { format: 'json' },\n            llm: {\n              target:\n                llmConfig.target ||\n                configManager.get('CHOREOGRAPHER_EXPERT_PROFILE') ||\n                'MASTER_COMMUNICATOR',\n              temperature: llmConfig.temperature ?? 0.65,\n              maxTokens: llmConfig.maxTokens ?? 2000,\n            },\n            verbose: llmConfig.verbose ?? this.logger.isLevelEnabled('debug'),\n            trackUsage:\n              llmConfig.trackUsage ??\n              configManager.get('LLM_TRACK_USAGE', true),\n          },\n          metadata: {\n            summary: `ChoreographerAgent: Setup scene for theme \"${context.payload.theme.substring(\n              0,\n              30\n            )}...\"`,\n          },\n        });\n\n      if (\n        !sceneSetupJson ||\n        typeof sceneSetupJson !== 'object' ||\n        !Array.isArray(sceneSetupJson.participants)\n      ) {\n        throw new DaitanOperationError(\n          'LLM response for scene setup was not a valid object or participants array is missing.'\n        );\n      }\n\n      sceneSetupJson.participants.forEach((p, idx) => {\n        if (\n          !p ||\n          typeof p.name !== 'string' ||\n          typeof p.role !== 'string' ||\n          typeof p.personality !== 'string' ||\n          typeof p.objective !== 'string' ||\n          typeof p.speakingStyle !== 'string' ||\n          typeof p.temperature !== 'number'\n        ) {\n          throw new DaitanOperationError(\n            `Participant object at index ${idx} in LLM response is malformed.`\n          );\n        }\n        p.innerWorld = [];\n        p.hintFromOutside = null;\n      });\n\n      const choreographyResult = {\n        ...sceneSetupJson,\n        conversationHistory: [],\n        nonVerbalActionsHistory: [],\n        llmConfig: llmConfigForParticipants || llmConfig,\n      };\n\n      this.logger.info(\n        `[${callId}] Successfully choreographed conversation scene. Topic: \"${choreographyResult.topic}\"`\n      );\n      // --- DEFINITIVE FIX ---\n      // The call to createSuccessResponse now correctly matches the method's\n      // signature: createSuccessResponse(output, summary, ...).\n      // The primary data payload `choreographyResult` is the first argument.\n      return this.createSuccessResponse(\n        choreographyResult,\n        `Scene setup complete.`,\n        llmUsageInfo,\n        sceneSetupJson\n      );\n    } catch (error) {\n      this.logger.error(\n        `[${callId}] Error during scene choreography: ${error.message}`\n      );\n      const daitanError =\n        error instanceof DaitanError\n          ? error\n          : new DaitanOperationError(\n              `Scene choreography by LLM failed: ${error.message}`,\n              { agentName: this.name },\n              error\n            );\n      return this.createErrorResponse(\n        daitanError.message,\n        `ChoreographerAgent failed to set up scene.`\n      );\n    }\n  }\n}\n", "// intelligence/src/intelligence/agents/chat/coachAgent.js\n/**\n * @file Defines the CoachAgent for analyzing conversation dynamics and providing coaching hints.\n * @module @daitanjs/intelligence/agents/chat/coachAgent\n */\nimport { BaseAgent } from '../baseAgent.js';\nimport {\n  DaitanConfigurationError,\n  DaitanOperationError,\n  DaitanError,\n} from '@daitanjs/error';\n\n/**\n * @typedef {import('../baseAgent.js').AgentContext} AgentContext\n * @typedef {import('../baseAgent.js').AgentResponse} AgentResponse\n * @typedef {import('../../../services/llmService.js').LLMUsageInfo} LLMUsageInfo\n */\n\n/**\n * @typedef {Object} CoachAgentConversationContext\n * @property {Object} currentSpeaker\n * @property {Array<Object>} participants\n * @property {string} language\n * @property {string} setting\n * @property {string} topic\n * @property {string} observedAs\n * @property {string} mood\n * @property {string[]} conversationHistory\n * @property {number} [temperature]\n * @property {import('../../../services/llmService.js').LLMServiceConfig} [llmConfig]\n */\n\n/** @typedef {Object} CoachAgentContextPayload @property {CoachAgentConversationContext} conversation */\n/** @typedef {AgentContext & { payload: CoachAgentContextPayload }} CoachAgentContext */\n/** @typedef {Object} SupervisionResult @property {number} staleness @property {string} analysis @property {string} hintForCurrentSpeaker @property {string} whichRobertGreenLaws */\n\n/**\n * CoachAgent analyzes conversation dynamics and provides Robert Greene-inspired coaching hints.\n */\nexport class CoachAgent extends BaseAgent {\n  /**\n   * @param {import('../../../services/llmService.js').LLMService} llmServiceInstance\n   */\n  constructor(llmServiceInstance) {\n    super(\n      'CoachAgent',\n      'Analyzes conversation dynamics and provides Robert Greene-inspired coaching hints.',\n      llmServiceInstance\n    );\n  }\n\n  /** @private */\n  _createPrompts(con) {\n    if (\n      !con.currentSpeaker ||\n      !con.participants ||\n      !con.language ||\n      !con.topic\n    ) {\n      throw new DaitanConfigurationError(\n        'Missing critical fields in conversationContext for CoachAgent instruction generation.'\n      );\n    }\n\n    const systemPrompt = {\n      persona:\n        'You are a psychologist coach, deeply versed in all works of Robert Greene. Your goal is to analyze a conversation and provide actionable advice.',\n      task: `Analyze the conversation and provide guidance for ${con.currentSpeaker.name}. The conversation involves ${con.participants.length} participants and is in ${con.language}.`,\n      outputFormat: `Respond in ${con.language} strictly in the following JSON format: { \"staleness\": number, \"analysis\": \"string\", \"hintForCurrentSpeaker\": \"string\", \"whichRobertGreenLaws\": \"string\" }`,\n      guidelines: [\n        'Staleness Score: Determine if the conversation is stale (0=fresh, 100=stale).',\n        \"Psychologist's Analysis: Provide your analysis of the current situation.\",\n        `Robert Greene Inspired Hint: Give a bold, explicit, and daring hint to ${con.currentSpeaker.name} to help them achieve their objective. Instruct on non-verbal actions as well as verbal ones.`,\n        \"Reference Robert Greene: State which law(s) or chapter(s) from Greene's books inspired your hint and briefly explain the connection.\",\n      ],\n    };\n\n    const userPrompt = `\nContext:\n- Setting: \"${con.setting || 'Not specified'}\"\n- Topic: \"${con.topic}\"\n- Observed As: \"${con.observedAs || 'Not specified'}\"\n- Mood: \"${con.mood || 'Neutral'}\"\n\nCurrent Speaker for Guidance: ${con.currentSpeaker.name}\n- Personality: ${con.currentSpeaker.personality || 'Not specified'}\n- Objective: \"${con.currentSpeaker.objective || 'Not specified'}\"\n\nRecent Conversation History (last 8 messages):\n---\n${(con.conversationHistory || []).slice(-8).join('\\n') || 'No recent history.'}\n---\nProvide your analysis and hint now.\n    `.trim();\n\n    return { system: systemPrompt, user: userPrompt };\n  }\n\n  /**\n   * @param {CoachAgentContext} context\n   * @returns {Promise<AgentResponse & { output: SupervisionResult | null }>}\n   */\n  async run(context) {\n    const callId = context.callId || `coach-${Date.now()}`;\n    this.logger.info(`CoachAgent run triggered.`, { callId });\n\n    if (!context.payload || !context.payload.conversation) {\n      return this.createErrorResponse(\n        'Conversation context is missing or invalid.',\n        'CoachAgent configuration error.'\n      );\n    }\n\n    const conversationContext = context.payload.conversation;\n    let prompts;\n    try {\n      prompts = this._createPrompts(conversationContext);\n    } catch (instrError) {\n      return this.createErrorResponse(\n        `Prompt generation failed: ${instrError.message}`,\n        'CoachAgent setup error.'\n      );\n    }\n\n    const agentLlmConfig = conversationContext.llmConfig || {};\n\n    try {\n      const { response: supervisionResultJson, usage: llmUsage } =\n        await this.llmService.generate({\n          prompt: prompts,\n          config: {\n            response: { format: 'json' },\n            llm: {\n              target: agentLlmConfig.target,\n              temperature:\n                agentLlmConfig.temperature ??\n                conversationContext.temperature ??\n                0.4,\n              maxTokens: agentLlmConfig.maxTokens ?? 800,\n            },\n            verbose: agentLlmConfig.verbose,\n            trackUsage: agentLlmConfig.trackUsage,\n          },\n          metadata: {\n            summary: `CoachAgent: Supervision for ${conversationContext.currentSpeaker?.name}`,\n          },\n        });\n\n      if (\n        !supervisionResultJson ||\n        typeof supervisionResultJson.staleness !== 'number' ||\n        typeof supervisionResultJson.analysis !== 'string' ||\n        typeof supervisionResultJson.hintForCurrentSpeaker !== 'string' ||\n        typeof supervisionResultJson.whichRobertGreenLaws !== 'string'\n      ) {\n        throw new DaitanOperationError(\n          'LLM response for supervision was malformed or missed fields.'\n        );\n      }\n\n      this.logger.info('Successfully generated coaching supervision.', {\n        callId,\n        staleness: supervisionResultJson.staleness,\n      });\n      return this.createSuccessResponse(\n        supervisionResultJson,\n        `CoachAgent provided supervision for ${conversationContext.currentSpeaker?.name}.`,\n        llmUsage\n      );\n    } catch (error) {\n      this.logger.error(\n        `Error generating coaching supervision: ${error.message}`,\n        { callId, errorName: error.name }\n      );\n      const errorOutput = {\n        errorOccurred: true,\n        errorMessage: error.message,\n        staleness: 50,\n        analysis: 'Failed to generate supervision due to an operational error.',\n        hintForCurrentSpeaker:\n          'An error occurred; unable to provide a hint at this time.',\n        whichRobertGreenLaws: 'N/A due to error.',\n      };\n      const daitanError =\n        error instanceof DaitanError\n          ? error\n          : new DaitanOperationError(\n              `Failed to generate supervision: ${error.message}`,\n              { agentName: this.name },\n              error\n            );\n      return this.createErrorResponse(\n        daitanError.message,\n        'CoachAgent encountered an error.',\n        errorOutput\n      );\n    }\n  }\n}\n", "// intelligence/src/intelligence/agents/chat/openingPhraseAgent.js\n/**\n * @file Defines the OpeningPhraseAgent for generating compelling conversation starters.\n * @module @daitanjs/intelligence/agents/chat/openingPhraseAgent\n */\nimport { BaseAgent } from '../baseAgent.js';\nimport {\n  DaitanConfigurationError,\n  DaitanOperationError,\n  DaitanError,\n} from '@daitanjs/error';\n\n/**\n * @typedef {import('../baseAgent.js').AgentContext} AgentContext\n * @typedef {import('../baseAgent.js').AgentResponse} AgentResponse\n * @typedef {import('../../../services/llmService.js').LLMUsageInfo} LLMUsageInfo\n */\n\n/**\n * @typedef {Object} OpeningPhraseAgentConversationContext\n * @property {Object} currentSpeaker\n * @property {Array<Object>} participants\n * @property {string} language\n * @property {string} topic\n * @property {string} [goal]\n * @property {string} [mood]\n * @property {string} [setting]\n * @property {string[]} [stageProps]\n * @property {number} [temperature]\n * @property {import('../../../services/llmService.js').LLMServiceConfig} [llmConfig]\n */\n\n/** @typedef {Object} OpeningPhraseAgentContextPayload @property {OpeningPhraseAgentConversationContext} conversation */\n/** @typedef {AgentContext & { payload: OpeningPhraseAgentContextPayload }} OpeningPhraseAgentContext */\n/** @typedef {Object} OpeningPhraseResult @property {string} openingPhrase */\n\n/**\n * OpeningPhraseAgent generates engaging opening phrases for conversations.\n */\nexport class OpeningPhraseAgent extends BaseAgent {\n  /**\n   * @param {import('../../../services/llmService.js').LLMService} llmServiceInstance\n   */\n  constructor(llmServiceInstance) {\n    super(\n      'OpeningPhraseAgent',\n      'Generates engaging opening phrases for conversations based on context and participant objectives.',\n      llmServiceInstance\n    );\n  }\n\n  /** @private */\n  _createPrompts(con) {\n    const speaker = con.currentSpeaker;\n    if (!speaker || !con.participants || !con.language || !con.topic) {\n      throw new DaitanConfigurationError(\n        'Missing critical fields in conversationContext for OpeningPhraseAgent.'\n      );\n    }\n    const otherParticipantsDesc =\n      (con.participants || [])\n        .filter((p) => p?.name !== speaker.name)\n        .map(\n          (p) =>\n            `- ${p.name} (Personality: ${p.personality || 'N/A'}, Intention: \"${\n              p.objective || 'N/A'\n            }\")`\n        )\n        .join('\\n    ') || 'None';\n\n    const systemPrompt = {\n      persona:\n        'You are a creative AI assistant specializing in crafting compelling conversation starters.',\n      task: `Generate an engaging opening phrase for ${speaker.name}. The phrase must be natural, contextually appropriate, and aligned with the speaker's personality, style, and objective. It must be in ${con.language}.`,\n      outputFormat:\n        'Respond STRICTLY in the following JSON format: { \"openingPhrase\": \"string\" }',\n    };\n\n    const userPrompt = `\nConversation Context:\n- Topic: \"${con.topic}\"\n- Desired Goal of Conversation: \"${con.goal || 'achieve a positive outcome'}\"\n- General Mood: \"${con.mood || 'Neutral'}\"\n- Setting: \"${con.setting || 'Not specified'}\"\n- Available Props: ${con.stageProps?.join(', ') || 'none'}\n\nInitial Speaker Details (${speaker.name}):\n- Role: ${speaker.role || 'Participant'}\n- Personality: ${speaker.personality || 'Neutral'}\n- Specific Intention: \"${speaker.objective || 'Not specified'}\"\n- Typical Speaking Style: ${speaker.speakingStyle || 'Natural'}\n\nOther Participants:\n${otherParticipantsDesc}\n\nPlease generate the opening phrase for ${speaker.name}.\n`.trim();\n\n    return { system: systemPrompt, user: userPrompt };\n  }\n\n  /**\n   * @param {OpeningPhraseAgentContext} context\n   * @returns {Promise<AgentResponse & { output: OpeningPhraseResult | null }>}\n   */\n  async run(context) {\n    const callId = context.callId || `openphrase-${Date.now()}`;\n    this.logger.info(`OpeningPhraseAgent run triggered.`, { callId });\n\n    if (!context.payload?.conversation) {\n      return this.createErrorResponse(\n        'Conversation context is missing or invalid.',\n        'OpeningPhraseAgent configuration error.'\n      );\n    }\n\n    const conversationContext = context.payload.conversation;\n    let prompts;\n    try {\n      prompts = this._createPrompts(conversationContext);\n    } catch (instrError) {\n      return this.createErrorResponse(\n        `Prompt generation failed: ${instrError.message}`,\n        'OpeningPhraseAgent setup error.'\n      );\n    }\n\n    const agentLlmConfig = conversationContext.llmConfig || {};\n\n    try {\n      const { response: openingPhraseResultJson, usage: llmUsage } =\n        await this.llmService.generate({\n          prompt: prompts,\n          config: {\n            response: { format: 'json' },\n            llm: {\n              target: agentLlmConfig.target,\n              temperature:\n                agentLlmConfig.temperature ??\n                conversationContext.temperature ??\n                0.85,\n              maxTokens: agentLlmConfig.maxTokens ?? 200,\n            },\n            verbose: agentLlmConfig.verbose,\n            trackUsage: agentLlmConfig.trackUsage,\n          },\n          metadata: {\n            summary: `OpeningPhraseAgent: Generate for ${conversationContext.currentSpeaker?.name}`,\n          },\n        });\n\n      if (\n        !openingPhraseResultJson?.openingPhrase ||\n        typeof openingPhraseResultJson.openingPhrase !== 'string'\n      ) {\n        throw new DaitanOperationError(\n          'LLM response for opening phrase was malformed.'\n        );\n      }\n\n      this.logger.info('Successfully generated opening phrase.', { callId });\n      return this.createSuccessResponse(\n        openingPhraseResultJson,\n        `Opening phrase generated.`,\n        llmUsage\n      );\n    } catch (error) {\n      this.logger.error(`Error generating opening phrase: ${error.message}`, {\n        callId,\n        errorName: error.name,\n      });\n      const errorOutput = {\n        openingPhrase: `Error: Could not generate an opening phrase.`,\n        errorOccurred: true,\n        errorMessage: error.message,\n      };\n      const daitanError =\n        error instanceof DaitanError\n          ? error\n          : new DaitanOperationError(\n              `Failed to generate opening phrase: ${error.message}`,\n              { agentName: this.name },\n              error\n            );\n      return this.createErrorResponse(\n        daitanError.message,\n        'OpeningPhraseAgent encountered an error.',\n        errorOutput\n      );\n    }\n  }\n}\n", "// intelligence/src/intelligence/agents/chat/participantAgent.js\n/**\n * @file Defines the ParticipantAgent for simulating a single turn in a conversation.\n * @module @daitanjs/intelligence/agents/chat/participantAgent\n */\nimport { BaseAgent } from '../baseAgent.js';\nimport { DaitanOperationError, DaitanError } from '@daitanjs/error';\nimport { getConfigManager } from '@daitanjs/config';\n\n/**\n * @typedef {import('../baseAgent.js').AgentContext} AgentContext\n * @typedef {import('../baseAgent.js').AgentResponse} AgentResponse\n */\n\n/**\n * @typedef {Object} ParticipantDetails @property {string} name @property {string} role @property {string} personality @property {string} objective @property {string} speakingStyle @property {number} temperature @property {string[]} [innerWorld] @property {string | null} [hintFromOutside]\n * @typedef {Object} FullConversationContextForParticipant @property {ParticipantDetails} currentSpeaker @property {Array<ParticipantDetails>} participants @property {string} language @property {string} setting @property {string} topic @property {string} [observedAs] @property {string} [mood] @property {string[]} conversationHistory @property {string[]} [nonVerbalActionsHistory] @property {string[]} [stageProps] @property {import('../../../services/llmService.js').LLMServiceConfig} [llmConfig]\n * @typedef {Object} ParticipantAgentContextPayload @property {FullConversationContextForParticipant} conversation @property {ParticipantDetails} [actingAsParticipant]\n * @typedef {AgentContext & { payload: ParticipantAgentContextPayload }} ParticipantAgentContext\n * @typedef {Object} ParticipantResponsePayload @property {number} objectives_achieved @property {string} answer @property {string} thoughts @property {string} actions\n */\n\n/**\n * ParticipantAgent represents an actor in a conversation, generating a single turn's response.\n */\nexport class ParticipantAgent extends BaseAgent {\n  /**\n   * @param {import('../../../services/llmService.js').LLMService} llmServiceInstance\n   */\n  constructor(llmServiceInstance) {\n    super(\n      'ParticipantRolePlayer',\n      'Simulates a participant in a conversation, generating a single turn including speech, thoughts, and actions.',\n      llmServiceInstance\n    );\n  }\n\n  /** @private */\n  _createPrompts(con, speaker) {\n    const otherParticipants = (con.participants || [])\n      .filter((p) => p?.name !== speaker.name)\n      .map(\n        (p) =>\n          `${p.name} (Role: ${p.role || 'N/A'}, Objective: \"${\n            p.objective || 'N/A'\n          }\")`\n      )\n      .join(', ');\n\n    const system = {\n      persona: `You are ${speaker.name}, a ${\n        speaker.role?.toLowerCase() || 'participant'\n      } with a ${\n        speaker.personality?.toLowerCase() || 'neutral'\n      } personality. You are in a conversation with: ${\n        otherParticipants || 'others'\n      }. The conversation is in ${con.language || 'English'}.`,\n      task: `Your task is to provide your next verbal \"answer\", your internal \"thoughts\", and your non-verbal \"actions\". Your response should balance natural conversation flow with your specific objective: \"${speaker.objective}\".`,\n      outputFormat:\n        'Respond ONLY with a single, valid JSON object in the format: {\"objectives_achieved\": number, \"answer\": \"string\", \"thoughts\": \"string\", \"actions\": \"string\"}',\n      guidelines: [\n        `\"answer\" is for your exact verbal utterance only.`,\n        `\"thoughts\" are your internal monologue.`,\n        `\"actions\" describe your non-verbal movements.`,\n        `\"objectives_achieved\" is a score from 0-100 on how much this response helps you achieve your objective.`,\n        `Be consistent with your persona: (Role: ${\n          speaker.role\n        }, Personality: ${speaker.personality}, Style: ${\n          speaker.speakingStyle || 'Natural'\n        }).`,\n        `Supervisor's hint: \"${\n          speaker.hintFromOutside || 'No specific hint provided.'\n        }\"`,\n      ],\n    };\n\n    const user = `\nContext:\n- Topic: \"${con.topic}\"\n- Setting: \"${con.setting || 'Not specified'}\"\n- Mood: \"${con.mood || 'Neutral'}\"\n- Props: ${con.stageProps?.join(', ') || 'none'}\n\nRecent Conversation History (last 6 turns):\n${\n  (con.conversationHistory || []).slice(-6).join('\\n') ||\n  'No prior conversation.'\n}\n\nYour Recent Inner Thoughts (last 3 turns):\n[${\n      (speaker.innerWorld || []).slice(-3).join('\\n') ||\n      'No recent personal thoughts.'\n    }]\n\nRecent Non-Verbal Actions in Scene:\n[${\n      (con.nonVerbalActionsHistory || []).slice(-3).join('\\n') ||\n      'No recent non-verbal actions.'\n    }]\n\n---\nBased on the above, generate your response now.\n`.trim();\n\n    return { system, user };\n  }\n\n  /**\n   * @param {ParticipantAgentContext} context\n   * @returns {Promise<AgentResponse & { output: ParticipantResponsePayload | null }>}\n   */\n  async run(context) {\n    const configManager = getConfigManager(); // Lazy-load\n    const callId = context.callId || `participant-${Date.now()}`;\n    const actingParticipant = context.payload?.conversation?.currentSpeaker;\n\n    if (!actingParticipant?.name) {\n      return this.createErrorResponse(\n        'Participant persona not defined.',\n        'Agent configuration error.'\n      );\n    }\n\n    // Dynamically set logger name for better tracing\n    this.logger = this.llmService.logger.child({\n      service: `daitan-agent-${actingParticipant.name}`,\n    });\n    this.logger.info(\n      `ParticipantAgent (${actingParticipant.name}) run triggered.`,\n      { callId }\n    );\n\n    const prompts = this._createPrompts(\n      context.payload.conversation,\n      actingParticipant\n    );\n    const participantLlmConfig = context.payload.conversation.llmConfig || {};\n\n    try {\n      const { response: participantResponseJson, usage: llmUsage } =\n        await this.llmService.generate({\n          prompt: prompts,\n          config: {\n            response: { format: 'json' },\n            llm: {\n              target:\n                participantLlmConfig.target ||\n                configManager.get('PARTICIPANT_EXPERT_PROFILE') ||\n                'FAST_TASKER',\n              temperature:\n                participantLlmConfig.temperature ??\n                actingParticipant.temperature ??\n                0.7,\n              maxTokens: participantLlmConfig.maxTokens ?? 500,\n            },\n            verbose: participantLlmConfig.verbose,\n            trackUsage: participantLlmConfig.trackUsage,\n          },\n          metadata: {\n            summary: `ParticipantAgent: ${actingParticipant.name}'s turn`,\n          },\n        });\n\n      if (\n        !participantResponseJson ||\n        typeof participantResponseJson.objectives_achieved !== 'number' ||\n        typeof participantResponseJson.answer !== 'string' ||\n        typeof participantResponseJson.thoughts !== 'string' ||\n        typeof participantResponseJson.actions !== 'string'\n      ) {\n        throw new DaitanOperationError(\n          'LLM response for participant turn was malformed.'\n        );\n      }\n\n      this.logger.info(\n        `Participant ${actingParticipant.name} generated response successfully.`\n      );\n      return this.createSuccessResponse(\n        participantResponseJson,\n        `${actingParticipant.name} completed their turn.`,\n        llmUsage\n      );\n    } catch (error) {\n      this.logger.error(\n        `Error during ${actingParticipant.name}'s turn generation: ${error.message}`\n      );\n      const daitanError =\n        error instanceof DaitanError\n          ? error\n          : new DaitanOperationError(\n              `LLM call failed for ${actingParticipant.name}: ${error.message}`\n            );\n      const errorOutput = {\n        objectives_achieved: 0,\n        answer: `(Error: Could not generate answer - ${daitanError.message.substring(\n          0,\n          50\n        )}...)`,\n        thoughts: 'Error prevented thought generation.',\n        actions: 'No action taken due to error.',\n      };\n      return this.createErrorResponse(\n        daitanError.message,\n        `Participant ${actingParticipant.name} failed to generate turn.`,\n        errorOutput\n      );\n    }\n  }\n}\n", "// intelligence/src/intelligence/workflows/index.js\n/**\n * @file Main entry point for AI agentic workflows using LangGraph.\n * @module @daitanjs/intelligence/workflows\n *\n * @description\n * This module provides tools and pre-defined graphs for creating and running\n * complex, multi-step AI workflows based on LangChain's LangGraph library.\n * It abstracts away the complexity of agent creation, offering high-level,\n * powerful preset workflows.\n *\n * Key Exports:\n * - **High-Level Preset Workflows**:\n *   - `runDeepResearchAgent`: A multi-hop, \"plan-and-execute\" agent that can answer complex questions requiring several steps of reasoning and searching. This is the most powerful research tool.\n *   - `searchAndUnderstand`: A powerful one-shot function to get a direct answer to a simple query from the web, with sources.\n *   - `runAutomatedResearchWorkflow`: An agent that researches a topic and generates a structured report.\n *\n * - **Graph Management & Execution**:\n *   - `DaitanLangGraph`: A wrapper around LangGraph's `StateGraph` to simplify graph definition.\n *   - `createGraphRunner`: A factory function that takes a compiled graph and returns an async function to execute it.\n *\n * - **Lower-Level Agentic Workflow Graphs**:\n *   - Factories like `createPlanAndExecuteAgentGraph` and `createReActAgentGraph` for building custom agents from scratch.\n */\nimport { getLogger } from '@daitanjs/development';\n\nconst workflowsIndexLogger = getLogger('daitan-workflows-index');\n\nworkflowsIndexLogger.debug(\n  'Exporting DaitanJS Intelligence Workflows module...'\n);\n\n// --- High-Level Preset Workflows ---\nexport { runDeepResearchAgent } from './presets/deepResearchAgent.js';\nexport { searchAndUnderstand } from './presets/searchAndUnderstand.js';\nexport { runAutomatedResearchWorkflow } from './presets/automatedResearchAgent.js';\n\n// --- Core LangGraph Management and Execution ---\nexport { DaitanLangGraph, createChatAgentState } from './langGraphManager.js';\nexport { createGraphRunner } from './graphRunner.js';\n\n// --- Pre-defined Agentic Workflow Graph Factories ---\nexport {\n  createParticipantAgentGraph,\n  participantAgentStateSchema,\n} from './participantAgentGraph.js';\nexport {\n  createPlanAndExecuteAgentGraph,\n  planAndExecuteAgentStateSchema,\n} from './planAndExecuteAgentGraph.js';\nexport {\n  createReActAgentGraph,\n  reactAgentStateSchema,\n} from './reactWithReflectionAgentGraph.js';\n\nworkflowsIndexLogger.info(\n  'DaitanJS Intelligence Workflows module exports ready.'\n);\n", "// intelligence/src/intelligence/workflows/presets/deepResearchAgent.js\n/**\n * @file Implements an enhanced hierarchical Plan-and-Execute agent with robust citation handling.\n * @module @daitanjs/intelligence/workflows/presets/deepResearchAgent\n * @description This agent creates detailed, adaptive multi-step plans with proper source tracking,\n * citation handling, and intelligent error recovery. It prioritizes internal knowledge while\n * supplementing with external sources when needed.\n */\nimport { getLogger } from '@daitanjs/development';\n// --- DEFINITIVE FIX: Change ../.. to ../../index.js ---\nimport {\n  DaitanLangGraph,\n  createGraphRunner,\n  askWithRetrieval,\n  searchAndUnderstand,\n  searchNews,\n} from '../../index.js';\nimport { DaitanInvalidInputError, DaitanOperationError } from '@daitanjs/error';\nimport { END } from '@langchain/langgraph';\nimport { generateIntelligence } from '../../core/llmOrchestrator.js';\nimport chalk from 'chalk';\n\nconst logger = getLogger('daitan-deep-research-agent');\n\n// --- Enhanced State Schema ---\nconst agentStateSchema = {\n  originalQuery: { value: (x, y) => y ?? x },\n  collectionName: { value: (x, y) => y ?? x },\n  plan: { value: (x, y) => y ?? x, default: () => [] },\n  pastSteps: { value: (x, y) => x.concat(y), default: () => [] },\n  finalAnswer: { value: (x, y) => y, default: () => null },\n  sources: { value: (x, y) => [...new Set([...x, ...y])], default: () => [] },\n  citationMap: { value: (x, y) => ({ ...x, ...y }), default: () => ({}) },\n  onProgress: { value: (x, y) => y ?? x },\n  retryCount: { value: (x, y) => y ?? x, default: () => 0 },\n  maxRetries: { value: (x, y) => y ?? x, default: () => 3 },\n};\n\n// --- Enhanced Tools with Citation Tracking ---\nconst availableTools = (collectionName) => ({\n  search_internal_knowledge: {\n    description:\n      'Primary tool for querying the internal knowledge base (RAG). Most trusted source. Use first for all queries related to documents, people, projects, or specific information that might be in the knowledge base.',\n    trustLevel: 'highest',\n    execute: async (query, citationMap = {}) => {\n      try {\n        const ragResult = await askWithRetrieval(query, {\n          collectionName,\n          useAnalysisPrompt: true,\n        });\n\n        if (\n          ragResult.text &&\n          !ragResult.text\n            .toLowerCase()\n            .includes(\"don't have enough information\")\n        ) {\n          console.log(\n            chalk.gray(\n              `> Internal Knowledge found:\\n--- RAG Start ---\\n${ragResult.text}\\n--- RAG End ---`\n            )\n          );\n\n          // Track internal knowledge as a source\n          const sourceId = `internal_kb_${Date.now()}`;\n          citationMap[sourceId] = {\n            type: 'internal_knowledge',\n            query: query,\n            timestamp: new Date().toISOString(),\n            trustLevel: 'highest',\n          };\n\n          return {\n            observation: `Internal Knowledge: ${ragResult.text}`,\n            sources: [sourceId],\n            citationMap: { [sourceId]: citationMap[sourceId] },\n          };\n        }\n\n        console.log(\n          chalk.gray(\n            `> Internal Knowledge found no relevant information for: \"${query}\"`\n          )\n        );\n        return {\n          observation:\n            'The internal knowledge base did not contain relevant information for this query.',\n          sources: [],\n          citationMap: {},\n        };\n      } catch (error) {\n        console.log(\n          chalk.red(`> Internal Knowledge search failed: ${error.message}`)\n        );\n        return {\n          observation: `Internal knowledge search failed: ${error.message}`,\n          sources: [],\n          citationMap: {},\n        };\n      }\n    },\n  },\n\n  search_web: {\n    description:\n      'Secondary tool for general web searches. Use to supplement internal knowledge or find recent information not available in the knowledge base. Less trusted than internal sources.',\n    trustLevel: 'medium',\n    execute: async (query, citationMap = {}) => {\n      try {\n        const result = await searchAndUnderstand(query, { numResults: 5 });\n        console.log(chalk.gray(`> Web Search found: ${result.answer}`));\n\n        // Extract and track web sources\n        const webSources = [];\n        const newCitationMap = {};\n\n        // Extract URLs from the result\n        const urlRegex = /https?:\\/\\/[^\\s\\]]+/g;\n        const urls = result.answer.match(urlRegex) || [];\n\n        urls.forEach((url, index) => {\n          const sourceId = `web_${Date.now()}_${index}`;\n          webSources.push(sourceId);\n          newCitationMap[sourceId] = {\n            type: 'web_search',\n            url: url,\n            query: query,\n            timestamp: new Date().toISOString(),\n            trustLevel: 'medium',\n          };\n        });\n\n        return {\n          observation: `Web Search: ${result.answer}`,\n          sources: webSources,\n          citationMap: newCitationMap,\n        };\n      } catch (error) {\n        console.log(chalk.red(`> Web search failed: ${error.message}`));\n        return {\n          observation: `Web search failed: ${error.message}`,\n          sources: [],\n          citationMap: {},\n        };\n      }\n    },\n  },\n\n  search_news: {\n    description:\n      'Specialized tool for recent news and current events. Use when the query involves recent developments, current status, or time-sensitive information.',\n    trustLevel: 'medium',\n    execute: async (query, citationMap = {}) => {\n      try {\n        const result = await searchNews(query, { numResults: 3 });\n        console.log(chalk.gray(`> News Search found: ${result.answer}`));\n\n        const newsSources = [];\n        const newCitationMap = {};\n\n        // Extract URLs and track news sources\n        const urlRegex = /https?:\\/\\/[^\\s\\]]+/g;\n        const urls = result.answer.match(urlRegex) || [];\n\n        urls.forEach((url, index) => {\n          const sourceId = `news_${Date.now()}_${index}`;\n          newsSources.push(sourceId);\n          newCitationMap[sourceId] = {\n            type: 'news_search',\n            url: url,\n            query: query,\n            timestamp: new Date().toISOString(),\n            trustLevel: 'medium',\n          };\n        });\n\n        return {\n          observation: `News Search: ${result.answer}`,\n          sources: newsSources,\n          citationMap: newCitationMap,\n        };\n      } catch (error) {\n        console.log(chalk.red(`> News search failed: ${error.message}`));\n        return {\n          observation: `News search failed: ${error.message}`,\n          sources: [],\n          citationMap: {},\n        };\n      }\n    },\n  },\n});\n\n// --- Enhanced Planning Node ---\nconst plannerNode = async (state) => {\n  const { originalQuery, onProgress, collectionName, retryCount } = state;\n  onProgress({\n    stage: 'Planning',\n    message:\n      'Analyzing query and developing comprehensive research strategy...',\n    status: 'running',\n  });\n\n  const toolDescriptions = Object.entries(availableTools(collectionName))\n    .map(\n      ([name, tool]) =>\n        `- ${name} (${tool.trustLevel} trust): ${tool.description}`\n    )\n    .join('\\n');\n\n  const plannerPrompt = `You are an expert research strategist. Create a comprehensive, adaptive plan to thoroughly answer the user's query using the available tools in order of trust priority.\n\n**TRUST HIERARCHY (USE IN THIS ORDER):**\n1. search_internal_knowledge (HIGHEST) - Always use first and multiple times with different angles\n2. search_web (MEDIUM) - Use to supplement missing information\n3. search_news (MEDIUM) - Use for recent/current information\n\n**User's Query:** \"${originalQuery}\"\n\n**Available Tools:**\n${toolDescriptions}\n\n**Planning Guidelines:**\n1. Start with broad internal knowledge searches, then narrow down to specifics\n2. Use multiple search_internal_knowledge queries with different phrasings to extract all relevant information\n3. Only use external tools (web/news) after exhausting internal knowledge\n4. For complex queries, break into logical sub-questions\n5. Always end with synthesis step (no tool required)\n6. Each step should build upon previous findings\n\n**Required JSON Format:**\n{\n  \"plan\": [\n    {\n      \"task\": \"Clear description of what this step accomplishes\",\n      \"tool\": \"tool_name\",\n      \"tool_input\": \"specific search query\",\n      \"rationale\": \"why this step is needed\"\n    },\n    ...\n    {\n      \"task\": \"Synthesize comprehensive final answer with proper citations\",\n      \"rationale\": \"combine all findings into authoritative response\"\n    }\n  ]\n}\n\nCreate a thorough plan with 4-8 steps that will comprehensively address the query:`;\n\n  try {\n    const { response } = await generateIntelligence({\n      prompt: { user: plannerPrompt },\n      config: {\n        response: { format: 'json' },\n        llm: { target: 'openai|gpt-4o' },\n        temperature: 0.3, // Lower temperature for more consistent planning\n      },\n    });\n\n    console.log(chalk.cyan.bold('\uD83C\uDFAF Research Strategy Created:'));\n    response.plan.forEach((step, i) => {\n      console.log(chalk.cyan(`   ${i + 1}. ${step.task}`));\n      if (step.rationale) {\n        console.log(chalk.gray(`      \u2192 ${step.rationale}`));\n      }\n    });\n\n    onProgress({\n      stage: 'Planning',\n      message: `Created ${response.plan.length}-step research plan`,\n      status: 'complete',\n    });\n\n    return { plan: response.plan };\n  } catch (error) {\n    logger.error('Planning failed:', error);\n    onProgress({\n      stage: 'Planning',\n      message: 'Failed to create research plan',\n      status: 'error',\n    });\n    return {\n      finalAnswer: `Research planning failed: ${error.message}. Please try rephrasing your query.`,\n      sources: [],\n      citationMap: {},\n    };\n  }\n};\n\n// --- Enhanced Executor Node ---\nconst executorNode = async (state) => {\n  const { plan, pastSteps, onProgress, collectionName, citationMap } = state;\n  const currentStepIndex = pastSteps.length;\n  const currentTask = plan[currentStepIndex];\n\n  onProgress({\n    stage: 'Research',\n    message: `Step ${currentStepIndex + 1}/${plan.length}: ${currentTask.task}`,\n    status: 'running',\n  });\n\n  // Dynamic context injection from previous steps\n  let toolInput = currentTask.tool_input;\n  if (typeof toolInput === 'string') {\n    // Replace context placeholders with actual findings\n    if (toolInput.includes('[previous_findings]') && pastSteps.length > 0) {\n      const lastObservation = pastSteps[pastSteps.length - 1].observation;\n      toolInput = toolInput.replace('[previous_findings]', lastObservation);\n    }\n\n    // Inject specific entities or names found in previous steps\n    if (toolInput.includes('[entities]') && pastSteps.length > 0) {\n      const entities = extractEntitiesFromPastSteps(pastSteps);\n      toolInput = toolInput.replace('[entities]', entities.join(', '));\n    }\n  }\n\n  const tools = availableTools(collectionName);\n  const tool = tools[currentTask.tool];\n\n  if (!tool) {\n    const errorMsg = `Invalid tool \"${\n      currentTask.tool\n    }\" specified in plan step ${currentStepIndex + 1}`;\n    console.log(chalk.red.bold('\u274C Tool Error:'), chalk.red(errorMsg));\n    return {\n      pastSteps: [\n        {\n          task: currentTask.task,\n          tool: currentTask.tool,\n          observation: errorMsg,\n          sources: [],\n          success: false,\n        },\n      ],\n    };\n  }\n\n  try {\n    console.log(chalk.blue.bold(`\\n\uD83D\uDD0D Executing: ${currentTask.tool}`));\n    console.log(chalk.blue(`   Query: \"${toolInput}\"`));\n\n    const result = await tool.execute(toolInput, citationMap);\n\n    console.log(\n      chalk.green.bold('\u2705 Result:'),\n      chalk.green(result.observation)\n    );\n\n    onProgress({\n      stage: 'Research',\n      message: `Step ${currentStepIndex + 1} completed successfully`,\n      status: 'running',\n    });\n\n    return {\n      pastSteps: [\n        {\n          task: currentTask.task,\n          tool: currentTask.tool,\n          toolInput: toolInput,\n          observation: result.observation,\n          sources: result.sources || [],\n          success: true,\n        },\n      ],\n      sources: result.sources || [],\n      citationMap: result.citationMap || {},\n    };\n  } catch (error) {\n    const errorMsg = `Tool execution failed: ${error.message}`;\n    console.log(chalk.red.bold('\u274C Execution Error:'), chalk.red(errorMsg));\n\n    onProgress({\n      stage: 'Research',\n      message: `Step ${currentStepIndex + 1} encountered an error`,\n      status: 'error',\n    });\n\n    return {\n      pastSteps: [\n        {\n          task: currentTask.task,\n          tool: currentTask.tool,\n          observation: errorMsg,\n          sources: [],\n          success: false,\n        },\n      ],\n    };\n  }\n};\n\n// --- Enhanced Synthesis Node ---\nconst synthesizerNode = async (state) => {\n  const { originalQuery, pastSteps, onProgress, sources, citationMap } = state;\n  onProgress({\n    stage: 'Synthesis',\n    message: 'Analyzing all findings and crafting comprehensive answer...',\n    status: 'running',\n  });\n\n  // Organize findings by trust level and success\n  const successfulSteps = pastSteps.filter((step) => step.success);\n  const failedSteps = pastSteps.filter((step) => !step.success);\n\n  const internalFindings = successfulSteps.filter(\n    (step) => step.tool === 'search_internal_knowledge'\n  );\n  const externalFindings = successfulSteps.filter(\n    (step) => step.tool === 'search_web' || step.tool === 'search_news'\n  );\n\n  // Build detailed context for synthesis\n  const researchLog = pastSteps\n    .map((step, index) => {\n      const status = step.success ? '\u2705' : '\u274C';\n      return (\n        `**Step ${index + 1}** ${status}\\n` +\n        `Task: ${step.task}\\n` +\n        `Tool: ${step.tool}\\n` +\n        `Result: ${step.observation}\\n` +\n        (step.sources?.length ? `Sources: ${step.sources.join(', ')}\\n` : '') +\n        '---'\n      );\n    })\n    .join('\\n\\n');\n\n  // Create citation reference guide\n  const citationGuide = Object.entries(citationMap)\n    .map(([id, info]) => {\n      if (info.type === 'internal_knowledge') {\n        return `[${id}]: Internal Knowledge Base (Query: \"${info.query}\")`;\n      } else if (info.url) {\n        return `[${id}]: ${info.url}`;\n      }\n      return `[${id}]: ${info.type}`;\n    })\n    .join('\\n');\n\n  const synthesisPrompt = `You are a master research analyst. Your task is to synthesize a comprehensive, authoritative answer to the user's query based on the research findings below.\n\n**CRITICAL SYNTHESIS REQUIREMENTS:**\n1. **Source Priority**: Prioritize internal knowledge findings over external sources\n2. **Citations**: Use [source_id] format for ALL factual claims, quotes, and data points\n3. **Quotes**: Include relevant direct quotes when available, properly attributed\n4. **Completeness**: Address all aspects of the original query\n5. **Transparency**: Acknowledge any limitations or gaps in the research\n6. **Structure**: Organize the answer logically with clear sections if needed\n\n**Original Query:** \"${originalQuery}\"\n\n**Research Findings:**\n${researchLog}\n\n**Citation Reference Guide:**\n${citationGuide}\n\n**Quality Standards:**\n- Every factual claim must be cited using [source_id]\n- Include direct quotes where relevant: \"quote text\" [source_id]\n- Distinguish between high-confidence (internal) vs medium-confidence (external) findings\n- If information conflicts between sources, note this explicitly\n- If research was incomplete, state what additional information would be helpful\n\n**Format Requirements:**\n- Use markdown formatting for structure and emphasis\n- Include a \"Sources\" section at the end listing all cited sources\n- If the query asked for a table/list format, provide that structure\n\nSynthesize a comprehensive, well-cited answer now:`;\n\n  try {\n    const { response } = await generateIntelligence({\n      prompt: { user: synthesisPrompt },\n      config: {\n        llm: { target: 'openai|gpt-4o' },\n        temperature: 0.2, // Lower temperature for more consistent synthesis\n      },\n    });\n\n    onProgress({\n      stage: 'Complete',\n      message: 'Research completed successfully',\n      status: 'complete',\n    });\n\n    return { finalAnswer: response };\n  } catch (error) {\n    logger.error('Synthesis failed:', error);\n    onProgress({\n      stage: 'Synthesis',\n      message: 'Failed to synthesize final answer',\n      status: 'error',\n    });\n\n    // Fallback: provide raw findings if synthesis fails\n    const fallbackAnswer = `Research completed but synthesis failed. Here are the key findings:\\n\\n${successfulSteps\n      .map((step, i) => `${i + 1}. ${step.observation}`)\n      .join('\\n\\n')}`;\n\n    return { finalAnswer: fallbackAnswer };\n  }\n};\n\n// --- Routing Logic ---\nconst shouldContinue = (state) => {\n  if (state.finalAnswer) {\n    return END;\n  }\n\n  const nextTaskIndex = state.pastSteps.length;\n  const nextTask = state.plan[nextTaskIndex];\n\n  if (!nextTask || !nextTask.tool) {\n    return 'synthesizer';\n  }\n\n  return 'executor';\n};\n\n// --- Utility Functions ---\nfunction extractEntitiesFromPastSteps(pastSteps) {\n  const entities = new Set();\n  const entityRegex = /\\b[A-Z][a-z]+(?: [A-Z][a-z]+)+\\b/g;\n\n  pastSteps.forEach((step) => {\n    if (step.success && step.observation) {\n      const matches = step.observation.match(entityRegex) || [];\n      matches.forEach((match) => entities.add(match));\n    }\n  });\n\n  return Array.from(entities);\n}\n\nfunction buildSourcesMap(citationMap) {\n  const sourcesMap = {};\n\n  Object.entries(citationMap).forEach(([id, info]) => {\n    if (info.type === 'internal_knowledge') {\n      sourcesMap[id] = `Internal Knowledge Base (${info.timestamp})`;\n    } else if (info.url) {\n      sourcesMap[id] = info.url;\n    } else {\n      sourcesMap[id] = `${info.type} source`;\n    }\n  });\n\n  return sourcesMap;\n}\n\n// --- Main Research Conductor ---\nexport async function runDeepResearchAgent(query, options = {}) {\n  const {\n    onProgress = () => {},\n    collectionName,\n    maxRetries = 3,\n    timeout = 300000, // 5 minutes default timeout\n  } = options;\n\n  if (!query?.trim()) {\n    throw new DaitanInvalidInputError('A valid, non-empty query is required.');\n  }\n\n  onProgress({\n    stage: 'Initialization',\n    message: 'Starting comprehensive research process...',\n    status: 'running',\n  });\n\n  // Build the enhanced research graph\n  const researchGraph = new DaitanLangGraph(agentStateSchema);\n\n  researchGraph\n    .addNode({ name: 'planner', action: plannerNode })\n    .addNode({ name: 'executor', action: executorNode })\n    .addNode({ name: 'synthesizer', action: synthesizerNode })\n    .setEntryPoint('planner')\n    .addConditionalEdge({\n      sourceNode: 'planner',\n      condition: shouldContinue,\n      pathMap: {\n        executor: 'executor',\n        synthesizer: 'synthesizer',\n      },\n    })\n    .addConditionalEdge({\n      sourceNode: 'executor',\n      condition: shouldContinue,\n      pathMap: {\n        executor: 'executor',\n        synthesizer: 'synthesizer',\n      },\n    })\n    .setFinishPoint('synthesizer');\n\n  const compiledGraph = researchGraph.compile();\n  const graphRunner = createGraphRunner(compiledGraph);\n\n  try {\n    const startTime = Date.now();\n\n    const finalState = await Promise.race([\n      graphRunner({\n        originalQuery: query.trim(),\n        onProgress,\n        collectionName,\n        maxRetries,\n      }),\n      new Promise((_, reject) =>\n        setTimeout(\n          () => reject(new Error('Research timeout exceeded')),\n          timeout\n        )\n      ),\n    ]);\n\n    const duration = Date.now() - startTime;\n    console.log(chalk.green.bold(`\\n\uD83C\uDF89 Research completed in ${duration}ms`));\n\n    // Build comprehensive response\n    const sourcesMap = buildSourcesMap(finalState.citationMap || {});\n    const uniqueSources = [...new Set(finalState.sources || [])];\n\n    if (\n      finalState.finalAnswer?.startsWith(\"I'm sorry\") ||\n      finalState.finalAnswer?.includes('failed')\n    ) {\n      throw new DaitanOperationError(finalState.finalAnswer);\n    }\n\n    return {\n      finalAnswer:\n        finalState.finalAnswer ||\n        'Research completed but no final answer was generated.',\n      sources: uniqueSources,\n      sourcesMap: sourcesMap,\n      plan: finalState.plan || [],\n      executionSteps: finalState.pastSteps || [],\n      citationMap: finalState.citationMap || {},\n      metadata: {\n        duration,\n        totalSteps: finalState.pastSteps?.length || 0,\n        successfulSteps:\n          finalState.pastSteps?.filter((s) => s?.success)?.length || 0,\n        timestamp: new Date().toISOString(),\n      },\n    };\n  } catch (error) {\n    logger.error('Research agent failed:', error);\n    onProgress({\n      stage: 'Error',\n      message: `Research failed: ${error.message}`,\n      status: 'error',\n    });\n\n    return {\n      finalAnswer: `Research process failed: ${error.message}. Please try rephrasing your query or check if the knowledge base is accessible.`,\n      sources: [],\n      sourcesMap: {},\n      plan: [],\n      executionSteps: [],\n      citationMap: {},\n      metadata: {\n        error: error.message,\n        timestamp: new Date().toISOString(),\n      },\n    };\n  }\n}\n", "// intelligence/src/intelligence/workflows/presets/searchAndUnderstand.js\n/**\n * @file A high-level workflow that searches the web, scrapes content, and synthesizes an answer.\n * @module @daitanjs/intelligence/workflows/presets/searchAndUnderstand\n */\nimport { getLogger } from '@daitanjs/development';\nimport { googleSearch, downloadAndExtract } from '@daitanjs/web';\nimport { generateIntelligence } from '../../core/llmOrchestrator.js';\n// CORRECTED: Import the necessary error classes\nimport { DaitanOperationError, DaitanInvalidInputError } from '@daitanjs/error';\n\nconst logger = getLogger('daitan-search-understand-workflow');\n\n/**\n * @typedef {import('@daitanjs/web/search').GoogleSearchResultItem} GoogleSearchResultItem\n * @typedef {import('../../core/llmOrchestrator.js').LLMUsageInfo} LLMUsageInfo\n * @typedef {import('../../core/llmOrchestrator.js').CallConfiguration} CallConfiguration\n */\n\n/**\n * @typedef {Object} UnderstandingResult\n * @property {string} answer - The synthesized, direct answer to the query.\n * @property {string[]} sources - An array of URLs used to generate the answer.\n * @property {LLMUsageInfo | null} usage - The token usage for the synthesis step.\n * @property {GoogleSearchResultItem[]} searchResults - The raw search results that were processed.\n */\n\n/**\n * @typedef {Object} SearchAndUnderstandOptions\n * @property {number} [numResults=3] - The number of top search results to process (1-5).\n * @property {CallConfiguration} [llmConfig] - Configuration for the `generateIntelligence` call used for synthesis.\n * @property {boolean} [verbose=false] - Enable detailed logging for the entire operation.\n */\n\nexport const searchAndUnderstand = async (query, options = {}) => {\n  const callId = `understand-${Date.now().toString(36)}`;\n  const { numResults = 3, llmConfig = {}, verbose = false } = options;\n\n  if (!query || typeof query !== 'string' || !query.trim()) {\n    throw new DaitanInvalidInputError(\n      'A valid query string is required for searchAndUnderstand.'\n    );\n  }\n\n  logger.info(\n    `[${callId}] searchAndUnderstand initiated for query: \"${query}\"`\n  );\n\n  try {\n    // Step 1: Search the web\n    logger.info(`[${callId}] Step 1: Searching the web...`);\n    const searchResults = await googleSearch({ query, num: numResults });\n    if (!searchResults || searchResults.length === 0) {\n      logger.warn(`[${callId}] No search results found. Cannot proceed.`);\n      return {\n        answer:\n          'I could not find any relevant information on the web for your query.',\n        sources: [],\n        usage: null,\n        searchResults: [],\n      };\n    }\n    const urlsToProcess = searchResults.map((res) => res.link);\n    logger.info(`[${callId}] Found ${urlsToProcess.length} URLs to process.`);\n\n    // Step 2: Scrape content from top results in parallel\n    logger.info(`[${callId}] Step 2: Scraping content from URLs...`);\n    const scrapingPromises = urlsToProcess.map(async (url) => {\n      try {\n        const content = await downloadAndExtract(url, {\n          strategy: 'robust',\n          outputFormat: 'cleanText',\n        });\n        return { url, content };\n      } catch (error) {\n        // This catch block is now safe because DaitanOperationError is imported.\n        logger.warn(`[${callId}] Failed to scrape ${url}: ${error.message}`);\n        return { url, content: null };\n      }\n    });\n\n    const scrapedContents = (await Promise.all(scrapingPromises)).filter(\n      (res) => res.content && res.content.trim()\n    );\n\n    if (scrapedContents.length === 0) {\n      logger.warn(\n        `[${callId}] Could not scrape any content. Cannot synthesize answer.`\n      );\n      return {\n        answer:\n          'I found search results, but was unable to access their content to provide a direct answer.',\n        sources: urlsToProcess,\n        usage: null,\n        searchResults,\n      };\n    }\n\n    // Step 3: Synthesize an answer using an LLM\n    logger.info(\n      `[${callId}] Step 3: Synthesizing answer from ${scrapedContents.length} sources...`\n    );\n    const contextForLLM = scrapedContents\n      .map(\n        (doc, i) =>\n          `--- Source ${i + 1} (URL: ${doc.url}) ---\\n${doc.content.substring(\n            0,\n            8000\n          )}\\n--- End Source ${i + 1} ---`\n      )\n      .join('\\n\\n');\n\n    // --- DEFINITIVE FIX: Stricter, more robust synthesis prompt ---\n    const synthesisPrompt = `You are a factual research assistant. Your task is to answer the user's query based strictly on the provided sources.\n\n**CRITICAL INSTRUCTIONS:**\n1. Read all sources carefully.\n2. If the information to answer the query is explicitly present in the sources, synthesize a direct answer and cite the source numbers in brackets, like this [1] or [1, 2].\n3. **If the sources DO NOT contain a clear answer, you MUST respond with the exact phrase: \"The provided sources do not contain a direct answer to this query.\"**\n4. DO NOT invent details, make assumptions, or combine unrelated information to form an answer. Your primary duty is to report what the sources say.\n\nQuery: \"${query}\"\n\nSources:\n${contextForLLM}`;\n\n    const { response, usage } = await generateIntelligence({\n      prompt: {\n        system: {\n          persona: 'You are an expert research assistant.',\n          task: \"Synthesize a direct answer to the user's query based strictly on the provided sources, citing each piece of information with its source number. If the information is not present, you must state that.\",\n        },\n        user: synthesisPrompt,\n      },\n      config: {\n        response: { format: 'text' },\n        llm: {\n          target: 'MASTER_COMMUNICATOR',\n          temperature: 0.0, // Set to 0.0 for factual, non-creative tasks\n          maxTokens: 1500,\n          ...(llmConfig.llm || {}),\n        },\n        verbose,\n        ...(llmConfig || {}),\n      },\n      metadata: { summary: `Synthesize answer for: ${query}` },\n    });\n\n    logger.info(`[${callId}] searchAndUnderstand completed successfully.`);\n\n    return {\n      answer: response,\n      sources: scrapedContents.map((doc) => doc.url),\n      usage,\n      searchResults,\n    };\n  } catch (error) {\n    logger.error(\n      `[${callId}] An unhandled error occurred in searchAndUnderstand: ${error.message}`\n    );\n    throw new DaitanOperationError(\n      `Failed to complete the search and understand process: ${error.message}`,\n      { query },\n      error\n    );\n  }\n};\n", "// intelligence/src/intelligence/workflows/presets/automatedResearchAgent.js\n/**\n * @file A pre-defined workflow for automated research on a topic.\n * @module @daitanjs/intelligence/workflows/presets/automatedResearchAgent\n *\n * @description\n * This module provides the `runAutomatedResearchWorkflow` function, which executes a\n * multi-step agentic workflow using LangGraph. The agent performs the following sequence:\n *\n * 1. **Deconstruct**: Breaks the main topic into a set of specific sub-queries.\n * 2. **Search**: Uses the underlying web search service to find relevant online articles for each sub-query.\n * 3. **Scrape & Summarize**: For each unique URL found, scrapes the content and generates a concise summary.\n * 4. **Synthesize**: Uses an LLM to create a final, comprehensive report based on the collected summaries, citing its sources.\n * 5. **Save**: Writes the final report to a local Markdown file.\n *\n * This serves as a powerful example of orchestrating multiple tools and LLM calls\n * to accomplish a complex research task, with hooks for detailed observability.\n */\nimport { DaitanLangGraph } from '../langGraphManager.js';\nimport { createGraphRunner } from '../graphRunner.js';\nimport { LLMService } from '../../../services/llmService.js';\nimport { googleSearch } from '@daitanjs/web'; // Use the direct service for structured output\nimport { downloadAndExtract } from '@daitanjs/web';\nimport { autoTagDocument } from '../../metadata/index.js';\nimport { writeFile } from '@daitanjs/utilities';\nimport { getLogger } from '@daitanjs/development';\nimport { DaitanOperationError, DaitanInvalidInputError } from '@daitanjs/error';\nimport path from 'path';\n\nconst researchLogger = getLogger('daitan-research-workflow');\n\n/**\n * @typedef {Object} ResearchState\n * @property {string} topic\n * @property {string[]} subQueries\n * @property {Array<{query: string, url: string, title: string}>} searchResults\n * @property {Array<{url: string, title: string, summary: string}>} summaries\n * @property {string | null} finalReport\n * @property {string | null} reportPath\n * @property {string | null} error\n * @property {LLMService} llmService\n */\nconst researchAgentStateSchema = {\n  topic: { value: (x, y) => y ?? x },\n  subQueries: { value: (x, y) => y ?? x, default: () => [] },\n  searchResults: {\n    value: (x, y) => (x || []).concat(y || []),\n    default: () => [],\n  },\n  summaries: { value: (x, y) => (x || []).concat(y || []), default: () => [] },\n  finalReport: { value: (x, y) => y ?? x, default: () => null },\n  reportPath: { value: (x, y) => y ?? x, default: () => null },\n  error: { value: (x, y) => y ?? x, default: () => null },\n  llmService: { value: (x, y) => y ?? x },\n};\n\nconst deconstructQueryNode = async (state) => {\n  researchLogger.info(`(1) Deconstructing topic: \"${state.topic}\"`);\n  try {\n    const { response } = await state.llmService.generate({\n      prompt: {\n        system: {\n          persona: 'You are an expert research planner.',\n          task: 'Deconstruct the given topic into 3-5 specific, answerable sub-queries that cover the key aspects of the topic. The queries should be suitable for a web search engine.',\n          outputFormat:\n            'Respond with a single JSON object with a single key \"queries\" which is an array of strings.',\n        },\n        user: state.topic,\n      },\n      config: { llm: { target: 'FAST_TASKER', temperature: 0.1 } },\n    });\n    if (!response?.queries || response.queries.length === 0) {\n      return { error: 'Failed to deconstruct topic into sub-queries.' };\n    }\n    return { subQueries: response.queries };\n  } catch (error) {\n    return { error: `Query deconstruction failed: ${error.message}` };\n  }\n};\n\nconst searchNode = async (state) => {\n  if (state.error) return;\n  researchLogger.info(\n    `(2) Searching for: ${state.subQueries.length} sub-queries.`\n  );\n  const allResults = [];\n  for (const query of state.subQueries) {\n    try {\n      // Use the direct service to get structured data, not the string-returning tool\n      const searchItems = await googleSearch({ query: query, num: 3 });\n      for (const item of searchItems) {\n        if (item.link) {\n          allResults.push({ query, url: item.link, title: item.title });\n        }\n      }\n    } catch (error) {\n      researchLogger.warn(\n        `Web search for sub-query \"${query}\" failed: ${error.message}`\n      );\n    }\n  }\n  if (allResults.length === 0) {\n    return { error: 'Web search returned no usable links.' };\n  }\n  return { searchResults: allResults };\n};\n\nconst scrapeAndSummarizeNode = async (state) => {\n  if (state.error) return;\n  const uniqueUrls = [\n    ...new Map(state.searchResults.map((item) => [item.url, item])).values(),\n  ];\n  researchLogger.info(\n    `(3) Scraping and summarizing ${uniqueUrls.length} unique URLs.`\n  );\n\n  const summaryPromises = uniqueUrls.map(async ({ url, title }) => {\n    try {\n      const extracted = await downloadAndExtract(url, {\n        parserType: 'cheerio',\n        mainContentSelectors: ['main', 'article', 'body'],\n      });\n      const fullText = (extracted || [])\n        .map((item) => item.text)\n        .join('\\n\\n')\n        .substring(0, 15000);\n\n      if (fullText.trim().length < 100) return null;\n\n      const { metadata } = await autoTagDocument(fullText, {\n        config: { llm: { target: 'FAST_TASKER', temperature: 0.0 } },\n      });\n      return { url, title, summary: metadata.summary };\n    } catch (error) {\n      researchLogger.warn(`Failed to process ${url}: ${error.message}`);\n      return null;\n    }\n  });\n\n  const summaries = (await Promise.all(summaryPromises)).filter(Boolean);\n  if (summaries.length === 0) {\n    return {\n      error:\n        'Could not successfully scrape and summarize any of the search results.',\n    };\n  }\n  return { summaries };\n};\n\nconst synthesizeReportNode = async (state) => {\n  if (state.error || state.summaries.length === 0) {\n    return {\n      finalReport:\n        state.error || 'Could not generate report due to lack of information.',\n    };\n  }\n  researchLogger.info('(4) Synthesizing final report.');\n  const synthesisPrompt = `You are an expert research analyst. Synthesize a comprehensive, well-structured report in Markdown on the topic: \"${\n    state.topic\n  }\". Use ONLY the following source summaries. For each piece of information you include, you MUST cite the source URL in parentheses, like this: (Source: https://example.com/article).\n\n--- SOURCE SUMMARIES ---\n${state.summaries\n  .map((s) => `URL: ${s.url}\\nTitle: ${s.title}\\nSummary: ${s.summary}`)\n  .join('\\n\\n')}`;\n\n  try {\n    const { response: finalReport } = await state.llmService.generate({\n      prompt: { user: synthesisPrompt },\n      config: {\n        response: { format: 'text' },\n        llm: { target: 'MASTER_COMMUNICATOR', maxTokens: 4000 },\n      },\n    });\n    return { finalReport };\n  } catch (error) {\n    return { error: `Report synthesis failed: ${error.message}` };\n  }\n};\n\nconst saveReportNode = async (state) => {\n  if (state.error || !state.finalReport) return;\n  researchLogger.info('(5) Saving final report to file.');\n  const fileName = `${state.topic\n    .replace(/[\\s/\\\\?%*:|\"<>]/g, '_')\n    .toLowerCase()}_report.md`;\n  const outputPath = path.resolve(process.cwd(), fileName);\n  try {\n    await writeFile(outputPath, state.finalReport);\n    return { reportPath: outputPath };\n  } catch (error) {\n    return { error: `Failed to save report: ${error.message}` };\n  }\n};\n\n/**\n * Creates and runs the automated research workflow.\n * @param {string} topic - The research topic.\n * @param {import('../graphRunner.js').CreateGraphRunnerOptions} [options] - Options for the graph runner, including callbacks.\n * @returns {Promise<ResearchState>} The final state of the graph.\n */\nexport const runAutomatedResearchWorkflow = async (topic, options = {}) => {\n  if (!topic || typeof topic !== 'string' || !topic.trim()) {\n    throw new DaitanInvalidInputError(\n      'A valid topic is required to run the research workflow.'\n    );\n  }\n\n  const researchGraph = new DaitanLangGraph(researchAgentStateSchema);\n  researchGraph.addNode({\n    name: 'Deconstruct Query',\n    action: deconstructQueryNode,\n  });\n  researchGraph.addNode({ name: 'Search Web', action: searchNode });\n  researchGraph.addNode({\n    name: 'Scrape & Summarize',\n    action: scrapeAndSummarizeNode,\n  });\n  researchGraph.addNode({\n    name: 'Synthesize Report',\n    action: synthesizeReportNode,\n  });\n  researchGraph.addNode({ name: 'Save Report', action: saveReportNode });\n\n  researchGraph.setEntryPoint('Deconstruct Query');\n  researchGraph.addEdge({\n    sourceNode: 'Deconstruct Query',\n    targetNode: 'Search Web',\n  });\n  researchGraph.addEdge({\n    sourceNode: 'Search Web',\n    targetNode: 'Scrape & Summarize',\n  });\n  researchGraph.addEdge({\n    sourceNode: 'Scrape & Summarize',\n    targetNode: 'Synthesize Report',\n  });\n  researchGraph.addEdge({\n    sourceNode: 'Synthesize Report',\n    targetNode: 'Save Report',\n  });\n  researchGraph.setFinishPoint('Save Report');\n\n  const compiledGraph = researchGraph.compile();\n  const graphRunner = createGraphRunner(compiledGraph, {\n    verbose: true,\n    ...options,\n  });\n\n  researchLogger.info(\n    `--- Starting Automated Research Workflow for: \"${topic}\" ---`\n  );\n  const finalState = await graphRunner({ topic, llmService: new LLMService() });\n  researchLogger.info(\n    `--- Automated Research Workflow for: \"${topic}\" Finished ---`\n  );\n\n  if (finalState.error) {\n    researchLogger.error('Workflow finished with an error:', finalState.error);\n  }\n  return finalState;\n};\n", "// File: src/intelligence/core/ollamaUtils.js\nimport axios from 'axios';\nimport { getLogger } from '@daitanjs/development';\n\nconst logger = getLogger('ollama-utils'); // Or your preferred logger setup\n\n/**\n * Checks if the Ollama server is reachable and responsive.\n * @param {string} baseURL - The base URL of the Ollama server (e.g., http://localhost:11434).\n * @returns {Promise<boolean>} True if the server is running, false otherwise.\n */\nexport const checkOllamaStatus = async (baseURL) => {\n  if (!baseURL) {\n    logger.warn('checkOllamaStatus: No baseURL provided for Ollama server.');\n    return false;\n  }\n  try {\n    // A simple GET request to the root of Ollama server usually returns \"Ollama is running\" or a similar confirmation.\n    // For a more robust check, one might target a specific endpoint like `/api/tags` if unauthenticated access is allowed,\n    // but a simple root check is often sufficient to see if the server is up.\n    const response = await axios.get(baseURL, { timeout: 2000 }); // 2-second timeout\n    // Check for a successful status code and potentially specific text if needed.\n    if (\n      response.status === 200 &&\n      response.data &&\n      typeof response.data === 'string' &&\n      response.data.toLowerCase().includes('ollama is running')\n    ) {\n      logger.debug(`Ollama server at ${baseURL} is responsive.`);\n      return true;\n    } else if (response.status === 200) {\n      // Some Ollama versions might just return 200 OK on base URL without specific text\n      logger.debug(\n        `Ollama server at ${baseURL} responded with status 200. Assuming responsive.`\n      );\n      return true;\n    }\n    logger.warn(\n      `Ollama server at ${baseURL} responded with status ${response.status} but unexpected content.`\n    );\n    return false;\n  } catch (error) {\n    if (axios.isAxiosError(error)) {\n      // logger.debug(`Ollama server at ${baseURL} not reachable: ${error.message}`);\n    } else {\n      logger.error(\n        `An unexpected error occurred while checking Ollama status at ${baseURL}: ${error.message}`\n      );\n    }\n    return false;\n  }\n};\n", "// intelligence/src/caching/cacheManager.js\n/**\n * @file Manages different types of caches (e.g., for LLM responses, embeddings) by leveraging the canonical CacheManager from @daitanjs/data.\n * @module @daitanjs/intelligence/caching/cacheManager\n */\nimport { getLogger } from '@daitanjs/development';\nimport { DaitanConfigurationError } from '@daitanjs/error';\nimport crypto from 'crypto';\nimport { CacheManager } from '@daitanjs/data';\n\nconst logger = getLogger('daitan-cache-manager');\n\n/**\n * @typedef {import('@daitanjs/data').CacheManager} DaitanCacheManager\n */\n\n/**\n * @typedef {Object} CacheConfig\n * @property {boolean} [enabled=false]\n * @property {number} [capacity=100]\n */\n\nconst globalCaches = {\n  llmResponses: null,\n  embeddings: null,\n};\n\n/**\n * Initializes and returns a named cache instance.\n * @param {'llmResponses' | 'embeddings'} cacheName\n * @param {CacheConfig} [config]\n * @returns {DaitanCacheManager | null}\n */\nexport const getCache = (cacheName, config = {}) => {\n  const { enabled = false, capacity = 100 } = config;\n\n  if (!globalCaches.hasOwnProperty(cacheName)) {\n    logger.warn(\n      `Cache name \"${cacheName}\" is not a recognized cache. No cache created.`\n    );\n    return null;\n  }\n\n  if (!enabled) {\n    if (globalCaches[cacheName]) {\n      globalCaches[cacheName].flushAll();\n      globalCaches[cacheName] = null;\n    }\n    return null;\n  }\n\n  if (globalCaches[cacheName]) {\n    const currentCapacity = globalCaches[cacheName].nodeCacheOptions.maxKeys;\n    if (currentCapacity !== capacity && capacity > 0) {\n      logger.warn(\n        `Cache \"${cacheName}\" capacity changed from ${currentCapacity} to ${capacity}. Re-initializing.`\n      );\n      globalCaches[cacheName].flushAll();\n      globalCaches[cacheName].close();\n      globalCaches[cacheName] = null;\n    } else {\n      return globalCaches[cacheName];\n    }\n  }\n\n  try {\n    const cacheInstance = new CacheManager({ maxKeys: capacity }, logger);\n    globalCaches[cacheName] = cacheInstance;\n    return cacheInstance;\n  } catch (error) {\n    throw new DaitanConfigurationError(\n      `Failed to create cache instance for \"${cacheName}\"`,\n      {},\n      error\n    );\n  }\n};\n\n/**\n * Generates a SHA256 hash for a given object or string to be used as a cache key.\n */\nexport const generateCacheKey = (object, prefix = '') => {\n  const stableStringify = (obj) => {\n    if (typeof obj !== 'object' || obj === null) return JSON.stringify(obj);\n    if (Array.isArray(obj)) return JSON.stringify(obj.map(stableStringify));\n    return JSON.stringify(\n      Object.keys(obj)\n        .sort()\n        .reduce((acc, key) => {\n          acc[key] = stableStringify(obj[key]);\n          return acc;\n        }, {})\n    );\n  };\n  const stringToHash =\n    typeof object === 'string' ? object : stableStringify(object);\n  const hash = crypto.createHash('sha256').update(stringToHash).digest('hex');\n  return prefix ? `${prefix}:${hash}` : hash;\n};\n\n/**\n * Clears a specific cache or all managed caches.\n */\nexport const clearCache = (cacheName = 'all') => {\n  if (cacheName === 'all') {\n    Object.keys(globalCaches).forEach((name) => {\n      if (globalCaches[name]) {\n        globalCaches[name].flushAll();\n      }\n    });\n  } else if (globalCaches[cacheName]) {\n    globalCaches[cacheName].flushAll();\n  }\n};\n", "// intelligence/src/intelligence/language/index.js\n// --- DEFINITIVE FIX: Change ../intelligence to ../intelligence/index.js ---\nimport { generateIntelligence } from '../intelligence/core/llmOrchestrator.js';\nimport { getLogger } from '@daitanjs/development';\nimport { getConfigManager } from '@daitanjs/config';\nimport {\n  DaitanConfigurationError,\n  DaitanOperationError,\n} from '@daitanjs/error';\n\nconst languageLogger = getLogger('daitan-language-services');\n\n/**\n * @typedef {Object} TranslateParams\n * @property {string} language - Target ISO language code (e.g., 'es', 'fr').\n * @property {string | string[] | Object} body - The text, array of texts, or object with string values to translate.\n * @property {string} [sourceLanguage] - Optional: Source language ISO code. If not provided, LLM will attempt to auto-detect.\n * @property {string} [llmTarget] - The LLM target, as an expert profile name (e.g., 'TRANSLATION_MULTILINGUAL') or 'provider|model' string.\n * @property {import('../../services/llmService.js').LLMServiceConfig} [llmConfigOptions] - Additional LLM config options.\n * @property {boolean} [verbose] - Verbosity for this specific translation call.\n */\n\n/**\n * Translates text, an array of texts, or string values within an object to a target language.\n *\n * @param {TranslateParams} params - Parameters for translation.\n * @returns {Promise<string | string[] | Object>} The translated text, array, or object.\n * @throws {DaitanConfigurationError} if required parameters are missing.\n * @throws {DaitanOperationError} if translation fails.\n */\nexport const translate = async ({\n  language,\n  body,\n  sourceLanguage,\n  llmTarget,\n  llmConfigOptions = {},\n  verbose: callSpecificVerbose,\n}) => {\n  const configManager = getConfigManager(); // Lazy-load\n  const callId = `translate-${Date.now()}`;\n  const effectiveVerbose =\n    callSpecificVerbose ??\n    (configManager.get('DEBUG_TRANSLATION', false) ||\n      configManager.get('DEBUG_INTELLIGENCE', false));\n\n  if (!language || typeof language !== 'string' || language.trim().length < 2) {\n    throw new DaitanConfigurationError(\n      'Target language code (e.g., \"es\", \"fr\") is required.'\n    );\n  }\n  if (body === undefined || body === null) {\n    return body;\n  }\n\n  const effectiveTarget =\n    llmTarget ||\n    configManager.get('LLM_TARGET_TRANSLATE') ||\n    'TRANSLATION_MULTILINGUAL';\n\n  const translateDataItem = async (textToTranslate, itemKey = 'text') => {\n    if (typeof textToTranslate !== 'string' || textToTranslate.trim() === '') {\n      return textToTranslate;\n    }\n\n    const taskInstructions = [\n      `Translate the provided text accurately into ${language} (ISO language code).`,\n      sourceLanguage\n        ? `The source text is in ${sourceLanguage}.`\n        : 'The source language will be auto-detected.',\n      'Respond ONLY with the translated text.',\n      'Do not add any explanations, apologies, or phrases like \"Here is the translation:\".',\n      'Preserve the original meaning, tone, and nuances as much as possible.',\n    ];\n\n    try {\n      if (effectiveVerbose) {\n        languageLogger.debug(`Translating text to ${language}.`, {\n          callId,\n          itemKey,\n          textPreview: textToTranslate.substring(0, 70) + '...',\n        });\n      }\n      const { response: translatedText, usage } = await generateIntelligence({\n        prompt: {\n          system: {\n            persona: 'You are an expert multilingual translator.',\n            task: taskInstructions.join(' '),\n          },\n          user: textToTranslate,\n        },\n        config: {\n          response: { format: 'text' },\n          llm: {\n            target: effectiveTarget,\n            temperature: llmConfigOptions.temperature ?? 0.1,\n            maxTokens:\n              llmConfigOptions.maxTokens ??\n              Math.max(256, Math.floor(textToTranslate.length * 2.8)),\n            apiKey: llmConfigOptions.apiKey,\n            baseURL: llmConfigOptions.baseURL,\n          },\n          verbose: effectiveVerbose,\n          trackUsage:\n            llmConfigOptions.trackUsage ??\n            configManager.get('LLM_TRACK_USAGE', true),\n        },\n        metadata: {\n          summary: `Translate to ${language}: ${textToTranslate.substring(\n            0,\n            30\n          )}...`,\n        },\n      });\n\n      if (effectiveVerbose && usage) {\n        languageLogger.debug('LLM usage for translation step:', {\n          callId,\n          itemKey,\n          usage,\n        });\n      }\n      return String(translatedText || '');\n    } catch (error) {\n      languageLogger.error(\n        `Error translating item \"${itemKey}\" to ${language}.`,\n        { callId, errorName: error.name, errorMessage: error.message }\n      );\n      return `[[TRANSLATION_ERROR: ${textToTranslate.substring(0, 30)}...]]`;\n    }\n  };\n\n  try {\n    if (typeof body === 'string') {\n      return await translateDataItem(body, 'string_body');\n    } else if (Array.isArray(body)) {\n      if (effectiveVerbose)\n        languageLogger.info(\n          `Translating an array of ${body.length} items to ${language}.`,\n          { callId }\n        );\n      return Promise.all(\n        body.map((item, index) =>\n          translateDataItem(item, `array_item_${index}`)\n        )\n      );\n    } else if (body && typeof body === 'object') {\n      if (effectiveVerbose)\n        languageLogger.info(\n          `Translating string values in an object to ${language}.`,\n          { callId, objectKeys: Object.keys(body) }\n        );\n\n      const translatedObject = {};\n      const keys = Object.keys(body);\n      const translationPromises = keys.map((key) =>\n        translateDataItem(body[key], `object_key_${key}`)\n      );\n      const translatedValues = await Promise.all(translationPromises);\n\n      keys.forEach((key, index) => {\n        translatedObject[key] = translatedValues[index];\n      });\n      return translatedObject;\n    } else {\n      return body;\n    }\n  } catch (error) {\n    languageLogger.error(\n      `Top-level error in translate function for language ${language}.`,\n      { callId, errorName: error.name },\n      error\n    );\n    throw new DaitanOperationError(\n      `Translation to ${language} failed: ${error.message}`,\n      { targetLanguage: language },\n      error\n    );\n  }\n};\n"],
  "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,IAAAA,uBAA0B;;;ACO1B,IAAAC,uBAA0B;AAC1B,IAAAC,kBAAiC;;;ACFjC,oBAA2B;AAC3B,uBAA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EACF,SAAS,OAAO;AACd,mBAAe;AAAA,MACb,sDAAsD,QAAQ;AAAA,MAC9D,EAAE,QAAQ,WAAW,MAAM,KAAK;AAAA,MAChC;AAAA,IACF;AACA,UAAM,IAAI;AAAA,MACR,kBAAkB,QAAQ,YAAY,MAAM,OAAO;AAAA,MACnD,EAAE,gBAAgB,SAAS;AAAA,MAC3B;AAAA,IACF;AAAA,EACF;AACF;;;A7D3KA,IAAM,sBAAkB,gCAAU,gCAAgC;AAElE,gBAAgB;AAAA,EACd;AACF;AA+DA,gBAAgB;AAAA,EACd;AACF;",
  "names": ["import_development", "import_development", "import_config", "import_development", "import_development", "import_development", "logger", "import_development", "logger", "import_development", "import_config", "import_error", "logger", "import_development", "import_development", "import_development", "import_error", "logger", "import_development", "import_development", "import_config", "import_error", "import_openai", "import_development", "import_config", "import_error", "import_development", "import_config", "import_error", "logger", "logger", "import_openai", "import_development", "import_config", "import_error", "import_memory", "import_development", "import_development", "import_config", "import_error", "path", "import_development", "import_config", "import_error", "import_development", "import_config", "import_path", "import_development", "import_config", "import_error", "import_documents", "path", "fs", "LangchainDocumentCore", "mammoth", "Papa", "import_development", "import_development", "import_config", "import_error", "import_error", "import_path", "import_chromadb", "import_development", "import_config", "import_error", "DirectChromaClient", "path", "import_development", "logger", "import_development", "import_development", "import_error", "import_zod", "import_development", "import_error", "import_zod", "TOOL_NAME", "import_development", "import_error", "import_zod", "util", "TOOL_NAME", "import_tools", "import_development", "import_error", "import_zod", "TOOL_NAME", "import_zod", "import_error", "import_zod", "import_zod", "import_zod", "import_error", "import_zod", "import_media", "import_error", "import_zod", "import_development", "import_error", "import_zod", "import_googleapis", "import_development", "import_error", "import_zod", "TOOL_NAME", "import_googleapis", "import_development", "import_error", "import_zod", "import_zod", "import_error", "import_development", "import_error", "import_tools", "import_zod", "import_messages", "import_development", "import_development", "import_config", "import_error", "import_langgraph", "import_messages", "import_development", "import_messages", "import_development", "import_config", "import_error", "import_error", "import_langgraph", "import_messages", "import_development", "import_error", "import_error", "import_prompts", "import_development", "import_config", "import_memory", "import_development", "logger", "import_error", "import_openai", "chalk", "sessionId", "import_development", "import_error", "import_development", "import_error", "import_config", "import_error", "import_error", "import_error", "import_config", "import_development", "import_development", "import_error", "import_langgraph", "import_chalk", "logger", "chalk", "plannerNode", "executorNode", "synthesizerNode", "import_development", "import_web", "import_error", "logger", "import_web", "import_development", "import_error", "import_path", "path", "import_development", "logger", "axios", "import_messages", "logger", "import_config", "import_development", "import_error", "import_data", "logger", "crypto", "import_development", "import_config", "import_error"]
}
