@hashgraphonline/conversational-agent 0.1.219 → 0.1.221
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/base-agent.d.ts +2 -0
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/langchain/form-aware-agent-executor.d.ts +6 -3
- package/dist/esm/index10.js +2 -2
- package/dist/esm/index21.js +1 -1
- package/dist/esm/index23.js +1 -1
- package/dist/esm/index25.js +0 -4
- package/dist/esm/index25.js.map +1 -1
- package/dist/esm/index29.js +0 -6
- package/dist/esm/index29.js.map +1 -1
- package/dist/esm/index31.js +4 -71
- package/dist/esm/index31.js.map +1 -1
- package/dist/esm/index37.js +11 -4
- package/dist/esm/index37.js.map +1 -1
- package/dist/esm/index38.js +6 -11
- package/dist/esm/index38.js.map +1 -1
- package/dist/esm/index39.js +24 -252
- package/dist/esm/index39.js.map +1 -1
- package/dist/esm/index40.js +5 -184
- package/dist/esm/index40.js.map +1 -1
- package/dist/esm/index41.js +252 -24
- package/dist/esm/index41.js.map +1 -1
- package/dist/esm/index42.js +184 -7
- package/dist/esm/index42.js.map +1 -1
- package/dist/esm/index6.js +1 -5
- package/dist/esm/index6.js.map +1 -1
- package/dist/esm/index7.js.map +1 -1
- package/dist/types/base-agent.d.ts +2 -0
- package/dist/types/langchain/form-aware-agent-executor.d.ts +6 -3
- package/package.json +6 -7
- package/src/base-agent.ts +4 -0
- package/src/conversational-agent.ts +3 -14
- package/src/langchain/form-aware-agent-executor.ts +64 -81
- package/src/langchain/langchain-agent.ts +24 -104
- package/src/services/formatters/format-converter-registry.ts +0 -5
package/dist/esm/index6.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index6.js","sources":["../../src/conversational-agent.ts"],"sourcesContent":["import {\n ServerSigner,\n getAllHederaCorePlugins,\n BasePlugin,\n} from 'hedera-agent-kit';\nimport { Logger, type NetworkType } from '@hashgraphonline/standards-sdk';\nimport { createAgent } from './agent-factory';\nimport { LangChainProvider } from './providers';\nimport type { ChatResponse, ConversationContext } from './base-agent';\nimport { ChatOpenAI } from '@langchain/openai';\nimport { ChatAnthropic } from '@langchain/anthropic';\nimport {\n HumanMessage,\n AIMessage,\n SystemMessage,\n} from '@langchain/core/messages';\nimport type { AgentOperationalMode, MirrorNodeConfig } from 'hedera-agent-kit';\nimport { HCS10Plugin } from './plugins/hcs-10/HCS10Plugin';\nimport { HCS2Plugin } from './plugins/hcs-2/HCS2Plugin';\nimport { InscribePlugin } from './plugins/inscribe/InscribePlugin';\nimport { HbarPlugin } from './plugins/hbar/HbarPlugin';\nimport { OpenConvaiState } from '@hashgraphonline/standards-agent-kit';\nimport type { IStateManager } from '@hashgraphonline/standards-agent-kit';\nimport { getSystemMessage } from './config/system-message';\nimport type { MCPServerConfig, MCPConnectionStatus } from './mcp/types';\nimport { ContentStoreManager } from './services/content-store-manager';\nimport { SmartMemoryManager, type SmartMemoryConfig } from './memory';\nimport {\n createEntityTools,\n ResolveEntitiesTool,\n ExtractEntitiesTool,\n} from './tools/entity-resolver-tool';\nimport type { FormSubmission } from './forms/types';\n\nexport type ToolDescriptor = {\n name: string;\n namespace?: string;\n};\n\nexport type ChatHistoryItem = {\n type: 'human' | 'ai' | 'system';\n content: string;\n};\n\nexport type AgentInstance = ReturnType<typeof createAgent>;\n\nexport type MirrorNetwork = 'testnet' | 'mainnet' | 'previewnet';\n\nconst DEFAULT_MODEL_NAME = 'gpt-4o';\nconst DEFAULT_TEMPERATURE = 0.1;\nconst DEFAULT_NETWORK = 'testnet';\nconst DEFAULT_OPERATIONAL_MODE: AgentOperationalMode = 'autonomous';\n\nexport interface ConversationalAgentOptions {\n accountId: string;\n privateKey: string;\n network?: NetworkType;\n openAIApiKey: string;\n openAIModelName?: string;\n llmProvider?: 'openai' | 'anthropic';\n verbose?: boolean;\n operationalMode?: AgentOperationalMode;\n userAccountId?: string;\n customSystemMessagePreamble?: string;\n customSystemMessagePostamble?: string;\n additionalPlugins?: BasePlugin[];\n stateManager?: IStateManager;\n scheduleUserTransactionsInBytesMode?: boolean;\n mirrorNodeConfig?: MirrorNodeConfig;\n disableLogging?: boolean;\n enabledPlugins?: string[];\n toolFilter?: (tool: { name: string; namespace?: string }) => boolean;\n mcpServers?: MCPServerConfig[];\n\n /** Enable automatic entity memory functionality (default: true) */\n entityMemoryEnabled?: boolean;\n\n /** Configuration for entity memory system */\n entityMemoryConfig?: SmartMemoryConfig;\n}\n\n/**\n * The ConversationalAgent class is an optional wrapper around the HederaConversationalAgent class,\n * which includes the OpenConvAIPlugin and the OpenConvaiState by default.\n * If you want to use a different plugin or state manager, you can pass them in the options.\n * This class is not required and the plugin can be used directly with the HederaConversationalAgent class.\n *\n * @param options - The options for the ConversationalAgent.\n * @returns A new instance of the ConversationalAgent class.\n */\nexport class ConversationalAgent {\n private static readonly NOT_INITIALIZED_ERROR = 'Agent not initialized. Call initialize() first.';\n protected agent?: AgentInstance;\n public hcs10Plugin: HCS10Plugin;\n public hcs2Plugin: HCS2Plugin;\n public inscribePlugin: InscribePlugin;\n public hbarPlugin: HbarPlugin;\n public stateManager: IStateManager;\n private options: ConversationalAgentOptions;\n public logger: Logger;\n public contentStoreManager?: ContentStoreManager;\n public memoryManager?: SmartMemoryManager | undefined;\n private entityTools?: {\n resolveEntities: ResolveEntitiesTool;\n extractEntities: ExtractEntitiesTool;\n };\n\n constructor(options: ConversationalAgentOptions) {\n this.options = options;\n this.stateManager = options.stateManager || new OpenConvaiState();\n this.hcs10Plugin = new HCS10Plugin();\n this.hcs2Plugin = new HCS2Plugin();\n this.inscribePlugin = new InscribePlugin();\n this.hbarPlugin = new HbarPlugin();\n this.logger = new Logger({\n module: 'ConversationalAgent',\n silent: options.disableLogging || false,\n });\n\n if (this.options.entityMemoryEnabled !== false) {\n if (!options.openAIApiKey) {\n throw new Error(\n 'OpenAI API key is required when entity memory is enabled'\n );\n }\n\n this.memoryManager = new SmartMemoryManager(\n this.options.entityMemoryConfig\n );\n this.logger.info('Entity memory initialized');\n\n this.entityTools = createEntityTools(options.openAIApiKey, 'gpt-4o-mini');\n this.logger.info('LLM-based entity resolver tools initialized');\n }\n }\n\n /**\n * Initialize the conversational agent with Hedera Hashgraph connection and AI configuration\n * @throws {Error} If account ID or private key is missing\n * @throws {Error} If initialization fails\n */\n async initialize(): Promise<void> {\n const {\n accountId,\n privateKey,\n network = DEFAULT_NETWORK,\n openAIApiKey,\n openAIModelName = DEFAULT_MODEL_NAME,\n llmProvider = 'openai',\n } = this.options;\n\n this.validateOptions(accountId, privateKey);\n\n try {\n const serverSigner = new ServerSigner(\n accountId!,\n privateKey!,\n network as MirrorNetwork\n );\n\n let llm: ChatOpenAI | ChatAnthropic;\n if (llmProvider === 'anthropic') {\n llm = new ChatAnthropic({\n apiKey: openAIApiKey,\n modelName: openAIModelName || 'claude-3-5-sonnet-20241022',\n temperature: DEFAULT_TEMPERATURE,\n });\n } else {\n const modelName = openAIModelName || 'gpt-4o-mini';\n const isGPT5Model =\n modelName.toLowerCase().includes('gpt-5') ||\n modelName.toLowerCase().includes('gpt5');\n llm = new ChatOpenAI({\n apiKey: openAIApiKey,\n modelName: openAIModelName,\n ...(isGPT5Model\n ? { temperature: 1 }\n : { temperature: DEFAULT_TEMPERATURE }),\n });\n }\n\n this.logger.info('Preparing plugins...');\n const allPlugins = this.preparePlugins();\n this.logger.info('Creating agent config...');\n const agentConfig = this.createAgentConfig(serverSigner, llm, allPlugins);\n\n this.logger.info('Creating agent...');\n this.agent = createAgent(agentConfig);\n this.logger.info('Agent created');\n\n this.logger.info('Configuring HCS10 plugin...');\n this.configureHCS10Plugin(allPlugins);\n this.logger.info('HCS10 plugin configured');\n\n this.contentStoreManager = new ContentStoreManager();\n await this.contentStoreManager.initialize();\n this.logger.info(\n 'ContentStoreManager initialized for content reference support'\n );\n\n this.logger.info('About to call agent.boot()');\n this.logger.info('🔥 About to call agent.boot()');\n await this.agent.boot();\n this.logger.info('agent.boot() completed');\n this.logger.info('🔥 agent.boot() completed');\n\n if (this.agent) {\n const cfg = agentConfig;\n cfg.filtering = cfg.filtering || {};\n const originalPredicate = cfg.filtering.toolPredicate as\n | ((t: ToolDescriptor) => boolean)\n | undefined;\n const userPredicate = this.options.toolFilter;\n cfg.filtering.toolPredicate = (tool: ToolDescriptor): boolean => {\n if (tool && tool.name === 'hedera-account-transfer-hbar') {\n return false;\n }\n if (tool && tool.name === 'hedera-hts-airdrop-token') {\n return false;\n }\n if (originalPredicate && !originalPredicate(tool)) {\n return false;\n }\n if (userPredicate && !userPredicate(tool)) {\n return false;\n }\n return true;\n };\n }\n\n if (this.options.mcpServers && this.options.mcpServers.length > 0) {\n this.connectMCP();\n }\n } catch (error) {\n this.logger.error('Failed to initialize ConversationalAgent:', error);\n throw error;\n }\n }\n\n /**\n * Get the HCS-10 plugin instance\n * @returns {HCS10Plugin} The HCS-10 plugin instance\n */\n getPlugin(): HCS10Plugin {\n return this.hcs10Plugin;\n }\n\n /**\n * Get the state manager instance\n * @returns {IStateManager} The state manager instance\n */\n getStateManager(): IStateManager {\n return this.stateManager;\n }\n\n /**\n * Get the underlying agent instance\n * @returns {ReturnType<typeof createAgent>} The agent instance\n * @throws {Error} If agent is not initialized\n */\n getAgent(): ReturnType<typeof createAgent> {\n if (!this.agent) {\n throw new Error(ConversationalAgent.NOT_INITIALIZED_ERROR);\n }\n return this.agent;\n }\n\n /**\n * Get the conversational agent instance (alias for getAgent)\n * @returns {ReturnType<typeof createAgent>} The agent instance\n * @throws {Error} If agent is not initialized\n */\n getConversationalAgent(): ReturnType<typeof createAgent> {\n return this.getAgent();\n }\n\n /**\n * Process a message through the conversational agent\n * @param {string} message - The message to process\n * @param {Array<{type: 'human' | 'ai'; content: string}>} chatHistory - Previous chat history\n * @returns {Promise<ChatResponse>} The agent's response\n * @throws {Error} If agent is not initialized\n */\n async processMessage(\n message: string,\n chatHistory: ChatHistoryItem[] = []\n ): Promise<ChatResponse> {\n if (!this.agent) {\n throw new Error('Agent not initialized. Call initialize() first.');\n }\n\n try {\n const resolvedMessage = message;\n\n const messages = chatHistory.map((msg) => {\n const content = msg.content;\n if (msg.type === 'system') {\n return new SystemMessage(content);\n }\n return msg.type === 'human'\n ? new HumanMessage(content)\n : new AIMessage(content);\n });\n\n const context: ConversationContext = { messages };\n const response = await this.agent.chat(resolvedMessage, context);\n\n if (\n this.memoryManager &&\n this.options.operationalMode !== 'returnBytes'\n ) {\n await this.extractAndStoreEntities(response, message);\n }\n\n this.logger.info('Message processed successfully');\n return response;\n } catch (error) {\n this.logger.error('Error processing message:', error);\n throw error;\n }\n }\n\n /**\n * Process form submission through the conversational agent\n * @param {FormSubmission} submission - The form submission data\n * @returns {Promise<ChatResponse>} The agent's response after processing the form\n * @throws {Error} If agent is not initialized or doesn't support form processing\n */\n async processFormSubmission(\n submission: FormSubmission\n ): Promise<ChatResponse> {\n if (!this.agent) {\n throw new Error(ConversationalAgent.NOT_INITIALIZED_ERROR);\n }\n\n const internalAgent = this.agent as {\n processFormSubmission?: (\n submission: FormSubmission\n ) => Promise<ChatResponse>;\n };\n if (\n !internalAgent.processFormSubmission ||\n typeof internalAgent.processFormSubmission !== 'function'\n ) {\n throw new Error('processFormSubmission not available on internal agent');\n }\n\n try {\n this.logger.info('Processing form submission:', {\n formId: submission.formId,\n toolName: submission.toolName,\n parameterKeys: Object.keys(submission.parameters || {}),\n hasContext: !!submission.context,\n });\n const response = await internalAgent.processFormSubmission(submission);\n this.logger.info('Form submission processed successfully');\n return response;\n } catch (error) {\n this.logger.error('Error processing form submission:', error);\n throw error;\n }\n }\n\n /**\n * Validates initialization options and throws if required fields are missing.\n *\n * @param accountId - The Hedera account ID\n * @param privateKey - The private key for the account\n * @throws {Error} If required fields are missing\n */\n private validateOptions(accountId?: string, privateKey?: string): void {\n if (!accountId || !privateKey) {\n throw new Error('Account ID and private key are required');\n }\n\n if (typeof accountId !== 'string') {\n throw new Error(\n `Account ID must be a string, received ${typeof accountId}`\n );\n }\n\n if (typeof privateKey !== 'string') {\n throw new Error(\n `Private key must be a string, received ${typeof privateKey}: ${JSON.stringify(\n privateKey\n )}`\n );\n }\n\n if (privateKey.length < 10) {\n throw new Error('Private key appears to be invalid (too short)');\n }\n }\n\n /**\n * Prepares the list of plugins to use based on configuration.\n *\n * @returns Array of plugins to initialize with the agent\n */\n private preparePlugins(): BasePlugin[] {\n const { additionalPlugins = [], enabledPlugins } = this.options;\n\n const standardPlugins = [\n this.hcs10Plugin,\n this.hcs2Plugin,\n this.inscribePlugin,\n this.hbarPlugin,\n ];\n\n const corePlugins = getAllHederaCorePlugins();\n\n if (enabledPlugins) {\n const enabledSet = new Set(enabledPlugins);\n const filteredPlugins = [...standardPlugins, ...corePlugins].filter(\n (plugin) => enabledSet.has(plugin.id)\n );\n return [...filteredPlugins, ...additionalPlugins];\n }\n\n return [...standardPlugins, ...corePlugins, ...additionalPlugins];\n }\n\n /**\n * Creates the agent configuration object.\n *\n * @param serverSigner - The server signer instance\n * @param llm - The language model instance\n * @param allPlugins - Array of plugins to use\n * @returns Configuration object for creating the agent\n */\n private createAgentConfig(\n serverSigner: ServerSigner,\n llm: ChatOpenAI | ChatAnthropic,\n allPlugins: BasePlugin[]\n ): Parameters<typeof createAgent>[0] {\n const {\n operationalMode = DEFAULT_OPERATIONAL_MODE,\n userAccountId,\n scheduleUserTransactionsInBytesMode,\n customSystemMessagePreamble,\n customSystemMessagePostamble,\n verbose = false,\n mirrorNodeConfig,\n disableLogging,\n accountId = '',\n } = this.options;\n\n return {\n framework: 'langchain',\n signer: serverSigner,\n execution: {\n mode: operationalMode === 'autonomous' ? 'direct' : 'bytes',\n operationalMode: operationalMode,\n ...(userAccountId && { userAccountId }),\n ...(scheduleUserTransactionsInBytesMode !== undefined && {\n scheduleUserTransactionsInBytesMode:\n scheduleUserTransactionsInBytesMode,\n scheduleUserTransactions: scheduleUserTransactionsInBytesMode,\n }),\n },\n ai: {\n provider: new LangChainProvider(llm),\n temperature: DEFAULT_TEMPERATURE,\n },\n filtering: {\n toolPredicate: (tool: ToolDescriptor): boolean => {\n if (tool.name === 'hedera-account-transfer-hbar') return false;\n if (this.options.toolFilter && !this.options.toolFilter(tool)) {\n return false;\n }\n return true;\n },\n },\n messaging: {\n systemPreamble:\n customSystemMessagePreamble || getSystemMessage(accountId),\n ...(customSystemMessagePostamble && {\n systemPostamble: customSystemMessagePostamble,\n }),\n conciseMode: true,\n },\n extensions: {\n plugins: allPlugins,\n ...(mirrorNodeConfig && {\n mirrorConfig: mirrorNodeConfig as Record<string, unknown>,\n }),\n },\n ...(this.options.mcpServers && {\n mcp: {\n servers: this.options.mcpServers,\n autoConnect: false,\n },\n }),\n debug: {\n verbose,\n silent: disableLogging ?? false,\n },\n };\n }\n\n /**\n * Configures the HCS-10 plugin with the state manager.\n *\n * @param allPlugins - Array of all plugins\n */\n private configureHCS10Plugin(allPlugins: BasePlugin[]): void {\n const hcs10 = allPlugins.find((p) => p.id === 'hcs-10');\n if (hcs10) {\n (\n hcs10 as BasePlugin & { appConfig?: Record<string, unknown> }\n ).appConfig = {\n stateManager: this.stateManager,\n };\n }\n }\n\n /**\n * Create a ConversationalAgent with specific plugins enabled\n */\n private static withPlugins(\n options: ConversationalAgentOptions,\n plugins: string[]\n ): ConversationalAgent {\n return new ConversationalAgent({\n ...options,\n enabledPlugins: plugins,\n });\n }\n\n /**\n * Create a ConversationalAgent with only HTS (Hedera Token Service) tools enabled\n */\n static withHTS(options: ConversationalAgentOptions): ConversationalAgent {\n return this.withPlugins(options, ['hts-token']);\n }\n\n /**\n * Create a ConversationalAgent with only HCS-2 tools enabled\n */\n static withHCS2(options: ConversationalAgentOptions): ConversationalAgent {\n return this.withPlugins(options, ['hcs-2']);\n }\n\n /**\n * Create a ConversationalAgent with only HCS-10 tools enabled\n */\n static withHCS10(options: ConversationalAgentOptions): ConversationalAgent {\n return this.withPlugins(options, ['hcs-10']);\n }\n\n /**\n * Create a ConversationalAgent with only inscription tools enabled\n */\n static withInscribe(\n options: ConversationalAgentOptions\n ): ConversationalAgent {\n return this.withPlugins(options, ['inscribe']);\n }\n\n /**\n * Create a ConversationalAgent with only account management tools enabled\n */\n static withAccount(options: ConversationalAgentOptions): ConversationalAgent {\n return this.withPlugins(options, ['account']);\n }\n\n /**\n * Create a ConversationalAgent with only file service tools enabled\n */\n static withFileService(\n options: ConversationalAgentOptions\n ): ConversationalAgent {\n return this.withPlugins(options, ['file-service']);\n }\n\n /**\n * Create a ConversationalAgent with only consensus service tools enabled\n */\n static withConsensusService(\n options: ConversationalAgentOptions\n ): ConversationalAgent {\n return this.withPlugins(options, ['consensus-service']);\n }\n\n /**\n * Create a ConversationalAgent with only smart contract tools enabled\n */\n static withSmartContract(\n options: ConversationalAgentOptions\n ): ConversationalAgent {\n return this.withPlugins(options, ['smart-contract']);\n }\n\n /**\n * Create a ConversationalAgent with all HCS standards plugins\n */\n static withAllStandards(\n options: ConversationalAgentOptions\n ): ConversationalAgent {\n return this.withPlugins(options, ['hcs-10', 'hcs-2', 'inscribe']);\n }\n\n /**\n * Create a ConversationalAgent with minimal Hedera tools (no HCS standards)\n */\n static minimal(options: ConversationalAgentOptions): ConversationalAgent {\n return this.withPlugins(options, []);\n }\n\n /**\n * Create a ConversationalAgent with MCP servers configured\n */\n static withMCP(\n options: ConversationalAgentOptions,\n mcpServers: MCPServerConfig[]\n ): ConversationalAgent {\n return new ConversationalAgent({\n ...options,\n mcpServers,\n });\n }\n\n /**\n * Extract and store entities from agent responses\n * @param response - Agent response containing potential entity information\n * @param originalMessage - Original user message for context\n */\n private async extractAndStoreEntities(\n response: unknown,\n originalMessage: string\n ): Promise<void> {\n if (!this.memoryManager || !this.entityTools) {\n return;\n }\n\n try {\n this.logger.info('Starting LLM-based entity extraction');\n\n const responseText = this.extractResponseText(response);\n\n const entitiesJson = await this.entityTools.extractEntities.call({\n response: responseText,\n userMessage: originalMessage,\n });\n\n try {\n const entities = JSON.parse(entitiesJson);\n\n for (const entity of entities) {\n if (\n entity &&\n typeof entity === 'object' &&\n 'name' in entity &&\n 'type' in entity &&\n 'id' in entity\n ) {\n this.logger.info(\n `Storing entity: ${entity.name} (${entity.type}) -> ${entity.id}`\n );\n\n const transactionId = this.extractTransactionId(response);\n const idStr = String(entity.id);\n const isHederaId = /^0\\.0\\.[0-9]+$/.test(idStr);\n if (!isHederaId) {\n this.logger.warn('Skipping non-ID entity from extraction', {\n id: idStr,\n name: String(entity.name),\n type: String(entity.type),\n });\n } else {\n this.memoryManager.storeEntityAssociation(\n idStr,\n String(entity.name),\n String(entity.type),\n transactionId\n );\n }\n }\n }\n\n if (entities.length > 0) {\n this.logger.info(\n `Stored ${entities.length} entities via LLM extraction`\n );\n } else {\n this.logger.info('No entities found in response via LLM extraction');\n }\n } catch (parseError) {\n this.logger.error(\n 'Failed to parse extracted entities JSON:',\n parseError\n );\n throw parseError;\n }\n } catch (error) {\n this.logger.error('Entity extraction failed:', error);\n throw error;\n }\n }\n\n /**\n * Extract transaction ID from response if available\n * @param response - Transaction response\n * @returns Transaction ID or undefined\n */\n private extractTransactionId(response: unknown): string | undefined {\n try {\n if (\n typeof response === 'object' &&\n response &&\n 'transactionId' in response\n ) {\n const responseWithTxId = response as { transactionId?: unknown };\n return typeof responseWithTxId.transactionId === 'string'\n ? responseWithTxId.transactionId\n : undefined;\n }\n if (typeof response === 'string') {\n const match = response.match(\n /transaction[\\s\\w]*ID[\\s:\"]*([0-9a-fA-F@\\.\\-]+)/i\n );\n return match ? match[1] : undefined;\n }\n return undefined;\n } catch {\n return undefined;\n }\n }\n\n /**\n * Connect to MCP servers asynchronously\n * @private\n */\n private connectMCP(): void {\n if (!this.agent || !this.options.mcpServers) {\n return;\n }\n\n this.agent\n .connectMCPServers()\n .catch((e) => {\n this.logger.error('Failed to connect MCP servers:', e);\n })\n .then(() => {\n this.logger.info('MCP servers connected successfully');\n });\n }\n\n /**\n * Get MCP connection status for all servers\n * @returns {Map<string, MCPConnectionStatus>} Connection status map\n */\n getMCPConnectionStatus(): Map<string, MCPConnectionStatus> {\n if (this.agent) {\n return this.agent.getMCPConnectionStatus();\n }\n return new Map();\n }\n\n /**\n * Check if a specific MCP server is connected\n * @param {string} serverName - Name of the server to check\n * @returns {boolean} True if connected, false otherwise\n */\n isMCPServerConnected(serverName: string): boolean {\n if (this.agent) {\n const statusMap = this.agent.getMCPConnectionStatus();\n const status = statusMap.get(serverName);\n return status?.connected ?? false;\n }\n return false;\n }\n\n /**\n * Clean up resources\n */\n async cleanup(): Promise<void> {\n try {\n this.logger.info('Cleaning up ConversationalAgent...');\n\n if (this.memoryManager) {\n try {\n this.memoryManager.dispose();\n this.logger.info('Memory manager cleaned up successfully');\n } catch (error) {\n this.logger.warn('Error cleaning up memory manager:', error);\n }\n this.memoryManager = undefined;\n }\n\n if (this.contentStoreManager) {\n await this.contentStoreManager.dispose();\n this.logger.info('ContentStoreManager cleaned up');\n }\n\n this.logger.info('ConversationalAgent cleanup completed');\n } catch (error) {\n this.logger.error('Error during cleanup:', error);\n }\n }\n\n private extractResponseText(response: unknown): string {\n if (typeof response === 'string') {\n return response;\n }\n\n if (response && typeof response === 'object' && 'output' in response) {\n const responseWithOutput = response as { output: unknown };\n return String(responseWithOutput.output);\n }\n\n return JSON.stringify(response);\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAgDA,MAAM,qBAAqB;AAC3B,MAAM,sBAAsB;AAC5B,MAAM,kBAAkB;AACxB,MAAM,2BAAiD;AAuChD,MAAM,uBAAN,MAAM,qBAAoB;AAAA,EAiB/B,YAAY,SAAqC;AAC/C,SAAK,UAAU;AACf,SAAK,eAAe,QAAQ,gBAAgB,IAAI,gBAAA;AAChD,SAAK,cAAc,IAAI,YAAA;AACvB,SAAK,aAAa,IAAI,WAAA;AACtB,SAAK,iBAAiB,IAAI,eAAA;AAC1B,SAAK,aAAa,IAAI,WAAA;AACtB,SAAK,SAAS,IAAI,OAAO;AAAA,MACvB,QAAQ;AAAA,MACR,QAAQ,QAAQ,kBAA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qBAAqB;AAC3B,aAAO,OAAO,mBAAmB,MAAM;AAAA,IACzC;AAEA,WAAO,KAAK,UAAU,QAAQ;AAAA,EAChC;AACF;AAltBE,qBAAwB,wBAAwB;AAD3C,IAAM,sBAAN;"}
|
|
1
|
+
{"version":3,"file":"index6.js","sources":["../../src/conversational-agent.ts"],"sourcesContent":["import {\n ServerSigner,\n getAllHederaCorePlugins,\n BasePlugin,\n} from 'hedera-agent-kit';\nimport { Logger, type NetworkType } from '@hashgraphonline/standards-sdk';\nimport { createAgent } from './agent-factory';\nimport { LangChainProvider } from './providers';\nimport type { ChatResponse, ConversationContext } from './base-agent';\nimport { ChatOpenAI } from '@langchain/openai';\nimport { ChatAnthropic } from '@langchain/anthropic';\nimport {\n HumanMessage,\n AIMessage,\n SystemMessage,\n} from '@langchain/core/messages';\nimport type { AgentOperationalMode, MirrorNodeConfig } from 'hedera-agent-kit';\nimport { HCS10Plugin } from './plugins/hcs-10/HCS10Plugin';\nimport { HCS2Plugin } from './plugins/hcs-2/HCS2Plugin';\nimport { InscribePlugin } from './plugins/inscribe/InscribePlugin';\nimport { HbarPlugin } from './plugins/hbar/HbarPlugin';\nimport { OpenConvaiState } from '@hashgraphonline/standards-agent-kit';\nimport type { IStateManager } from '@hashgraphonline/standards-agent-kit';\nimport { getSystemMessage } from './config/system-message';\nimport type { MCPServerConfig, MCPConnectionStatus } from './mcp/types';\nimport { ContentStoreManager } from './services/content-store-manager';\nimport { SmartMemoryManager, type SmartMemoryConfig } from './memory';\nimport {\n createEntityTools,\n ResolveEntitiesTool,\n ExtractEntitiesTool,\n} from './tools/entity-resolver-tool';\nimport type { FormSubmission } from './forms/types';\n\nexport type ToolDescriptor = {\n name: string;\n namespace?: string;\n};\n\nexport type ChatHistoryItem = {\n type: 'human' | 'ai' | 'system';\n content: string;\n};\n\nexport type AgentInstance = ReturnType<typeof createAgent>;\n\nexport type MirrorNetwork = 'testnet' | 'mainnet' | 'previewnet';\n\nconst DEFAULT_MODEL_NAME = 'gpt-4o';\nconst DEFAULT_TEMPERATURE = 0.1;\nconst DEFAULT_NETWORK = 'testnet';\nconst DEFAULT_OPERATIONAL_MODE: AgentOperationalMode = 'autonomous';\n\nexport interface ConversationalAgentOptions {\n accountId: string;\n privateKey: string;\n network?: NetworkType;\n openAIApiKey: string;\n openAIModelName?: string;\n llmProvider?: 'openai' | 'anthropic';\n verbose?: boolean;\n operationalMode?: AgentOperationalMode;\n userAccountId?: string;\n customSystemMessagePreamble?: string;\n customSystemMessagePostamble?: string;\n additionalPlugins?: BasePlugin[];\n stateManager?: IStateManager;\n scheduleUserTransactionsInBytesMode?: boolean;\n mirrorNodeConfig?: MirrorNodeConfig;\n disableLogging?: boolean;\n enabledPlugins?: string[];\n toolFilter?: (tool: { name: string; namespace?: string }) => boolean;\n mcpServers?: MCPServerConfig[];\n\n /** Enable automatic entity memory functionality (default: true) */\n entityMemoryEnabled?: boolean;\n\n /** Configuration for entity memory system */\n entityMemoryConfig?: SmartMemoryConfig;\n}\n\n/**\n * The ConversationalAgent class is an optional wrapper around the HederaConversationalAgent class,\n * which includes the OpenConvAIPlugin and the OpenConvaiState by default.\n * If you want to use a different plugin or state manager, you can pass them in the options.\n * This class is not required and the plugin can be used directly with the HederaConversationalAgent class.\n *\n * @param options - The options for the ConversationalAgent.\n * @returns A new instance of the ConversationalAgent class.\n */\nexport class ConversationalAgent {\n private static readonly NOT_INITIALIZED_ERROR =\n 'Agent not initialized. Call initialize() first.';\n protected agent?: AgentInstance;\n public hcs10Plugin: HCS10Plugin;\n public hcs2Plugin: HCS2Plugin;\n public inscribePlugin: InscribePlugin;\n public hbarPlugin: HbarPlugin;\n public stateManager: IStateManager;\n private options: ConversationalAgentOptions;\n public logger: Logger;\n public contentStoreManager?: ContentStoreManager;\n public memoryManager?: SmartMemoryManager | undefined;\n private entityTools?: {\n resolveEntities: ResolveEntitiesTool;\n extractEntities: ExtractEntitiesTool;\n };\n\n constructor(options: ConversationalAgentOptions) {\n this.options = options;\n this.stateManager = options.stateManager || new OpenConvaiState();\n this.hcs10Plugin = new HCS10Plugin();\n this.hcs2Plugin = new HCS2Plugin();\n this.inscribePlugin = new InscribePlugin();\n this.hbarPlugin = new HbarPlugin();\n this.logger = new Logger({\n module: 'ConversationalAgent',\n silent: options.disableLogging || false,\n });\n\n if (this.options.entityMemoryEnabled !== false) {\n if (!options.openAIApiKey) {\n throw new Error(\n 'OpenAI API key is required when entity memory is enabled'\n );\n }\n\n this.memoryManager = new SmartMemoryManager(\n this.options.entityMemoryConfig\n );\n this.logger.info('Entity memory initialized');\n\n this.entityTools = createEntityTools(options.openAIApiKey, 'gpt-4o-mini');\n this.logger.info('LLM-based entity resolver tools initialized');\n }\n }\n\n /**\n * Initialize the conversational agent with Hedera Hashgraph connection and AI configuration\n * @throws {Error} If account ID or private key is missing\n * @throws {Error} If initialization fails\n */\n async initialize(): Promise<void> {\n const {\n accountId,\n privateKey,\n network = DEFAULT_NETWORK,\n openAIApiKey,\n openAIModelName = DEFAULT_MODEL_NAME,\n llmProvider = 'openai',\n } = this.options;\n\n this.validateOptions(accountId, privateKey);\n\n try {\n const serverSigner = new ServerSigner(\n accountId!,\n privateKey!,\n network as MirrorNetwork\n );\n\n let llm: ChatOpenAI | ChatAnthropic;\n if (llmProvider === 'anthropic') {\n llm = new ChatAnthropic({\n apiKey: openAIApiKey,\n modelName: openAIModelName || 'claude-3-5-sonnet-20241022',\n temperature: DEFAULT_TEMPERATURE,\n });\n } else {\n const modelName = openAIModelName || 'gpt-4o-mini';\n const isGPT5Model =\n modelName.toLowerCase().includes('gpt-5') ||\n modelName.toLowerCase().includes('gpt5');\n llm = new ChatOpenAI({\n apiKey: openAIApiKey,\n modelName: openAIModelName,\n ...(isGPT5Model\n ? { temperature: 1 }\n : { temperature: DEFAULT_TEMPERATURE }),\n });\n }\n\n this.logger.info('Preparing plugins...');\n const allPlugins = this.preparePlugins();\n this.logger.info('Creating agent config...');\n const agentConfig = this.createAgentConfig(serverSigner, llm, allPlugins);\n\n this.logger.info('Creating agent...');\n this.agent = createAgent(agentConfig);\n this.logger.info('Agent created');\n\n this.logger.info('Configuring HCS10 plugin...');\n this.configureHCS10Plugin(allPlugins);\n this.logger.info('HCS10 plugin configured');\n\n this.contentStoreManager = new ContentStoreManager();\n await this.contentStoreManager.initialize();\n this.logger.info(\n 'ContentStoreManager initialized for content reference support'\n );\n\n this.logger.info('About to call agent.boot()');\n this.logger.info('🔥 About to call agent.boot()');\n await this.agent.boot();\n this.logger.info('agent.boot() completed');\n this.logger.info('🔥 agent.boot() completed');\n\n if (this.agent) {\n const cfg = agentConfig;\n cfg.filtering = cfg.filtering || {};\n const originalPredicate = cfg.filtering.toolPredicate as\n | ((t: ToolDescriptor) => boolean)\n | undefined;\n const userPredicate = this.options.toolFilter;\n cfg.filtering.toolPredicate = (tool: ToolDescriptor): boolean => {\n if (tool && tool.name === 'hedera-account-transfer-hbar') {\n return false;\n }\n if (tool && tool.name === 'hedera-hts-airdrop-token') {\n return false;\n }\n if (originalPredicate && !originalPredicate(tool)) {\n return false;\n }\n if (userPredicate && !userPredicate(tool)) {\n return false;\n }\n return true;\n };\n }\n\n if (this.options.mcpServers && this.options.mcpServers.length > 0) {\n this.connectMCP();\n }\n } catch (error) {\n this.logger.error('Failed to initialize ConversationalAgent:', error);\n throw error;\n }\n }\n\n /**\n * Get the HCS-10 plugin instance\n * @returns {HCS10Plugin} The HCS-10 plugin instance\n */\n getPlugin(): HCS10Plugin {\n return this.hcs10Plugin;\n }\n\n /**\n * Get the state manager instance\n * @returns {IStateManager} The state manager instance\n */\n getStateManager(): IStateManager {\n return this.stateManager;\n }\n\n /**\n * Get the underlying agent instance\n * @returns {ReturnType<typeof createAgent>} The agent instance\n * @throws {Error} If agent is not initialized\n */\n getAgent(): ReturnType<typeof createAgent> {\n if (!this.agent) {\n throw new Error(ConversationalAgent.NOT_INITIALIZED_ERROR);\n }\n return this.agent;\n }\n\n /**\n * Get the conversational agent instance (alias for getAgent)\n * @returns {ReturnType<typeof createAgent>} The agent instance\n * @throws {Error} If agent is not initialized\n */\n getConversationalAgent(): ReturnType<typeof createAgent> {\n return this.getAgent();\n }\n\n /**\n * Process a message through the conversational agent\n * @param {string} message - The message to process\n * @param {Array<{type: 'human' | 'ai'; content: string}>} chatHistory - Previous chat history\n * @returns {Promise<ChatResponse>} The agent's response\n * @throws {Error} If agent is not initialized\n */\n async processMessage(\n message: string,\n chatHistory: ChatHistoryItem[] = []\n ): Promise<ChatResponse> {\n if (!this.agent) {\n throw new Error('Agent not initialized. Call initialize() first.');\n }\n\n try {\n const resolvedMessage = message;\n\n const messages = chatHistory.map((msg) => {\n const content = msg.content;\n if (msg.type === 'system') {\n return new SystemMessage(content);\n }\n return msg.type === 'human'\n ? new HumanMessage(content)\n : new AIMessage(content);\n });\n\n const context: ConversationContext = { messages };\n const response = await this.agent.chat(resolvedMessage, context);\n\n if (\n this.memoryManager &&\n this.options.operationalMode !== 'returnBytes'\n ) {\n await this.extractAndStoreEntities(response, message);\n }\n\n this.logger.info('Message processed successfully');\n return response;\n } catch (error) {\n this.logger.error('Error processing message:', error);\n throw error;\n }\n }\n\n /**\n * Process form submission through the conversational agent\n * @param {FormSubmission} submission - The form submission data\n * @returns {Promise<ChatResponse>} The agent's response after processing the form\n * @throws {Error} If agent is not initialized or doesn't support form processing\n */\n async processFormSubmission(\n submission: FormSubmission\n ): Promise<ChatResponse> {\n if (!this.agent) {\n throw new Error(ConversationalAgent.NOT_INITIALIZED_ERROR);\n }\n\n try {\n this.logger.info('Processing form submission:', {\n formId: submission.formId,\n toolName: submission.toolName,\n parameterKeys: Object.keys(submission.parameters || {}),\n hasContext: !!submission.context,\n });\n const response = await this.agent.processFormSubmission(submission);\n this.logger.info('Form submission processed successfully');\n return response;\n } catch (error) {\n this.logger.error('Error processing form submission:', error);\n throw error;\n }\n }\n\n /**\n * Validates initialization options and throws if required fields are missing.\n *\n * @param accountId - The Hedera account ID\n * @param privateKey - The private key for the account\n * @throws {Error} If required fields are missing\n */\n private validateOptions(accountId?: string, privateKey?: string): void {\n if (!accountId || !privateKey) {\n throw new Error('Account ID and private key are required');\n }\n\n if (typeof accountId !== 'string') {\n throw new Error(\n `Account ID must be a string, received ${typeof accountId}`\n );\n }\n\n if (typeof privateKey !== 'string') {\n throw new Error(\n `Private key must be a string, received ${typeof privateKey}: ${JSON.stringify(\n privateKey\n )}`\n );\n }\n\n if (privateKey.length < 10) {\n throw new Error('Private key appears to be invalid (too short)');\n }\n }\n\n /**\n * Prepares the list of plugins to use based on configuration.\n *\n * @returns Array of plugins to initialize with the agent\n */\n private preparePlugins(): BasePlugin[] {\n const { additionalPlugins = [], enabledPlugins } = this.options;\n\n const standardPlugins = [\n this.hcs10Plugin,\n this.hcs2Plugin,\n this.inscribePlugin,\n this.hbarPlugin,\n ];\n\n const corePlugins = getAllHederaCorePlugins();\n\n if (enabledPlugins) {\n const enabledSet = new Set(enabledPlugins);\n const filteredPlugins = [...standardPlugins, ...corePlugins].filter(\n (plugin) => enabledSet.has(plugin.id)\n );\n return [...filteredPlugins, ...additionalPlugins];\n }\n\n return [...standardPlugins, ...corePlugins, ...additionalPlugins];\n }\n\n /**\n * Creates the agent configuration object.\n *\n * @param serverSigner - The server signer instance\n * @param llm - The language model instance\n * @param allPlugins - Array of plugins to use\n * @returns Configuration object for creating the agent\n */\n private createAgentConfig(\n serverSigner: ServerSigner,\n llm: ChatOpenAI | ChatAnthropic,\n allPlugins: BasePlugin[]\n ): Parameters<typeof createAgent>[0] {\n const {\n operationalMode = DEFAULT_OPERATIONAL_MODE,\n userAccountId,\n scheduleUserTransactionsInBytesMode,\n customSystemMessagePreamble,\n customSystemMessagePostamble,\n verbose = false,\n mirrorNodeConfig,\n disableLogging,\n accountId = '',\n } = this.options;\n\n return {\n framework: 'langchain',\n signer: serverSigner,\n execution: {\n mode: operationalMode === 'autonomous' ? 'direct' : 'bytes',\n operationalMode: operationalMode,\n ...(userAccountId && { userAccountId }),\n ...(scheduleUserTransactionsInBytesMode !== undefined && {\n scheduleUserTransactionsInBytesMode:\n scheduleUserTransactionsInBytesMode,\n scheduleUserTransactions: scheduleUserTransactionsInBytesMode,\n }),\n },\n ai: {\n provider: new LangChainProvider(llm),\n temperature: DEFAULT_TEMPERATURE,\n },\n filtering: {\n toolPredicate: (tool: ToolDescriptor): boolean => {\n if (tool.name === 'hedera-account-transfer-hbar') return false;\n if (this.options.toolFilter && !this.options.toolFilter(tool)) {\n return false;\n }\n return true;\n },\n },\n messaging: {\n systemPreamble:\n customSystemMessagePreamble || getSystemMessage(accountId),\n ...(customSystemMessagePostamble && {\n systemPostamble: customSystemMessagePostamble,\n }),\n conciseMode: true,\n },\n extensions: {\n plugins: allPlugins,\n ...(mirrorNodeConfig && {\n mirrorConfig: mirrorNodeConfig as Record<string, unknown>,\n }),\n },\n ...(this.options.mcpServers && {\n mcp: {\n servers: this.options.mcpServers,\n autoConnect: false,\n },\n }),\n debug: {\n verbose,\n silent: disableLogging ?? false,\n },\n };\n }\n\n /**\n * Configures the HCS-10 plugin with the state manager.\n *\n * @param allPlugins - Array of all plugins\n */\n private configureHCS10Plugin(allPlugins: BasePlugin[]): void {\n const hcs10 = allPlugins.find((p) => p.id === 'hcs-10');\n if (hcs10) {\n (\n hcs10 as BasePlugin & { appConfig?: Record<string, unknown> }\n ).appConfig = {\n stateManager: this.stateManager,\n };\n }\n }\n\n /**\n * Create a ConversationalAgent with specific plugins enabled\n */\n private static withPlugins(\n options: ConversationalAgentOptions,\n plugins: string[]\n ): ConversationalAgent {\n return new ConversationalAgent({\n ...options,\n enabledPlugins: plugins,\n });\n }\n\n /**\n * Create a ConversationalAgent with only HTS (Hedera Token Service) tools enabled\n */\n static withHTS(options: ConversationalAgentOptions): ConversationalAgent {\n return this.withPlugins(options, ['hts-token']);\n }\n\n /**\n * Create a ConversationalAgent with only HCS-2 tools enabled\n */\n static withHCS2(options: ConversationalAgentOptions): ConversationalAgent {\n return this.withPlugins(options, ['hcs-2']);\n }\n\n /**\n * Create a ConversationalAgent with only HCS-10 tools enabled\n */\n static withHCS10(options: ConversationalAgentOptions): ConversationalAgent {\n return this.withPlugins(options, ['hcs-10']);\n }\n\n /**\n * Create a ConversationalAgent with only inscription tools enabled\n */\n static withInscribe(\n options: ConversationalAgentOptions\n ): ConversationalAgent {\n return this.withPlugins(options, ['inscribe']);\n }\n\n /**\n * Create a ConversationalAgent with only account management tools enabled\n */\n static withAccount(options: ConversationalAgentOptions): ConversationalAgent {\n return this.withPlugins(options, ['account']);\n }\n\n /**\n * Create a ConversationalAgent with only file service tools enabled\n */\n static withFileService(\n options: ConversationalAgentOptions\n ): ConversationalAgent {\n return this.withPlugins(options, ['file-service']);\n }\n\n /**\n * Create a ConversationalAgent with only consensus service tools enabled\n */\n static withConsensusService(\n options: ConversationalAgentOptions\n ): ConversationalAgent {\n return this.withPlugins(options, ['consensus-service']);\n }\n\n /**\n * Create a ConversationalAgent with only smart contract tools enabled\n */\n static withSmartContract(\n options: ConversationalAgentOptions\n ): ConversationalAgent {\n return this.withPlugins(options, ['smart-contract']);\n }\n\n /**\n * Create a ConversationalAgent with all HCS standards plugins\n */\n static withAllStandards(\n options: ConversationalAgentOptions\n ): ConversationalAgent {\n return this.withPlugins(options, ['hcs-10', 'hcs-2', 'inscribe']);\n }\n\n /**\n * Create a ConversationalAgent with minimal Hedera tools (no HCS standards)\n */\n static minimal(options: ConversationalAgentOptions): ConversationalAgent {\n return this.withPlugins(options, []);\n }\n\n /**\n * Create a ConversationalAgent with MCP servers configured\n */\n static withMCP(\n options: ConversationalAgentOptions,\n mcpServers: MCPServerConfig[]\n ): ConversationalAgent {\n return new ConversationalAgent({\n ...options,\n mcpServers,\n });\n }\n\n /**\n * Extract and store entities from agent responses\n * @param response - Agent response containing potential entity information\n * @param originalMessage - Original user message for context\n */\n private async extractAndStoreEntities(\n response: unknown,\n originalMessage: string\n ): Promise<void> {\n if (!this.memoryManager || !this.entityTools) {\n return;\n }\n\n try {\n this.logger.info('Starting LLM-based entity extraction');\n\n const responseText = this.extractResponseText(response);\n\n const entitiesJson = await this.entityTools.extractEntities.call({\n response: responseText,\n userMessage: originalMessage,\n });\n\n try {\n const entities = JSON.parse(entitiesJson);\n\n for (const entity of entities) {\n if (\n entity &&\n typeof entity === 'object' &&\n 'name' in entity &&\n 'type' in entity &&\n 'id' in entity\n ) {\n this.logger.info(\n `Storing entity: ${entity.name} (${entity.type}) -> ${entity.id}`\n );\n\n const transactionId = this.extractTransactionId(response);\n const idStr = String(entity.id);\n const isHederaId = /^0\\.0\\.[0-9]+$/.test(idStr);\n if (!isHederaId) {\n this.logger.warn('Skipping non-ID entity from extraction', {\n id: idStr,\n name: String(entity.name),\n type: String(entity.type),\n });\n } else {\n this.memoryManager.storeEntityAssociation(\n idStr,\n String(entity.name),\n String(entity.type),\n transactionId\n );\n }\n }\n }\n\n if (entities.length > 0) {\n this.logger.info(\n `Stored ${entities.length} entities via LLM extraction`\n );\n } else {\n this.logger.info('No entities found in response via LLM extraction');\n }\n } catch (parseError) {\n this.logger.error(\n 'Failed to parse extracted entities JSON:',\n parseError\n );\n throw parseError;\n }\n } catch (error) {\n this.logger.error('Entity extraction failed:', error);\n throw error;\n }\n }\n\n /**\n * Extract transaction ID from response if available\n * @param response - Transaction response\n * @returns Transaction ID or undefined\n */\n private extractTransactionId(response: unknown): string | undefined {\n try {\n if (\n typeof response === 'object' &&\n response &&\n 'transactionId' in response\n ) {\n const responseWithTxId = response as { transactionId?: unknown };\n return typeof responseWithTxId.transactionId === 'string'\n ? responseWithTxId.transactionId\n : undefined;\n }\n if (typeof response === 'string') {\n const match = response.match(\n /transaction[\\s\\w]*ID[\\s:\"]*([0-9a-fA-F@\\.\\-]+)/i\n );\n return match ? match[1] : undefined;\n }\n return undefined;\n } catch {\n return undefined;\n }\n }\n\n /**\n * Connect to MCP servers asynchronously\n * @private\n */\n private connectMCP(): void {\n if (!this.agent || !this.options.mcpServers) {\n return;\n }\n\n this.agent\n .connectMCPServers()\n .catch((e) => {\n this.logger.error('Failed to connect MCP servers:', e);\n })\n .then(() => {\n this.logger.info('MCP servers connected successfully');\n });\n }\n\n /**\n * Get MCP connection status for all servers\n * @returns {Map<string, MCPConnectionStatus>} Connection status map\n */\n getMCPConnectionStatus(): Map<string, MCPConnectionStatus> {\n if (this.agent) {\n return this.agent.getMCPConnectionStatus();\n }\n return new Map();\n }\n\n /**\n * Check if a specific MCP server is connected\n * @param {string} serverName - Name of the server to check\n * @returns {boolean} True if connected, false otherwise\n */\n isMCPServerConnected(serverName: string): boolean {\n if (this.agent) {\n const statusMap = this.agent.getMCPConnectionStatus();\n const status = statusMap.get(serverName);\n return status?.connected ?? false;\n }\n return false;\n }\n\n /**\n * Clean up resources\n */\n async cleanup(): Promise<void> {\n try {\n this.logger.info('Cleaning up ConversationalAgent...');\n\n if (this.memoryManager) {\n try {\n this.memoryManager.dispose();\n this.logger.info('Memory manager cleaned up successfully');\n } catch (error) {\n this.logger.warn('Error cleaning up memory manager:', error);\n }\n this.memoryManager = undefined;\n }\n\n if (this.contentStoreManager) {\n await this.contentStoreManager.dispose();\n this.logger.info('ContentStoreManager cleaned up');\n }\n\n this.logger.info('ConversationalAgent cleanup completed');\n } catch (error) {\n this.logger.error('Error during cleanup:', error);\n }\n }\n\n private extractResponseText(response: unknown): string {\n if (typeof response === 'string') {\n return response;\n }\n\n if (response && typeof response === 'object' && 'output' in response) {\n const responseWithOutput = response as { output: unknown };\n return String(responseWithOutput.output);\n }\n\n return JSON.stringify(response);\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAgDA,MAAM,qBAAqB;AAC3B,MAAM,sBAAsB;AAC5B,MAAM,kBAAkB;AACxB,MAAM,2BAAiD;AAuChD,MAAM,uBAAN,MAAM,qBAAoB;AAAA,EAkB/B,YAAY,SAAqC;AAC/C,SAAK,UAAU;AACf,SAAK,eAAe,QAAQ,gBAAgB,IAAI,gBAAA;AAChD,SAAK,cAAc,IAAI,YAAA;AACvB,SAAK,aAAa,IAAI,WAAA;AACtB,SAAK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ACpE,YAAM,qBAAqB;AAC3B,aAAO,OAAO,mBAAmB,MAAM;AAAA,IACzC;AAEA,WAAO,KAAK,UAAU,QAAQ;AAAA,EAChC;AACF;AAvsBE,qBAAwB,wBACtB;AAFG,IAAM,sBAAN;"}
|
package/dist/esm/index7.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index7.js","sources":["../../src/base-agent.ts"],"sourcesContent":["import type { BaseMessage } from '@langchain/core/messages';\nimport type { StructuredTool } from '@langchain/core/tools';\nimport type { TransactionReceipt } from '@hashgraph/sdk';\nimport {\n HederaAgentKit,\n ServerSigner,\n TokenUsageCallbackHandler,\n TokenUsage,\n BasePlugin,\n} from 'hedera-agent-kit';\nimport type { CostCalculation } from 'hedera-agent-kit';\nimport type { AIProvider, VercelAIProvider, BAMLProvider } from './providers';\nimport { Logger } from '@hashgraphonline/standards-sdk';\nimport type { MCPServerConfig, MCPConnectionStatus } from './mcp/types';\n\nexport interface ToolFilterConfig {\n namespaceWhitelist?: string[];\n toolBlacklist?: string[];\n toolPredicate?: (tool: StructuredTool) => boolean;\n}\n\nexport type ExecutionMode = 'direct' | 'bytes';\nexport type OperationalMode = 'autonomous' | 'returnBytes';\n\nexport interface HederaAgentConfiguration {\n signer: ServerSigner;\n execution?: {\n mode?: ExecutionMode;\n operationalMode?: OperationalMode;\n userAccountId?: string;\n scheduleUserTransactions?: boolean;\n scheduleUserTransactionsInBytesMode?: boolean;\n };\n ai?: {\n provider?: AIProvider;\n llm?: unknown;\n apiKey?: string;\n modelName?: string;\n temperature?: number;\n };\n filtering?: ToolFilterConfig;\n messaging?: {\n systemPreamble?: string;\n systemPostamble?: string;\n conciseMode?: boolean;\n };\n extensions?: {\n plugins?: BasePlugin[];\n mirrorConfig?: Record<string, unknown>;\n modelCapability?: string;\n };\n mcp?: {\n servers?: MCPServerConfig[];\n autoConnect?: boolean;\n };\n debug?: {\n verbose?: boolean;\n silent?: boolean;\n };\n}\n\nexport interface ConversationContext {\n messages: BaseMessage[];\n metadata?: Record<string, unknown>;\n}\n\nexport interface ChatResponse {\n output: string;\n message?: string;\n transactionBytes?: string;\n receipt?: TransactionReceipt | object;\n scheduleId?: string;\n transactionId?: string;\n notes?: string[];\n error?: string;\n intermediateSteps?: unknown;\n rawToolOutput?: unknown;\n tokenUsage?: TokenUsage;\n cost?: CostCalculation;\n metadata?: Record<string, unknown>;\n tool_calls?: Array<{\n id: string;\n name: string;\n args: Record<string, unknown>;\n output?: string;\n }>;\n formMessage?: unknown;\n requiresForm?: boolean;\n [key: string]: unknown;\n}\n\nexport interface UsageStats extends TokenUsage {\n cost: CostCalculation;\n}\n\nexport abstract class BaseAgent {\n protected logger: Logger;\n protected agentKit: HederaAgentKit | undefined;\n protected tools: StructuredTool[] = [];\n protected initialized = false;\n protected tokenTracker: TokenUsageCallbackHandler | undefined;\n\n constructor(protected config: HederaAgentConfiguration) {\n this.logger = new Logger({\n module: 'BaseAgent',\n silent: config.debug?.silent || false,\n });\n }\n\n abstract boot(): Promise<void>;\n abstract chat(\n message: string,\n context?: ConversationContext\n ): Promise<ChatResponse>;\n abstract shutdown(): Promise<void>;\n abstract switchMode(mode: OperationalMode): void;\n abstract getUsageStats(): UsageStats;\n abstract getUsageLog(): UsageStats[];\n abstract clearUsageStats(): void;\n abstract connectMCPServers(): Promise<void>;\n abstract getMCPConnectionStatus(): Map<string, MCPConnectionStatus>;\n\n public getCore(): HederaAgentKit | undefined {\n return this.agentKit;\n }\n\n protected filterTools(tools: StructuredTool[]): StructuredTool[] {\n let filtered = [...tools];\n const filter = this.config.filtering;\n\n if (!filter) return filtered;\n\n if (filter.namespaceWhitelist?.length) {\n filtered = filtered.filter((tool) => {\n const namespace = (tool as StructuredTool & { namespace?: string })\n .namespace;\n return !namespace || filter.namespaceWhitelist!.includes(namespace);\n });\n }\n\n if (filter.toolBlacklist?.length) {\n filtered = filtered.filter(\n (tool) => !filter.toolBlacklist!.includes(tool.name)\n );\n }\n\n if (filter.toolPredicate) {\n filtered = filtered.filter(filter.toolPredicate);\n }\n\n this.logger.debug(`Filtered tools: ${tools.length} → ${filtered.length}`);\n return filtered;\n }\n\n protected buildSystemPrompt(): string {\n const parts: string[] = [];\n const operatorId = this.config.signer.getAccountId().toString();\n const userAccId = this.config.execution?.userAccountId;\n\n if (this.config.messaging?.systemPreamble) {\n parts.push(this.config.messaging.systemPreamble);\n }\n\n parts.push(\n `You are a helpful Hedera assistant. Your primary operator account is ${operatorId}. ` +\n `You have tools to interact with the Hedera Hashgraph. ` +\n `When using any tool, provide all necessary parameters as defined by that tool's schema and description.`\n );\n\n parts.push(\n `\\nMETADATA QUALITY PRINCIPLES: When collecting user input for metadata creation across any tool:` +\n `\\n• Prioritize meaningful, valuable content over technical file information` +\n `\\n• Focus on attributes that add value for end users and collectors` +\n `\\n• Avoid auto-generating meaningless technical attributes as user-facing metadata` +\n `\\n• When fields are missing or inadequate, use forms to collect quality metadata` +\n `\\n• Encourage descriptive names, collectible traits, and storytelling elements`\n );\n\n if (userAccId) {\n parts.push(\n `The user you are assisting has a personal Hedera account ID: ${userAccId}. ` +\n `IMPORTANT: When the user says things like \"I want to send HBAR\" or \"transfer my tokens\", you MUST use ${userAccId} as the sender/from account. ` +\n `For example, if user says \"I want to send 2 HBAR to 0.0.800\", you must set up a transfer where ${userAccId} sends the HBAR, not your operator account.`\n );\n }\n\n const operationalMode =\n this.config.execution?.operationalMode || 'returnBytes';\n if (operationalMode === 'autonomous') {\n parts.push(\n `\\nOPERATIONAL MODE: 'autonomous'. Your goal is to execute transactions directly using your tools. ` +\n `Your account ${operatorId} will be the payer for these transactions. ` +\n `Even if the user's account (${\n userAccId || 'a specified account'\n }) is the actor in the transaction body (e.g., sender of HBAR), ` +\n `you (the agent with operator ${operatorId}) are still executing and paying. For HBAR transfers, ensure the amounts in the 'transfers' array sum to zero (as per tool schema), balancing with your operator account if necessary.`\n );\n } else {\n if (\n this.config.execution?.scheduleUserTransactionsInBytesMode &&\n userAccId\n ) {\n parts.push(\n `\\nOPERATIONAL MODE: 'returnBytes' with scheduled transactions for user actions. ` +\n `When a user asks for a transaction to be prepared (e.g., creating a token, topic, transferring assets for them to sign, etc), ` +\n `you MUST default to creating a Scheduled Transaction using the appropriate tool with the metaOption 'schedule: true'. ` +\n `The user (with account ID ${userAccId}) will be the one to ultimately pay for and (if needed) sign the inner transaction. ` +\n `Your operator account (${operatorId}) will pay for creating the schedule entity itself. ` +\n `You MUST return the ScheduleId and details of the scheduled operation in a structured JSON format with these fields: success, op, schedule_id, description, payer_account_id_scheduled_tx, and scheduled_transaction_details.`\n );\n } else {\n parts.push(\n `\\nOPERATIONAL MODE: 'returnBytes'. Your goal is to provide transaction bytes when possible. ` +\n `When a user asks for a transaction to be prepared (e.g., for them to sign, or for scheduling without the default scheduling flow), ` +\n `you MUST call the appropriate tool. ` +\n `IMPORTANT: Only use metaOption 'returnBytes: true' for tools that explicitly support it (like HBAR transfers, token operations). ` +\n `Many tools (inscriptions, HCS-2, HCS-20, etc.) do NOT support returnBytes and will execute directly - this is expected behavior. ` +\n `For tools without returnBytes support, simply call them with their standard parameters. ` +\n `If you need raw bytes for the user to sign for their own account ${\n userAccId || 'if specified'\n }, ensure the tool constructs the transaction body accordingly when returnBytes IS supported.`\n );\n }\n }\n\n if (this.config.messaging?.conciseMode !== false) {\n parts.push(\n '\\nAlways be concise. If the tool provides a JSON string as its primary output (especially in returnBytes mode), make your accompanying text brief. If the tool does not provide JSON output or an error occurs, your narrative becomes primary; if notes were generated by the tool in such cases, append them to your textual response.'\n );\n }\n\n if (this.config.messaging?.systemPostamble) {\n parts.push(this.config.messaging.systemPostamble);\n }\n\n return parts.join('\\n');\n }\n\n isReady(): boolean {\n return this.initialized;\n }\n}\n\nexport type { AIProvider, VercelAIProvider, BAMLProvider };\n"],"names":[],"mappings":";AA+FO,MAAe,UAAU;AAAA,EAO9B,YAAsB,QAAkC;AAAlC,SAAA,SAAA;AAJtB,SAAU,QAA0B,CAAA;AACpC,SAAU,cAAc;A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AM,kBACJ,KAAK,OAAO,WAAW,mBAAmB;AAC5C,QAAI,oBAAoB,cAAc;AACpC,YAAM;AAAA,QACJ;AAAA,+GACkB,UAAU,0EAExB,aAAa,qBACf,+FACgC,UAAU;AAAA,MAAA;AAAA,IAEhD,OAAO;AACL,UACE,KAAK,OAAO,WAAW,uCACvB,WACA;AACA,cAAM;AAAA,UACJ;AAAA,8VAG+B,SAAS,8GACZ,UAAU;AAAA,QAAA;AAAA,MAG1C,OAAO;AACL,cAAM;AAAA,UACJ;AAAA,8pBAOI,aAAa,cACf;AAAA,QAAA;AAAA,MAEN;AAAA,IACF;AAEA,QAAI,KAAK,OAAO,WAAW,gBAAgB,OAAO;AAChD,YAAM;AAAA,QACJ;AAAA,MAAA;AAAA,IAEJ;AAEA,QAAI,KAAK,OAAO,WAAW,iBAAiB;AAC1C,YAAM,KAAK,KAAK,OAAO,UAAU,eAAe;AAAA,IAClD;AAEA,WAAO,MAAM,KAAK,IAAI;AAAA,EACxB;AAAA,EAEA,UAAmB;AACjB,WAAO,KAAK;AAAA,EACd;AACF;"}
|
|
1
|
+
{"version":3,"file":"index7.js","sources":["../../src/base-agent.ts"],"sourcesContent":["import type { BaseMessage } from '@langchain/core/messages';\nimport type { StructuredTool } from '@langchain/core/tools';\nimport type { TransactionReceipt } from '@hashgraph/sdk';\nimport {\n HederaAgentKit,\n ServerSigner,\n TokenUsageCallbackHandler,\n TokenUsage,\n BasePlugin,\n} from 'hedera-agent-kit';\nimport type { CostCalculation } from 'hedera-agent-kit';\nimport type { AIProvider, VercelAIProvider, BAMLProvider } from './providers';\nimport { Logger } from '@hashgraphonline/standards-sdk';\nimport type { MCPServerConfig, MCPConnectionStatus } from './mcp/types';\nimport type { FormSubmission } from './forms/types';\n\nexport interface ToolFilterConfig {\n namespaceWhitelist?: string[];\n toolBlacklist?: string[];\n toolPredicate?: (tool: StructuredTool) => boolean;\n}\n\nexport type ExecutionMode = 'direct' | 'bytes';\nexport type OperationalMode = 'autonomous' | 'returnBytes';\n\nexport interface HederaAgentConfiguration {\n signer: ServerSigner;\n execution?: {\n mode?: ExecutionMode;\n operationalMode?: OperationalMode;\n userAccountId?: string;\n scheduleUserTransactions?: boolean;\n scheduleUserTransactionsInBytesMode?: boolean;\n };\n ai?: {\n provider?: AIProvider;\n llm?: unknown;\n apiKey?: string;\n modelName?: string;\n temperature?: number;\n };\n filtering?: ToolFilterConfig;\n messaging?: {\n systemPreamble?: string;\n systemPostamble?: string;\n conciseMode?: boolean;\n };\n extensions?: {\n plugins?: BasePlugin[];\n mirrorConfig?: Record<string, unknown>;\n modelCapability?: string;\n };\n mcp?: {\n servers?: MCPServerConfig[];\n autoConnect?: boolean;\n };\n debug?: {\n verbose?: boolean;\n silent?: boolean;\n };\n}\n\nexport interface ConversationContext {\n messages: BaseMessage[];\n metadata?: Record<string, unknown>;\n}\n\nexport interface ChatResponse {\n output: string;\n message?: string;\n transactionBytes?: string;\n receipt?: TransactionReceipt | object;\n scheduleId?: string;\n transactionId?: string;\n notes?: string[];\n error?: string;\n intermediateSteps?: unknown;\n rawToolOutput?: unknown;\n tokenUsage?: TokenUsage;\n cost?: CostCalculation;\n metadata?: Record<string, unknown>;\n tool_calls?: Array<{\n id: string;\n name: string;\n args: Record<string, unknown>;\n output?: string;\n }>;\n formMessage?: unknown;\n requiresForm?: boolean;\n [key: string]: unknown;\n}\n\nexport interface UsageStats extends TokenUsage {\n cost: CostCalculation;\n}\n\nexport abstract class BaseAgent {\n protected logger: Logger;\n protected agentKit: HederaAgentKit | undefined;\n protected tools: StructuredTool[] = [];\n protected initialized = false;\n protected tokenTracker: TokenUsageCallbackHandler | undefined;\n\n constructor(protected config: HederaAgentConfiguration) {\n this.logger = new Logger({\n module: 'BaseAgent',\n silent: config.debug?.silent || false,\n });\n }\n\n abstract boot(): Promise<void>;\n abstract chat(\n message: string,\n context?: ConversationContext\n ): Promise<ChatResponse>;\n abstract processFormSubmission(\n submission: FormSubmission\n ): Promise<ChatResponse>;\n abstract shutdown(): Promise<void>;\n abstract switchMode(mode: OperationalMode): void;\n abstract getUsageStats(): UsageStats;\n abstract getUsageLog(): UsageStats[];\n abstract clearUsageStats(): void;\n abstract connectMCPServers(): Promise<void>;\n abstract getMCPConnectionStatus(): Map<string, MCPConnectionStatus>;\n\n public getCore(): HederaAgentKit | undefined {\n return this.agentKit;\n }\n\n protected filterTools(tools: StructuredTool[]): StructuredTool[] {\n let filtered = [...tools];\n const filter = this.config.filtering;\n\n if (!filter) return filtered;\n\n if (filter.namespaceWhitelist?.length) {\n filtered = filtered.filter((tool) => {\n const namespace = (tool as StructuredTool & { namespace?: string })\n .namespace;\n return !namespace || filter.namespaceWhitelist!.includes(namespace);\n });\n }\n\n if (filter.toolBlacklist?.length) {\n filtered = filtered.filter(\n (tool) => !filter.toolBlacklist!.includes(tool.name)\n );\n }\n\n if (filter.toolPredicate) {\n filtered = filtered.filter(filter.toolPredicate);\n }\n\n this.logger.debug(`Filtered tools: ${tools.length} → ${filtered.length}`);\n return filtered;\n }\n\n protected buildSystemPrompt(): string {\n const parts: string[] = [];\n const operatorId = this.config.signer.getAccountId().toString();\n const userAccId = this.config.execution?.userAccountId;\n\n if (this.config.messaging?.systemPreamble) {\n parts.push(this.config.messaging.systemPreamble);\n }\n\n parts.push(\n `You are a helpful Hedera assistant. Your primary operator account is ${operatorId}. ` +\n `You have tools to interact with the Hedera Hashgraph. ` +\n `When using any tool, provide all necessary parameters as defined by that tool's schema and description.`\n );\n\n parts.push(\n `\\nMETADATA QUALITY PRINCIPLES: When collecting user input for metadata creation across any tool:` +\n `\\n• Prioritize meaningful, valuable content over technical file information` +\n `\\n• Focus on attributes that add value for end users and collectors` +\n `\\n• Avoid auto-generating meaningless technical attributes as user-facing metadata` +\n `\\n• When fields are missing or inadequate, use forms to collect quality metadata` +\n `\\n• Encourage descriptive names, collectible traits, and storytelling elements`\n );\n\n if (userAccId) {\n parts.push(\n `The user you are assisting has a personal Hedera account ID: ${userAccId}. ` +\n `IMPORTANT: When the user says things like \"I want to send HBAR\" or \"transfer my tokens\", you MUST use ${userAccId} as the sender/from account. ` +\n `For example, if user says \"I want to send 2 HBAR to 0.0.800\", you must set up a transfer where ${userAccId} sends the HBAR, not your operator account.`\n );\n }\n\n const operationalMode =\n this.config.execution?.operationalMode || 'returnBytes';\n if (operationalMode === 'autonomous') {\n parts.push(\n `\\nOPERATIONAL MODE: 'autonomous'. Your goal is to execute transactions directly using your tools. ` +\n `Your account ${operatorId} will be the payer for these transactions. ` +\n `Even if the user's account (${\n userAccId || 'a specified account'\n }) is the actor in the transaction body (e.g., sender of HBAR), ` +\n `you (the agent with operator ${operatorId}) are still executing and paying. For HBAR transfers, ensure the amounts in the 'transfers' array sum to zero (as per tool schema), balancing with your operator account if necessary.`\n );\n } else {\n if (\n this.config.execution?.scheduleUserTransactionsInBytesMode &&\n userAccId\n ) {\n parts.push(\n `\\nOPERATIONAL MODE: 'returnBytes' with scheduled transactions for user actions. ` +\n `When a user asks for a transaction to be prepared (e.g., creating a token, topic, transferring assets for them to sign, etc), ` +\n `you MUST default to creating a Scheduled Transaction using the appropriate tool with the metaOption 'schedule: true'. ` +\n `The user (with account ID ${userAccId}) will be the one to ultimately pay for and (if needed) sign the inner transaction. ` +\n `Your operator account (${operatorId}) will pay for creating the schedule entity itself. ` +\n `You MUST return the ScheduleId and details of the scheduled operation in a structured JSON format with these fields: success, op, schedule_id, description, payer_account_id_scheduled_tx, and scheduled_transaction_details.`\n );\n } else {\n parts.push(\n `\\nOPERATIONAL MODE: 'returnBytes'. Your goal is to provide transaction bytes when possible. ` +\n `When a user asks for a transaction to be prepared (e.g., for them to sign, or for scheduling without the default scheduling flow), ` +\n `you MUST call the appropriate tool. ` +\n `IMPORTANT: Only use metaOption 'returnBytes: true' for tools that explicitly support it (like HBAR transfers, token operations). ` +\n `Many tools (inscriptions, HCS-2, HCS-20, etc.) do NOT support returnBytes and will execute directly - this is expected behavior. ` +\n `For tools without returnBytes support, simply call them with their standard parameters. ` +\n `If you need raw bytes for the user to sign for their own account ${\n userAccId || 'if specified'\n }, ensure the tool constructs the transaction body accordingly when returnBytes IS supported.`\n );\n }\n }\n\n if (this.config.messaging?.conciseMode !== false) {\n parts.push(\n '\\nAlways be concise. If the tool provides a JSON string as its primary output (especially in returnBytes mode), make your accompanying text brief. If the tool does not provide JSON output or an error occurs, your narrative becomes primary; if notes were generated by the tool in such cases, append them to your textual response.'\n );\n }\n\n if (this.config.messaging?.systemPostamble) {\n parts.push(this.config.messaging.systemPostamble);\n }\n\n return parts.join('\\n');\n }\n\n isReady(): boolean {\n return this.initialized;\n }\n}\n\nexport type { AIProvider, VercelAIProvider, BAMLProvider };\n"],"names":[],"mappings":";AAgGO,MAAe,UAAU;AAAA,EAO9B,YAAsB,QAAkC;AAAlC,SAAA,SAAA;AAJtB,SAAU,QAA0B,CAAA;AACpC,SAAU,cAAc;AAItB,SAAK,SAAS,IAAI,OAAO;AAAA,MACvB,QAAQ;AAAA,MACR,QAAQ,OAAO,OAAO,UAAU;AAAA,IAAA,CACjC;AAAA,EACH;AAAA,EAkBO,UAAsC;AAC3C,WAAO,KAAK;AAAA,EACd;AAAA,EAEU,YAAY,OAA2C;AAC/D,QAAI,WAAW,CAAC,GAAG,KAAK;AACxB,UAAM,SAAS,KAAK,OAAO;AAE3B,QAAI,CAAC,OAAQ,QAAO;AAEpB,QAAI,OAAO,oBAAoB,QAAQ;AACrC,iBAAW,SAAS,OAAO,CAAC,SAAS;AACnC,cAAM,YAAa,KAChB;AACH,eAAO,CAAC,aAAa,OAAO,mBAAoB,SAAS,SAAS;AAAA,MACpE,CAAC;AAAA,IACH;AAEA,QAAI,OAAO,eAAe,QAAQ;AAChC,iBAAW,SAAS;AAAA,QAClB,CAAC,SAAS,CAAC,OAAO,cAAe,SAAS,KAAK,IAAI;AAAA,MAAA;AAAA,IAEvD;AAEA,QAAI,OAAO,eAAe;AACxB,iBAAW,SAAS,OAAO,OAAO,aAAa;AAAA,IACjD;AAEA,SAAK,OAAO,MAAM,m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ederaAgentKit, ServerSigner, TokenUsageCallbackHandler, TokenUsage, Ba
|
|
|
5
5
|
import { AIProvider, VercelAIProvider, BAMLProvider } from './providers';
|
|
6
6
|
import { Logger } from '@hashgraphonline/standards-sdk';
|
|
7
7
|
import { MCPServerConfig, MCPConnectionStatus } from './mcp/types';
|
|
8
|
+
import { FormSubmission } from './forms/types';
|
|
8
9
|
|
|
9
10
|
export interface ToolFilterConfig {
|
|
10
11
|
namespaceWhitelist?: string[];
|
|
@@ -90,6 +91,7 @@ export declare abstract class BaseAgent {
|
|
|
90
91
|
constructor(config: HederaAgentConfiguration);
|
|
91
92
|
abstract boot(): Promise<void>;
|
|
92
93
|
abstract chat(message: string, context?: ConversationContext): Promise<ChatResponse>;
|
|
94
|
+
abstract processFormSubmission(submission: FormSubmission): Promise<ChatResponse>;
|
|
93
95
|
abstract shutdown(): Promise<void>;
|
|
94
96
|
abstract switchMode(mode: OperationalMode): void;
|
|
95
97
|
abstract getUsageStats(): UsageStats;
|
|
@@ -5,15 +5,18 @@ import { ChainValues } from '@langchain/core/utils/types';
|
|
|
5
5
|
import { CallbackManagerForChainRun } from '@langchain/core/callbacks/manager';
|
|
6
6
|
import { RunnableConfig } from '@langchain/core/runnables';
|
|
7
7
|
|
|
8
|
+
interface ToolWithOriginal {
|
|
9
|
+
originalTool?: {
|
|
10
|
+
call?: (args: Record<string, unknown>) => Promise<string>;
|
|
11
|
+
};
|
|
12
|
+
}
|
|
8
13
|
interface PendingFormData {
|
|
9
14
|
toolName: string;
|
|
10
15
|
originalInput: unknown;
|
|
11
16
|
originalToolInput?: unknown;
|
|
12
17
|
schema: unknown;
|
|
13
18
|
toolRef?: ToolInterface | undefined;
|
|
14
|
-
originalToolRef?:
|
|
15
|
-
call?: (args: Record<string, unknown>) => Promise<string>;
|
|
16
|
-
} | undefined;
|
|
19
|
+
originalToolRef?: ToolWithOriginal['originalTool'];
|
|
17
20
|
}
|
|
18
21
|
/**
|
|
19
22
|
* Parameter preprocessing callback interface
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hashgraphonline/conversational-agent",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.221",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/cjs/index.cjs",
|
|
6
6
|
"module": "./dist/esm/index.js",
|
|
@@ -95,18 +95,17 @@
|
|
|
95
95
|
},
|
|
96
96
|
"dependencies": {
|
|
97
97
|
"@hashgraph/sdk": "^2.69.0",
|
|
98
|
-
"@hashgraphonline/standards-agent-kit": "
|
|
98
|
+
"@hashgraphonline/standards-agent-kit": "0.2.135",
|
|
99
99
|
"@hashgraphonline/standards-sdk": "0.0.187",
|
|
100
100
|
"@langchain/anthropic": "^0.3.26",
|
|
101
|
-
"@langchain/core": "^0.3.
|
|
102
|
-
"@langchain/openai": "^0.6.
|
|
103
|
-
"@modelcontextprotocol/sdk": "^1.17.
|
|
101
|
+
"@langchain/core": "^0.3.72",
|
|
102
|
+
"@langchain/openai": "^0.6.9",
|
|
103
|
+
"@modelcontextprotocol/sdk": "^1.17.4",
|
|
104
104
|
"axios": "^1.11.0",
|
|
105
105
|
"bignumber.js": "^9.3.1",
|
|
106
|
-
"electron-log": "^5.4.2",
|
|
107
106
|
"ethers": "^6.15.0",
|
|
108
107
|
"hedera-agent-kit": "^2.0.3",
|
|
109
|
-
"langchain": "^0.3.
|
|
108
|
+
"langchain": "^0.3.31",
|
|
110
109
|
"tiktoken": "^1.0.22",
|
|
111
110
|
"zod": "^3.25.0",
|
|
112
111
|
"zod-to-json-schema": "^3.24.6"
|
package/src/base-agent.ts
CHANGED
|
@@ -12,6 +12,7 @@ import type { CostCalculation } from 'hedera-agent-kit';
|
|
|
12
12
|
import type { AIProvider, VercelAIProvider, BAMLProvider } from './providers';
|
|
13
13
|
import { Logger } from '@hashgraphonline/standards-sdk';
|
|
14
14
|
import type { MCPServerConfig, MCPConnectionStatus } from './mcp/types';
|
|
15
|
+
import type { FormSubmission } from './forms/types';
|
|
15
16
|
|
|
16
17
|
export interface ToolFilterConfig {
|
|
17
18
|
namespaceWhitelist?: string[];
|
|
@@ -112,6 +113,9 @@ export abstract class BaseAgent {
|
|
|
112
113
|
message: string,
|
|
113
114
|
context?: ConversationContext
|
|
114
115
|
): Promise<ChatResponse>;
|
|
116
|
+
abstract processFormSubmission(
|
|
117
|
+
submission: FormSubmission
|
|
118
|
+
): Promise<ChatResponse>;
|
|
115
119
|
abstract shutdown(): Promise<void>;
|
|
116
120
|
abstract switchMode(mode: OperationalMode): void;
|
|
117
121
|
abstract getUsageStats(): UsageStats;
|
|
@@ -89,7 +89,8 @@ export interface ConversationalAgentOptions {
|
|
|
89
89
|
* @returns A new instance of the ConversationalAgent class.
|
|
90
90
|
*/
|
|
91
91
|
export class ConversationalAgent {
|
|
92
|
-
private static readonly NOT_INITIALIZED_ERROR =
|
|
92
|
+
private static readonly NOT_INITIALIZED_ERROR =
|
|
93
|
+
'Agent not initialized. Call initialize() first.';
|
|
93
94
|
protected agent?: AgentInstance;
|
|
94
95
|
public hcs10Plugin: HCS10Plugin;
|
|
95
96
|
public hcs2Plugin: HCS2Plugin;
|
|
@@ -333,18 +334,6 @@ export class ConversationalAgent {
|
|
|
333
334
|
throw new Error(ConversationalAgent.NOT_INITIALIZED_ERROR);
|
|
334
335
|
}
|
|
335
336
|
|
|
336
|
-
const internalAgent = this.agent as {
|
|
337
|
-
processFormSubmission?: (
|
|
338
|
-
submission: FormSubmission
|
|
339
|
-
) => Promise<ChatResponse>;
|
|
340
|
-
};
|
|
341
|
-
if (
|
|
342
|
-
!internalAgent.processFormSubmission ||
|
|
343
|
-
typeof internalAgent.processFormSubmission !== 'function'
|
|
344
|
-
) {
|
|
345
|
-
throw new Error('processFormSubmission not available on internal agent');
|
|
346
|
-
}
|
|
347
|
-
|
|
348
337
|
try {
|
|
349
338
|
this.logger.info('Processing form submission:', {
|
|
350
339
|
formId: submission.formId,
|
|
@@ -352,7 +341,7 @@ export class ConversationalAgent {
|
|
|
352
341
|
parameterKeys: Object.keys(submission.parameters || {}),
|
|
353
342
|
hasContext: !!submission.context,
|
|
354
343
|
});
|
|
355
|
-
const response = await
|
|
344
|
+
const response = await this.agent.processFormSubmission(submission);
|
|
356
345
|
this.logger.info('Form submission processed successfully');
|
|
357
346
|
return response;
|
|
358
347
|
} catch (error) {
|
|
@@ -29,15 +29,54 @@ interface HashLinkResponse {
|
|
|
29
29
|
message: string;
|
|
30
30
|
}
|
|
31
31
|
|
|
32
|
+
interface ToolWithOriginal {
|
|
33
|
+
originalTool?: {
|
|
34
|
+
call?: (args: Record<string, unknown>) => Promise<string>;
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
interface ActionWithToolInput {
|
|
39
|
+
toolInput?: Record<string, unknown>;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
interface ZodSchemaDefinition {
|
|
43
|
+
_def?: {
|
|
44
|
+
typeName?: string;
|
|
45
|
+
shape?: (() => Record<string, z.ZodTypeAny>) | Record<string, z.ZodTypeAny>;
|
|
46
|
+
innerType?: z.ZodTypeAny;
|
|
47
|
+
defaultValue?: unknown;
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
interface ToolWrapper {
|
|
52
|
+
executeOriginal?: (args: Record<string, unknown>) => Promise<string>;
|
|
53
|
+
getOriginalTool?: () => {
|
|
54
|
+
_call?: (args: Record<string, unknown>) => Promise<string>;
|
|
55
|
+
call?: (args: Record<string, unknown>) => Promise<string>;
|
|
56
|
+
};
|
|
57
|
+
originalTool?: {
|
|
58
|
+
_call?: (args: Record<string, unknown>) => Promise<string>;
|
|
59
|
+
call?: (args: Record<string, unknown>) => Promise<string>;
|
|
60
|
+
};
|
|
61
|
+
call?: (args: Record<string, unknown>) => Promise<string>;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
interface CallableTool {
|
|
65
|
+
_call?: (args: Record<string, unknown>) => Promise<string>;
|
|
66
|
+
call?: (args: Record<string, unknown>) => Promise<string>;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
interface ToolWithSchema {
|
|
70
|
+
schema?: Record<string, unknown>;
|
|
71
|
+
}
|
|
72
|
+
|
|
32
73
|
interface PendingFormData {
|
|
33
74
|
toolName: string;
|
|
34
75
|
originalInput: unknown;
|
|
35
76
|
originalToolInput?: unknown;
|
|
36
77
|
schema: unknown;
|
|
37
78
|
toolRef?: ToolInterface | undefined;
|
|
38
|
-
originalToolRef?:
|
|
39
|
-
| { call?: (args: Record<string, unknown>) => Promise<string> }
|
|
40
|
-
| undefined;
|
|
79
|
+
originalToolRef?: ToolWithOriginal['originalTool'];
|
|
41
80
|
}
|
|
42
81
|
|
|
43
82
|
interface ToolResponse {
|
|
@@ -368,13 +407,7 @@ export class FormAwareAgentExecutor extends AgentExecutor {
|
|
|
368
407
|
originalToolInput: toolInput,
|
|
369
408
|
schema: schemaToUse,
|
|
370
409
|
toolRef: tool as ToolInterface | undefined,
|
|
371
|
-
originalToolRef: (
|
|
372
|
-
tool as unknown as {
|
|
373
|
-
originalTool?: {
|
|
374
|
-
call?: (args: Record<string, unknown>) => Promise<string>;
|
|
375
|
-
};
|
|
376
|
-
}
|
|
377
|
-
).originalTool,
|
|
410
|
+
originalToolRef: (tool as ToolWithOriginal).originalTool,
|
|
378
411
|
};
|
|
379
412
|
this.pendingForms.set(formMessage.id, formData);
|
|
380
413
|
globalPendingForms.set(formMessage.id, formData);
|
|
@@ -416,7 +449,8 @@ export class FormAwareAgentExecutor extends AgentExecutor {
|
|
|
416
449
|
typeof preprocessedInput === 'object' &&
|
|
417
450
|
'__requestForm' in (preprocessedInput as Record<string, unknown>)
|
|
418
451
|
) {
|
|
419
|
-
const rf = (preprocessedInput as Record<string, unknown>)
|
|
452
|
+
const rf = (preprocessedInput as Record<string, unknown>)
|
|
453
|
+
.__requestForm as {
|
|
420
454
|
id?: string;
|
|
421
455
|
title?: string;
|
|
422
456
|
description?: string;
|
|
@@ -430,7 +464,9 @@ export class FormAwareAgentExecutor extends AgentExecutor {
|
|
|
430
464
|
submitLabel?: string;
|
|
431
465
|
};
|
|
432
466
|
|
|
433
|
-
const formId =
|
|
467
|
+
const formId =
|
|
468
|
+
rf.id ||
|
|
469
|
+
`form_${Date.now()}_${Math.random().toString(36).slice(2)}`;
|
|
434
470
|
const formMessage = {
|
|
435
471
|
type: 'form',
|
|
436
472
|
id: formId,
|
|
@@ -484,9 +520,7 @@ export class FormAwareAgentExecutor extends AgentExecutor {
|
|
|
484
520
|
originalToolInput: toolInput,
|
|
485
521
|
schema: resolvedSchema,
|
|
486
522
|
toolRef: tool as ToolInterface | undefined,
|
|
487
|
-
originalToolRef: (
|
|
488
|
-
tool as unknown as { originalTool?: { call?: (a: Record<string, unknown>) => Promise<string> } }
|
|
489
|
-
).originalTool,
|
|
523
|
+
originalToolRef: (tool as ToolWithOriginal).originalTool,
|
|
490
524
|
});
|
|
491
525
|
globalPendingForms.set(formId, {
|
|
492
526
|
toolName,
|
|
@@ -511,8 +545,7 @@ export class FormAwareAgentExecutor extends AgentExecutor {
|
|
|
511
545
|
});
|
|
512
546
|
|
|
513
547
|
try {
|
|
514
|
-
(action as
|
|
515
|
-
preprocessedInput as Record<string, unknown>;
|
|
548
|
+
(action as ActionWithToolInput).toolInput = preprocessedInput;
|
|
516
549
|
} catch {}
|
|
517
550
|
} else {
|
|
518
551
|
this.formLogger.debug(`No parameter changes needed for ${toolName}`);
|
|
@@ -543,15 +576,13 @@ export class FormAwareAgentExecutor extends AgentExecutor {
|
|
|
543
576
|
}
|
|
544
577
|
|
|
545
578
|
try {
|
|
546
|
-
const obj = schema as
|
|
579
|
+
const obj = schema as ZodSchemaDefinition;
|
|
547
580
|
const def = obj._def;
|
|
548
581
|
if (!def || def.typeName !== 'ZodObject') {
|
|
549
582
|
return false;
|
|
550
583
|
}
|
|
551
584
|
const rawShape: unknown =
|
|
552
|
-
typeof
|
|
553
|
-
? (def as { shape: () => Record<string, z.ZodTypeAny> }).shape()
|
|
554
|
-
: (def as { shape?: Record<string, z.ZodTypeAny> }).shape;
|
|
585
|
+
typeof def.shape === 'function' ? def.shape() : def.shape;
|
|
555
586
|
if (!rawShape || typeof rawShape !== 'object') {
|
|
556
587
|
return false;
|
|
557
588
|
}
|
|
@@ -561,22 +592,14 @@ export class FormAwareAgentExecutor extends AgentExecutor {
|
|
|
561
592
|
return false;
|
|
562
593
|
}
|
|
563
594
|
const unwrapOptional = (s: z.ZodTypeAny): z.ZodTypeAny => {
|
|
564
|
-
const inner = (
|
|
565
|
-
s as unknown as {
|
|
566
|
-
_def?: { typeName?: string; innerType?: z.ZodTypeAny };
|
|
567
|
-
}
|
|
568
|
-
)._def;
|
|
595
|
+
const inner = (s as ZodSchemaDefinition)._def;
|
|
569
596
|
if (inner && inner.typeName === 'ZodOptional' && inner.innerType) {
|
|
570
597
|
return inner.innerType;
|
|
571
598
|
}
|
|
572
599
|
return s;
|
|
573
600
|
};
|
|
574
601
|
const unwrapped = unwrapOptional(fieldSchema);
|
|
575
|
-
const fdef = (
|
|
576
|
-
unwrapped as unknown as {
|
|
577
|
-
_def?: { typeName?: string; defaultValue?: unknown };
|
|
578
|
-
}
|
|
579
|
-
)._def;
|
|
602
|
+
const fdef = (unwrapped as ZodSchemaDefinition)._def;
|
|
580
603
|
if (!fdef) {
|
|
581
604
|
return true;
|
|
582
605
|
}
|
|
@@ -626,11 +649,7 @@ export class FormAwareAgentExecutor extends AgentExecutor {
|
|
|
626
649
|
(t) => t.name === actionToolName
|
|
627
650
|
) as ToolInterface | undefined;
|
|
628
651
|
const originalToolCandidate =
|
|
629
|
-
(toolInstance as
|
|
630
|
-
originalTool?: {
|
|
631
|
-
call?: (args: Record<string, unknown>) => Promise<string>;
|
|
632
|
-
};
|
|
633
|
-
}) || {};
|
|
652
|
+
(toolInstance as ToolWithOriginal) || {};
|
|
634
653
|
const pf: PendingFormData = {
|
|
635
654
|
toolName: actionToolName,
|
|
636
655
|
originalInput: inputs,
|
|
@@ -901,35 +920,19 @@ export class FormAwareAgentExecutor extends AgentExecutor {
|
|
|
901
920
|
}
|
|
902
921
|
|
|
903
922
|
try {
|
|
904
|
-
const maybeWrapper = tool as
|
|
905
|
-
executeOriginal?: (args: Record<string, unknown>) => Promise<string>;
|
|
906
|
-
getOriginalTool?: () => {
|
|
907
|
-
_call?: (args: Record<string, unknown>) => Promise<string>;
|
|
908
|
-
call?: (args: Record<string, unknown>) => Promise<string>;
|
|
909
|
-
};
|
|
910
|
-
originalTool?: {
|
|
911
|
-
_call?: (args: Record<string, unknown>) => Promise<string>;
|
|
912
|
-
call?: (args: Record<string, unknown>) => Promise<string>;
|
|
913
|
-
};
|
|
914
|
-
call?: (args: Record<string, unknown>) => Promise<string>;
|
|
915
|
-
};
|
|
923
|
+
const maybeWrapper = tool as ToolWrapper;
|
|
916
924
|
let toolOutput: string;
|
|
917
925
|
if (typeof maybeWrapper.executeOriginal === 'function') {
|
|
918
926
|
toolOutput = await maybeWrapper.executeOriginal(mergedToolInput);
|
|
919
927
|
} else if (typeof maybeWrapper.getOriginalTool === 'function') {
|
|
920
928
|
const ot = maybeWrapper.getOriginalTool();
|
|
921
|
-
const otCall = ot as
|
|
922
|
-
_call?: (a: Record<string, unknown>) => Promise<string>;
|
|
923
|
-
call?: (a: Record<string, unknown>) => Promise<string>;
|
|
924
|
-
};
|
|
929
|
+
const otCall = ot as CallableTool;
|
|
925
930
|
if (ot && typeof otCall._call === 'function') {
|
|
926
931
|
toolOutput = await otCall._call(mergedToolInput);
|
|
927
932
|
} else if (ot && typeof otCall.call === 'function') {
|
|
928
933
|
toolOutput = await otCall.call(mergedToolInput);
|
|
929
934
|
} else {
|
|
930
|
-
const tcall = tool as
|
|
931
|
-
call?: (a: Record<string, unknown>) => Promise<string>;
|
|
932
|
-
};
|
|
935
|
+
const tcall = tool as CallableTool;
|
|
933
936
|
if (typeof tcall.call === 'function') {
|
|
934
937
|
toolOutput = await tcall.call(mergedToolInput);
|
|
935
938
|
} else {
|
|
@@ -948,18 +951,8 @@ export class FormAwareAgentExecutor extends AgentExecutor {
|
|
|
948
951
|
typeof maybeWrapper.originalTool.call === 'function'
|
|
949
952
|
) {
|
|
950
953
|
toolOutput = await maybeWrapper.originalTool.call(mergedToolInput);
|
|
951
|
-
} else if (
|
|
952
|
-
|
|
953
|
-
tool as unknown as {
|
|
954
|
-
call?: (a: Record<string, unknown>) => Promise<string>;
|
|
955
|
-
}
|
|
956
|
-
).call === 'function'
|
|
957
|
-
) {
|
|
958
|
-
toolOutput = await (
|
|
959
|
-
tool as unknown as {
|
|
960
|
-
call: (a: Record<string, unknown>) => Promise<string>;
|
|
961
|
-
}
|
|
962
|
-
).call(mergedToolInput);
|
|
954
|
+
} else if (typeof (tool as CallableTool).call === 'function') {
|
|
955
|
+
toolOutput = await (tool as CallableTool).call!(mergedToolInput);
|
|
963
956
|
} else {
|
|
964
957
|
throw new Error(
|
|
965
958
|
'No callable tool implementation found for form submission'
|
|
@@ -969,16 +962,6 @@ export class FormAwareAgentExecutor extends AgentExecutor {
|
|
|
969
962
|
let responseMetadata: Record<string, unknown> = {};
|
|
970
963
|
let formattedOutput: string;
|
|
971
964
|
|
|
972
|
-
this.formLogger.info('🔍 METADATA EXTRACTION: Analyzing tool output', {
|
|
973
|
-
outputType: typeof toolOutput,
|
|
974
|
-
outputLength: toolOutput?.length || 0,
|
|
975
|
-
isString: typeof toolOutput === 'string',
|
|
976
|
-
firstChars:
|
|
977
|
-
typeof toolOutput === 'string'
|
|
978
|
-
? toolOutput.substring(0, 100)
|
|
979
|
-
: 'not-string',
|
|
980
|
-
});
|
|
981
|
-
|
|
982
965
|
try {
|
|
983
966
|
const parsed = JSON.parse(toolOutput);
|
|
984
967
|
this.formLogger.info(
|
|
@@ -1077,7 +1060,7 @@ export class FormAwareAgentExecutor extends AgentExecutor {
|
|
|
1077
1060
|
);
|
|
1078
1061
|
return {
|
|
1079
1062
|
toolName: lastStep.action.tool,
|
|
1080
|
-
schema: (tool as
|
|
1063
|
+
schema: (tool as ToolWithSchema).schema,
|
|
1081
1064
|
};
|
|
1082
1065
|
}
|
|
1083
1066
|
}
|
|
@@ -1102,7 +1085,7 @@ export class FormAwareAgentExecutor extends AgentExecutor {
|
|
|
1102
1085
|
this.formLogger.info('Found tool from input steps:', action.tool);
|
|
1103
1086
|
return {
|
|
1104
1087
|
toolName: action.tool,
|
|
1105
|
-
schema: (tool as
|
|
1088
|
+
schema: (tool as ToolWithSchema).schema,
|
|
1106
1089
|
};
|
|
1107
1090
|
}
|
|
1108
1091
|
}
|
|
@@ -1144,7 +1127,7 @@ export class FormAwareAgentExecutor extends AgentExecutor {
|
|
|
1144
1127
|
if ('schema' in tool) {
|
|
1145
1128
|
return {
|
|
1146
1129
|
toolName: tool.name,
|
|
1147
|
-
schema: (tool as
|
|
1130
|
+
schema: (tool as ToolWithSchema).schema,
|
|
1148
1131
|
};
|
|
1149
1132
|
}
|
|
1150
1133
|
}
|
|
@@ -1163,7 +1146,7 @@ export class FormAwareAgentExecutor extends AgentExecutor {
|
|
|
1163
1146
|
|
|
1164
1147
|
for (const tool of this.tools) {
|
|
1165
1148
|
if ('schema' in tool) {
|
|
1166
|
-
const toolSchema = (tool as
|
|
1149
|
+
const toolSchema = (tool as ToolWithSchema).schema;
|
|
1167
1150
|
if (this.schemaMatchesErrorPaths(toolSchema, errorPaths)) {
|
|
1168
1151
|
this.formLogger.info(
|
|
1169
1152
|
'Detected tool from error path analysis:',
|