@hashgraphonline/conversational-agent 0.1.218 → 0.1.220

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.
Files changed (63) hide show
  1. package/dist/cjs/base-agent.d.ts +2 -0
  2. package/dist/cjs/core/tool-registry.d.ts +7 -0
  3. package/dist/cjs/index.cjs +1 -1
  4. package/dist/cjs/index.cjs.map +1 -1
  5. package/dist/cjs/langchain/form-aware-agent-executor.d.ts +14 -3
  6. package/dist/cjs/langchain/form-validating-tool-wrapper.d.ts +81 -0
  7. package/dist/cjs/langchain/index.d.ts +1 -0
  8. package/dist/esm/index.js +7 -4
  9. package/dist/esm/index.js.map +1 -1
  10. package/dist/esm/index10.js +2 -2
  11. package/dist/esm/index21.js +1 -1
  12. package/dist/esm/index23.js +3 -3
  13. package/dist/esm/index25.js +0 -4
  14. package/dist/esm/index25.js.map +1 -1
  15. package/dist/esm/index29.js +78 -9
  16. package/dist/esm/index29.js.map +1 -1
  17. package/dist/esm/index30.js +184 -1215
  18. package/dist/esm/index30.js.map +1 -1
  19. package/dist/esm/index31.js +1193 -116
  20. package/dist/esm/index31.js.map +1 -1
  21. package/dist/esm/index32.js +120 -99
  22. package/dist/esm/index32.js.map +1 -1
  23. package/dist/esm/index33.js +106 -38
  24. package/dist/esm/index33.js.map +1 -1
  25. package/dist/esm/index34.js +41 -98
  26. package/dist/esm/index34.js.map +1 -1
  27. package/dist/esm/index35.js +103 -21
  28. package/dist/esm/index35.js.map +1 -1
  29. package/dist/esm/index36.js +21 -12
  30. package/dist/esm/index36.js.map +1 -1
  31. package/dist/esm/index37.js +11 -6
  32. package/dist/esm/index37.js.map +1 -1
  33. package/dist/esm/index38.js +6 -4
  34. package/dist/esm/index38.js.map +1 -1
  35. package/dist/esm/index39.js +5 -224
  36. package/dist/esm/index39.js.map +1 -1
  37. package/dist/esm/index40.js +213 -142
  38. package/dist/esm/index40.js.map +1 -1
  39. package/dist/esm/index41.js +181 -24
  40. package/dist/esm/index41.js.map +1 -1
  41. package/dist/esm/index42.js +24 -89
  42. package/dist/esm/index42.js.map +1 -1
  43. package/dist/esm/index43.js +95 -0
  44. package/dist/esm/index43.js.map +1 -0
  45. package/dist/esm/index5.js +2 -2
  46. package/dist/esm/index6.js +3 -7
  47. package/dist/esm/index6.js.map +1 -1
  48. package/dist/esm/index7.js.map +1 -1
  49. package/dist/esm/index8.js +1 -1
  50. package/dist/types/base-agent.d.ts +2 -0
  51. package/dist/types/core/tool-registry.d.ts +7 -0
  52. package/dist/types/langchain/form-aware-agent-executor.d.ts +14 -3
  53. package/dist/types/langchain/form-validating-tool-wrapper.d.ts +81 -0
  54. package/dist/types/langchain/index.d.ts +1 -0
  55. package/package.json +1 -1
  56. package/src/base-agent.ts +4 -0
  57. package/src/conversational-agent.ts +3 -14
  58. package/src/core/tool-registry.ts +45 -1
  59. package/src/langchain/form-aware-agent-executor.ts +219 -80
  60. package/src/langchain/form-validating-tool-wrapper.ts +356 -0
  61. package/src/langchain/index.ts +1 -0
  62. package/src/langchain/langchain-agent.ts +24 -104
  63. package/src/services/formatters/format-converter-registry.ts +0 -5
@@ -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,kBAAkB;AAAA,IAAA,CACnC;AAED,QAAI,KAAK,QAAQ,wBAAwB,OAAO;AAC9C,UAAI,CAAC,QAAQ,cAAc;AACzB,cAAM,IAAI;AAAA,UACR;AAAA,QAAA;AAAA,MAEJ;AAEA,WAAK,gBAAgB,IAAI;AAAA,QACvB,KAAK,QAAQ;AAAA,MAAA;AAEf,WAAK,OAAO,KAAK,2BAA2B;AAE5C,WAAK,cAAc,kBAAkB,QAAQ,cAAc,aAAa;AACxE,WAAK,OAAO,KAAK,6CAA6C;AAAA,IAChE;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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AA;AAAA;AAAA;AAAA,EAOA,qBAAqB,YAA6B;AAChD,QAAI,KAAK,OAAO;AACd,YAAM,YAAY,KAAK,MAAM,uBAAA;AAC7B,YAAM,SAAS,UAAU,IAAI,UAAU;AACvC,aAAO,QAAQ,aAAa;AAAA,IAC9B;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,UAAyB;AAC7B,QAAI;AACF,WAAK,OAAO,KAAK,oCAAoC;AAErD,UAAI,KAAK,eAAe;AACtB,YAAI;AACF,eAAK,cAAc,QAAA;AACnB,eAAK,OAAO,KAAK,wCAAwC;AAAA,QAC3D,SAAS,OAAO;AACd,eAAK,OAAO,KAAK,qCAAqC,KAAK;AAAA,QAC7D;AACA,aAAK,gBAAgB;AAAA,MACvB;AAEA,UAAI,KAAK,qBAAqB;AAC5B,cAAM,KAAK,oBAAoB,QAAA;AAC/B,aAAK,OAAO,KAAK,gCAAgC;AAAA,MACnD;AAEA,WAAK,OAAO,KAAK,uCAAuC;AAAA,IAC1D,SAAS,OAAO;AACd,WAAK,OAAO,MAAM,yBAAyB,KAAK;AAAA,IAClD;AAAA,EACF;AAAA,EAEQ,oBAAoB,UAA2B;AACrD,QAAI,OAAO,aAAa,UAAU;AAChC,aAAO;AAAA,IACT;AAEA,QAAI,YAAY,OAAO,aAAa,YAAY,YAAY,UAAU;AACpE,YAAM,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,iBAAiB,IAAI,eAAA;AAC1B,SAAK,aAAa,IAAI,WAAA;AACtB,SAAK,SAAS,IAAI,OAAO;AAAA,MACvB,QAAQ;AAAA,MACR,QAAQ,QAAQ,kBAAkB;AAAA,IAAA,CACnC;AAED,QAAI,KAAK,QAAQ,wBAAwB,OAAO;AAC9C,UAAI,CAAC,QAAQ,cAAc;AACzB,cAAM,IAAI;AAAA,UACR;AAAA,QAAA;AAAA,MAEJ;AAEA,WAAK,gBAAgB,IAAI;AAAA,QACvB,KAAK,QAAQ;AAAA,MAAA;AAEf,WAAK,OAAO,KAAK,2BAA2B;AAE5C,WAA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;AAAA;AAAA;AAAA;AAAA,EAOA,qBAAqB,YAA6B;AAChD,QAAI,KAAK,OAAO;AACd,YAAM,YAAY,KAAK,MAAM,uBAAA;AAC7B,YAAM,SAAS,UAAU,IAAI,UAAU;AACvC,aAAO,QAAQ,aAAa;AAAA,IAC9B;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,UAAyB;AAC7B,QAAI;AACF,WAAK,OAAO,KAAK,oCAAoC;AAErD,UAAI,KAAK,eAAe;AACtB,YAAI;AACF,eAAK,cAAc,QAAA;AACnB,eAAK,OAAO,KAAK,wCAAwC;AAAA,QAC3D,SAAS,OAAO;AACd,eAAK,OAAO,KAAK,qCAAqC,KAAK;AAAA,QAC7D;AACA,aAAK,gBAAgB;AAAA,MACvB;AAEA,UAAI,KAAK,qBAAqB;AAC5B,cAAM,KAAK,oBAAoB,QAAA;AAC/B,aAAK,OAAO,KAAK,gCAAgC;AAAA,MACnD;AAEA,WAAK,OAAO,KAAK,uCAAuC;AAAA,IAC1D,SAAS,OAAO;AACd,WAAK,OAAO,MAAM,yBAAyB,KAAK;AAAA,IAClD;AAAA,EACF;AAAA,EAEQ,oBAAoB,UAA2B;AACrD,QAAI,OAAO,aAAa,UAAU;AAChC,aAAO;AAAA,IACT;AAEA,QAAI,YAAY,OAAO,aAAa,YAAY,YAAY,UAAU;AACpE,YAAM,qBAAqB;AAC3B,aAAO,OAAO,mBAAmB,MAAM;AAAA,IACzC;AAEA,WAAO,KAAK,UAAU,QAAQ;AAAA,EAChC;AACF;AAvsBE,qBAAwB,wBACtB;AAFG,IAAM,sBAAN;"}
@@ -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;AAItB,SAAK,SAAS,IAAI,OAAO;AAAA,MACvB,QAAQ;AAAA,MACR,QAAQ,OAAO,OAAO,UAAU;AAAA,IAAA,CACjC;AAAA,EACH;AAAA,EAeO,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,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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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AW;AACb,YAAM;AAAA,QACJ,gEAAgE,SAAS,2GACkC,SAAS,+HAChB,SAAS;AAAA,MAAA;AAAA,IAEjH;AAEA,UAAM,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,4 +1,4 @@
1
- import { LangChainAgent } from "./index30.js";
1
+ import { LangChainAgent } from "./index31.js";
2
2
  function createAgent(config) {
3
3
  const framework = config.framework || "langchain";
4
4
  switch (framework) {
@@ -5,6 +5,7 @@ import { HederaAgentKit, 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;
@@ -1,5 +1,7 @@
1
1
  import { StructuredTool } from '@langchain/core/tools';
2
+ import { z } from 'zod';
2
3
  import { Logger } from '@hashgraphonline/standards-sdk';
4
+ import { FormValidatingToolWrapper } from '../langchain/form-validating-tool-wrapper';
3
5
 
4
6
  /**
5
7
  * Tool capabilities configuration for registry entries
@@ -38,6 +40,7 @@ export interface ToolMetadata {
38
40
  export interface ToolRegistryEntry {
39
41
  tool: StructuredTool;
40
42
  metadata: ToolMetadata;
43
+ wrapper?: FormValidatingToolWrapper<z.ZodObject<z.ZodRawShape>> | undefined;
41
44
  originalTool: StructuredTool;
42
45
  }
43
46
  /**
@@ -116,6 +119,10 @@ export declare class ToolRegistry {
116
119
  * Check if tool has render configuration
117
120
  */
118
121
  private hasRenderConfig;
122
+ /**
123
+ * Determine if tool should be wrapped
124
+ */
125
+ private shouldWrapTool;
119
126
  /**
120
127
  * Check if schema is ZodObject-like
121
128
  */
@@ -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
@@ -57,6 +60,10 @@ export declare class FormAwareAgentExecutor extends AgentExecutor {
57
60
  * Override _call to intercept Zod validation errors at the execution level
58
61
  */
59
62
  _call(inputs: Record<string, unknown>): Promise<Record<string, unknown>>;
63
+ /**
64
+ * Handles Zod validation errors by generating forms
65
+ */
66
+ private handleValidationError;
60
67
  /**
61
68
  * Get a copy of pending forms for preservation during executor recreation
62
69
  */
@@ -77,6 +84,10 @@ export declare class FormAwareAgentExecutor extends AgentExecutor {
77
84
  * Attempts to find tool from execution context
78
85
  */
79
86
  private findToolFromContext;
87
+ /**
88
+ * Additional fallback to detect tool from error context
89
+ */
90
+ private detectToolFromErrorContext;
80
91
  /**
81
92
  * Checks if a schema structure matches error paths
82
93
  */
@@ -0,0 +1,81 @@
1
+ import { StructuredTool } from '@langchain/core/tools';
2
+ import { z } from 'zod';
3
+ import { CallbackManagerForToolRun } from '@langchain/core/callbacks/manager';
4
+ import { FormGenerator } from '../forms/form-generator';
5
+
6
+ export interface FormValidationConfig {
7
+ requireAllFields?: boolean;
8
+ skipFields?: string[];
9
+ customValidation?: (input: unknown) => boolean;
10
+ }
11
+ /**
12
+ * Generic wrapper for StructuredTools that intercepts execution to check for missing required fields
13
+ * and generates forms when validation would benefit from user input.
14
+ *
15
+ * Tools can implement the FormValidatable interface to provide custom validation logic.
16
+ * Otherwise, falls back to schema-based validation.
17
+ */
18
+ export declare class FormValidatingToolWrapper<TSchema extends z.ZodObject<z.ZodRawShape, z.UnknownKeysParam, z.ZodTypeAny>> extends StructuredTool<TSchema> {
19
+ private originalTool;
20
+ private formGenerator;
21
+ private validationConfig;
22
+ private logger;
23
+ name: string;
24
+ description: string;
25
+ schema: TSchema;
26
+ constructor(originalTool: StructuredTool<TSchema>, formGenerator: FormGenerator, config?: FormValidationConfig);
27
+ /**
28
+ * Validate the input against the schema
29
+ */
30
+ private validateInput;
31
+ /**
32
+ * Gets the shape keys from the schema if it's a ZodObject
33
+ */
34
+ private getSchemaShape;
35
+ /**
36
+ * Executes the wrapped tool's original implementation directly, bypassing wrapper logic.
37
+ */
38
+ executeOriginal(input: Record<string, unknown>, runManager?: CallbackManagerForToolRun): Promise<string>;
39
+ /**
40
+ * Provides access to the wrapped tool instance for executors that want to bypass the wrapper.
41
+ */
42
+ getOriginalTool(): StructuredTool<TSchema>;
43
+ /**
44
+ * Checks if tool implements FormValidatable method
45
+ */
46
+ private hasFormValidatableMethod;
47
+ /**
48
+ * Expose FormValidatable methods by delegating to the underlying tool when available.
49
+ */
50
+ getFormSchema(): z.ZodSchema;
51
+ getEssentialFields(): string[];
52
+ isFieldEmpty(fieldName: string, value: unknown): boolean;
53
+ /**
54
+ * Calculates which fields are missing from the input
55
+ */
56
+ private calculateMissingFields;
57
+ /**
58
+ * Creates a form message with optional JSON schema
59
+ */
60
+ private createFormMessage;
61
+ /**
62
+ * Type guard to check if a schema is a ZodObject
63
+ */
64
+ private isZodObject;
65
+ /**
66
+ * Check if we should generate a form for this tool invocation
67
+ */
68
+ private shouldGenerateForm;
69
+ /**
70
+ * Checks if input has bypass flags that skip form generation
71
+ */
72
+ private hasFormBypassFlags;
73
+ /**
74
+ * Override _call to intercept tool execution
75
+ */
76
+ protected _call(input: z.infer<TSchema>, runManager?: CallbackManagerForToolRun): Promise<string>;
77
+ }
78
+ /**
79
+ * Wrap a tool with form validation capabilities
80
+ */
81
+ export declare function wrapToolWithFormValidation<TSchema extends z.ZodObject<z.ZodRawShape, z.UnknownKeysParam, z.ZodTypeAny>>(tool: StructuredTool<TSchema>, formGenerator: FormGenerator, config?: FormValidationConfig): FormValidatingToolWrapper<TSchema>;
@@ -1,2 +1,3 @@
1
1
  export * from './form-aware-agent-executor';
2
+ export * from './form-validating-tool-wrapper';
2
3
  export * from './langchain-agent';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hashgraphonline/conversational-agent",
3
- "version": "0.1.218",
3
+ "version": "0.1.220",
4
4
  "type": "module",
5
5
  "main": "./dist/cjs/index.cjs",
6
6
  "module": "./dist/esm/index.js",
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 = 'Agent not initialized. Call initialize() first.';
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 internalAgent.processFormSubmission(submission);
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) {
@@ -1,6 +1,10 @@
1
1
  import { StructuredTool } from '@langchain/core/tools';
2
2
  import { z } from 'zod';
3
3
  import { Logger } from '@hashgraphonline/standards-sdk';
4
+ import {
5
+ FormValidatingToolWrapper,
6
+ wrapToolWithFormValidation,
7
+ } from '../langchain/form-validating-tool-wrapper';
4
8
  import { FormGenerator } from '../forms/form-generator';
5
9
  import { isFormValidatable } from '@hashgraphonline/standards-agent-kit';
6
10
 
@@ -44,6 +48,7 @@ export interface ToolMetadata {
44
48
  export interface ToolRegistryEntry {
45
49
  tool: StructuredTool;
46
50
  metadata: ToolMetadata;
51
+ wrapper?: FormValidatingToolWrapper<z.ZodObject<z.ZodRawShape>> | undefined;
47
52
  originalTool: StructuredTool;
48
53
  }
49
54
 
@@ -152,6 +157,22 @@ export class ToolRegistry {
152
157
  } catch {}
153
158
 
154
159
  let finalTool: StructuredTool = tool;
160
+ let wrapper:
161
+ | FormValidatingToolWrapper<z.ZodObject<z.ZodRawShape>>
162
+ | undefined;
163
+
164
+ if (this.shouldWrapTool(tool, capabilities, options)) {
165
+ wrapper = wrapToolWithFormValidation(
166
+ tool as StructuredTool<z.ZodObject<z.ZodRawShape>>,
167
+ this.formGenerator,
168
+ {
169
+ requireAllFields: false,
170
+ skipFields: ['metaOptions'],
171
+ ...options.wrapperConfig,
172
+ }
173
+ ) as FormValidatingToolWrapper<z.ZodObject<z.ZodRawShape>>;
174
+ finalTool = wrapper as StructuredTool;
175
+ }
155
176
 
156
177
  try {
157
178
  if (metadata.entityResolutionPreferences) {
@@ -165,6 +186,7 @@ export class ToolRegistry {
165
186
  const entry: ToolRegistryEntry = {
166
187
  tool: finalTool,
167
188
  metadata,
189
+ wrapper,
168
190
  originalTool: tool,
169
191
  };
170
192
 
@@ -329,6 +351,24 @@ export class ToolRegistry {
329
351
  return !!(schema && schema._renderConfig);
330
352
  }
331
353
 
354
+ /**
355
+ * Determine if tool should be wrapped
356
+ */
357
+ private shouldWrapTool(
358
+ tool: StructuredTool,
359
+ capabilities: ToolCapabilities,
360
+ options: ToolRegistrationOptions
361
+ ): boolean {
362
+ if (options.skipWrapper) {
363
+ return false;
364
+ }
365
+
366
+ if (options.forceWrapper) {
367
+ return true;
368
+ }
369
+
370
+ return capabilities.requiresWrapper;
371
+ }
332
372
 
333
373
  /**
334
374
  * Check if schema is ZodObject-like
@@ -373,7 +413,11 @@ export class ToolRegistry {
373
413
  };
374
414
 
375
415
  for (const entry of this.tools.values()) {
376
- stats.unwrappedTools++;
416
+ if (entry.wrapper) {
417
+ stats.wrappedTools++;
418
+ } else {
419
+ stats.unwrappedTools++;
420
+ }
377
421
 
378
422
  stats.categoryCounts[entry.metadata.category]++;
379
423
  stats.priorityCounts[entry.metadata.capabilities.priority]++;