@hashgraphonline/conversational-agent 0.2.216 → 0.2.218
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/cli/readme.md +181 -0
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.ts +1 -0
- package/dist/cjs/plugins/community/swarm/SwarmPlugin.d.ts +17 -0
- package/dist/cjs/plugins/community/swarm/__tests__/SwarmPlugin.mocks.d.ts +1 -0
- package/dist/cjs/plugins/community/swarm/__tests__/SwarmPlugin.test.d.ts +1 -0
- package/dist/cjs/plugins/community/swarm/__tests__/tools/CreatePostageStampTool.test.d.ts +1 -0
- package/dist/cjs/plugins/community/swarm/__tests__/tools/DownloadDataTool.test.d.ts +1 -0
- package/dist/cjs/plugins/community/swarm/__tests__/tools/DownloadFilesTool.test.d.ts +1 -0
- package/dist/cjs/plugins/community/swarm/__tests__/tools/ExtendPostageStampTool.test.d.ts +1 -0
- package/dist/cjs/plugins/community/swarm/__tests__/tools/GetPostageStampTool.test.d.ts +1 -0
- package/dist/cjs/plugins/community/swarm/__tests__/tools/ListPostageStampsTool.test.d.ts +1 -0
- package/dist/cjs/plugins/community/swarm/__tests__/tools/QueryUploadProgressTool.test.d.ts +1 -0
- package/dist/cjs/plugins/community/swarm/__tests__/tools/ReadFeedTool.test.d.ts +1 -0
- package/dist/cjs/plugins/community/swarm/__tests__/tools/SwarmTool.mocks.d.ts +14 -0
- package/dist/cjs/plugins/community/swarm/__tests__/tools/UpdateFeedTool.test.d.ts +1 -0
- package/dist/cjs/plugins/community/swarm/__tests__/tools/UploadDataTool.test.d.ts +1 -0
- package/dist/cjs/plugins/community/swarm/__tests__/tools/UploadFileTool.test.d.ts +1 -0
- package/dist/cjs/plugins/community/swarm/__tests__/tools/UploadFolderTool.test.d.ts +1 -0
- package/dist/cjs/plugins/community/swarm/config.d.ts +6 -0
- package/dist/cjs/plugins/community/swarm/constants.d.ts +8 -0
- package/dist/cjs/plugins/community/swarm/index.d.ts +2 -0
- package/dist/cjs/plugins/community/swarm/model.d.ts +23 -0
- package/dist/cjs/plugins/community/swarm/tools/CreatePostageStampTool.d.ts +47 -0
- package/dist/cjs/plugins/community/swarm/tools/DownloadDataTool.d.ts +35 -0
- package/dist/cjs/plugins/community/swarm/tools/DownloadFilesTool.d.ts +41 -0
- package/dist/cjs/plugins/community/swarm/tools/ExtendPostageStampTool.d.ts +47 -0
- package/dist/cjs/plugins/community/swarm/tools/GetPostageStampTool.d.ts +35 -0
- package/dist/cjs/plugins/community/swarm/tools/ListPostageStampsTool.d.ts +53 -0
- package/dist/cjs/plugins/community/swarm/tools/QueryUploadProgressTool.d.ts +35 -0
- package/dist/cjs/plugins/community/swarm/tools/ReadFeedTool.d.ts +41 -0
- package/dist/cjs/plugins/community/swarm/tools/UpdateFeedTool.d.ts +47 -0
- package/dist/cjs/plugins/community/swarm/tools/UploadDataTool.d.ts +47 -0
- package/dist/cjs/plugins/community/swarm/tools/UploadFileTool.d.ts +53 -0
- package/dist/cjs/plugins/community/swarm/tools/UploadFolderTool.d.ts +47 -0
- package/dist/cjs/plugins/community/swarm/utils.d.ts +22 -0
- package/dist/cjs/plugins/index.d.ts +1 -0
- package/dist/esm/index.js +33 -31
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/index10.js +13 -677
- package/dist/esm/index10.js.map +1 -1
- package/dist/esm/index11.js +601 -234
- package/dist/esm/index11.js.map +1 -1
- package/dist/esm/index12.js +296 -136
- package/dist/esm/index12.js.map +1 -1
- package/dist/esm/index13.js +127 -235
- package/dist/esm/index13.js.map +1 -1
- package/dist/esm/index14.js +247 -84
- package/dist/esm/index14.js.map +1 -1
- package/dist/esm/index15.js +81 -159
- package/dist/esm/index15.js.map +1 -1
- package/dist/esm/index16.js +155 -229
- package/dist/esm/index16.js.map +1 -1
- package/dist/esm/index17.js +238 -140
- package/dist/esm/index17.js.map +1 -1
- package/dist/esm/index18.js +139 -493
- package/dist/esm/index18.js.map +1 -1
- package/dist/esm/index19.js +479 -91
- package/dist/esm/index19.js.map +1 -1
- package/dist/esm/index20.js +88 -147
- package/dist/esm/index20.js.map +1 -1
- package/dist/esm/index21.js +127 -666
- package/dist/esm/index21.js.map +1 -1
- package/dist/esm/index22.js +698 -44
- package/dist/esm/index22.js.map +1 -1
- package/dist/esm/index23.js +45 -304
- package/dist/esm/index23.js.map +1 -1
- package/dist/esm/index24.js +303 -153
- package/dist/esm/index24.js.map +1 -1
- package/dist/esm/index25.js +150 -117
- package/dist/esm/index25.js.map +1 -1
- package/dist/esm/index26.js +154 -18
- package/dist/esm/index26.js.map +1 -1
- package/dist/esm/index27.js +18 -22
- package/dist/esm/index27.js.map +1 -1
- package/dist/esm/index28.js +15 -74
- package/dist/esm/index28.js.map +1 -1
- package/dist/esm/index29.js +70 -295
- package/dist/esm/index29.js.map +1 -1
- package/dist/esm/index30.js +279 -100
- package/dist/esm/index30.js.map +1 -1
- package/dist/esm/index31.js +86 -922
- package/dist/esm/index31.js.map +1 -1
- package/dist/esm/index32.js +904 -189
- package/dist/esm/index32.js.map +1 -1
- package/dist/esm/index33.js +185 -1169
- package/dist/esm/index33.js.map +1 -1
- package/dist/esm/index34.js +1218 -112
- package/dist/esm/index34.js.map +1 -1
- package/dist/esm/index35.js +111 -99
- package/dist/esm/index35.js.map +1 -1
- package/dist/esm/index36.js +113 -8
- package/dist/esm/index36.js.map +1 -1
- package/dist/esm/index37.js +8 -45
- package/dist/esm/index37.js.map +1 -1
- package/dist/esm/index38.js +41 -102
- package/dist/esm/index38.js.map +1 -1
- package/dist/esm/index39.js +96 -55
- package/dist/esm/index39.js.map +1 -1
- package/dist/esm/index4.js +1 -1
- package/dist/esm/index40.js +58 -71
- package/dist/esm/index40.js.map +1 -1
- package/dist/esm/index41.js +79 -21
- package/dist/esm/index41.js.map +1 -1
- package/dist/esm/index42.js +21 -5
- package/dist/esm/index42.js.map +1 -1
- package/dist/esm/index43.js +26 -11
- package/dist/esm/index43.js.map +1 -1
- package/dist/esm/index44.js +12 -322
- package/dist/esm/index44.js.map +1 -1
- package/dist/esm/index45.js +66 -173
- package/dist/esm/index45.js.map +1 -1
- package/dist/esm/index46.js +69 -24
- package/dist/esm/index46.js.map +1 -1
- package/dist/esm/index47.js +47 -88
- package/dist/esm/index47.js.map +1 -1
- package/dist/esm/index48.js +100 -7
- package/dist/esm/index48.js.map +1 -1
- package/dist/esm/index49.js +79 -0
- package/dist/esm/index49.js.map +1 -0
- package/dist/esm/index5.js +2 -2
- package/dist/esm/index50.js +75 -0
- package/dist/esm/index50.js.map +1 -0
- package/dist/esm/index51.js +124 -0
- package/dist/esm/index51.js.map +1 -0
- package/dist/esm/index52.js +58 -0
- package/dist/esm/index52.js.map +1 -0
- package/dist/esm/index53.js +83 -0
- package/dist/esm/index53.js.map +1 -0
- package/dist/esm/index54.js +100 -0
- package/dist/esm/index54.js.map +1 -0
- package/dist/esm/index55.js +118 -0
- package/dist/esm/index55.js.map +1 -0
- package/dist/esm/index56.js +108 -0
- package/dist/esm/index56.js.map +1 -0
- package/dist/esm/index57.js +8 -0
- package/dist/esm/index57.js.map +1 -0
- package/dist/esm/index58.js +325 -0
- package/dist/esm/index58.js.map +1 -0
- package/dist/esm/index59.js +187 -0
- package/dist/esm/index59.js.map +1 -0
- package/dist/esm/index6.js +132 -833
- package/dist/esm/index6.js.map +1 -1
- package/dist/esm/index60.js +10 -0
- package/dist/esm/index60.js.map +1 -0
- package/dist/esm/index61.js +98 -0
- package/dist/esm/index61.js.map +1 -0
- package/dist/esm/index62.js +131 -0
- package/dist/esm/index62.js.map +1 -0
- package/dist/esm/index63.js +19 -0
- package/dist/esm/index63.js.map +1 -0
- package/dist/esm/index7.js +826 -75
- package/dist/esm/index7.js.map +1 -1
- package/dist/esm/index8.js +91 -13
- package/dist/esm/index8.js.map +1 -1
- package/dist/esm/index9.js +13 -17
- package/dist/esm/index9.js.map +1 -1
- package/dist/types/index.d.ts +1 -0
- package/dist/types/plugins/community/swarm/SwarmPlugin.d.ts +17 -0
- package/dist/types/plugins/community/swarm/__tests__/SwarmPlugin.mocks.d.ts +1 -0
- package/dist/types/plugins/community/swarm/__tests__/SwarmPlugin.test.d.ts +1 -0
- package/dist/types/plugins/community/swarm/__tests__/tools/CreatePostageStampTool.test.d.ts +1 -0
- package/dist/types/plugins/community/swarm/__tests__/tools/DownloadDataTool.test.d.ts +1 -0
- package/dist/types/plugins/community/swarm/__tests__/tools/DownloadFilesTool.test.d.ts +1 -0
- package/dist/types/plugins/community/swarm/__tests__/tools/ExtendPostageStampTool.test.d.ts +1 -0
- package/dist/types/plugins/community/swarm/__tests__/tools/GetPostageStampTool.test.d.ts +1 -0
- package/dist/types/plugins/community/swarm/__tests__/tools/ListPostageStampsTool.test.d.ts +1 -0
- package/dist/types/plugins/community/swarm/__tests__/tools/QueryUploadProgressTool.test.d.ts +1 -0
- package/dist/types/plugins/community/swarm/__tests__/tools/ReadFeedTool.test.d.ts +1 -0
- package/dist/types/plugins/community/swarm/__tests__/tools/SwarmTool.mocks.d.ts +14 -0
- package/dist/types/plugins/community/swarm/__tests__/tools/UpdateFeedTool.test.d.ts +1 -0
- package/dist/types/plugins/community/swarm/__tests__/tools/UploadDataTool.test.d.ts +1 -0
- package/dist/types/plugins/community/swarm/__tests__/tools/UploadFileTool.test.d.ts +1 -0
- package/dist/types/plugins/community/swarm/__tests__/tools/UploadFolderTool.test.d.ts +1 -0
- package/dist/types/plugins/community/swarm/config.d.ts +6 -0
- package/dist/types/plugins/community/swarm/constants.d.ts +8 -0
- package/dist/types/plugins/community/swarm/index.d.ts +2 -0
- package/dist/types/plugins/community/swarm/model.d.ts +23 -0
- package/dist/types/plugins/community/swarm/tools/CreatePostageStampTool.d.ts +47 -0
- package/dist/types/plugins/community/swarm/tools/DownloadDataTool.d.ts +35 -0
- package/dist/types/plugins/community/swarm/tools/DownloadFilesTool.d.ts +41 -0
- package/dist/types/plugins/community/swarm/tools/ExtendPostageStampTool.d.ts +47 -0
- package/dist/types/plugins/community/swarm/tools/GetPostageStampTool.d.ts +35 -0
- package/dist/types/plugins/community/swarm/tools/ListPostageStampsTool.d.ts +53 -0
- package/dist/types/plugins/community/swarm/tools/QueryUploadProgressTool.d.ts +35 -0
- package/dist/types/plugins/community/swarm/tools/ReadFeedTool.d.ts +41 -0
- package/dist/types/plugins/community/swarm/tools/UpdateFeedTool.d.ts +47 -0
- package/dist/types/plugins/community/swarm/tools/UploadDataTool.d.ts +47 -0
- package/dist/types/plugins/community/swarm/tools/UploadFileTool.d.ts +53 -0
- package/dist/types/plugins/community/swarm/tools/UploadFolderTool.d.ts +47 -0
- package/dist/types/plugins/community/swarm/utils.d.ts +22 -0
- package/dist/types/plugins/index.d.ts +1 -0
- package/package.json +37 -27
- package/src/index.ts +1 -0
- package/src/plugins/community/swarm/README.md +279 -0
- package/src/plugins/community/swarm/SwarmPlugin.ts +178 -0
- package/src/plugins/community/swarm/__tests__/SwarmPlugin.mocks.ts +105 -0
- package/src/plugins/community/swarm/__tests__/SwarmPlugin.test.ts +93 -0
- package/src/plugins/community/swarm/__tests__/tools/CreatePostageStampTool.test.ts +152 -0
- package/src/plugins/community/swarm/__tests__/tools/DownloadDataTool.test.ts +93 -0
- package/src/plugins/community/swarm/__tests__/tools/DownloadFilesTool.test.ts +163 -0
- package/src/plugins/community/swarm/__tests__/tools/ExtendPostageStampTool.test.ts +132 -0
- package/src/plugins/community/swarm/__tests__/tools/GetPostageStampTool.test.ts +83 -0
- package/src/plugins/community/swarm/__tests__/tools/ListPostageStampsTool.test.ts +219 -0
- package/src/plugins/community/swarm/__tests__/tools/QueryUploadProgressTool.test.ts +169 -0
- package/src/plugins/community/swarm/__tests__/tools/ReadFeedTool.test.ts +133 -0
- package/src/plugins/community/swarm/__tests__/tools/SwarmTool.mocks.ts +67 -0
- package/src/plugins/community/swarm/__tests__/tools/UpdateFeedTool.test.ts +148 -0
- package/src/plugins/community/swarm/__tests__/tools/UploadDataTool.test.ts +125 -0
- package/src/plugins/community/swarm/__tests__/tools/UploadFileTool.test.ts +194 -0
- package/src/plugins/community/swarm/__tests__/tools/UploadFolderTool.test.ts +118 -0
- package/src/plugins/community/swarm/config.ts +6 -0
- package/src/plugins/community/swarm/constants.ts +12 -0
- package/src/plugins/community/swarm/index.ts +2 -0
- package/src/plugins/community/swarm/model.ts +23 -0
- package/src/plugins/community/swarm/tools/CreatePostageStampTool.ts +137 -0
- package/src/plugins/community/swarm/tools/DownloadDataTool.ts +79 -0
- package/src/plugins/community/swarm/tools/DownloadFilesTool.ts +155 -0
- package/src/plugins/community/swarm/tools/ExtendPostageStampTool.ts +112 -0
- package/src/plugins/community/swarm/tools/GetPostageStampTool.ts +92 -0
- package/src/plugins/community/swarm/tools/ListPostageStampsTool.ts +124 -0
- package/src/plugins/community/swarm/tools/QueryUploadProgressTool.ts +109 -0
- package/src/plugins/community/swarm/tools/ReadFeedTool.ts +110 -0
- package/src/plugins/community/swarm/tools/UpdateFeedTool.ts +149 -0
- package/src/plugins/community/swarm/tools/UploadDataTool.ts +109 -0
- package/src/plugins/community/swarm/tools/UploadFileTool.ts +163 -0
- package/src/plugins/community/swarm/tools/UploadFolderTool.ts +150 -0
- package/src/plugins/community/swarm/utils.ts +172 -0
- package/src/plugins/index.ts +1 -0
- package/cli/dist/CLIApp.d.ts +0 -11
- package/cli/dist/CLIApp.d.ts.map +0 -1
- package/cli/dist/CLIApp.js +0 -128
- package/cli/dist/CLIApp.js.map +0 -1
- package/cli/dist/LocalConversationalAgent.d.ts +0 -37
- package/cli/dist/LocalConversationalAgent.js +0 -58
- package/cli/dist/app.d.ts +0 -18
- package/cli/dist/app.d.ts.map +0 -1
- package/cli/dist/app.js +0 -14
- package/cli/dist/app.js.map +0 -1
- package/cli/dist/cli.d.ts +0 -3
- package/cli/dist/cli.d.ts.map +0 -1
- package/cli/dist/cli.js +0 -87
- package/cli/dist/cli.js.map +0 -1
- package/cli/dist/components/AppContainer.d.ts +0 -16
- package/cli/dist/components/AppContainer.js +0 -24
- package/cli/dist/components/AppScreens.d.ts +0 -2
- package/cli/dist/components/AppScreens.js +0 -259
- package/cli/dist/components/ChatScreen.d.ts +0 -21
- package/cli/dist/components/ChatScreen.d.ts.map +0 -1
- package/cli/dist/components/ChatScreen.js +0 -40
- package/cli/dist/components/ChatScreen.js.map +0 -1
- package/cli/dist/components/DebugLoadingScreen.d.ts +0 -5
- package/cli/dist/components/DebugLoadingScreen.js +0 -31
- package/cli/dist/components/LoadingScreen.d.ts +0 -3
- package/cli/dist/components/LoadingScreen.d.ts.map +0 -1
- package/cli/dist/components/LoadingScreen.js +0 -17
- package/cli/dist/components/LoadingScreen.js.map +0 -1
- package/cli/dist/components/LoadingScreenDebug.d.ts +0 -5
- package/cli/dist/components/LoadingScreenDebug.js +0 -27
- package/cli/dist/components/MCPConfigScreen.d.ts +0 -28
- package/cli/dist/components/MCPConfigScreen.d.ts.map +0 -1
- package/cli/dist/components/MCPConfigScreen.js +0 -186
- package/cli/dist/components/MCPConfigScreen.js.map +0 -1
- package/cli/dist/components/ScreenRouter.d.ts +0 -13
- package/cli/dist/components/ScreenRouter.d.ts.map +0 -1
- package/cli/dist/components/ScreenRouter.js +0 -23
- package/cli/dist/components/ScreenRouter.js.map +0 -1
- package/cli/dist/components/SetupScreen.d.ts +0 -16
- package/cli/dist/components/SetupScreen.d.ts.map +0 -1
- package/cli/dist/components/SetupScreen.js +0 -67
- package/cli/dist/components/SetupScreen.js.map +0 -1
- package/cli/dist/components/SingleLoadingScreen.d.ts +0 -5
- package/cli/dist/components/SingleLoadingScreen.js +0 -27
- package/cli/dist/components/StatusBadge.d.ts +0 -10
- package/cli/dist/components/StatusBadge.d.ts.map +0 -1
- package/cli/dist/components/StatusBadge.js +0 -24
- package/cli/dist/components/StatusBadge.js.map +0 -1
- package/cli/dist/components/TerminalWindow.d.ts +0 -9
- package/cli/dist/components/TerminalWindow.d.ts.map +0 -1
- package/cli/dist/components/TerminalWindow.js +0 -19
- package/cli/dist/components/TerminalWindow.js.map +0 -1
- package/cli/dist/components/WelcomeScreen.d.ts +0 -12
- package/cli/dist/components/WelcomeScreen.d.ts.map +0 -1
- package/cli/dist/components/WelcomeScreen.js +0 -47
- package/cli/dist/components/WelcomeScreen.js.map +0 -1
- package/cli/dist/context/AppContext.d.ts +0 -68
- package/cli/dist/context/AppContext.js +0 -363
- package/cli/dist/headless-runner.d.ts +0 -17
- package/cli/dist/headless-runner.d.ts.map +0 -1
- package/cli/dist/headless-runner.js +0 -128
- package/cli/dist/headless-runner.js.map +0 -1
- package/cli/dist/hooks/useInitializeAgent.d.ts +0 -19
- package/cli/dist/hooks/useInitializeAgent.d.ts.map +0 -1
- package/cli/dist/hooks/useInitializeAgent.js +0 -29
- package/cli/dist/hooks/useInitializeAgent.js.map +0 -1
- package/cli/dist/hooks/useStableState.d.ts +0 -38
- package/cli/dist/hooks/useStableState.d.ts.map +0 -1
- package/cli/dist/hooks/useStableState.js +0 -69
- package/cli/dist/hooks/useStableState.js.map +0 -1
- package/cli/dist/managers/AgentManager.d.ts +0 -58
- package/cli/dist/managers/AgentManager.d.ts.map +0 -1
- package/cli/dist/managers/AgentManager.js +0 -121
- package/cli/dist/managers/AgentManager.js.map +0 -1
- package/cli/dist/managers/ConfigManager.d.ts +0 -54
- package/cli/dist/managers/ConfigManager.d.ts.map +0 -1
- package/cli/dist/managers/ConfigManager.js +0 -188
- package/cli/dist/managers/ConfigManager.js.map +0 -1
- package/cli/dist/types.d.ts +0 -52
- package/cli/dist/types.d.ts.map +0 -1
- package/cli/dist/types.js +0 -34
- package/cli/dist/types.js.map +0 -1
package/dist/cjs/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("hedera-agent-kit"),t=require("@hashgraphonline/standards-agent-kit"),r=require("@hashgraphonline/standards-sdk"),o=require("zod"),n=require("@hashgraph/sdk"),s=require("bignumber.js"),i=require("@langchain/core/tools"),a=require("langchain/agents"),c=require("zod-to-json-schema"),l=require("@langchain/core/prompts"),g=require("@langchain/openai"),h=require("@modelcontextprotocol/sdk/client/index.js"),u=require("@modelcontextprotocol/sdk/client/stdio.js"),m=require("@langchain/core/messages"),d=require("tiktoken"),p=require("crypto"),f=require("@langchain/anthropic");class y extends e.BasePlugin{constructor(){super(...arguments),this.id="hcs-10",this.name="HCS-10 Plugin",this.description="HCS-10 agent tools for decentralized agent registration, connections, and messaging on Hedera",this.version="1.0.0",this.author="Hashgraph Online",this.namespace="hcs10",this.tools=[]}async initialize(e){await super.initialize(e);const o=e.config.hederaKit;var n;if(o)try{this.stateManager=e.stateManager||e.config.stateManager||this.appConfig?.stateManager||new t.OpenConvaiState;const a=o.signer.getAccountId().toString(),c="returnBytes"===String(o.operationalMode||"returnBytes");let l,g="",h="",u=o.signer.getOperatorPrivateKey();try{l="function"==typeof u?.toString?u.toString():"";const e=new r.HCS10Client({network:o.network,operatorId:a,operatorPrivateKey:u,logLevel:"error"}),t=await e.retrieveProfile(a);t.success&&t.topicInfo&&(g=t.topicInfo.inboundTopic,h=t.topicInfo.outboundTopic)}catch(s){this.context.logger.warn("Skipping profile topic discovery",s)}const m={name:`Agent ${a}`,accountId:a,inboundTopicId:g,outboundTopicId:h};if(!c&&l&&(m.privateKey=l),this.stateManager.setCurrentAgent(m),this.context.logger.info(`Set current agent: ${a} with topics ${g}/${h}`),!c&&this.stateManager&&!this.stateManager.getConnectionsManager())try{const e=new r.HCS10Client({network:o.network,operatorId:a,operatorPrivateKey:u??"",logLevel:"error"});"object"==typeof(n=this.stateManager)&&null!==n&&"initializeConnectionsManager"in n&&"function"==typeof n.initializeConnectionsManager?this.stateManager.initializeConnectionsManager(e):this.context.logger.warn("StateManager does not support connection manager initialization"),this.context.logger.info("ConnectionsManager initialized in HCS10Plugin")}catch(i){this.context.logger.warn("Could not initialize ConnectionsManager:",i)}this.initializeTools(),this.context.logger.info("HCS-10 Plugin initialized successfully")}catch(a){this.context.logger.error("Failed to initialize HCS-10 plugin:",a)}else this.context.logger.warn("HederaKit not found in context. HCS-10 tools will not be available.")}initializeTools(){if(!this.stateManager)throw new Error("StateManager must be initialized before creating tools");const e=this.context.config.hederaKit;if(!e)throw new Error("HederaKit not found in context config");const r=new t.HCS10Builder(e,this.stateManager);this.tools=[new t.RegisterAgentTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger}),new t.FindRegistrationsTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger}),new t.RetrieveProfileTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger}),new t.InitiateConnectionTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger}),new t.ListConnectionsTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger}),new t.SendMessageToConnectionTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger}),new t.CheckMessagesTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger}),new t.ConnectionMonitorTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger}),new t.ManageConnectionRequestsTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger}),new t.AcceptConnectionRequestTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger}),new t.ListUnapprovedConnectionRequestsTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger})]}getTools(){return this.tools}getStateManager(){return this.stateManager}async cleanup(){this.tools=[],delete this.stateManager,this.context?.logger&&this.context.logger.info("HCS-10 Plugin cleaned up")}}class w extends e.BasePlugin{constructor(){super(...arguments),this.id="hcs-2",this.name="HCS-2 Plugin",this.description="HCS-2 registry management tools for decentralized registries on Hedera",this.version="1.0.0",this.author="Hashgraph Online",this.namespace="hcs2",this.tools=[]}async initialize(e){await super.initialize(e);if(e.config.hederaKit)try{this.initializeTools(),this.context.logger.info("HCS-2 Plugin initialized successfully")}catch(t){this.context.logger.error("Failed to initialize HCS-2 plugin:",t)}else this.context.logger.warn("HederaKit not found in context. HCS-2 tools will not be available.")}initializeTools(){const e=this.context.config.hederaKit;if(!e)throw new Error("HederaKit not found in context config");const r=new t.HCS2Builder(e);this.tools=[new t.CreateRegistryTool({hederaKit:e,hcs2Builder:r,logger:this.context.logger}),new t.RegisterEntryTool({hederaKit:e,hcs2Builder:r,logger:this.context.logger}),new t.UpdateEntryTool({hederaKit:e,hcs2Builder:r,logger:this.context.logger}),new t.DeleteEntryTool({hederaKit:e,hcs2Builder:r,logger:this.context.logger}),new t.MigrateRegistryTool({hederaKit:e,hcs2Builder:r,logger:this.context.logger}),new t.QueryRegistryTool({hederaKit:e,hcs2Builder:r,logger:this.context.logger})]}getTools(){return this.tools}async cleanup(){this.tools=[],this.context?.logger&&this.context.logger.info("HCS-2 Plugin cleaned up")}}const T=new class{constructor(){this.configurations=[],this.providers=[],this.registerOrderCounter=0,this.logger=new r.Logger({module:"FieldGuidanceRegistry"})}registerToolConfiguration(e){this.configurations.push(e)}registerToolProvider(e,t,r){const o=r?.id??`provider-${this.providers.length+1}`,n=r?.priority??0;if(this.providers.some(e=>e.id===o))throw this.logger.error("Duplicate provider id",{id:o}),new Error("DUPLICATE_PROVIDER_ID");return this.providers.push({id:o,priority:n,pattern:e,provider:t,order:this.registerOrderCounter++}),o}unregisterProvider(e){this.providers=this.providers.filter(t=>t.id!==e)}listProviders(){return this.providers.map(({id:e,priority:t,pattern:r})=>({id:e,priority:t,pattern:r}))}getFieldGuidance(e,t){if("false"===process.env.CA_FORM_GUIDANCE_ENABLED)return null;for(const o of this.configurations){if(("string"==typeof o.toolPattern?e.toLowerCase().includes(o.toolPattern.toLowerCase()):o.toolPattern.test(e))&&o.fields[t]){const r=o.fields[t],n=this.pickMatchingProviders(e);if(0===n.length)return r;let s={...r};for(const o of[...n].reverse()){const r=this.safeGetFieldGuidance(o,t,e);r&&(s=this.mergeGuidance(s,r))}return s}}const r=this.pickMatchingProviders(e);if(r.length>0){let o={};for(const n of[...r].reverse()){const r=this.safeGetFieldGuidance(n,t,e);r&&(o=this.mergeGuidance(o,r))}return Object.keys(o).length>0?o:null}return null}getGlobalGuidance(e){if("false"===process.env.CA_FORM_GUIDANCE_ENABLED)return null;for(const r of this.configurations){if(("string"==typeof r.toolPattern?e.toLowerCase().includes(r.toolPattern.toLowerCase()):r.toolPattern.test(e))&&r.globalGuidance){const t=r.globalGuidance,o=this.pickMatchingProviders(e);if(0===o.length)return t;let n=t.warnings,s=t.qualityStandards;for(const r of[...o].reverse()){const t=this.safeGetGlobalGuidance(r,e);t&&(n=t.warnings??n,s=t.qualityStandards??s)}const i={};return void 0!==n&&(i.warnings=n),void 0!==s&&(i.qualityStandards=s),i}}const t=this.pickMatchingProviders(e);if(t.length>0){let r,o;for(const s of[...t].reverse()){const t=this.safeGetGlobalGuidance(s,e);t&&(r=t.warnings??r,o=t.qualityStandards??o)}const n={};return void 0!==r&&(n.warnings=r),void 0!==o&&(n.qualityStandards=o),Object.keys(n).length>0?n:null}return null}validateFieldValue(e,t,r){const o=this.getFieldGuidance(e,t),n=[],s=[];if(!o||"string"!=typeof r)return{isValid:!0,warnings:n,errors:s};if(o.warnings)for(const i of o.warnings)i.pattern.test(r)&&n.push(i.message);if(o.validationRules){const{rejectPatterns:e,qualityChecks:t}=o.validationRules;if(e)for(const o of e)o.pattern.test(r)&&s.push(`Rejected: ${o.reason}`);if(t){if(t.forbidTechnicalTerms){const e=r.toLowerCase();for(const r of t.forbidTechnicalTerms)e.includes(r.toLowerCase())&&s.push(`Avoid technical terms like "${r}" in NFT metadata`)}if(t.requireSpecificTerms){const e=r.toLowerCase();t.requireSpecificTerms.some(t=>e.includes(t.toLowerCase()))||n.push(`Consider including terms like: ${t.requireSpecificTerms.join(", ")}`)}if(t.minNonTechnicalWords){r.split(/\s+/).filter(e=>e.length>2).length<t.minNonTechnicalWords&&n.push(`Consider providing more descriptive content (at least ${t.minNonTechnicalWords} meaningful words)`)}}}return{isValid:0===s.length,warnings:n,errors:s}}clear(){this.configurations=[],this.providers=[],this.registerOrderCounter=0}pickMatchingProviders(e){return this.providers.filter(t=>"string"==typeof t.pattern?e.toLowerCase().includes(t.pattern.toLowerCase()):t.pattern.test(e)).sort((e,t)=>t.priority!==e.priority?t.priority-e.priority:t.order-e.order).map(e=>({id:e.id,provider:e.provider,priority:e.priority,order:e.order}))}safeGetFieldGuidance(e,t,r){try{return e.provider.getFieldGuidance(t,{toolName:r})??null}catch(o){return this.logger.warn("Provider getFieldGuidance failed",{id:e.id,err:o}),null}}safeGetGlobalGuidance(e,t){try{return e.provider.getGlobalGuidance?.(t)??null}catch(r){return this.logger.warn("Provider getGlobalGuidance failed",{id:e.id,err:r}),null}}mergeGuidance(e,t){const r={},o=t.suggestions??e.suggestions;void 0!==o&&(r.suggestions=o);const n=t.predefinedOptions??e.predefinedOptions;void 0!==n&&(r.predefinedOptions=n);const s=t.warnings??e.warnings;void 0!==s&&(r.warnings=s);const i=t.validationRules??e.validationRules;void 0!==i&&(r.validationRules=i);const a=t.fieldTypeOverride??e.fieldTypeOverride;void 0!==a&&(r.fieldTypeOverride=a);const c=t.contextualHelpText??e.contextualHelpText;return void 0!==c&&(r.contextualHelpText=c),r}};class S extends e.BasePlugin{constructor(){super(...arguments),this.id="inscribe",this.name="Inscribe Plugin",this.description="Content inscription tools for storing data on Hedera Consensus Service",this.version="1.0.0",this.author="Hashgraph Online",this.namespace="inscribe",this.tools=[],this.providerId=null}async initialize(e){await super.initialize(e);if(e.config.hederaKit)try{this.initializeTools();try{const e={getFieldGuidance:e=>"name"===e?{suggestions:["Sunset Landscape #42","Digital Abstract Art"],contextualHelpText:"Create a distinctive name that collectors will find appealing"}:"description"===e?{fieldTypeOverride:"textarea",suggestions:["A beautiful piece representing..."]}:null,getGlobalGuidance:()=>({qualityStandards:["Use meaningful names that describe the artwork or content"]})};this.providerId=T.registerToolProvider(/hashinal/i,e,{id:"inscribe:hashinal:provider",priority:1})}catch(t){this.context.logger.warn("Could not register Inscribe field guidance provider")}this.context.logger.info("Inscribe Plugin initialized successfully")}catch(r){this.context.logger.error("Failed to initialize Inscribe plugin:",r)}else this.context.logger.warn("HederaKit not found in context. Inscription tools will not be available.")}initializeTools(){const e=this.context.config.hederaKit;if(!e)throw new Error("HederaKit not found in context config");const r=new t.InscriberBuilder(e);this.tools=[new t.InscribeFromUrlTool({hederaKit:e,inscriberBuilder:r,logger:this.context.logger}),new t.InscribeFromFileTool({hederaKit:e,inscriberBuilder:r,logger:this.context.logger}),new t.InscribeFromBufferTool({hederaKit:e,inscriberBuilder:r,logger:this.context.logger}),new t.InscribeHashinalTool({hederaKit:e,inscriberBuilder:r,logger:this.context.logger}),new t.RetrieveInscriptionTool({hederaKit:e,inscriberBuilder:r,logger:this.context.logger})]}getTools(){return this.tools}async cleanup(){if(this.tools=[],this.providerId){try{T.unregisterProvider(this.providerId)}catch{}this.providerId=null}this.context?.logger&&this.context.logger.info("Inscribe Plugin cleaned up")}}class b extends e.BaseServiceBuilder{constructor(e){super(e)}transferHbar(e,t=!0){this.clearNotes();const r=new n.TransferTransaction;if(!e.transfers||0===e.transfers.length)throw new Error("HbarTransferParams must include at least one transfer.");let o=new s(0),i=!1;if(t&&this.kit.userAccountId&&"provideBytes"===this.kit.operationalMode&&1===e.transfers.length){const t=e.transfers[0],o="string"==typeof t.amount||"number"==typeof t.amount?t.amount:t.amount.toString(),a=new s(o);if(a.isPositive()){const e="string"==typeof t.accountId?n.AccountId.fromString(t.accountId):t.accountId,o=a.toFixed(8,s.ROUND_DOWN),c=n.Hbar.fromString(o);this.logger.info(`[AccountBuilder.transferHbar] Configuring user-initiated scheduled transfer: ${c.toString()} from ${this.kit.userAccountId} to ${e.toString()}`),this.addNote(`Configured HBAR transfer from your account (${this.kit.userAccountId}) to ${e.toString()} for ${c.toString()}.`),r.addHbarTransfer(e,c),r.addHbarTransfer(n.AccountId.fromString(this.kit.userAccountId),c.negated()),i=!0}}if(!i){const t=[];for(const r of e.transfers){const e="string"==typeof r.accountId?n.AccountId.fromString(r.accountId):r.accountId,i="string"==typeof r.amount||"number"==typeof r.amount?r.amount:r.amount.toString(),a=new s(i),c=a.toFixed(8,s.ROUND_DOWN);this.logger.info(`Processing transfer: ${i} HBAR (rounded to ${c}) for account ${e.toString()}`);const l=n.Hbar.fromString(c);t.push({accountId:e,amount:a,hbar:l});const g=l.toTinybars();o=o.plus(g.toString())}if(!o.isZero()&&(this.logger.warn(`Transfer sum not zero: ${o.toString()} tinybars off. Adjusting last transfer.`),t.length>0)){const e=t[t.length-1],r=o.dividedBy(-1e8),i=e.amount.plus(r).toFixed(8,s.ROUND_DOWN);e.hbar=n.Hbar.fromString(i),this.logger.info(`Adjusted last transfer for ${e.accountId.toString()} to ${i} HBAR`)}for(const e of t)r.addHbarTransfer(e.accountId,e.hbar)}return void 0!==e.memo&&(null===e.memo?this.logger.warn("Received null for memo in transferHbar."):r.setTransactionMemo(e.memo)),this.setCurrentTransaction(r),this}}const C=o.z.object({accountId:o.z.string().describe('Account ID for the transfer (e.g., "0.0.xxxx").'),amount:o.z.union([o.z.number(),o.z.string()]).describe("HBAR amount in decimal format (e.g., 1 for 1 HBAR, 0.5 for 0.5 HBAR). Positive for credit, negative for debit. DO NOT multiply by 10^8 for tinybars - just use the HBAR amount directly.")}),k=o.z.object({transfers:o.z.array(C).min(1).describe('Array of transfers. For simple transfers from your operator account, just include the recipient with positive amount: [{accountId: "0.0.800", amount: 1}]. For complex multi-party transfers, include all parties with negative amounts for senders and positive for receivers.'),memo:o.z.string().optional().describe("Optional. Memo for the transaction.")});class v extends e.BaseHederaTransactionTool{constructor(){super(...arguments),this.name="hedera-account-transfer-hbar-v2",this.description='PRIMARY TOOL FOR HBAR TRANSFERS: Transfers HBAR between accounts. For simple transfers from the operator account, just specify the recipient with a positive amount (e.g., [{accountId: "0.0.800", amount: 1}] to send 1 HBAR to 0.0.800). The sender will be automatically added. For multi-party transfers (e.g., "A sends 5 HBAR to C and B sends 3 HBAR to C"), include ALL transfers with their amounts (negative for senders, positive for receivers).',this.specificInputSchema=k,this.namespace="account"}getServiceBuilder(){return new b(this.hederaKit)}async callBuilderMethod(e,t){await e.transferHbar(t)}}class I extends i.StructuredTool{constructor(e,t){super(),this.name="hedera-hts-airdrop-token",this.description="Airdrops fungible tokens to multiple recipients. Automatically converts human-readable amounts to smallest units based on token decimals.",this.schema=o.z.object({tokenId:o.z.string().describe('The ID of the fungible token to airdrop (e.g., "0.0.yyyy").'),recipients:o.z.array(o.z.object({accountId:o.z.string().describe('Recipient account ID (e.g., "0.0.xxxx").'),amount:o.z.union([o.z.number(),o.z.string()]).describe('Amount in human-readable format (e.g., "10" for 10 tokens).')})).min(1).describe("Array of recipient objects, each with accountId and amount."),memo:o.z.string().optional().describe("Optional. Memo for the transaction.")}),this.originalTool=e,this.agentKit=t,this.logger=new r.Logger({module:"AirdropToolWrapper"})}async _call(e){try{this.logger.info(`Processing airdrop request for token ${e.tokenId} with ${e.recipients.length} recipients`);const t=(await this.getTokenInfo(e.tokenId)).decimals||0;this.logger.info(`Token ${e.tokenId} has ${t} decimal places`);const r=e.recipients.map(e=>{const r="string"==typeof e.amount?parseFloat(e.amount):e.amount,o=this.convertToSmallestUnits(r,t);return this.logger.info(`Converting amount for ${e.accountId}: ${r} tokens → ${o} smallest units`),{...e,amount:o.toString()}}),o={...e,recipients:r};return this.logger.info("Calling original airdrop tool with converted amounts"),await this.originalTool._call(o)}catch(t){throw this.logger.error("Error in airdrop tool wrapper:",t),t}}convertToSmallestUnits(e,t){return Math.floor(e*Math.pow(10,t))}async getTokenInfo(e){try{return await this.queryTokenInfo(e)}catch(t){throw t}}async queryTokenInfo(e){try{this.logger.info("Querying token info using mirror node");const t=this.agentKit.mirrorNode;if(t){const r=await t.getTokenInfo(e);if(r&&void 0!==r.decimals){const t=parseInt(r.decimals.toString())||0;return this.logger.info(`Token ${e} found with ${t} decimals`),{...r,decimals:t}}}else{this.logger.info("MirrorNode not found in agentKit, attempting to access via fetch");const t="mainnet"===(this.agentKit.network||"testnet")?"https://mainnet.mirrornode.hedera.com":"https://testnet.mirrornode.hedera.com",r=await fetch(`${t}/api/v1/tokens/${e}`);if(r.ok){const t=await r.json(),o=parseInt(String(t.decimals||"0"));return this.logger.info(`Token ${e} found with ${o} decimals via API`),{...t,decimals:o}}}throw new Error("Token data not found or missing decimals field")}catch(t){return this.logger.warn(`Failed to query token info for ${e}:`,t),this.logger.info("Falling back to assumed 0 decimal places (smallest units)"),{decimals:0}}}}class x extends e.BasePlugin{constructor(){super(...arguments),this.id="hbar",this.name="HBAR Plugin",this.description="HBAR operations: transfer tool with robust decimal handling and compatibility with airdrop improvements",this.version="1.0.0",this.author="Hashgraph Online",this.namespace="account",this.tools=[],this.originalAirdropTool=null}async initialize(e){await super.initialize(e);if(e.config.hederaKit)try{this.initializeTools(),this.context.logger.info("HBAR Plugin initialized successfully")}catch(t){this.context.logger.error("Failed to initialize HBAR plugin:",t)}else this.context.logger.warn("HederaKit not found in context. HBAR tools will not be available.")}initializeTools(){const t=this.context.config.hederaKit;if(!t)throw new Error("HederaKit not found in context config");const r=new v({hederaKit:t,logger:this.context.logger});this.tools=[r];try{this.context.logger.info("Creating wrapper for passed original airdrop tool");const r=new e.HederaAirdropTokenTool({hederaKit:t,logger:this.context.logger}),o=new I(r,t);this.tools.push(o),this.context.logger.info("Added wrapped airdrop tool to HBAR Plugin")}catch(o){this.context.logger.error("Error creating airdrop tool wrapper:",o)}this.context.logger.info(`HBAR Plugin tools initialized with ${this.tools.length} tools`)}getTools(){return this.tools}async shutdown(){this.tools=[]}}class M{constructor(){this.patterns=new Map,this.initializeDefaultPatterns()}static getInstance(){return M.instance||(M.instance=new M),M.instance}initializeDefaultPatterns(){this.register("numeric-supply-exact",{pattern:["maxSupply","minSupply","totalSupply"],type:"number",priority:15}),this.register("numeric-supply",{pattern:/supply$/i,type:"number",priority:10}),this.register("numeric-amounts",{pattern:/(?:amount|quantity|count|total|sum|value)$/i,type:"number",priority:8}),this.register("numeric-time",{pattern:/(?:period|duration|time|timeout|delay|interval)$/i,type:"number",priority:8}),this.register("numeric-limits",{pattern:/(?:limit|max|min|threshold|size|length)$/i,type:"number",priority:7}),this.register("currency",{pattern:/(?:price|cost|fee|payment|balance|amount)$/i,type:"currency",priority:9}),this.register("percentage",{pattern:/(?:percent|percentage|rate|ratio)$/i,type:"percentage",priority:9}),this.register("boolean-freeze",{pattern:["freezeDefault","freeze"],type:"checkbox",priority:10}),this.register("boolean-flags",{pattern:/(?:is|has|can|should|enable|disable|active|default|allow)(?:[A-Z]|$)/,type:"checkbox",priority:8}),this.register("textarea",{pattern:/(?:memo|description|notes|comment|message|content|body|text)$/i,type:"textarea",priority:8}),this.register("array-fees",{pattern:["customFees","fees"],type:"array",priority:10}),this.register("array-general",{pattern:/(?:list|items|array|collection)$/i,type:"array",priority:7}),this.register("object-options",{pattern:["metaOptions","options"],type:"object",priority:10}),this.register("object-config",{pattern:/(?:config|settings|configuration|metadata|data|info)$/i,type:"object",priority:7}),this.register("select-type",{pattern:/(?:type|kind|category|status|state|mode)$/i,type:"select",priority:7})}register(e,t){this.patterns.set(e,t)}unregister(e){return this.patterns.delete(e)}detectType(e){const t=[];for(const r of this.patterns.values()){let o=!1;Array.isArray(r.pattern)?o=r.pattern.some(t=>e===t||e.toLowerCase()===t.toLowerCase()):r.pattern instanceof RegExp&&(o=r.pattern.test(e)),o&&t.push({type:r.type,priority:r.priority??5})}return t.length>0?(t.sort((e,t)=>t.priority-e.priority),t[0].type):null}getPatterns(){return new Map(this.patterns)}clear(){this.patterns.clear()}reset(){this.clear(),this.initializeDefaultPatterns()}}const R=M.getInstance(),A="Too many requests. Please wait a moment and try again.",F="I'm receiving too many requests right now. Please wait a moment and try again.";var E=(e=>(e.TOPIC_ID="topicId",e.HRL="hrl",e.SCHEDULE_ID="scheduleId",e.TOKEN_ID="tokenId",e.ADDRESS="address",e.SYMBOL="symbol",e.SERIAL_NUMBER="serialNumber",e.METADATA="metadata",e.ACCOUNT_ID="accountId",e.ALIAS="alias",e.EVM_ADDRESS="evmAddress",e.CONTRACT_ID="contractId",e.FILE_ID="fileId",e.ANY="any",e))(E||{});const P="the topic",O="the token";E.TOPIC_ID,E.TOKEN_ID,E.ACCOUNT_ID,E.CONTRACT_ID;const N={ESSENTIAL:"essential",COMMON:"common",ADVANCED:"advanced",EXPERT:"expert"};function L(e){return"object"==typeof e&&null!==e&&"shape"in e}class ${constructor(){this.logger=new r.Logger({module:"FormGenerator"})}generateFormFromError(e,t,r,o){const n=this.extractValidationErrors(e),s=this.identifyMissingFields(n,t),i=this.createFormConfig(t,s,r);return{type:"form",id:`form_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,formConfig:i,originalPrompt:o,toolName:r,validationErrors:n}}async generateFormFromSchema(e,t,r,o){let n;if(this.logger.info("🏁 FormGenerator.generateFormFromSchema starting",{toolName:r.toolName,partialInput:t,hasSchema:!!e,hasShape:!(!e||!L(e)),hasPreCalculatedFields:void 0!==o,preCalculatedFieldsSize:o?.size||0}),void 0!==o)n=o,this.logger.info("📋 Using pre-calculated missing fields",{missingFieldsCount:n.size,missingFields:Array.from(n)});else{n=new Set;const t=this.extractZodObject(e);if(t){const e=t.shape;for(const t of Object.keys(e))n.add(t),this.logger.info(`⭐ Including all fields from focused schema: ${t}`)}this.logger.info("📋 Using ALL fields from focused schema",{totalFields:t?Object.keys(t.shape).length:0,missingFieldsCount:n.size,missingFields:Array.from(n)})}const s=this.createFormConfig(e,n,r.toolName,o);return{type:"form",id:`form_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,formConfig:s,originalPrompt:r.toolDescription||`Complete ${r.toolName}`,toolName:r.toolName,validationErrors:[]}}extractValidationErrors(e){return e.issues.map(e=>({path:e.path.map(e=>String(e)),message:e.message,code:e.code}))}identifyMissingFields(e,t){const r=new Set;return e.forEach(e=>{const t=e.path.join(".");t&&r.add(t)}),r}createFormConfig(e,t,r,o){const n=this.extractRenderConfigsSafely(e),s=this.generateFieldOrderingSafely(e),i=this.generateFormFields(e,n,t,s,o,r),a=T.getGlobalGuidance(r);let c=this.generateFormDescription(r,t.size);return a?.qualityStandards&&(c+="\n\nQuality Guidelines:\n"+a.qualityStandards.map(e=>`• ${e}`).join("\n")),{title:this.generateFormTitle(r),description:c,fields:i,submitLabel:"Continue",cancelLabel:"Cancel",metadata:{toolName:r,missingFieldCount:t.size,globalGuidance:a}}}extractRenderConfigsSafely(e){try{if("function"==typeof t.extractRenderConfigs)return t.extractRenderConfigs(e)}catch(r){this.logger.warn("Could not extract render configs:",r)}return{fields:{},groups:{},order:[],metadata:{}}}generateFieldOrderingSafely(e){try{if("function"==typeof t.generateFieldOrdering){const r=t.generateFieldOrdering(e);return{sections:Object.values(r.sections).map(e=>({fields:e.fields}))}}}catch(r){this.logger.warn("Could not generate field ordering:",r)}return{sections:[]}}getFieldPriority(e,t,r){if(t?.ui?.priority){const e=t.ui.priority;if(Object.values(N).includes(e))return e}if(!0===r)return N.ESSENTIAL;const o=t?.ui;return!0===o?.advanced?N.ADVANCED:!0===o?.expert?N.EXPERT:N.COMMON}determineFieldsToInclude(e,t,r){const o=new Set;if(void 0===r){this.logger.info("⭐ Focused schema mode - including ALL fields from schema");this.extractFieldsFromSchema(e).forEach(e=>{o.add(e),this.logger.info(`✅ Including focused schema field: ${e}`)})}else r.size>0?(this.logger.info(`📋 Using ONLY pre-calculated missing fields (${r.size} fields)`,{fields:Array.from(r)}),r.forEach(e=>{o.add(e),this.logger.info(`✅ Including pre-calculated field: ${e}`)})):(this.logger.info("⚠️ No pre-calculated fields, falling back to schema analysis"),this.includeRequiredMissingFields(e,t,o));return o}includeRequiredMissingFields(e,t,r){this.extractFieldsFromSchema(e).forEach(o=>{const n=this.isFieldRequired(e,o),s=t.has(o),i=s&&n;this.logger.info(`🔍 FormGenerator field inclusion check: ${o}`,{isRequired:n,isMissing:s,shouldInclude:i}),i&&r.add(o)})}createOrderedFields(e,t,r,o,n){const s=[],i=new Set;if(t.sections.length>0){t.sections.flatMap(e=>e.fields).forEach(t=>{if(e.has(t)&&!i.has(t)){const e=this.createFormField(t,r.fields[t],o,t,n);e&&(s.push(e),i.add(t))}})}return e.forEach(e=>{if(!i.has(e)){const t=this.createFormField(e,r.fields[e],o,e,n);t&&s.push(t)}}),s}generateFormFields(e,t,r,o,n,s){const i=this.determineFieldsToInclude(e,r,n);let a=this.createOrderedFields(i,o,t,e,s);return 0===a.length&&r.size>0&&(a=Array.from(r).map(r=>this.createFormField(r,t.fields[r],e,r,s)).filter(e=>null!=e)),a}createFormField(e,t,r,o,n){const s=this.mapFieldType(t?.fieldType,r,o),i=this.isFieldRequired(r,o||e),a=n?T.getFieldGuidance(n,e):null,c=a?.fieldTypeOverride||s,l={name:e,label:t?.ui?.label||this.humanizeFieldName(e),type:c,required:i,priority:this.getFieldPriority(e,t,i)};if(a&&(a.suggestions&&a.suggestions.length>0&&(l.suggestions=a.suggestions,l.placeholder||(l.placeholder=`e.g., ${a.suggestions[0]}`)),a.predefinedOptions&&(l.options=[...l.options||[],...a.predefinedOptions]),a.contextualHelpText&&(l.helpText=a.contextualHelpText),a.warnings&&(l.warnings=a.warnings.map(e=>e.message)),a.validationRules)){const{qualityChecks:e}=a.validationRules;e&&(l.contextualGuidance={qualityStandards:[],examples:a.suggestions||[],avoidPatterns:e.forbidTechnicalTerms||[]},e.minNonTechnicalWords&&l.contextualGuidance.qualityStandards?.push(`Use at least ${e.minNonTechnicalWords} meaningful words`),e.forbidTechnicalTerms&&l.contextualGuidance.qualityStandards?.push(`Avoid technical terms like: ${e.forbidTechnicalTerms.join(", ")}`))}if(t&&(l.renderConfig=t),t?.ui?.placeholder&&(l.placeholder=t.ui.placeholder),t?.ui?.helpText&&(l.helpText=t.ui.helpText),t?.constraints){const e={};void 0!==t.constraints.min&&(e.min=t.constraints.min),void 0!==t.constraints.max&&(e.max=t.constraints.max),void 0!==t.constraints.minLength&&(e.minLength=t.constraints.minLength),void 0!==t.constraints.maxLength&&(e.maxLength=t.constraints.maxLength),void 0!==t.constraints.pattern&&(e.pattern=t.constraints.pattern),Object.keys(e).length>0&&(l.validation=e)}return t?.options&&(l.options=t.options.map(e=>({value:String(e.value),label:e.label,...void 0!==e.disabled&&{disabled:e.disabled}}))),l}mapFieldType(e,t,r){if(!e&&t&&r){const e=this.inferTypeFromSchema(t,r);if(e)return e}if(!e&&r){const e=R.detectType(r);if(e)return e}if(!e)return"text";const o=e.toLowerCase();return["text","string"].includes(o)?"text":["number","integer","float","decimal"].includes(o)?"number":["select","enum","dropdown"].includes(o)?"select":["checkbox","boolean","bool"].includes(o)?"checkbox":["textarea","longtext","multiline"].includes(o)?"textarea":["file","upload","attachment"].includes(o)?"file":["array","list"].includes(o)?"array":["object","json"].includes(o)?"object":["currency","money","price"].includes(o)?"currency":["percentage","percent"].includes(o)?"percentage":"text"}humanizeFieldName(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\./g," ").trim().split(" ").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}generateFormTitle(e){return`Complete ${e.replace(/Tool$/,"").replace(/Hedera/g,"").replace(/([A-Z])/g," $1").trim()} Information`}extractZodObject(e){try{const t=e._def;if(t&&"ZodObject"===t.typeName)return e}catch(t){this.logger.debug("Could not extract ZodObject from schema:",t)}return null}extractFieldsFromSchema(e){const t=[],r=this.extractZodObject(e);if(r)return t.push(...Object.keys(r.shape)),t;try{const r=e._def;if(r&&"ZodUnion"===r.typeName&&r.options){const e=r.options[0],o=this.extractZodObject(e);o&&t.push(...Object.keys(o.shape))}}catch(o){this.logger.debug("Could not extract fields from schema structure:",o)}return t}inferTypeFromSchema(e,t){try{const r=this.extractZodObject(e);if(!r)return null;const o=r.shape;if(!o)return null;let n=o[t];if(!n)return null;const s=n._def;if(s&&"ZodOptional"===s.typeName&&s.innerType&&(n=s.innerType),!n||!n._def)return null;const i=n._def.typeName,a=t.toLowerCase();switch(i){case"ZodString":return a.includes("memo")||a.includes("description")?"textarea":"text";case"ZodNumber":return a.includes("percent")?"percentage":a.includes("price")||a.includes("cost")?"currency":"number";case"ZodBoolean":return"checkbox";case"ZodEnum":case"ZodNativeEnum":return"select";case"ZodArray":return"array";case"ZodObject":return"object";default:return"text"}}catch(r){this.logger.debug("Could not infer type from schema:",r)}return null}isFieldRequired(e,t){if(!e||!t)return!1;try{const r=this.extractZodObject(e);if(!r)return!1;const o=r.shape;if(!o||!o[t])return!1;const n=o[t];if(!n||!n._def)return!0;const s=n._def,i=s.typeName;return"ZodOptional"!==i&&("ZodDefault"!==i&&void 0===s.defaultValue)}catch(r){this.logger.debug(`Could not determine if field ${t} is required:`,r)}return!1}generateFormDescription(e,t){return 0===t?"Please provide the required information to continue with your request.":`Please provide the following ${t} required field${1!==t?"s":""} to continue with your request.`}generateJsonSchemaForm(e,t,r){const o=c.zodToJsonSchema(e,{target:"jsonSchema7"}),n={};let s=o;if(r&&r.size>0){const e=o;if(e.properties&&"object"==typeof e.properties){const t={...e,type:"object",properties:{},required:[]};let o=0;r.forEach(r=>{e.properties&&e.properties[r]&&(t.properties[r]=e.properties[r],o++)}),Array.isArray(e.required)&&(t.required=e.required.filter(e=>r.has(e))),o>0&&(s=t)}}return this.extractFieldsFromSchema(e).forEach(t=>{const r=this.isFieldRequired(e,t),o=this.getFieldPriority(t,void 0,r),s=t.toLowerCase();switch("attributes"!==s&&"metadata"!==s&&"properties"!==s||(n[t]={"ui:options":{collapsible:!0,collapsed:!0}}),o){case"essential":r&&(n[t]={...n[t],"ui:help":"Required field"});break;case"advanced":case"expert":n[t]={...n[t],"ui:options":{...n[t]?.["ui:options"],collapsed:!0}}}}),{jsonSchema:s,uiSchema:n}}}class B{constructor(e){this.formGenerator=new $,this.logger=e||new r.Logger({module:"FormEngine"})}async generateForm(e,r,n,s){const i={tool:r,input:n,...s};try{return t.isFormValidatable(r)?await this.generateFormValidatableForm(r,n,i):n instanceof o.ZodError?await this.generateErrorBasedForm(r,n,i):this.hasRenderConfig(r)?await this.generateRenderConfigForm(r,n,i):this.isZodObject(r.schema)?await this.generateSchemaBasedForm(r,n,i):null}catch(a){throw this.logger.error(`Failed to generate form for tool: ${e}`,{error:a instanceof Error?a.message:String(a)}),a}}async processSubmission(e,t){this.validateSubmission(e);const r=this.extractBaseToolInput(t),o=this.extractSubmissionData(e);return this.mergeInputData(r,o)}shouldGenerateForm(e,r){const o=r;if(!0===o?.__fromForm||!1===o?.renderForm)return!1;if(t.isFormValidatable(e))try{return e.shouldGenerateForm(r)}catch(n){return this.logger.error(`Error calling shouldGenerateForm() on ${e.name}:`,n),!1}return!this.validateInput(e,r).isValid}async generateFormFromError(e,t,r,o){return this.formGenerator.generateFormFromError(e,r,t,o)}async generateFormValidatableForm(e,t,r){const{schemaToUse:o,isFocusedSchema:n}=this.resolveFormSchema(e),s=this.determineMissingFields(e,t,o,n);return this.generateFormWithSchema(e,t,o,s)}async generateSchemaBasedForm(e,t,r){const o=e.schema,n=await this.formGenerator.generateFormFromSchema(o,t,{toolName:e.name,toolDescription:e.description},r.missingFields);if(this.isZodObject(o))try{const{jsonSchema:e,uiSchema:s}=this.formGenerator.generateJsonSchemaForm(o,t,r.missingFields||new Set);n.jsonSchema=e,n.uiSchema=s}catch(s){this.logger.warn("Failed to generate JSON Schema for schema-based tool:",s)}return n.partialInput=t,n}async generateRenderConfigForm(e,t,r){const o=e.schema,n=this.extractRenderConfig(e),s=await this.formGenerator.generateFormFromSchema(o,t,{toolName:e.name,toolDescription:e.description},r.missingFields);return n&&(s.formConfig.metadata={...s.formConfig.metadata,renderConfig:n}),s.partialInput=t,s}async generateErrorBasedForm(e,t,r){return this.formGenerator.generateFormFromError(t,e.schema,e.name,r.input?String(r.input):"")}validateInput(e,t){try{return e.schema.parse(t),{isValid:!0}}catch(r){if(r instanceof o.ZodError){return{isValid:!1,errors:r.errors.map(e=>`${e.path.join(".")}: ${e.message}`)}}return{isValid:!1,errors:["Validation failed"]}}}isZodObject(e){if(!e||"object"!=typeof e)return!1;const t=e;return Boolean(t._def&&"ZodObject"===t._def.typeName)}hasRenderConfig(e){const t=e.schema;return!(!t||!t._renderConfig)}extractRenderConfig(e){const t=e.schema;return t?._renderConfig}resolveFormSchema(e){const t=e;if(t.getFormSchema){const e=t.getFormSchema();if(e)return{schemaToUse:e,isFocusedSchema:!0}}return{schemaToUse:e.schema,isFocusedSchema:!1}}determineMissingFields(e,t,r,o){const n=new Set;if(!t||"object"!=typeof t)return n;const s=t,i=e;if(i.getEssentialFields){const e=i.getEssentialFields();for(const t of e)(!(t in s)||i.isFieldEmpty&&i.isFieldEmpty(t,s[t]))&&n.add(t)}return n}async generateFormWithSchema(e,t,r,o){const n=await this.formGenerator.generateFormFromSchema(r,t,{toolName:e.name,toolDescription:e.description},o);if(this.isZodObject(r))try{const{jsonSchema:e,uiSchema:s}=this.formGenerator.generateJsonSchemaForm(r,t,o);n.jsonSchema=e,n.uiSchema=s}catch(s){this.logger.warn("Failed to generate JSON Schema:",s)}return n.partialInput=t,n}validateSubmission(e){if(!e.toolName)throw new Error("Tool name is required in form submission");if(!e.parameters)throw new Error("Parameters are required in form submission")}extractBaseToolInput(e){return e?.originalInput||{}}extractSubmissionData(e){return{...e.parameters,__fromForm:!0}}mergeInputData(e,t){return{...e,...t}}getRegisteredStrategies(){return["FormValidatable","SchemaBased","RenderConfig","ZodErrorBased"]}getRegisteredMiddleware(){return["FormSubmissionValidator"]}}class D{static isHashLinkResponse(e){if(!e||"object"!=typeof e)return!1;const t=e;return!(!0!==t.success||"inscription"!==t.type||!t.hashLinkBlock||"object"!=typeof t.hashLinkBlock)}static formatHashLinkResponse(e){const t=e.hashLinkBlock,r=e.metadata||{},o=e.inscription||{};let n="✅ Interactive content created successfully!\n\n";return r.name&&(n+=`**${r.name}**\n`),r.description&&(n+=`${r.description}\n\n`),(o.topicId||t.attributes.topicId)&&(n+=`📍 **Topic ID:** ${o.topicId||t.attributes.topicId}\n`),(o.hrl||t.attributes.hrl)&&(n+=`🔗 **HRL:** ${o.hrl||t.attributes.hrl}\n`),o.cdnUrl&&(n+=`🌐 **CDN URL:** ${o.cdnUrl}\n`),r.creator&&(n+=`👤 **Creator:** ${r.creator}\n`),n+="\n⚡ Interactive content will load below",n.trim()}static isInscriptionResponse(e){if(!e||"object"!=typeof e)return!1;const t=e;return!(!0!==t.success||"inscription"!==t.type||!t.inscription||"object"!=typeof t.inscription)}static formatInscriptionResponse(e){const t=e.inscription,r=e.metadata||{};let o=`✅ ${e.title||"Inscription Complete"}\n\n`;return r.name&&(o+=`**${r.name}**\n`),r.description&&(o+=`${r.description}\n\n`),t.topicId&&(o+=`📍 **Topic ID:** ${t.topicId}\n`),t.hrl&&(o+=`🔗 **HRL:** ${t.hrl}\n`),t.cdnUrl&&(o+=`🌐 **CDN URL:** ${t.cdnUrl}\n`),r.creator&&(o+=`👤 **Creator:** ${r.creator}\n`),o.trim()}static formatResponse(e){try{const t=JSON.parse(e);return D.isHashLinkResponse(t)?D.formatHashLinkResponse(t):D.isInscriptionResponse(t)?D.formatInscriptionResponse(t):e}catch{return e}}}const _=new Map;class z extends a.AgentExecutor{constructor(...e){super(...e),this.pendingForms=new Map,this.formGenerator=new $,this.formEngine=new B(new r.Logger({module:"FormAwareAgentExecutor.FormEngine"})),this.formLogger=new r.Logger({module:"FormAwareAgentExecutor"}),this.parameterPreprocessingCallback=void 0}isZodObject(e){return e instanceof o.z.ZodObject}hasHashLinkBlock(e){return"object"==typeof e&&null!==e&&"hashLinkBlock"in e&&"object"==typeof e.hashLinkBlock&&null!==e.hashLinkBlock}setParameterPreprocessingCallback(e){this.parameterPreprocessingCallback=e}async _takeNextStep(e,r,o,n,s){this.formLogger.info("🛡️ BULLETPROOF INTERCEPTION: _takeNextStep called",{availableTools:Object.keys(e),inputKeys:Object.keys(r)});const i=await this.agent.plan(o,r,n?.getChild());if("returnValues"in i)return this.formLogger.info("Agent returned finish action, passing through"),i;const a=i,c=a.tool,l=a.toolInput;this.formLogger.info(`🎯 INTERCEPTING TOOL CALL: ${c}`,{toolInput:l,hasInNameToolMap:c in e,toolInputKeys:Object.keys(l||{})});const g=e[c]||this.tools.find(e=>e.name===c);if(!g)throw this.formLogger.error(`Tool ${c} not found in registry`),new Error(`Tool "${c}" not found`);let h=!1;if(t.isFormValidatable(g)){this.formLogger.info(`🔍 Tool ${c} implements FormValidatable, checking shouldGenerateForm()`,{toolInput:l});try{h=g.shouldGenerateForm(l),this.formLogger.info(`FormValidatable.shouldGenerateForm() result: ${h}`,{toolName:c,toolInput:l})}catch(u){this.formLogger.error(`Error calling shouldGenerateForm() on ${c}:`,u),h=!1}}if(h){this.formLogger.info(`🚨 FORM GENERATION TRIGGERED for ${c}`);try{let e,o=!1;if(t.isFormValidatable(g)){this.formLogger.info(`🎯 Tool ${c} is FormValidatable, attempting to get focused schema`);try{const t=g.getFormSchema();t?(e=t,o=!0,this.formLogger.info(`✅ Successfully obtained focused schema for ${c}`)):(this.formLogger.warn(`getFormSchema() returned null/undefined for ${c}, using default schema`),e=g.schema,o=!1)}catch(u){this.formLogger.error(`Failed to get focused schema from ${c}:`,u),this.formLogger.info(`Falling back to default schema for ${c}`),e=g.schema,o=!1}}else this.formLogger.info(`Tool ${c} is not FormValidatable, using default schema`),e=g.schema,o=!1;let n,s="unknown";try{if(this.isZodObject(e)){const t=e.shape;t&&"object"==typeof t&&(s=Object.keys(t).length.toString())}}catch{}if(this.formLogger.info(`📋 Generating form with ${o?"FOCUSED":"DEFAULT"} schema`,{toolName:c,schemaType:e?.constructor?.name,estimatedFieldCount:s,isFocusedSchema:o}),o)this.formLogger.info("⭐ Using focused schema - letting FormGenerator determine fields from schema"),n=void 0;else{if(n=new Set,this.isZodObject(e)){const r=e.shape||{};for(const o of Object.keys(r)){const r=(l||{})[o],s=t.isFormValidatable(g)&&g.isFieldEmpty?g.isFieldEmpty(o,r):void 0===r||""===r||null===r||Array.isArray(r)&&0===r.length,i=this.isFieldRequired(e,o),a=!(!t.isFormValidatable(g)||!g.getEssentialFields)&&g.getEssentialFields().includes(o);this.formLogger.info(`🔍 Field analysis: ${o}`,{value:r,isEmpty:s,isRequired:i,isEssential:a,willAddToMissingFields:s&&(i||a)}),s&&(i||a)&&n.add(o)}}this.formLogger.info("📋 Missing fields analysis complete",{totalFields:this.isZodObject(e)?Object.keys(e.shape).length:0,missingFieldsCount:n.size,missingFields:Array.from(n)})}const i=await this.formGenerator.generateFormFromSchema(e,l,{toolName:c,toolDescription:g.description},n);if(this.isZodObject(e))try{const{jsonSchema:t,uiSchema:r}=this.formGenerator.generateJsonSchemaForm(e,l,n);i.jsonSchema=t,i.uiSchema=r}catch(u){this.formLogger.warn("Failed to generate JSON Schema for RJSF:",u)}i.partialInput=l;const h={toolName:c,originalInput:r,originalToolInput:l,schema:e,toolRef:g,originalToolRef:g.originalTool};this.pendingForms.set(i.id,h),_.set(i.id,h),this.formLogger.info(`✅ FORM INTERCEPT SUCCESS for ${c}`);const m={requiresForm:!0,formMessage:i};return[{action:a,observation:JSON.stringify(m)}]}catch(u){this.formLogger.error(`Form generation failed for ${c}:`,u)}}if(this.formLogger.info(`⚪ Passing through to normal tool execution for ${c}`),this.parameterPreprocessingCallback&&l){this.formLogger.info(`🔄 Applying parameter preprocessing for ${c}`);try{const e=await this.parameterPreprocessingCallback(c,l);if(e&&"object"==typeof e&&"__requestForm"in e){const o=e.__requestForm,n=o.id||`form_${Date.now()}_${Math.random().toString(36).slice(2)}`,s={type:"form",id:n,originalPrompt:"Parameter validation required",toolName:c,formConfig:{title:o.title||"Complete required parameters",description:o.description||"One or more parameters require confirmation. Please review and submit.",submitLabel:o.submitLabel||"Continue",fields:(o.fields||[]).map(e=>{const t=["text","number","select","checkbox","textarea"].includes(e.type)?e.type:"text";return{name:e.name,label:e.label,type:t,required:e.required??!0,options:e.options}})}},i=t.isFormValidatable(g)?(()=>{try{return g.getFormSchema()||g.schema}catch{return g.schema}})():g.schema;return this.pendingForms.set(n,{toolName:c,originalInput:r,originalToolInput:l,schema:i,toolRef:g,originalToolRef:g.originalTool}),_.set(n,{toolName:c,originalInput:r,originalToolInput:l,schema:i}),[{action:a,observation:JSON.stringify({requiresForm:!0,formMessage:s})}]}if(JSON.stringify(e)!==JSON.stringify(l)){this.formLogger.info(`📝 Parameters preprocessed for ${c}:`,{original:Object.keys(l),preprocessed:Object.keys(e),hasChanges:!0});try{a.toolInput=e}catch{}}else this.formLogger.debug(`No parameter changes needed for ${c}`)}catch(m){this.formLogger.warn(`Parameter preprocessing failed for ${c}, using original parameters:`,m)}}return super._takeNextStep(e,r,o,n,s)}isFieldRequired(e,t){if(!e||!t)return!1;try{const r=e._def;if(!r||"ZodObject"!==r.typeName)return!1;const o="function"==typeof r.shape?r.shape():r.shape;if(!o||"object"!=typeof o)return!1;const n=o[t];if(!n)return!1;const s=(e=>{const t=e._def;return t&&"ZodOptional"===t.typeName&&t.innerType?t.innerType:e})(n)._def;return!s||"ZodOptional"!==s.typeName&&"ZodDefault"!==s.typeName&&void 0===s.defaultValue}catch(r){this.formLogger.debug(`Could not determine if field ${t} is required:`,r)}return!1}async _call(e){try{const t=await super._call(e);if(t.intermediateSteps&&Array.isArray(t.intermediateSteps))for(const r of t.intermediateSteps)if(r.observation)try{const o="string"==typeof r.observation?JSON.parse(r.observation):r.observation;if(o.requiresForm&&o.formMessage){this.formLogger.info("Tool requested form generation",{toolName:r.action?.tool,hasForm:!0});const n=r.action?.tool||"unknown",s=this.tools.find(e=>e.name===n),i=s||{},a={toolName:n,originalInput:e,originalToolInput:r.action?.toolInput,schema:null,toolRef:s,originalToolRef:i?.originalTool};return this.pendingForms.set(o.formMessage.id,a),_.set(o.formMessage.id,a),{...t,requiresForm:!0,formMessage:o.formMessage,output:o.message||"Please complete the form to continue."}}if(o.hashLinkBlock||o.success&&o.inscription&&o.hashLinkBlock){this.formLogger.info("Tool returned HashLink blocks",{toolName:r.action?.tool,hasHashLink:!0,blockId:o.hashLinkBlock?.blockId});const e=this.processHashLinkResponse(o);return{...t,hasHashLinkBlocks:!0,hashLinkBlock:e.hashLinkBlock,output:e.message}}}catch{}return t}catch(t){if(t instanceof o.ZodError)return this.formLogger.info("Intercepted ZodError during agent execution"),this.handleValidationError(t,e,[]);throw t}}async handleValidationError(e,t,r){this.formLogger.info("Zod validation error detected, generating form",{errorIssues:e.issues.length,inputKeys:Object.keys(t)});let o=this.extractToolInfoFromError(e,t,r);if(!o){this.formLogger.warn("Could not extract tool info from validation error, trying fallback detection");const t=this.detectToolFromErrorContext(e);if(!t)throw this.formLogger.error("No tool detected for form generation, rethrowing error"),e;o=t}this.formLogger.info("Generating form for tool:",{toolName:o.toolName,hasSchema:!!o.schema});const n=this.formGenerator.generateFormFromError(e,o.schema,o.toolName,t.input||"");return this.pendingForms.set(n.id,{toolName:o.toolName,originalInput:t,schema:o.schema}),_.set(n.id,{toolName:o.toolName,originalInput:t,schema:o.schema}),{output:this.formatFormResponse(n),formMessage:n,requiresForm:!0,intermediateSteps:r||[]}}getPendingForms(){return new Map(this.pendingForms)}restorePendingForms(e){for(const[t,r]of e)this.pendingForms.set(t,r)}async processFormSubmission(e){if(this.formLogger.info("🚀 FormAwareAgentExecutor.processFormSubmission called!",{submissionFormId:e.formId,submissionToolName:e.toolName}),!e)throw new Error("Form submission is null or undefined");if(!e.formId)throw new Error("Form submission missing formId");if(!e.parameters||null===e.parameters||"object"!=typeof e.parameters||Array.isArray(e.parameters))throw new Error(`Form submission parameters are invalid: ${typeof e.parameters}, isNull: ${null===e.parameters}, isArray: ${Array.isArray(e.parameters)}, parameters: ${JSON.stringify(e.parameters)}`);this.formLogger.info("Processing form submission:",{formId:e.formId,toolName:e.toolName,parameterKeys:Object.keys(e.parameters),parametersType:typeof e.parameters,parametersIsNull:null===e.parameters,parametersIsUndefined:void 0===e.parameters,hasContext:!!e.context});let t=this.pendingForms.get(e.formId);if(!t&&(t=_.get(e.formId),!t))throw new Error(`No pending form found for ID: ${e.formId}`);this.pendingForms.delete(e.formId),_.delete(e.formId);const r=t.toolRef||this.tools.find(e=>e.name===t.toolName);if(!r)throw new Error(`Tool not found for form submission: ${t.toolName}`);let n={};try{t.originalToolInput&&"object"==typeof t.originalToolInput&&(n={...t.originalToolInput})}catch(a){this.formLogger.warn("Failed to extract base tool input, using empty object:",a),n={}}let s={};try{e.parameters&&"object"==typeof e.parameters&&(s={...e.parameters})}catch(a){this.formLogger.warn("Failed to extract submission parameters, using empty object:",a),s={}}const i={};try{Object.keys(n).forEach(e=>{const t=n[e];null!=t&&(i[e]=t)}),Object.keys(s).forEach(e=>{const t=s[e];null!=t&&(i[e]=t)}),i.renderForm=!1,i.__fromForm=!0,this.formLogger.info("Successfully merged tool input:",{baseKeys:Object.keys(n),submissionKeys:Object.keys(s),mergedKeys:Object.keys(i)})}catch(a){throw this.formLogger.error("Failed to merge tool input data:",a),new Error(`Failed to merge tool input data: ${a instanceof Error?a.message:"Unknown error"}`)}try{const o=r;let n;if("function"==typeof o.executeOriginal)n=await o.executeOriginal(i);else if("function"==typeof o.getOriginalTool){const e=o.getOriginalTool(),t=e;if(e&&"function"==typeof t._call)n=await t._call(i);else if(e&&"function"==typeof t.call)n=await t.call(i);else{const e=r;if("function"!=typeof e.call)throw new Error("No callable tool implementation found for form submission");n=await e.call(i)}}else if(o.originalTool&&"function"==typeof o.originalTool._call)n=await o.originalTool._call(i);else if(o.originalTool&&"function"==typeof o.originalTool.call)n=await o.originalTool.call(i);else{if("function"!=typeof r.call)throw new Error("No callable tool implementation found for form submission");n=await r.call(i)}let s,c={};try{const e=JSON.parse(n);if(this.formLogger.info("✅ METADATA EXTRACTION: Successfully parsed JSON",{jsonKeys:Object.keys(e),hasHashLinkBlock:!!e.hashLinkBlock}),e&&"object"==typeof e)if(D.isHashLinkResponse(e)){this.formLogger.info("🔗 HASHLINK DETECTED: Processing HashLink response separately to preserve metadata");const t=e;c={...c,hashLinkBlock:t.hashLinkBlock,...t},s=D.formatHashLinkResponse(e),this.formLogger.info("🔗 METADATA PRESERVED: HashLink metadata extracted for component rendering",{blockId:this.hasHashLinkBlock(c)?c.hashLinkBlock.blockId:void 0,hasTemplate:!!this.hasHashLinkBlock(c)&&!!c.hashLinkBlock.template})}else s=D.formatResponse(n),c={...c,hashLinkBlock:e.hashLinkBlock,...e};else s=D.formatResponse(n)}catch(a){this.formLogger.warn("❌ METADATA EXTRACTION: Tool output is not JSON",{error:a instanceof Error?a.message:"unknown error",outputSample:"string"==typeof n?n.substring(0,200):"not-string"}),s=D.formatResponse(n)}return{output:s,formCompleted:!0,originalFormId:e.formId,intermediateSteps:[],metadata:c,rawToolOutput:n,toolName:t.toolName}}catch(a){if(a instanceof o.ZodError)return this.handleValidationError(a,i,[]);throw a}}extractToolInfoFromError(e,t,r){try{if(r.length>0){const e=r[r.length-1];if(e.action&&e.action.tool){const t=this.tools.find(t=>t.name===e.action.tool);if(t&&"schema"in t)return this.formLogger.info("Found tool from intermediate steps:",e.action.tool),{toolName:e.action.tool,schema:t.schema}}}const e=t.intermediateSteps||[];if(e.length>0){const t=e[e.length-1];let r;if(r=Array.isArray(t)&&t.length>0?t[0]:t.action?t.action:t,r&&r.tool){const e=this.tools.find(e=>e.name===r.tool);if(e&&"schema"in e)return this.formLogger.info("Found tool from input steps:",r.tool),{toolName:r.tool,schema:e.schema}}}const o=this.findToolFromContext(t);return o?(this.formLogger.info("Found tool from context:",o.toolName),o):null}catch(o){return this.formLogger.error("Error extracting tool info:",o),null}}findToolFromContext(e){const t=e.input||"";for(const r of this.tools){if(this.extractToolKeywords(r.name).some(e=>t.toLowerCase().includes(e.toLowerCase()))&&"schema"in r)return{toolName:r.name,schema:r.schema}}return null}detectToolFromErrorContext(e){const t=e.issues.map(e=>e.path.join("."));for(const r of this.tools)if("schema"in r){const e=r.schema;if(this.schemaMatchesErrorPaths(e,t))return this.formLogger.info("Detected tool from error path analysis:",r.name),{toolName:r.name,schema:e}}return null}schemaMatchesErrorPaths(e,t){const r=e;if(!r||!r._def)return!1;try{const e=r._def;if("ZodObject"===e.typeName){const r=e.shape,o=Object.keys(r||{});return t.some(e=>{const t=e.split(".")[0];return o.includes(t)})}}catch(o){this.formLogger.debug("Error analyzing schema structure:",o)}return!1}extractToolKeywords(e){return[...e.replace(/([A-Z])/g," $1").toLowerCase().split(/[\s_-]+/).filter(e=>e.length>2),e.toLowerCase()]}formatFormResponse(e){const t=e.formConfig.fields.length,r=e.formConfig.fields.slice(0,3).map(e=>`• ${e.label}`).join("\n");return`I need some additional information to complete your request.\n\n${e.formConfig.description}\n\nRequired fields:\n${r}${t>3?`\n... and ${t-3} more`:""}\n\nPlease fill out the form below to continue.`}hasPendingForms(){return this.pendingForms.size>0}getPendingFormsInfo(){return Array.from(this.pendingForms.entries()).map(([e,t])=>({formId:e,toolName:t.toolName}))}processHashLinkResponse(e){try{let t;if((e.hashLinkBlock||e.success&&e.hashLinkBlock)&&(t=e.hashLinkBlock),!t)throw new Error("HashLink block data not found in response");if(!t.blockId||!t.hashLink||!t.attributes)throw new Error("Invalid HashLink block structure - missing required fields");let r="Content processed successfully!";if(e.success&&e.inscription){const t=e.inscription,o=e.metadata||{};r=`✅ ${t.standard} Hashinal inscription completed!\n\n`,o.name&&(r+=`**${o.name}**\n`),o.description&&(r+=`${o.description}\n\n`),r+=`📍 **Topic ID:** ${t.topicId}\n`,r+=`🔗 **HRL:** ${t.hrl}\n`,t.cdnUrl&&(r+=`🌐 **CDN URL:** ${t.cdnUrl}\n`),o.creator&&(r+=`👤 **Creator:** ${o.creator}\n`)}return this.formLogger.info("Processed HashLink response",{blockId:t.blockId,hashLink:t.hashLink,hasTemplate:!!t.template,attributeCount:Object.keys(t.attributes||{}).length}),{hasHashLinkBlocks:!0,hashLinkBlock:t,message:r}}catch(t){return this.formLogger.error("Error processing HashLink response:",t),{hasHashLinkBlocks:!1,message:"Content processed, but interactive display is not available."}}}getFormEngineStatistics(){return{strategies:this.formEngine.getRegisteredStrategies(),middleware:this.formEngine.getRegisteredMiddleware()}}}class H{constructor(e){this.config=e,this.tools=[],this.initialized=!1,this.logger=new r.Logger({module:"BaseAgent",silent:e.debug?.silent||!1})}getCore(){return this.agentKit}filterTools(e){let t=[...e];const r=this.config.filtering;return r?(r.namespaceWhitelist?.length&&(t=t.filter(e=>{const t=e.namespace;return!t||r.namespaceWhitelist.includes(t)})),r.toolBlacklist?.length&&(t=t.filter(e=>!r.toolBlacklist.includes(e.name))),r.toolPredicate&&(t=t.filter(r.toolPredicate)),this.logger.debug(`Filtered tools: ${e.length} → ${t.length}`),t):t}buildSystemPrompt(){const e=[],t=this.config.signer.getAccountId().toString(),r=this.config.execution?.userAccountId;this.config.messaging?.systemPreamble&&e.push(this.config.messaging.systemPreamble),e.push(`You are a helpful Hedera assistant. Your primary operator account is ${t}. You have tools to interact with the Hedera Hashgraph. When using any tool, provide all necessary parameters as defined by that tool's schema and description.`),e.push("\nMETADATA QUALITY PRINCIPLES: When collecting user input for metadata creation across any tool:\n• Prioritize meaningful, valuable content over technical file information\n• Focus on attributes that add value for end users and collectors\n• Avoid auto-generating meaningless technical attributes as user-facing metadata\n• When fields are missing or inadequate, use forms to collect quality metadata\n• Encourage descriptive names, collectible traits, and storytelling elements"),r&&e.push(`The user you are assisting has a personal Hedera account ID: ${r}. IMPORTANT: When the user says things like "I want to send HBAR" or "transfer my tokens", you MUST use ${r} as the sender/from account. For example, if user says "I want to send 2 HBAR to 0.0.800", you must set up a transfer where ${r} sends the HBAR, not your operator account.`);return"autonomous"===(this.config.execution?.operationalMode||"returnBytes")?e.push(`\nOPERATIONAL MODE: 'autonomous'. Your goal is to execute transactions directly using your tools. Your account ${t} will be the payer for these transactions. Even if the user's account (${r||"a specified account"}) is the actor in the transaction body (e.g., sender of HBAR), you (the agent with operator ${t}) 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.`):this.config.execution?.scheduleUserTransactionsInBytesMode&&r?e.push(`\nOPERATIONAL MODE: 'returnBytes' with scheduled transactions for user actions. When a user asks for a transaction to be prepared (e.g., creating a token, topic, transferring assets for them to sign, etc), you MUST default to creating a Scheduled Transaction using the appropriate tool with the metaOption 'schedule: true'. The user (with account ID ${r}) will be the one to ultimately pay for and (if needed) sign the inner transaction. Your operator account (${t}) will pay for creating the schedule entity itself. 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.`):e.push(`\nOPERATIONAL MODE: 'returnBytes'. Your goal is to provide transaction bytes when possible. When a user asks for a transaction to be prepared (e.g., for them to sign, or for scheduling without the default scheduling flow), you MUST call the appropriate tool. IMPORTANT: Only use metaOption 'returnBytes: true' for tools that explicitly support it (like HBAR transfers, token operations). Many tools (inscriptions, HCS-2, HCS-20, etc.) do NOT support returnBytes and will execute directly - this is expected behavior. For tools without returnBytes support, simply call them with their standard parameters. If you need raw bytes for the user to sign for their own account ${r||"if specified"}, ensure the tool constructs the transaction body accordingly when returnBytes IS supported.`),!1!==this.config.messaging?.conciseMode&&e.push("\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."),this.config.messaging?.systemPostamble&&e.push(this.config.messaging.systemPostamble),e.join("\n")}isReady(){return this.initialized}}class j{constructor(e,t){this.contentStorage=e,this.logger=t}analyzeResponse(e){const t=[];let r=0;this.extractContentFromResponse(e,t),r=t.reduce((e,t)=>e+t.sizeBytes,0);const o=t.reduce((e,t)=>Math.max(e,t.sizeBytes),0);return{shouldProcess:t.some(e=>this.contentStorage.shouldUseReference("string"==typeof e.content?e.content:JSON.stringify(e.content))),contents:t,totalSize:r,largestContentSize:o}}async processResponse(e,t,r){try{const o=this.analyzeResponse(e);if(!o.shouldProcess)return{content:e,wasProcessed:!1};return await this.createReferencedResponse(e,o,t,r)}catch(o){return this.logger.error("Error processing MCP response:",o),{content:e,wasProcessed:!1,errors:[o instanceof Error?o.message:"Unknown processing error"]}}}extractContentFromResponse(e,t){if(null!=e)if(Array.isArray(e))e.forEach(e=>this.extractContentFromResponse(e,t));else{if("object"==typeof e){const r=e;if("text"===r.type&&"string"==typeof r.text)return void t.push({content:r.text,type:"text",sizeBytes:globalThis.Buffer.byteLength(r.text,"utf8"),mimeType:this.detectMimeType(r.text)});if("image"===r.type&&"string"==typeof r.data)return void t.push({content:r.data,type:"image",sizeBytes:Math.ceil(.75*r.data.length),mimeType:r.mimeType||"image/jpeg"});if("resource"===r.type&&r.resource){const e=JSON.stringify(r.resource);return void t.push({content:e,type:"resource",sizeBytes:globalThis.Buffer.byteLength(e,"utf8"),mimeType:"application/json"})}return void Object.values(r).forEach(e=>this.extractContentFromResponse(e,t))}"string"==typeof e&&e.length>1e3&&t.push({content:e,type:"text",sizeBytes:globalThis.Buffer.byteLength(e,"utf8"),mimeType:this.detectMimeType(e)})}}async createReferencedResponse(e,t,r,o){const n=this.deepClone(e),s=[];let i=!1,a=0;for(const g of t.contents)if(this.contentStorage.shouldUseReference("string"==typeof g.content?g.content:JSON.stringify(g.content)))try{const e=globalThis.Buffer.from("string"==typeof g.content?g.content:JSON.stringify(g.content),"utf8"),t={contentType:this.mapMimeTypeToContentType(g.mimeType),source:"mcp_tool",mcpToolName:`${r}::${o}`,tags:["mcp_response",r,o]};void 0!==g.mimeType&&(t.mimeType=g.mimeType);const s=await this.contentStorage.storeContentIfLarge(e,t);s&&(this.replaceContentInResponse(n,g.content,this.createLightweightReference(s)),i=!0,a+=e.length)}catch(l){s.push(`Failed to create reference: ${l instanceof Error?l.message:"Unknown error"}`)}const c={content:n,wasProcessed:!0,referenceCreated:i,originalSize:a};return s.length>0&&(c.errors=s),c}createLightweightReference(e){return{type:"content_reference",referenceId:e.referenceId,preview:e.preview,size:e.metadata.sizeBytes,contentType:e.metadata.contentType,format:"ref://{id}",_isReference:!0}}replaceContentInResponse(e,t,r){if(null!=e)if(Array.isArray(e))for(let o=0;o<e.length;o++)e[o]===t?e[o]=r:this.replaceContentInResponse(e[o],t,r);else if("object"==typeof e){const o=e;if("text"===o.type&&o.text===t){for(const e of Object.keys(o))delete o[e];if("object"==typeof r&&null!==r){const e=r;for(const t of Object.keys(e))o[t]=e[t]}return}for(const e in o)o[e]===t?o[e]=r:this.replaceContentInResponse(o[e],t,r)}}detectMimeType(e){return e.trim().startsWith("{")||e.trim().startsWith("[")?"application/json":e.includes("<html>")||e.includes("<!DOCTYPE")?"text/html":e.includes("# ")||e.includes("## ")?"text/markdown":"text/plain"}mapMimeTypeToContentType(e){return e?e.startsWith("text/plain")?"text":"application/json"===e?"json":"text/html"===e?"html":"text/markdown"===e?"markdown":e.startsWith("text/")?"text":"binary":"text"}deepClone(e){if(null===e||"object"!=typeof e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e))return e.map(e=>this.deepClone(e));const t={};for(const r in e)e.hasOwnProperty(r)&&(t[r]=this.deepClone(e[r]));return t}}class U{constructor(e,t){this.clients=new Map,this.tools=new Map,this.logger=e,t&&(this.contentProcessor=new j(t,e))}async connectServer(e){try{if(this.isServerConnected(e.name))return{serverName:e.name,connected:!1,error:`Server ${e.name} is already connected`,tools:[]};if(e.transport&&"stdio"!==e.transport)throw new Error(`Transport ${e.transport} not yet supported`);const t=new u.StdioClientTransport({command:e.command,args:e.args,...e.env&&{env:e.env}}),r=new h.Client({name:`conversational-agent-${e.name}`,version:"1.0.0"},{capabilities:{}});await r.connect(t),this.clients.set(e.name,r);const o=(await r.listTools()).tools.map(t=>{const r=t,{description:o,...n}=r;return{...void 0!==o&&"string"==typeof o?{...n,description:o}:{...n},serverName:e.name}});return this.tools.set(e.name,o),this.logger.info(`Connected to MCP server ${e.name} with ${o.length} tools`),{serverName:e.name,connected:!0,tools:o}}catch(t){return this.logger.error(`Failed to connect to MCP server ${e.name}:`,t),{serverName:e.name,connected:!1,error:t instanceof Error?t.message:"Unknown error",tools:[]}}}async executeTool(e,t,r){const o=this.clients.get(e);if(!o)throw new Error(`MCP server ${e} not connected`);this.logger.debug(`Executing MCP tool ${t} on server ${e}`,r);try{const n=await o.callTool({name:t,arguments:r});if(this.contentProcessor){const r=await this.contentProcessor.processResponse(n,e,t);return r.wasProcessed&&(this.logger.debug(`Processed MCP response from ${e}::${t}`,{referenceCreated:r.referenceCreated,originalSize:r.originalSize,errors:r.errors}),r.errors&&r.errors.length>0&&this.logger.warn(`Content processing warnings for ${e}::${t}:`,r.errors)),r.content}return n}catch(n){throw this.logger.error(`Error executing MCP tool ${t}:`,n),n}}async disconnectAll(){for(const[t,r]of this.clients)try{await r.close(),this.logger.info(`Disconnected from MCP server ${t}`)}catch(e){this.logger.error(`Error disconnecting MCP server ${t}:`,e)}this.clients.clear(),this.tools.clear()}getAllTools(){const e=[];for(const t of this.tools.values())e.push(...t);return e}getServerTools(e){return this.tools.get(e)||[]}isServerConnected(e){return this.clients.has(e)}getConnectedServers(){return Array.from(this.clients.keys())}enableContentProcessing(e){this.contentProcessor=new j(e,this.logger),this.logger.info("Content processing enabled for MCP responses")}disableContentProcessing(){delete this.contentProcessor,this.logger.info("Content processing disabled for MCP responses")}isContentProcessingEnabled(){return void 0!==this.contentProcessor}analyzeResponseContent(e){if(!this.contentProcessor)throw new Error("Content processing is not enabled");return this.contentProcessor.analyzeResponse(e)}}function K(e,t,o){const n=q(e.inputSchema),s=`${e.serverName}_${e.name}`.replace(/[^a-zA-Z0-9_]/g,"_");let a=e.description||`MCP tool ${e.name} from ${e.serverName}`;return o?.toolDescriptions?.[e.name]&&(a=`${a}\n\n${o.toolDescriptions[e.name]}`),o?.additionalContext&&(a=`${a}\n\nContext: ${o.additionalContext}`),new i.DynamicStructuredTool({name:s,description:a,schema:n,func:async o=>{try{const n=await t.executeTool(e.serverName,e.name,o);let s="";if("string"==typeof n)s=n;else if(n&&"object"==typeof n&&"content"in n){const e=n.content;if(Array.isArray(e)){s=e.filter(e=>"object"==typeof e&&null!==e&&"type"in e&&"text"===e.type&&"text"in e).map(e=>e.text).join("\n")}else s=JSON.stringify(e)}else s=JSON.stringify(n);const i=globalThis.Buffer.from(s,"utf8"),a=10240;if(i.length>a||r.shouldUseReference(i)){const t=r.ContentStoreService.getInstance();if(t)try{return`content-ref:${await t.storeContent(i,{contentType:"text",source:"mcp",mcpToolName:`${e.serverName}_${e.name}`,originalSize:i.length})}`}catch{}}return s}catch(n){const t=n instanceof Error?n.message:"Unknown error";return`Error executing MCP tool ${e.name}: ${t}`}}})}function q(e){if(!e||"object"!=typeof e)return o.z.object({});const t=e;if(t.type&&"object"!==t.type)return G(t);if(!t.properties||"object"!=typeof t.properties)return o.z.object({});const r={};for(const[o,n]of Object.entries(t.properties)){let e=G(n);Array.isArray(t.required)&&t.required.includes(o)||(e=e.optional()),r[o]=e}return o.z.object(r)}function G(e){if(!e||"object"!=typeof e||!("type"in e))return o.z.unknown();const t=e;let r;switch(t.type){case"string":r=o.z.string(),t.enum&&Array.isArray(t.enum)&&(r=o.z.enum(t.enum));break;case"number":r=o.z.number(),"minimum"in t&&"number"==typeof t.minimum&&(r=r.min(t.minimum)),"maximum"in t&&"number"==typeof t.maximum&&(r=r.max(t.maximum));break;case"integer":r=o.z.number().int(),"minimum"in t&&"number"==typeof t.minimum&&(r=r.min(t.minimum)),"maximum"in t&&"number"==typeof t.maximum&&(r=r.max(t.maximum));break;case"boolean":r=o.z.boolean();break;case"array":r=t.items?o.z.array(G(t.items)):o.z.array(o.z.unknown());break;case"object":r="properties"in t?q(t):o.z.object({}).passthrough();break;default:r=o.z.unknown()}return"description"in t&&"string"==typeof t.description&&(r=r.describe(t.description)),r}const W=class e{constructor(e="gpt-4o"){this.modelName=String(e);try{this.encoding=d.encoding_for_model(e)}catch{this.encoding=d.encoding_for_model("gpt-4o"),this.modelName="gpt-4o"}}countTokens(e){if(!e||""===e.trim())return 0;try{return this.encoding.encode(e).length}catch{return Math.ceil(1.3*e.split(/\s+/).length)}}countMessageTokens(t){return this.countTokens(String(t.content??""))+this.countTokens(this.getMessageRole(t))+e.MESSAGE_OVERHEAD+e.ROLE_OVERHEAD}countMessagesTokens(e){if(!e||0===e.length)return 0;let t=0;for(const r of e)t+=this.countMessageTokens(r);return t}estimateSystemPromptTokens(t){if(!t||""===t.trim())return 0;return this.countTokens(t)+this.countTokens("system")+e.MESSAGE_OVERHEAD+e.ROLE_OVERHEAD}estimateContextSize(e,t){return this.estimateSystemPromptTokens(e)+this.countMessagesTokens(t)+10}getMessageRole(e){switch(e._getType()){case"human":default:return"user";case"ai":return"assistant";case"system":return"system";case"function":return"function";case"tool":return"tool"}}getModelName(){return this.modelName}dispose(){try{this.encoding.free()}catch{}}};W.MESSAGE_OVERHEAD=3,W.ROLE_OVERHEAD=1;let V=W;const J=class e{constructor(t=e.DEFAULT_MAX_TOKENS,r=e.DEFAULT_RESERVE_TOKENS,o){if(this.messages=[],this.systemPrompt="",this.systemPromptTokens=0,r>=t)throw new Error("Reserve tokens must be less than max tokens");this.maxTokens=t,this.reserveTokens=r,this.tokenCounter=o||new V}addMessage(e){this.tokenCounter.countMessageTokens(e),this.messages.push(e);let t=[];return this.getCurrentTokenCount()>this.maxTokens-this.reserveTokens&&(this.messages.pop(),t=this.pruneToFit(),this.messages.push(e)),{added:!0,prunedMessages:t,currentTokenCount:this.getCurrentTokenCount(),remainingCapacity:this.getRemainingTokenCapacity()}}pruneToFit(){const t=[],r=this.maxTokens-this.reserveTokens;for(;this.getCurrentTokenCount()>r&&this.messages.length>0;){const r=Math.min(e.PRUNING_BATCH_SIZE,this.messages.length);for(let e=0;e<r;e++){const e=this.messages.shift();e&&t.push(e)}if(t.length>1e3)break}return t}getCurrentTokenCount(){const e=this.tokenCounter.countMessagesTokens(this.messages);return this.systemPromptTokens+e}getRemainingTokenCapacity(){return Math.max(0,this.maxTokens-this.getCurrentTokenCount())}canAddMessage(e){const t=this.tokenCounter.countMessageTokens(e),r=this.getCurrentTokenCount()+t>this.maxTokens-this.reserveTokens;return!(t>this.maxTokens)&&(!r||this.messages.length>0)}getMessages(){return[...this.messages]}clear(){this.messages=[]}setSystemPrompt(e){this.systemPrompt=e,this.systemPromptTokens=this.tokenCounter.estimateSystemPromptTokens(e)}getSystemPrompt(){return this.systemPrompt}getConfig(){return{maxTokens:this.maxTokens,reserveTokens:this.reserveTokens,currentTokens:this.getCurrentTokenCount(),messageCount:this.messages.length,systemPromptTokens:this.systemPromptTokens}}updateLimits(e,t){if(void 0!==t&&t>=e)throw new Error("Reserve tokens must be less than max tokens");this.maxTokens=e,void 0!==t&&(this.reserveTokens=t),this.getCurrentTokenCount()>this.maxTokens-this.reserveTokens&&this.pruneToFit()}getStats(){const e=this.getCurrentTokenCount(),t=this.maxTokens,r=e/t*100;return{totalMessages:this.messages.length,currentTokens:e,maxTokens:t,reserveTokens:this.reserveTokens,systemPromptTokens:this.systemPromptTokens,usagePercentage:Math.round(100*r)/100,remainingCapacity:this.getRemainingTokenCapacity(),canAcceptMore:this.getRemainingTokenCapacity()>this.reserveTokens}}dispose(){this.clear(),this.tokenCounter.dispose()}};J.DEFAULT_MAX_TOKENS=8e3,J.DEFAULT_RESERVE_TOKENS=1e3,J.PRUNING_BATCH_SIZE=2;let Z=J;class X{static generateId(e){const t=p.createHash("sha256");return t.update(e),t.digest("hex")}static isValidReferenceId(e){return!(!e||"string"!=typeof e)&&(64===e.length&&/^[a-f0-9]+$/.test(e))}static extractReferenceId(e){if(!e||"string"!=typeof e)return null;const t=e.match(/^ref:\/\/([a-f0-9]{64})$/);return t?t[1]:this.isValidReferenceId(e)?e:null}static formatReference(e){return`ref://${e}`}static generateTestId(e){const t=globalThis.Buffer.from(`test-${e}-${Date.now()}`);return this.generateId(t)}}const Y={sizeThresholdBytes:10240,maxAgeMs:36e5,maxReferences:100,maxTotalStorageBytes:104857600,enableAutoCleanup:!0,cleanupIntervalMs:3e5,enablePersistence:!1,storageBackend:"memory",cleanupPolicies:{recent:{maxAgeMs:18e5,priority:1},userContent:{maxAgeMs:72e5,priority:2},agentGenerated:{maxAgeMs:36e5,priority:3},default:{maxAgeMs:36e5,priority:4}}};class Q extends Error{constructor(e,t,r,o){super(e),this.type=t,this.referenceId=r,this.suggestedActions=o,this.name="ContentReferenceError"}}const ee=class e{constructor(t=e.DEFAULT_MAX_STORAGE,r){this.messages=[],this.idCounter=0,this.contentStore=new Map,this.maxStorage=t,this.referenceConfig={...Y,...r},this.referenceStats={activeReferences:0,totalStorageBytes:0,recentlyCleanedUp:0,totalResolutions:0,failedResolutions:0,averageContentSize:0,storageUtilization:0,performanceMetrics:{averageCreationTimeMs:0,averageResolutionTimeMs:0,averageCleanupTimeMs:0,creationTimes:[],resolutionTimes:[],cleanupTimes:[]}},this.referenceConfig.enableAutoCleanup&&this.startReferenceCleanupTimer()}storeMessages(e){if(0===e.length)return{stored:0,dropped:0};const t=new Date;let r=0;const o=e.map(e=>({message:e,storedAt:t,id:this.generateId()}));for(this.messages.push(...o);this.messages.length>this.maxStorage;)this.messages.shift(),r++;return{stored:o.length,dropped:r}}getRecentMessages(e){if(e<=0||0===this.messages.length)return[];const t=Math.max(0,this.messages.length-e);return this.messages.slice(t).map(e=>e.message)}searchMessages(e,t={}){if(!e||0===this.messages.length)return[];const{caseSensitive:r=!1,limit:o,useRegex:n=!1}=t;let s=[];if(n)try{const t=new RegExp(e,r?"g":"gi");s=this.messages.filter(e=>t.test(e.message.content)).map(e=>e.message)}catch{return[]}else{const t=r?e:e.toLowerCase();s=this.messages.filter(e=>{const o=e.message.content;return(r?o:o.toLowerCase()).includes(t)}).map(e=>e.message)}return o?s.slice(0,o):s}getMessagesFromTimeRange(e,t){return e>t||0===this.messages.length?[]:this.messages.filter(r=>r.storedAt>=e&&r.storedAt<=t).map(e=>e.message)}getStorageStats(){const e=this.messages.length,t=e>0?Math.round(e/this.maxStorage*100):0;let r,o;return e>0&&(r=this.messages[0].storedAt,o=this.messages[e-1].storedAt),{totalMessages:e,maxStorageLimit:this.maxStorage,usagePercentage:t,oldestMessageTime:r,newestMessageTime:o}}clear(){this.messages=[],this.idCounter=0}getTotalStoredMessages(){return this.messages.length}updateStorageLimit(e){if(e<=0)throw new Error("Storage limit must be greater than 0");for(this.maxStorage=e;this.messages.length>this.maxStorage;)this.messages.shift()}getMessagesByType(e,t){const r=this.messages.filter(t=>t.message._getType()===e).map(e=>e.message);return t?r.slice(0,t):r}getConfig(){return{maxStorage:this.maxStorage,currentUsage:this.messages.length,utilizationPercentage:this.messages.length/this.maxStorage*100}}generateId(){return`msg_${++this.idCounter}_${Date.now()}`}getRecentMessagesByTime(e){if(e<=0||0===this.messages.length)return[];const t=new Date(Date.now()-60*e*1e3);return this.messages.filter(e=>e.storedAt>=t).map(e=>e.message)}exportMessages(){return this.messages.map(e=>({content:"string"==typeof e.message.content?e.message.content:JSON.stringify(e.message.content),type:e.message._getType(),storedAt:e.storedAt.toISOString(),id:e.id}))}shouldUseReference(e){return(globalThis.Buffer.isBuffer(e)?e.length:globalThis.Buffer.byteLength(e,"utf8"))>this.referenceConfig.sizeThresholdBytes}async storeContentIfLarge(e,t){const r=globalThis.Buffer.isBuffer(e)?e:globalThis.Buffer.from(e,"utf8");if(!this.isImageContent(t.mimeType,t.fileName)&&!this.shouldUseReference(r))return null;const o={contentType:t.contentType||this.detectContentType(r,t.mimeType),sizeBytes:r.length,source:t.source,tags:[]};return void 0!==t.mimeType&&(o.mimeType=t.mimeType),void 0!==t.mcpToolName&&(o.mcpToolName=t.mcpToolName),void 0!==t.fileName&&(o.fileName=t.fileName),void 0!==t.tags&&(o.tags=t.tags),void 0!==t.customMetadata&&(o.customMetadata=t.customMetadata),await this.storeContent(r,o)}async storeContent(e,t){const r=Date.now();try{const o=new Date,n=X.generateId(e),s={...t,createdAt:o,lastAccessedAt:o,accessCount:0},i={content:e,metadata:s,state:"active"},a=this.calculateExpirationTime(t.source);void 0!==a&&(i.expiresAt=a),this.contentStore.set(n,i),this.updateStatsAfterStore(e.length),await this.enforceReferenceStorageLimits();const c=this.createContentPreview(e,s.contentType),l={contentType:s.contentType,sizeBytes:s.sizeBytes,source:s.source};void 0!==s.fileName&&(l.fileName=s.fileName),void 0!==s.mimeType&&(l.mimeType=s.mimeType);const g={referenceId:n,state:"active",preview:c,metadata:l,createdAt:o,format:"ref://{id}"},h=Date.now()-r;return this.recordPerformanceMetric("creation",h),g}catch(o){const e=Date.now()-r;throw this.recordPerformanceMetric("creation",e),new Q(`Failed to store content: ${o instanceof Error?o.message:"Unknown error"}`,"system_error",void 0,["Try again","Check storage limits","Contact administrator"])}}async resolveReference(e){const t=Date.now();try{if(!X.isValidReferenceId(e))return this.referenceStats.failedResolutions++,{success:!1,error:"Invalid reference ID format",errorType:"not_found",suggestedActions:["Check the reference ID format","Ensure the reference ID is complete"]};const r=this.contentStore.get(e);if(!r)return this.referenceStats.failedResolutions++,{success:!1,error:"Reference not found",errorType:"not_found",suggestedActions:["Verify the reference ID","Check if the content has expired","Request fresh content"]};if(r.expiresAt&&r.expiresAt<new Date)return r.state="expired",this.referenceStats.failedResolutions++,{success:!1,error:"Reference has expired",errorType:"expired",suggestedActions:["Request fresh content","Use alternative content source"]};if("active"!==r.state)return this.referenceStats.failedResolutions++,{success:!1,error:`Reference is ${r.state}`,errorType:"expired"===r.state?"expired":"corrupted",suggestedActions:["Request fresh content","Check reference validity"]};r.metadata.lastAccessedAt=new Date,r.metadata.accessCount++,this.referenceStats.totalResolutions++;const o=Date.now()-t;return this.recordPerformanceMetric("resolution",o),{success:!0,content:r.content,metadata:r.metadata}}catch(r){const e=Date.now()-t;return this.recordPerformanceMetric("resolution",e),this.referenceStats.failedResolutions++,{success:!1,error:`System error resolving reference: ${r instanceof Error?r.message:"Unknown error"}`,errorType:"system_error",suggestedActions:["Try again","Contact administrator"]}}}async hasReference(e){if(!X.isValidReferenceId(e))return!1;const t=this.contentStore.get(e);return!!t&&(t.expiresAt&&t.expiresAt<new Date?(t.state="expired",!1):"active"===t.state)}async cleanupReference(e){const t=this.contentStore.get(e);return!!t&&(this.referenceStats.totalStorageBytes-=t.content.length,this.referenceStats.activeReferences--,this.referenceStats.recentlyCleanedUp++,this.contentStore.delete(e),!0)}async getStats(){return this.updateReferenceStorageStats(),{...this.referenceStats,performanceMetrics:{averageCreationTimeMs:this.calculateAverage(this.referenceStats.performanceMetrics.creationTimes),averageResolutionTimeMs:this.calculateAverage(this.referenceStats.performanceMetrics.resolutionTimes),averageCleanupTimeMs:this.calculateAverage(this.referenceStats.performanceMetrics.cleanupTimes)}}}async updateConfig(e){this.referenceConfig={...this.referenceConfig,...e},this.cleanupTimer&&(clearInterval(this.cleanupTimer),delete this.cleanupTimer),this.referenceConfig.enableAutoCleanup&&this.startReferenceCleanupTimer()}async performCleanup(){const e=Date.now(),t=[];let r=0;try{const n=new Date,s=[];for(const[e,t]of this.contentStore.entries()){let r=!1;t.expiresAt&&t.expiresAt<n&&(r=!0,t.state="expired");const o=n.getTime()-t.metadata.createdAt.getTime();o>this.getCleanupPolicy(t.metadata.source).maxAgeMs&&(r=!0),"cleanup_pending"===t.state&&(r=!0),r&&s.push(e)}s.sort((e,t)=>{const r=this.contentStore.get(e),o=this.contentStore.get(t),n=this.getCleanupPolicy(r.metadata.source).priority;return this.getCleanupPolicy(o.metadata.source).priority-n});for(const e of s)try{await this.cleanupReference(e)&&r++}catch(o){t.push(`Failed to cleanup ${e}: ${o instanceof Error?o.message:"Unknown error"}`)}if(this.contentStore.size>this.referenceConfig.maxReferences){const e=Array.from(this.contentStore.entries()).sort(([,e],[,t])=>e.metadata.lastAccessedAt.getTime()-t.metadata.lastAccessedAt.getTime()),n=this.contentStore.size-this.referenceConfig.maxReferences;for(let s=0;s<n&&s<e.length;s++){const[n]=e[s];try{await this.cleanupReference(n)&&r++}catch(o){t.push(`Failed to cleanup excess reference ${n}: ${o instanceof Error?o.message:"Unknown error"}`)}}}const i=Date.now()-e;return this.recordPerformanceMetric("cleanup",i),{cleanedUp:r,errors:t}}catch(o){const n=Date.now()-e;this.recordPerformanceMetric("cleanup",n);const s=`Cleanup process failed: ${o instanceof Error?o.message:"Unknown error"}`;return t.push(s),{cleanedUp:r,errors:t}}}getReferenceConfig(){return{...this.referenceConfig}}async enforceReferenceStorageLimits(){this.contentStore.size>=this.referenceConfig.maxReferences&&await this.performCleanup(),this.referenceStats.totalStorageBytes>=this.referenceConfig.maxTotalStorageBytes&&await this.performCleanup()}calculateExpirationTime(e){const t=this.getCleanupPolicy(e);return new Date(Date.now()+t.maxAgeMs)}getCleanupPolicy(e){switch(e){case"mcp_tool":return this.referenceConfig.cleanupPolicies.recent;case"user_upload":return this.referenceConfig.cleanupPolicies.userContent;case"agent_generated":return this.referenceConfig.cleanupPolicies.agentGenerated;default:return this.referenceConfig.cleanupPolicies.default}}detectContentType(e,t){if(t)return"text/html"===t?"html":"text/markdown"===t?"markdown":"application/json"===t?"json":t.startsWith("text/")?"text":"binary";const r=e.toString("utf8",0,Math.min(e.length,1e3));return r.startsWith("{")||r.startsWith("[")?"json":r.includes("<html>")||r.includes("<!DOCTYPE")?"html":r.includes("#")&&r.includes("\n")?"markdown":"text"}createContentPreview(e,t){let r=e.toString("utf8",0,Math.min(e.length,400));if("html"===t)r=r.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim();else if("json"===t)try{const e=JSON.parse(r);r=JSON.stringify(e,null,0)}catch{}return r=r.trim(),r.length>200&&(r=r.substring(0,200)+"..."),r||"[Binary content]"}updateStatsAfterStore(e){this.referenceStats.activeReferences++,this.referenceStats.totalStorageBytes+=e,this.updateReferenceStorageStats()}updateReferenceStorageStats(){let e;this.referenceStats.activeReferences>0&&(this.referenceStats.averageContentSize=this.referenceStats.totalStorageBytes/this.referenceStats.activeReferences),this.referenceStats.storageUtilization=this.referenceStats.totalStorageBytes/this.referenceConfig.maxTotalStorageBytes*100;let t=0;for(const[r,o]of this.contentStore.entries())o.metadata.accessCount>t&&(t=o.metadata.accessCount,e=r);void 0!==e?this.referenceStats.mostAccessedReferenceId=e:delete this.referenceStats.mostAccessedReferenceId}isImageContent(e,t){if(e&&e.startsWith("image/"))return!0;if(t){const e=t.toLowerCase();return[".png",".jpg",".jpeg",".gif",".bmp",".webp",".svg",".tiff",".ico"].some(t=>e.endsWith(t))}return!1}recordPerformanceMetric(e,t){const r=this.referenceStats.performanceMetrics;switch(e){case"creation":r.creationTimes.push(t),r.creationTimes.length>100&&r.creationTimes.shift();break;case"resolution":r.resolutionTimes.push(t),r.resolutionTimes.length>100&&r.resolutionTimes.shift();break;case"cleanup":r.cleanupTimes.push(t),r.cleanupTimes.length>100&&r.cleanupTimes.shift()}}calculateAverage(e){return 0===e.length?0:e.reduce((e,t)=>e+t,0)/e.length}startReferenceCleanupTimer(){this.cleanupTimer=setInterval(async()=>{try{await this.performCleanup()}catch{}},this.referenceConfig.cleanupIntervalMs)}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),delete this.cleanupTimer),this.contentStore.clear(),this.clear()}};ee.DEFAULT_MAX_STORAGE=1e3;let te=ee;const re='"isEntityAssociation":true',oe=class e{constructor(t={}){this.config={...e.DEFAULT_CONFIG,...t},this.logger=new r.Logger({module:"SmartMemoryManager"}),this.tokenCounter=new V(this.config.modelName),this._contentStorage=new te(this.config.storageLimit),this.memoryWindow=new Z(this.config.maxTokens,this.config.reserveTokens,this.tokenCounter)}get contentStorage(){return this._contentStorage}addMessage(e){const t=this.memoryWindow.addMessage(e);t.prunedMessages.length>0&&this._contentStorage.storeMessages(t.prunedMessages)}getMessages(){return this.memoryWindow.getMessages()}clear(e=!1){this.memoryWindow.clear(),e&&this._contentStorage.clear()}setSystemPrompt(e){this.memoryWindow.setSystemPrompt(e)}getSystemPrompt(){return this.memoryWindow.getSystemPrompt()}searchHistory(e,t={}){return this._contentStorage.searchMessages(e,t)}getRecentHistory(e){return this._contentStorage.getRecentMessages(e)}canAddMessage(e){return this.memoryWindow.canAddMessage(e)}getMemoryStats(){const e=this.memoryWindow.getStats();return{totalActiveMessages:e.totalMessages,currentTokenCount:e.currentTokens,maxTokens:e.maxTokens,remainingCapacity:e.remainingCapacity,systemPromptTokens:e.systemPromptTokens,usagePercentage:e.usagePercentage}}getStorageStats(){return this._contentStorage.getStorageStats()}getOverallStats(){const e=this.getMemoryStats(),t=this.getStorageStats();return{activeMemory:e,storage:t,totalMessagesManaged:e.totalActiveMessages+t.totalMessages,activeMemoryUtilization:e.usagePercentage,storageUtilization:t.usagePercentage}}updateConfig(e){this.config={...this.config,...e},void 0===e.maxTokens&&void 0===e.reserveTokens||this.memoryWindow.updateLimits(this.config.maxTokens,this.config.reserveTokens),void 0!==e.storageLimit&&this._contentStorage.updateStorageLimit(this.config.storageLimit)}getConfig(){return{...this.config}}getHistoryFromTimeRange(e,t){return this._contentStorage.getMessagesFromTimeRange(e,t)}getHistoryByType(e,t){return this._contentStorage.getMessagesByType(e,t)}getRecentHistoryByTime(e){return this._contentStorage.getRecentMessagesByTime(e)}exportState(){return{config:this.config,activeMessages:this.memoryWindow.getMessages().map(e=>({content:e.content,type:e._getType()})),systemPrompt:this.memoryWindow.getSystemPrompt(),memoryStats:this.getMemoryStats(),storageStats:this.getStorageStats(),storedMessages:this._contentStorage.exportMessages()}}getContextSummary(e=!1){const t=this.getMessages(),r={activeMessageCount:t.length,systemPrompt:this.getSystemPrompt(),recentMessages:t.slice(-5),memoryUtilization:this.getMemoryStats().usagePercentage,hasStoredHistory:this.getStorageStats().totalMessages>0};return e?{...r,recentStoredMessages:this.getRecentHistory(10),storageStats:this.getStorageStats()}:r}performMaintenance(){}storeEntityAssociation(e,t,r,o,n){try{if(!e||"string"!=typeof e||0===e.trim().length)return;if(!t||"string"!=typeof t||0===t.trim().length)return;if(!r||"string"!=typeof r||0===r.trim().length)return;const s=e.trim(),i=t.trim().substring(0,100),a=this.normalizeEntityType(r);let c="";"tokenid"===a?c="Use this as tokenId for HTS operations":"topicid"===a?c="Can be used for HCS operations, HRLs for minting with the format hcs://1/<topicId>, etc.":"accountid"===a&&(c="Can be used for account based operations");const l={entityId:s,entityName:i,entityType:a,createdAt:new Date,isEntityAssociation:!0,...c?{usage:c}:{},..."topicId"===a?{hrl:`hcs://1/${s}`}:{},...null!=o&&""!==o.trim()?{transactionId:o.trim()}:{},...n&&""!==n.trim()?{sessionId:n.trim()}:{}},g=JSON.stringify(l),h={_getType:()=>"system",content:g,id:`entity_${s}_${Date.now()}`,name:"entity_association",additional_kwargs:{entityId:s,entityName:i,entityType:a,isEntityAssociation:!0,...n&&""!==n.trim()?{sessionId:n.trim()}:{}}};try{this.memoryWindow.addMessage(new m.SystemMessage(g))}catch{}this._contentStorage.storeMessages([h])}catch(s){this.logger.error("Failed to store entity association",{entityId:e,entityName:t,entityType:r,error:s instanceof Error?s.message:String(s)})}}normalizeEntityType(e){const t=(e||"").trim();if(0===t.length)return"";const r=t.replace(/[^a-z]/gi,"").toLowerCase(),o={topic:"topicId",topicid:"topicId",token:"tokenId",tokenid:"tokenId",account:"accountId",accountid:"accountId",contract:"contractId",contractid:"contractId",file:"fileId",fileid:"fileId",schedule:"scheduleId",scheduleid:"scheduleId"};return Object.prototype.hasOwnProperty.call(o,r)?o[r]:(/^[a-z]+Id$/.test(t),t)}resolveEntityReference(e,t={}){try{if(!e||"string"!=typeof e)return[];const r=e.trim();if(0===r.length)return[];r.length;const{entityType:o,limit:n=10,fuzzyMatch:s=!0}=t,i=Math.max(1,Math.min(n||10,100)),a=/^0\.0\.\d+$/.test(r),c=this._contentStorage.searchMessages(r.substring(0,200),{caseSensitive:!1,limit:2*i}),l=[];for(const e of c)try{const t=e.content;if(t.includes(re)||t.includes("entityId")){const e=JSON.parse(t);if(e.entityId&&e.entityName&&e.entityType){if(o&&e.entityType!==o)continue;if(a&&e.entityId!==r)continue;l.push(e)}}}catch{continue}if(s&&0===l.length&&!a){const t=[e.toLowerCase(),"token","account",o||""].filter(Boolean);for(const r of t){if(r===e.toLowerCase())continue;const t=this._contentStorage.searchMessages(r,{caseSensitive:!1,limit:n});for(const e of t)try{const t=e.content;if(t.includes(re)){const e=JSON.parse(t);if(e.entityId&&e.entityName&&e.entityType){if(o&&e.entityType!==o)continue;l.push(e)}}}catch{continue}}}const g=l.filter((e,t,r)=>r.findIndex(t=>t.entityId===e.entityId)===t).sort((e,t)=>new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime());return g.slice(0,i)}catch(r){return this.logger.error("Failed to resolve entity reference",{query:e,options:t,error:r instanceof Error?r.message:String(r)}),[]}}getEntityAssociations(e){try{const r=e?e.trim():void 0,o=r?this.normalizeEntityType(r):void 0;if(e&&(!r||0===r.length))return[];const n=o||"entityId",s=this._contentStorage.searchMessages(n,{caseSensitive:!1,limit:100}),i=[];for(const e of s)try{const t=e.content;if(t.includes(re)){const e=JSON.parse(t);if(e.entityId&&e.entityName&&e.entityType){if(o&&e.entityType!==o)continue;e.createdAt&&"string"==typeof e.createdAt&&(e.createdAt=new Date(e.createdAt)),i.push(e)}}}catch(t){this.logger.warn("Failed to parse entity association from message",{messageContent:"string"==typeof e.content?e.content.substring(0,100):"non-string",error:t instanceof Error?t.message:String(t)});continue}const a=new Map,c=e=>e instanceof Date?e.getTime():new Date(e).getTime();for(const e of i){const t=a.get(e.entityId);if(!t){a.set(e.entityId,e);continue}const r=c(t.createdAt),o=c(e.createdAt);(o>r||!!e.transactionId&&!t.transactionId)&&a.set(e.entityId,{...t,...e})}return Array.from(a.values()).sort((e,t)=>c(t.createdAt)-c(e.createdAt))}catch(r){return this.logger.error("Failed to get entity associations",{entityType:e,error:r instanceof Error?r.message:String(r)}),[]}}dispose(){this.memoryWindow.dispose(),this._contentStorage.dispose(),this.tokenCounter.dispose()}};oe.DEFAULT_CONFIG={maxTokens:8e3,reserveTokens:1e3,modelName:"gpt-4o",storageLimit:1e3};let ne=oe;class se extends i.StructuredTool{constructor(e,t,o={}){super(),this.originalTool=e,this.formGenerator=t,this.validationConfig=o,this.logger=new r.Logger({module:"FormValidatingToolWrapper"}),this.name=e.name,this.description=e.description,this.schema=e.schema,this.logger.info(`🔧 FormValidatingToolWrapper created for tool: ${this.name}`,{originalToolName:e.name,originalToolType:e.constructor.name,wrapperType:this.constructor.name})}validateInput(e){try{return this.schema.parse(e),{isValid:!0}}catch(t){if(t instanceof o.z.ZodError){return{isValid:!1,errors:t.errors.filter(e=>{const t=e.path[0];return!this.validationConfig.skipFields?.includes(t)}).map(e=>`${e.path.join(".")}: ${e.message}`)}}return{isValid:!1,errors:["Validation failed"]}}}getSchemaShape(){return this.isZodObject(this.schema)?Object.keys(this.schema.shape):[]}async executeOriginal(e,t){const r=this.originalTool;if("_call"in r&&"function"==typeof r._call)return r._call(e,t);if("call"in r&&"function"==typeof r.call)return r.call(e,t);throw new Error("Original tool has no callable implementation")}getOriginalTool(){return this.originalTool}hasFormValidatableMethod(e,t){return null!==e&&"object"==typeof e&&t in e&&"function"==typeof e[t]}getFormSchema(){return this.hasFormValidatableMethod(this.originalTool,"getFormSchema")?this.originalTool.getFormSchema():this.schema}getEssentialFields(){return this.hasFormValidatableMethod(this.originalTool,"getEssentialFields")?this.originalTool.getEssentialFields():[]}isFieldEmpty(e,t){return this.hasFormValidatableMethod(this.originalTool,"isFieldEmpty")?this.originalTool.isFieldEmpty(e,t):null==t||""===t||!(!Array.isArray(t)||0!==t.length)}calculateMissingFields(e,t){const r=new Set;if(!t)return r;const o=this.getEssentialFields();for(const n of o){const t=e[n];this.isFieldEmpty(n,t)&&r.add(n)}return r}async createFormMessage(e,t,r){let o=await this.formGenerator.generateFormFromSchema(e,t,{toolName:this.name,toolDescription:this.description},r);if(this.isZodObject(e))try{const{jsonSchema:n,uiSchema:s}=this.formGenerator.generateJsonSchemaForm(e,t,r);o={...o,jsonSchema:n,uiSchema:s}}catch(n){this.logger.warn("Failed to generate JSON Schema for RJSF:",n)}return o.partialInput=t,o}isZodObject(e){const t=e._def;return!(!t||"ZodObject"!==t.typeName)}shouldGenerateForm(e){if(this.logger.info(`shouldGenerateForm called for ${this.name}/${this.originalTool.name}`,{input:e,hasCustomValidation:!!this.validationConfig.customValidation}),this.validationConfig.customValidation){const t=!this.validationConfig.customValidation(e);return this.logger.info(`Custom validation result: ${t}`),t}if(t.isFormValidatable(this.originalTool))return this.logger.info(`Tool ${this.originalTool.name} implements FormValidatable, using custom logic`),this.originalTool.shouldGenerateForm(e);this.logger.info(`Tool ${this.originalTool.name} using schema validation only`);const r=this.validateInput(e);return this.logger.info(`Schema validation for ${this.originalTool.name}:`,{isValid:r.isValid,errors:r.errors}),!r.isValid}hasFormBypassFlags(e){return!0===e.__fromForm||!1===e.renderForm}async _call(e,r){this.logger.info(`🚨🚨🚨 FormValidatingToolWrapper._call INTERCEPTING ${this.name} 🚨🚨🚨`,{input:e,inputKeys:Object.keys(e),schemaShape:this.getSchemaShape(),stackTrace:(new Error).stack?.split("\n").slice(0,5)});const o=e;if(this.hasFormBypassFlags(o))return this.logger.info("Bypassing form generation and executing original tool due to submission flags"),this.executeOriginal(o,r);const n=this.shouldGenerateForm(e);if(this.logger.info(`FormValidatingToolWrapper decision for ${this.name}:`,{shouldGenerateForm:n,toolName:this.name,originalToolName:this.originalTool.name}),n){this.logger.info(`Generating form for incomplete input in ${this.name}`);try{const r=t.isFormValidatable(this.originalTool),o=r?this.getFormSchema():this.schema,n=this.calculateMissingFields(e,r),s=this.isZodObject(o)?Object.keys(o.shape):[];this.logger.info(`Using ${r?"CUSTOM":"DEFAULT"} schema for form generation`,{toolName:this.originalTool.name,schemaType:o.constructor?.name,schemaFields:s,isCustomSchema:r});const i={requiresForm:!0,formMessage:await this.createFormMessage(o,e,n),message:`Please complete the form to provide the required information for ${this.name}.`};return this.logger.info(`FormValidatingToolWrapper returning form result for ${this.name}`),JSON.stringify(i)}catch(s){this.logger.error("Failed to generate form:",s)}}return this.logger.info(`FormValidatingToolWrapper passing through to original tool ${this.name}`),this.executeOriginal(e,r)}}function ie(e,t,r={}){return new se(e,t,r)}class ae{constructor(e){this.tools=new Map,this.formGenerator=new $,this.logger=e||new r.Logger({module:"ToolRegistry"})}registerTool(e,t={}){const r=this.analyzeToolCapabilities(e),o={name:e.name,version:"1.0.0",category:t.metadata?.category||"core",description:e.description,capabilities:r,dependencies:[],schema:e.schema,...t.metadata};try{if(!o.entityResolutionPreferences){const t=e.schema,r=t&&"object"==typeof t&&t._entityResolutionPreferences;r&&"object"==typeof r&&(o.entityResolutionPreferences=r)}}catch{}try{const t=e.schema,r=t&&t._def;if("ZodObject"===r?.typeName){const t=("function"==typeof r.shape?r.shape?.()||{}:r.shape||{}).metadata;if(!!t&&"ZodArray"===t._def?.typeName&&"ZodString"===t._def?.type?._def?.typeName&&"string"==typeof e.description){o.entityResolutionPreferences||(o.entityResolutionPreferences={inscription:"hrl"});const t=" NOTE: When referencing inscriptions or media, provide canonical Hashlink Resource Locators (e.g., hcs://<standard>/<topicId>) rather than external URLs or embedded JSON.";e.description.includes("Hashlink Resource Locators")||(e.description=`${e.description}${t}`)}}}catch{}let n,s=e;this.shouldWrapTool(e,r,t)&&(n=ie(e,this.formGenerator,{requireAllFields:!1,skipFields:["metaOptions"],...t.wrapperConfig}),s=n);try{o.entityResolutionPreferences&&(s.entityResolutionPreferences=o.entityResolutionPreferences)}catch{}const i={tool:s,metadata:o,wrapper:n,originalTool:e,options:{priority:r.priority,capability:"basic",enabled:!0,namespace:o.category}};this.tools.set(e.name,i);try{const t=o.fieldGuidance;t&&T.registerToolConfiguration(t);const r=o.fieldGuidanceProvider;if(r){const o=t?.toolPattern??e.name;T.registerToolProvider(o,r,{id:`${e.name}:field-guidance-provider`,priority:0})}}catch{}}getTool(e){return this.tools.get(e)||null}getToolsByCapability(e,t){const r=[];for(const o of this.tools.values())void 0!==t?o.metadata.capabilities[e]===t&&r.push(o):o.metadata.capabilities[e]&&r.push(o);return r}getToolsByQuery(e){const t=[];for(const r of this.tools.values()){let o=!0;if(e.name&&r.metadata.name!==e.name&&(o=!1),e.category&&r.metadata.category!==e.category&&(o=!1),e.capabilities)for(const[t,n]of Object.entries(e.capabilities))if(r.metadata.capabilities[t]!==n){o=!1;break}o&&t.push(r)}return t}getAllTools(){return Array.from(this.tools.values()).map(e=>e.tool)}getAllRegistryEntries(){return Array.from(this.tools.values())}getToolNames(){return Array.from(this.tools.keys())}getToolsByPriority(e){return this.getToolsByCapability("priority",e)}getEnabledTools(){return this.getAllRegistryEntries()}getToolsByNamespace(e){return e?this.getToolsByQuery({category:e}):this.getAllRegistryEntries()}hasCapability(e){for(const t of this.tools.values())if(t.metadata.capabilities[e])return!0;return!1}updateToolOptions(e,t){const r=this.tools.get(e);return!!r&&(r.metadata={...r.metadata,...t},!0)}hasTool(e){return this.tools.has(e)}unregisterTool(e){return this.tools.delete(e)}clear(){this.tools.clear()}analyzeToolCapabilities(e){const r=t.isFormValidatable(e),o=this.hasRenderConfig(e),n=this.isZodObjectLike(e.schema),s=r||o,i=s&&n;let a="medium",c="core";s&&i?a="critical":s?a="high":(e.description?.toLowerCase().includes("query")||e.description?.toLowerCase().includes("search"))&&(a="low");const l=e;return e.constructor.name.includes("MCP")||l.isMCPTool?c="mcp":(l.isExtension||e.constructor.name.includes("Extension"))&&(c="extension"),{supportsFormValidation:s,requiresWrapper:i,priority:a,category:c}}hasRenderConfig(e){const t=e.schema;return!(!t||!t._renderConfig)}shouldWrapTool(e,t,r){return!r.skipWrapper&&(!!r.forceWrapper||t.requiresWrapper)}isZodObjectLike(e){if(!e||"object"!=typeof e)return!1;const t=e,r=t._def;return e instanceof o.z.ZodObject||"ZodObject"===r?.typeName||"shape"in t&&"object"==typeof t.shape}getStatistics(){const e={totalTools:this.tools.size,wrappedTools:0,unwrappedTools:0,categoryCounts:{core:0,extension:0,mcp:0},priorityCounts:{low:0,medium:0,high:0,critical:0}};for(const t of this.tools.values())t.wrapper?e.wrappedTools++:e.unwrappedTools++,e.categoryCounts[t.metadata.category]++,e.priorityCounts[t.metadata.capabilities.priority]++;return e}}class ce{constructor(e,t,o,n){this.toolRegistry=e,this.formEngine=t,this.memory=o,this.logger=n||new r.Logger({module:"ExecutionPipeline"})}async execute(e,t,r){const o=`trace-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,n=Date.now(),s=this.toolRegistry.getTool(e);if(!s)throw new Error(`Tool not found in registry: ${e}`);const i={toolName:e,input:t,session:r||this.buildDefaultSession(),memory:this.memory,traceId:o,toolEntry:s};try{const e=await this.checkFormGeneration(i);if(e.requiresForm&&e.formMessage)return{success:!1,output:"Form generation required",requiresForm:!0,formMessage:e.formMessage,traceId:o,executionTime:Date.now()-n};return{success:!0,output:await this.executeToolDirect(i),traceId:o,executionTime:Date.now()-n}}catch(a){return this.handleExecutionError(a,i,o,Date.now()-n)}}async executeWithValidation(e,t,r){return this.execute(e,t,r)}async processFormSubmission(e,t,r,o){const n=`form-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,s=Date.now();try{const n={formId:t,toolName:e,parameters:r,timestamp:Date.now()},s=await this.formEngine.processSubmission(n);return this.execute(e,s,o)}catch(i){return{success:!1,output:"Form submission processing failed",error:i instanceof Error?i.message:String(i),traceId:n,executionTime:Date.now()-s}}}async checkFormGeneration(e){const t=e.input;if(!0===t?.__fromForm||!1===t?.renderForm)return{requiresForm:!1};if(!this.formEngine.shouldGenerateForm(e.toolEntry.tool,e.input))return{requiresForm:!1};const r=await this.formEngine.generateForm(e.toolName,e.toolEntry.tool,e.input);return r?{requiresForm:!0,formMessage:r}:{requiresForm:!1}}async executeToolDirect(e){const{toolEntry:t,input:r}=e,o={...r||{},renderForm:!1};return t.wrapper?this.executeWrappedTool(t,o):await t.tool.call(o)}async executeWrappedTool(e,t){const r=e.wrapper;if(!r)throw new Error("Tool wrapper not found");const o=r;return o.executeOriginal?await o.executeOriginal(t):o.originalTool?.call?await o.originalTool.call(t):await e.originalTool.call(t)}handleExecutionError(e,t,r,n){const s=e instanceof Error?e.message:String(e);return e instanceof o.ZodError?{success:!1,output:"Validation error occurred",error:s,traceId:r,executionTime:n}:(this.logger.error(`Tool execution failed: ${t.toolName}`,{traceId:r,error:s}),{success:!1,output:"Tool execution failed",error:s,traceId:r,executionTime:n})}buildDefaultSession(){return{sessionId:`session-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,timestamp:Date.now()}}getStatistics(){return{totalMiddleware:0,registeredMiddleware:[]}}}function le(e){if(!e||"object"!=typeof e)return!1;const t=e;if(!("hashLinkBlock"in t)||!t.hashLinkBlock||"object"!=typeof t.hashLinkBlock)return!1;const r=t.hashLinkBlock;return"blockId"in r&&"hashLink"in r&&"template"in r&&"attributes"in r&&"string"==typeof r.blockId&&"string"==typeof r.hashLink&&"string"==typeof r.template&&"object"==typeof r.attributes}class ge extends H{constructor(){super(...arguments),this.systemMessage="",this.mcpConnectionStatus=new Map}addToolRawToMemory(e,t){try{const r=`[tool-raw:${e}] ${t}`;this.smartMemory.addMessage(new m.SystemMessage(r))}catch{}}persistToolRaw(e,t){try{let r="";if("string"==typeof t)r=this.isJSON(t)?t:JSON.stringify({output:t});else if(void 0!==t)try{r=JSON.stringify(t)}catch{r=String(t)}else r=JSON.stringify({observation:null});this.addToolRawToMemory(e,r)}catch{}}persistIntermediateSteps(e){if(e&&Array.isArray(e))try{for(const t of e){const e=t?.action?.tool||"unknown",r=t?.observation;this.persistToolRaw(e,r)}}catch{}}getInscriptionTool(){const e=this.toolRegistry.getToolsByCapability("priority","critical");for(const r of e){const e=r.tool,t=e.name.toLowerCase(),o=e.description?.toLowerCase()||"";if(t.includes("inscribe")||t.includes("hashinal")||o.includes("inscribe")||o.includes("hashinal"))return e}const t=this.toolRegistry.getAllRegistryEntries();for(const r of t){const e=r.tool,t=e.name.toLowerCase(),o=e.description?.toLowerCase()||"";if(t.includes("inscribe")||t.includes("hashinal")||o.includes("inscribe")||o.includes("hashinal"))return e}return null}async executeToolDirect(e,t,r=!1){if(r&&this.executionPipeline&&this.smartMemory){const r={sessionId:`session-${Date.now()}`,timestamp:Date.now()},o=await this.executionPipeline.execute(e,t,r);if(!o.success)throw new Error(o.error||"Pipeline execution failed");return o.output}const o=this.toolRegistry.getTool(e);if(!o)throw new Error(`Tool not found: ${e}`);let n={...t};if(this.pendingParameterPreprocessingCallback){this.logger.info("Applying parameter preprocessing in executeToolDirect",{toolName:e,hasCallback:!0,parameterKeys:Object.keys(t)});try{n=await this.pendingParameterPreprocessingCallback(e,t),JSON.stringify(n)!==JSON.stringify(t)&&this.logger.info("Parameters preprocessed successfully",{toolName:e,originalKeys:Object.keys(t),processedKeys:Object.keys(n),changes:Object.keys(n).filter(e=>n[e]!==t[e])})}catch(i){this.logger.warn("Parameter preprocessing failed, using original parameters",{toolName:e,error:i instanceof Error?i.message:"Unknown error"}),n=t}}const s={...n,renderForm:!1};if(o.wrapper){const e=o.tool;if(e.originalTool?.call)return await e.originalTool.call(s)}return await o.tool.call(s)}createToolResponse(e){return{output:e,message:e,notes:[]}}async handleToolExecution(e,t){let r=!1,o=null;try{if(e.includes("TOOL_EXECUTION")){const t=JSON.parse(e);"TOOL_EXECUTION"===t.type&&(r=!0,o=t)}}catch{}if(!r||!o?.formId)return null;try{const e=o.parameters||{},t=o.toolName;if(t){const r=await this.executeToolDirect(t,e);try{const e=this.isJSON(r)?r:JSON.stringify({output:r});this.addToolRawToMemory(t,e)}catch{}return this.createToolResponse(r)}}catch{}const n={formId:o.formId,toolName:o.toolName||"",parameters:o.parameters||{},timestamp:Date.now()};return this.executor&&"processFormSubmission"in this.executor&&"function"==typeof this.executor.processFormSubmission?this.processFormSubmission(n,t):null}async handleDirectToolExecution(e){if("string"!=typeof e||!e.includes("Please execute the following tool:"))return null;try{const t=e.match(/Tool:\s*(.+)/),r=e.indexOf("Arguments:");if(t&&-1!==r){const o=t[1].trim(),n=e.slice(r+10).trim();let s={};try{s=JSON.parse(n)}catch{}const i=await this.executeToolDirect(o,s);try{const e=this.isJSON(i)?i:JSON.stringify({output:i});this.addToolRawToMemory(o,e)}catch{}return this.createToolResponse(i)}}catch{}return null}async handleJsonToolCalls(e,t){if("string"!=typeof e)return null;try{const r=e.trim();if(!(r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]")))return null;const o=JSON.parse(r),n=o.formId,s=o.toolName||"",i=o.parameters||{};if(n&&this.executor&&"processFormSubmission"in this.executor&&"function"==typeof this.executor.processFormSubmission)return this.processFormSubmission({formId:n,toolName:s,parameters:i,timestamp:Date.now()},t);if(s){const e=await this.executeToolDirect(s,i);try{const t=this.isJSON(e)?e:JSON.stringify({output:e});this.addToolRawToMemory(s,t)}catch{}return this.createToolResponse(e)}}catch{}return null}async handleContentRefMessages(e){if("string"!=typeof e||!e.includes("content-ref:"))return null;try{const t=this.getInscriptionTool();if(!t)return null;const r=e.match(/content-ref:([A-Za-z0-9_\-]+)/i)||e.match(/content-ref:([^\s)]+)/i),o=r&&r[1]?`content-ref:${r[1]}`:e.match(/content-ref:[^\s)]+/i)?.[0]||void 0,n=o?{contentRef:o,renderForm:!0,withHashLinkBlocks:!0}:{renderForm:!0,withHashLinkBlocks:!0},s=await t.call(n);let i;try{i="string"==typeof s?JSON.parse(s):s}catch{}if(i&&i.requiresForm&&i.formMessage){const r=new Map,o={input:e,chat_history:this.smartMemory.getMessages()},s=i.formMessage;r.set(s.id,{toolName:t.name,originalInput:o,originalToolInput:n,schema:null});const a=this.executor;"function"==typeof a.restorePendingForms&&a.restorePendingForms(r);const c=i.message||"Please complete the form to continue.";return{output:c,message:c,notes:[],requiresForm:!0,formMessage:s}}}catch{}return null}async processExecutorResult(t){let r="";if("string"==typeof t.output)r=t.output;else if(t.output)try{r=JSON.stringify(t.output)}catch{r=String(t.output)}let o={output:r,message:r,notes:[],intermediateSteps:t.intermediateSteps};if(t.requiresForm&&t.formMessage&&(o.formMessage=t.formMessage,o.requiresForm=!0),t.intermediateSteps&&Array.isArray(t.intermediateSteps)){const e=t.intermediateSteps.map((e,t)=>({id:`call_${t}`,name:e.action?.tool||"unknown",args:e.action?.toolInput||{},output:"string"==typeof e.observation?e.observation:JSON.stringify(e.observation)}));e.length>0&&(o.tool_calls=e),this.persistIntermediateSteps(t.intermediateSteps)}const n=t?.intermediateSteps||[],s=[...n].reverse().find(e=>"string"==typeof e?.observation&&this.isJSON(e.observation))?.observation;if(s)try{const e=JSON.parse(s);if(D.isInscriptionResponse(e)){const t=D.formatInscriptionResponse(e);o.output=t,o.message=t,e.inscription&&(o.inscription=e.inscription),e.metadata&&(o.metadata={...o.metadata,...e.metadata})}else"string"==typeof e.message&&e.message.trim().length>0&&(o.message=e.message,o.output=e.message),!0===e.success&&delete o.error,"string"==typeof e.transactionBytes&&(o.metadata={...o.metadata,transactionBytes:e.transactionBytes}),"string"==typeof e.scheduleId&&(o.scheduleId=e.scheduleId);const t=this.processHashLinkBlocks(e);t.hashLinkBlock&&(o.metadata={...o.metadata,...t})}catch(a){this.logger.error("Error parsing intermediate steps:",a)}if(o.output&&""!==o.output.trim()||(o.output="Agent action complete."),o.output&&this.smartMemory.addMessage(new m.AIMessage(o.output)),this.tokenTracker){const t=this.tokenTracker.getLatestTokenUsage();t&&(o.tokenUsage=t,o.cost=e.calculateTokenCostSync(t))}const i=this.smartMemory.getMemoryStats();return o.metadata={...o.metadata,memoryStats:{activeMessages:i.totalActiveMessages,tokenUsage:i.currentTokenCount,maxTokens:i.maxTokens,usagePercentage:i.usagePercentage}},this.logger.info("LangChainAgent.chat returning response:",o),o}loadContextMessages(e){if(!this.smartMemory||!e?.messages||0===e.messages.length)return;const t=this.smartMemory.getMessages(),r=new Set(t.map(e=>`${e.constructor.name}:${e.content}`));for(const o of e.messages){let e,t;if(o instanceof m.HumanMessage||o instanceof m.AIMessage||o instanceof m.SystemMessage)e=o.constructor,t=o.content;else{if(!(o&&"object"==typeof o&&"content"in o&&"type"in o))continue;{t=String(o.content);const r=String(o.type);if("human"===r)e=m.HumanMessage;else if("ai"===r)e=m.AIMessage;else{if("system"!==r)continue;e=m.SystemMessage}}}const n=`${e.name}:${t}`;r.has(n)||(this.smartMemory.addMessage(new e(t)),r.add(n))}}async boot(){if(this.logger.info("🚨🚨🚨 LANGCHAIN AGENT BOOT METHOD CALLED 🚨🚨🚨"),this.initialized)this.logger.warn("Agent already initialized");else try{this.agentKit=await this.createAgentKit(),await this.agentKit.initialize();const t=this.config.ai?.modelName||process.env.OPENAI_MODEL_NAME||"gpt-4o-mini";try{"function"==typeof e.TokenUsageCallbackHandler?this.tokenTracker=new e.TokenUsageCallbackHandler(t):this.logger.warn("TokenUsageCallbackHandler unavailable or not a constructor; skipping token tracking")}catch{this.logger.warn("TokenUsageCallbackHandler threw; skipping token tracking")}this.toolRegistry=new ae(this.logger);const r=this.agentKit.getAggregatedLangChainTools();this.logger.info("=== TOOL REGISTRATION START ==="),this.logger.info("All tools from agentKit:",r.map(e=>e.name));const o=this.filterTools(r);this.logger.info("Filtered tools for registration:",o.map(e=>e.name));for(const e of o){this.logger.info(`🔧 Registering tool: ${e.name}`);const t={},r=e.name.toLowerCase(),o=e.description?.toLowerCase()||"";if("hedera-hts-mint-nft"===e.name){const t=e.call.bind(e);e.call=async e=>{if(e.metaOptions&&"object"==typeof e.metaOptions){const t=e.metaOptions;t.transactionMemo&&(this.logger.warn("🚨 WORKAROUND: Stripping transactionMemo from hedera-hts-mint-nft to avoid bug",{originalMemo:t.transactionMemo}),delete t.transactionMemo)}return t(e)}}(r.includes("inscribe")||r.includes("hashinal")||o.includes("inscribe")||o.includes("hashinal"))&&(t.forceWrapper=!0,t.metadata={category:"core",version:"1.0.0",dependencies:[]},this.logger.info(`🎯 CRITICAL TOOL DEBUG - ${e.name} schema:`,{hasSchema:!!e.schema,schemaType:e.schema?.constructor?.name,hasRenderConfig:!!e.schema?._renderConfig,renderConfig:e.schema?._renderConfig})),this.toolRegistry.registerTool(e,t)}this.tools=this.toolRegistry.getAllTools(),this.logger.info(`🚀 TOOLS REGISTERED: ${this.tools.length} tools`);const n=this.toolRegistry.getStatistics();this.logger.info("📊 Tool Registry Statistics:",{total:n.totalTools,wrapped:n.wrappedTools,unwrapped:n.unwrappedTools,categories:n.categoryCounts,priorities:n.priorityCounts});const s=this.getInscriptionTool();if(s){this.toolRegistry.getTool(s.name)&&this.logger.info(`✅ Inscription tool registered: ${s.name}`)}const i=this.toolRegistry.getToolNames(),a=new Set(i);if(i.length!==a.size){this.logger.error("DUPLICATE TOOL NAMES DETECTED in registry!");const e=i.filter((e,t)=>i.indexOf(e)!==t);throw new Error(`Duplicate tool names detected: ${e.join(", ")}`)}this.config.mcp?.servers&&this.config.mcp.servers.length>0&&(!1!==this.config.mcp.autoConnect?await this.initializeMCP():(this.logger.info("MCP servers configured but autoConnect=false, skipping synchronous connection"),this.mcpManager=new U(this.logger))),this.smartMemory=new ne({modelName:t,maxTokens:9e4,reserveTokens:1e4,storageLimit:1e3}),this.logger.info("SmartMemoryManager initialized:",{modelName:t,toolsCount:this.tools.length,maxTokens:9e4,reserveTokens:1e4}),this.formEngine=new B(this.logger),this.executionPipeline=new ce(this.toolRegistry,this.formEngine,this.smartMemory,this.logger),this.systemMessage=this.buildSystemPrompt(),this.smartMemory.setSystemPrompt(this.systemMessage),await this.createExecutor(),this.initialized=!0,this.logger.info("LangChain Hedera agent initialized with ToolRegistry")}catch(t){throw this.logger.error("Failed to initialize agent:",t),t}}async chat(e,t){if(!this.initialized||!this.executor||!this.smartMemory)throw new Error("Agent not initialized. Call boot() first.");try{const r=await this.handleToolExecution(e,t);if(r)return r;const o=await this.handleDirectToolExecution(e);if(o)return o;const n=await this.handleJsonToolCalls(e,t);if(n)return n;const s=await this.handleContentRefMessages(e);if(s)return s;this.logger.info("LangChainAgent.chat called with:",{message:e,contextLength:t?.messages?.length||0}),this.loadContextMessages(t),this.smartMemory.addMessage(new m.HumanMessage(e));const i=this.smartMemory.getMemoryStats();this.logger.info("Memory stats before execution:",{totalMessages:i.totalActiveMessages,currentTokens:i.currentTokenCount,maxTokens:i.maxTokens,usagePercentage:i.usagePercentage,toolsCount:this.tools.length});const a=this.smartMemory.getMessages();this.logger.info("Current messages in memory:",{count:a.length});try{const e=a.map(e=>String(e.content||"")).filter(e=>"string"==typeof e&&(e.includes("[instruction:")||e.includes("[tool-next-steps:")));e.length>0&&this.logger.info("Instruction/next-steps messages in memory:",{messages:e})}catch{}const c=await this.executor.invoke({input:e,chat_history:a});return this.logger.info("LangChainAgent executor result:",c),this.processExecutorResult(c)}catch(r){return this.logger.error("LangChainAgent.chat error:",r),this.handleError(r)}}async shutdown(){this.mcpManager&&await this.mcpManager.disconnectAll(),this.smartMemory&&(this.smartMemory.dispose(),this.smartMemory=void 0),this.toolRegistry&&this.toolRegistry.clear(),this.executor=void 0,this.agentKit=void 0,this.tools=[],this.initialized=!1,this.logger.info("Agent cleaned up")}switchMode(e){this.config.execution?this.config.execution.operationalMode=e:this.config.execution={operationalMode:e},this.agentKit&&(this.agentKit.operationalMode=e),this.systemMessage=this.buildSystemPrompt(),this.logger.info(`Operational mode switched to: ${e}`)}getUsageStats(){if(!this.tokenTracker)return{promptTokens:0,completionTokens:0,totalTokens:0,cost:{totalCost:0}};const t=this.tokenTracker.getTotalTokenUsage(),r=e.calculateTokenCostSync(t);return{...t,cost:r}}getUsageLog(){return this.tokenTracker?this.tokenTracker.getTokenUsageHistory().map(t=>({...t,cost:e.calculateTokenCostSync(t)})):[]}clearUsageStats(){this.tokenTracker&&(this.tokenTracker.reset(),this.logger.info("Usage statistics cleared"))}getMCPConnectionStatus(){return new Map(this.mcpConnectionStatus)}async processFormSubmission(t,r){if(!this.initialized||!this.executor||!this.smartMemory)throw new Error("Agent not initialized. Call boot() first.");try{if(!t.parameters||"object"!=typeof t.parameters){this.logger.error("Invalid form submission parameters:",{parameters:t.parameters,type:typeof t.parameters});const e=JSON.stringify(t,null,2);return this.handleError(new Error(`Invalid form submission parameters: ${e}`))}this.loadContextMessages(r);const n={...t,parameters:t.parameters||{}},s=await this.executor.processFormSubmission(n),i=s?.metadata?{...s.metadata}:{};try{const e=s.rawToolOutput,t=s.toolName||"unknown";if("string"==typeof e&&e.trim().length>0){const r=this.isJSON(e)?e:JSON.stringify({output:e});this.addToolRawToMemory(t,r)}}catch{}let a="Form processed successfully.";if("string"==typeof s.output)a=s.output;else if(s.output)try{a=JSON.stringify(s.output)}catch{a=String(s.output)}let c={output:a,message:a,notes:[],intermediateSteps:s.intermediateSteps};if(s.metadata&&(c.metadata={...c.metadata,...s.metadata},this.logger.info("🔍 DEBUG: Metadata after merge from result:",{hasMetadata:!!c.metadata,metadataKeys:c.metadata?Object.keys(c.metadata):[],hasHashLinkBlock:le(c.metadata),hashLinkBlockContent:le(c.metadata)?c.metadata.hashLinkBlock:void 0})),s.requiresForm&&s.formMessage&&(c.formMessage=s.formMessage,c.requiresForm=!0),s.intermediateSteps&&Array.isArray(s.intermediateSteps)){const e=s.intermediateSteps.map((e,t)=>{const r=e?.action?.tool||"unknown",o=e?.action?.toolInput||{},n=e?.observation;let s="";if("string"==typeof n)s=n;else if(n&&"object"==typeof n)try{s=JSON.stringify(n)}catch{s=String(n)}else void 0!==n&&(s=String(n));return{id:`call_${t}`,name:r,args:o,output:s}});e.length>0&&(c.tool_calls=e),this.persistIntermediateSteps(s.intermediateSteps)}const l=s?.intermediateSteps?.[0]?.observation;if(l&&"string"==typeof l&&this.isJSON(l))try{const e=JSON.parse(l);c={...c,...e};const t=this.processHashLinkBlocks(e);t.hashLinkBlock&&(c.metadata={...c.metadata,...t})}catch(o){this.logger.error("Error parsing intermediate steps:",o)}if(c.output&&this.smartMemory.addMessage(new m.AIMessage(c.output)),this.tokenTracker){const t=this.tokenTracker.getLatestTokenUsage();t&&(c.tokenUsage=t,c.cost=e.calculateTokenCostSync(t))}const g=this.smartMemory.getMemoryStats();return this.logger.info("🔍 DEBUG: Metadata before memoryStats merge:",{hasMetadata:!!c.metadata,metadataKeys:c.metadata?Object.keys(c.metadata):[],hasHashLinkBlock:le(c.metadata)}),c.metadata={...i,...c.metadata,memoryStats:{activeMessages:g.totalActiveMessages,tokenUsage:g.currentTokenCount,maxTokens:g.maxTokens,usagePercentage:g.usagePercentage}},this.logger.info("🔍 DEBUG: Final response metadata before return:",{hasMetadata:!!c.metadata,metadataKeys:c.metadata?Object.keys(c.metadata):[],hasHashLinkBlock:le(c.metadata),fullMetadata:c.metadata}),le(i)&&!le(c.metadata)&&(this.logger.error("❌ CRITICAL: HashLink metadata was lost during processing!"),this.logger.error("Original metadata had hashLinkBlock:",i.hashLinkBlock),this.logger.error("Final metadata missing hashLinkBlock")),c}catch(o){return this.logger.error("Form submission processing error:",o),this.handleError(o)}}hasPendingForms(){return!!this.executor&&this.executor.hasPendingForms()}getPendingFormsInfo(){return this.executor?this.executor.getPendingFormsInfo():[]}async createAgentKit(){const t=[...e.getAllHederaCorePlugins(),...this.config.extensions?.plugins||[]],r=this.config.execution?.operationalMode||"returnBytes",o=this.config.ai?.modelName||"gpt-4o";return new e.HederaAgentKit(this.config.signer,{plugins:t},r,this.config.execution?.userAccountId,this.config.execution?.scheduleUserTransactionsInBytesMode??!1,void 0,o,this.config.extensions?.mirrorConfig,this.config.debug?.silent??!1)}async createExecutor(){const e=this.executor?.getPendingForms()||new Map;let t;if(this.config.ai?.provider&&this.config.ai.provider.getModel)t=this.config.ai.provider.getModel();else if(this.config.ai?.llm)t=this.config.ai.llm;else{const e=this.config.ai?.apiKey||process.env.OPENAI_API_KEY;if(!e)throw new Error("OpenAI API key required");const r=this.config.ai?.modelName||"gpt-4o-mini",o=r.toLowerCase().includes("gpt-5")||r.toLowerCase().includes("gpt5");t=new g.ChatOpenAI({apiKey:e,modelName:r,callbacks:this.tokenTracker?[this.tokenTracker]:[],...o?{temperature:1}:{}})}const r=l.ChatPromptTemplate.fromMessages([["system",this.systemMessage],new l.MessagesPlaceholder("chat_history"),["human","{input}"],new l.MessagesPlaceholder("agent_scratchpad")]),o=this.tools,n=this.getInscriptionTool();if(n){this.toolRegistry.getTool(n.name)&&this.logger.info(`✅ Inscription tool registered: ${n.name}`)}const s=this.toolRegistry.getStatistics();this.logger.info("🛡️ TOOL SECURITY REPORT:",{totalTools:s.totalTools,wrappedTools:s.wrappedTools,unwrappedTools:s.unwrappedTools,categories:s.categoryCounts,priorities:s.priorityCounts}),this.logger.info(`📊 Tool Security Summary: ${s.wrappedTools} wrapped, ${s.unwrappedTools} unwrapped`);const i=await a.createOpenAIToolsAgent({llm:t,tools:o,prompt:r});this.executor=new z({agent:i,tools:o,verbose:this.config.debug?.verbose??!1,returnIntermediateSteps:!0}),this.pendingParameterPreprocessingCallback&&(this.executor.setParameterPreprocessingCallback(this.pendingParameterPreprocessingCallback),this.logger.info("Parameter preprocessing callback re-applied to new executor",{hasCallback:!0})),e.size>0&&(this.logger.info(`Restoring ${e.size} pending forms to new executor`),this.executor.restorePendingForms(e)),this.logger.info("FormAwareAgentExecutor initialization complete")}setParameterPreprocessingCallback(e){this.pendingParameterPreprocessingCallback=e,this.executor?(this.executor.setParameterPreprocessingCallback(e),this.logger.info("Parameter preprocessing callback configured",{hasCallback:!!e})):this.logger.warn("Cannot set parameter preprocessing callback: executor not initialized")}handleError(t){const r=t instanceof Error?t.message:"Unknown error";let o,n;this.logger.error("Chat error:",t),this.tokenTracker&&(o=this.tokenTracker.getLatestTokenUsage(),o&&(n=e.calculateTokenCostSync(o)));let s=r,i=r;r.includes("429")?r.includes("quota")?(s="API quota exceeded. Please check your OpenAI billing and usage limits.",i="I'm currently unable to respond because the API quota has been exceeded. Please check your OpenAI account billing and usage limits, then try again."):(s=A,i=F):r.includes("401")||r.includes("unauthorized")?(s="API authentication failed. Please check your API key configuration.",i="There's an issue with the API authentication. Please check your OpenAI API key configuration in settings."):r.includes("timeout")?(s="Request timed out. Please try again.",i="The request took too long to process. Please try again."):r.includes("network")||r.includes("fetch")?(s="Network error. Please check your internet connection and try again.",i="There was a network error. Please check your internet connection and try again."):r.includes("400")&&(s=r,i=r);const a={output:i,message:s,error:r,notes:[]};return o&&(a.tokenUsage=o),n&&(a.cost=n),a}async initializeMCP(){this.mcpManager=new U(this.logger);for(const e of this.config.mcp.servers){if(!1===e.autoConnect){this.logger.info(`Skipping MCP server ${e.name} (autoConnect=false)`);continue}const t=await this.mcpManager.connectServer(e);if(t.connected){this.logger.info(`Connected to MCP server ${t.serverName} with ${t.tools.length} tools`);for(const r of t.tools){const t=K(r,this.mcpManager,e);this.toolRegistry.registerTool(t,{metadata:{category:"mcp",version:"1.0.0",dependencies:[e.name]}})}this.tools=this.toolRegistry.getAllTools()}else this.logger.error(`Failed to connect to MCP server ${t.serverName}: ${t.error}`)}}async connectMCPServers(){this.config.mcp?.servers&&0!==this.config.mcp.servers.length&&(this.mcpManager||(this.mcpManager=new U(this.logger)),this.logger.info(`Starting background MCP server connections for ${this.config.mcp.servers.length} servers...`),this.config.mcp.servers.forEach(e=>{this.connectServerInBackground(e)}),this.logger.info("MCP server connections initiated in background"))}connectServerInBackground(e){const t=e.name;setTimeout(async()=>{try{this.logger.info(`Background connecting to MCP server: ${t}`);const r=await this.mcpManager.connectServer(e);if(this.mcpConnectionStatus.set(t,r),r.connected){this.logger.info(`Successfully connected to MCP server ${r.serverName} with ${r.tools.length} tools`);for(const t of r.tools){const r=K(t,this.mcpManager,e);this.toolRegistry.registerTool(r,{metadata:{category:"mcp",version:"1.0.0",dependencies:[e.name]}})}this.tools=this.toolRegistry.getAllTools(),this.initialized&&this.executor&&(this.logger.info(`Recreating executor with ${this.tools.length} total tools`),await this.createExecutor())}else this.logger.error(`Failed to connect to MCP server ${r.serverName}: ${r.error}`)}catch(r){this.logger.error(`Background connection failed for MCP server ${t}:`,r),this.mcpConnectionStatus.set(t,{connected:!1,serverName:t,tools:[],error:r instanceof Error?r.message:"Connection failed"})}},1e3)}processHashLinkBlocks(e){try{const t=e;if(e&&"object"==typeof e&&t.hashLinkBlock&&"object"==typeof t.hashLinkBlock){const e=t.hashLinkBlock;if(e.blockId&&e.hashLink&&e.template&&e.attributes&&"string"==typeof e.blockId&&"string"==typeof e.hashLink&&"string"==typeof e.template&&"object"==typeof e.attributes)return this.logger.info("HashLink block detected:",{blockId:e.blockId,hashLink:e.hashLink,template:e.template,attributeKeys:Object.keys(e.attributes)}),{hashLinkBlock:{blockId:e.blockId,hashLink:e.hashLink,template:e.template,attributes:e.attributes}};this.logger.warn("Invalid HashLink block structure detected:",e)}}catch(t){this.logger.error("Error processing HashLink blocks:",t)}return{}}isJSON(e){if("string"!=typeof e)return!1;const t=e.trim();if(!t)return!1;if(!(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")))return!1;try{return JSON.parse(t),!0}catch{return!1}}}function he(e){const t=e.framework||"langchain";switch(t){case"langchain":return new ge(e);case"vercel":throw new Error("Vercel AI SDK support coming soon");case"baml":throw new Error("BAML support coming soon");default:throw new Error(`Unknown framework: ${t}`)}}class ue extends e.AbstractSigner{getAccountId(){return this.account}getNetwork(){return this.network}constructor(e,t,r){super(),this.account=n.AccountId.fromString(e),this.network=t,this.client="mainnet"===t?n.Client.forMainnet():n.Client.forTestnet(),this.exec=r??null,this.ephemeralKey=n.PrivateKey.generateED25519()}getOperatorPrivateKey(){return this.ephemeralKey}getClient(){return this.client}async signAndExecuteTransaction(e){if(!this.exec)throw new Error("BrowserSigner executor not available");e.isFrozen()||await e.freezeWith(this.client);const t=globalThis.Buffer.from(e.toBytes()).toString("base64"),{transactionId:o}=await this.exec(t,this.network),s=new r.HederaMirrorNode(this.network),i=Date.now()+6e4;for(;Date.now()<i;){try{const e=await s.getTransaction(o);if(e&&e.result)return n.TransactionReceipt.fromBytes(globalThis.Buffer.from(e.result,"base64"))}catch{}await new Promise(e=>setTimeout(e,1200))}return n.TransactionReceipt.fromBytes(globalThis.Buffer.from(""))}async getPublicKey(){const e="mainnet"===this.network?"mainnet":"testnet",t=new r.HederaMirrorNode(e,new r.Logger({module:"BrowserSigner"})),o=await t.getPublicKey(this.account.toString()),s="function"==typeof o?.toString?o.toString():String(o);return n.PublicKey.fromString(s)}}class me{constructor(e){this.model=e}async generate(e,t){const r=await this.model.invoke(e,t);return"string"==typeof r?r:r.toString()}async*stream(e,t){const r=await this.model.stream(e,t);for await(const o of r)yield"string"==typeof o?o:o.toString()}getModel(){return this.model}}let de=null;function pe(){return de}const fe=o.z.object({url:o.z.string().url(),maxCharacters:o.z.number().int().min(256,"Minimum length is 256 characters").max(8e3,"Maximum length is 8000 characters").optional().default(3e3)});class ye extends e.BaseHederaQueryTool{constructor(e){const{fetchImpl:t,...r}=e;super(r),this.name="web_page_snapshot",this.description="Fetches the visible text content of a web page for analysis.",this.namespace="browser",this.specificInputSchema=fe,this.fetchImpl=t??fetch}async executeQuery(e){const t=e.maxCharacters??3e3;try{const r=await this.fetchImpl(e.url,{redirect:"follow"});if(!r.ok)return`Failed to load ${e.url}: HTTP ${r.status}`;const o=await r.text(),n=this.normalizeHtml(o);return n?n.length>t?`${n.slice(0,t)}…`:n:"The fetched page did not contain readable text."}catch(r){return this.logger.error("WebPageSnapshotTool failed",r),`Failed to fetch content for ${e.url}: ${r instanceof Error?r.message:String(r)}`}}normalizeHtml(e){return e.replace(/<script[\s\S]*?<\/script>/gi," ").replace(/<style[\s\S]*?<\/style>/gi," ").replace(/<!--([\s\S]*?)-->/g," ").replace(/<[^>]+>/g," ").replace(/ /gi," ").replace(/&/gi,"&").replace(/</gi,"<").replace(/>/gi,">").replace(/"/gi,'"').replace(/'/gi,"'").replace(/\s+/g," ").trim()}}class we extends e.BasePlugin{constructor(){super(...arguments),this.id="web-browser",this.name="Web Browser Plugin",this.description="Provides tools for fetching live web page content to enrich assistant understanding.",this.version="0.1.0",this.author="Hashgraph Online",this.namespace="browser",this.tools=[]}async initialize(e){await super.initialize(e);const t=e.config.hederaKit;if(!t)return this.context.logger.warn("WebBrowserPlugin skipped because HederaAgentKit was not present in plugin context."),void(this.tools=[]);const r=new ye({hederaKit:t,logger:this.context.logger});this.tools=[r],this.context.logger.info("Web Browser Plugin initialized with snapshot tool")}getTools(){return this.tools}async cleanup(){this.tools=[]}}const Te=e=>`You are a helpful assistant managing Hashgraph Online HCS-10 connections, messages, HCS-2 registries, content inscription, and Hedera Hashgraph operations.\n\nYou have access to tools for:\n- HCS-10: registering agents, finding registered agents, initiating connections, listing active connections, sending messages over connections, and checking for new messages\n- HCS-2: creating registries, registering entries, updating entries, deleting entries, migrating registries, and querying registry contents\n- Inscription: inscribing content from URLs, files, or buffers, creating Hashinal NFTs, and retrieving inscriptions\n- Hedera Token Service (HTS): creating tokens, transferring tokens, airdropping tokens, and managing token operations\n\n\n*** IMPORTANT CONTEXT ***\nYou are currently operating as agent: ${e||"unknown"} on the Hedera Hashgraph\nWhen users ask about "my profile", "my account", "my connections", etc., use this account ID: ${e||"unknown"}\n\n*** CRITICAL ENTITY HANDLING RULES ***\n- When users refer to entities (tokens, topics, accounts) with pronouns like "it", "that", "the token/topic", etc., ALWAYS use the most recently created entity of that type\n- Entity IDs look like "0.0.XXXXXX" and are stored in memory after creation\n- NEVER use example or placeholder IDs like "0.0.123456" - always use actual created entity IDs\n- Account ID ${e} is NOT a token - tokens and accounts are different entities\n\n Remember the connection numbers when listing connections, as users might refer to them.`;class Se{constructor(e){this.storage=e}async storeContent(e,t){const r={contentType:"binary",sizeBytes:e.length,source:"system",...t};return(await this.storage.storeContent(e,r)).referenceId}async resolveReference(e){const t=await this.storage.resolveReference(e);if(t.success&&t.content){const e={content:t.content};return t.metadata&&(e.metadata={...void 0!==t.metadata.mimeType&&{mimeType:t.metadata.mimeType},...void 0!==t.metadata.fileName&&{fileName:t.metadata.fileName},originalSize:t.metadata.sizeBytes}),e}throw new Error(t.error||"Reference not found")}async hasReference(e){return await this.storage.hasReference(e)}async cleanupReference(e){await this.storage.cleanupReference(e)}async getStats(){return await this.storage.getStats()}async updateConfig(e){const t={sizeThresholdBytes:e.maxSize||10240,enableAutoCleanup:e.enableCompression||!0,...e};return await this.storage.updateConfig(t)}async performCleanup(){await this.storage.performCleanup()}async dispose(){return Promise.resolve(this.storage.dispose())}}class be{constructor(e){this.adapter=e}async resolveReference(e){return await this.adapter.resolveReference(e)}shouldUseReference(e){return r.shouldUseReference(e)}extractReferenceId(e){return r.extractReferenceId(e)}}class Ce{constructor(e=1e3,t,o){this.isRegistered=!1,this.logger=o||new r.Logger({module:"ContentStoreManager"}),this.contentStorage=new te(e,t),this.adapter=new Se(this.contentStorage),this.resolver=new be(this.adapter)}async initialize(){if(this.isRegistered)this.logger.warn("ContentStoreManager is already initialized");else try{r.ContentStoreService&&"function"==typeof r.ContentStoreService.setInstance?await r.ContentStoreService.setInstance(this.adapter):this.logger.warn("ContentStoreService.setInstance is unavailable; skipping registration"),r.ContentResolverRegistry&&"function"==typeof r.ContentResolverRegistry.register?r.ContentResolverRegistry.register(this.resolver):this.logger.warn("ContentResolverRegistry.register is unavailable; skipping registration"),this.isRegistered=!0,this.logger.info("ContentStoreManager initialized and registered for cross-package access")}catch(e){throw this.logger.error("Failed to initialize ContentStoreManager:",e),e}}getContentStorage(){return this.contentStorage}async getStats(){return await this.contentStorage.getStats()}async updateConfig(e){return await this.contentStorage.updateConfig(e)}async performCleanup(){return await this.contentStorage.performCleanup()}shouldUseReference(e){return this.contentStorage.shouldUseReference(e)}async storeContentIfLarge(e,t){const r={source:"system",contentType:"binary",...t};return await this.contentStorage.storeContentIfLarge(e,r)}async dispose(){this.isRegistered&&(this.contentStorage.dispose(),r.ContentStoreService&&"function"==typeof r.ContentStoreService.dispose&&r.ContentStoreService.dispose(),r.ContentResolverRegistry&&"function"==typeof r.ContentResolverRegistry.unregister&&r.ContentResolverRegistry.unregister(),this.isRegistered=!1,this.logger.info("ContentStoreManager disposed and unregistered"))}isInitialized(){return this.isRegistered}}const ke=new r.Logger({module:"EntityResolverTool"}),ve=o.z.object({message:o.z.string().describe("The message containing entity references to resolve"),entities:o.z.array(o.z.object({entityId:o.z.string(),entityName:o.z.string(),entityType:o.z.string()})).describe("Available entities in memory")}),Ie=o.z.object({response:o.z.string().describe("Agent response text to extract entities from"),userMessage:o.z.string().describe("Original user message for context")});class xe extends i.StructuredTool{constructor(e){super(),this.name="resolve_entities",this.description='Resolves entity references like "the topic", "it", "that" to actual entity IDs',this.schema=ve,this.llm=e}async _call(e){const{message:t,entities:r}=e;if(!r||0===r.length)return t;const o=this.groupEntitiesByType(r),n=`Task: Replace entity references with IDs.\n\n${this.buildEntityContext(o)}\n\nMessage: "${t}"\n\nRules:\n- "the topic" or "that topic" → replace with most recent topic ID\n- "the token" or "that token" → replace with most recent token ID\n- "it" or "that" after action verb → replace with most recent entity ID\n- "airdrop X" without token ID → add most recent token ID as first parameter\n- Token operations without explicit token → use most recent token ID\n\nExamples:\n- "submit on the topic" → "submit on 0.0.6543472"\n- "airdrop the token" → "airdrop 0.0.123456"\n- "airdrop 10 to 0.0.5842697" → "airdrop 0.0.123456 10 to 0.0.5842697"\n- "mint 100" → "mint 0.0.123456 100"\n\nReturn ONLY the resolved message:`;try{return(await this.llm.invoke(n)).content.trim()}catch(s){return ke.error("ResolveEntitiesTool failed:",s),t}}groupEntitiesByType(e){return e.reduce((e,t)=>(e[t.entityType]||(e[t.entityType]=[]),e[t.entityType].push(t),e),{})}buildEntityContext(e){let t="Available entities:\n";for(const[r,o]of Object.entries(e)){const e=o[0];t+=`- Most recent ${r}: "${e.entityName}" = ${e.entityId}\n`}return t}}class Me extends i.StructuredTool{constructor(e){super(),this.name="extract_entities",this.description="Extracts newly created entities from agent responses",this.schema=Ie,this.llm=e}async _call(e){const{response:t,userMessage:r}=e,o=`Extract ONLY newly created entities from this response.\n\nUser asked: "${r.substring(0,200)}"\nResponse: ${t.substring(0,3e3)}\n\nLook for:\n- Success messages with new entity IDs\n- Words like "created", "new", "successfully" followed by entity IDs\n\nReturn JSON array of created entities:\n[{"id": "0.0.XXX", "name": "name", "type": "topic|token|account"}]\n\nIf none created, return: []\n\nJSON:`;try{const e=await this.llm.invoke(o),t=e.content.match(/\[[\s\S]*?\]/);return t?t[0]:"[]"}catch(n){return ke.error("ExtractEntitiesTool failed:",n),"[]"}}}function Re(e){return{resolveEntities:new xe(e),extractEntities:new Me(e)}}class Ae{constructor(){this.converters=new Map,this.entityTypeCache=new Map,this.logger=new r.Logger({module:"FormatConverterRegistry"}),this.defaultCacheTTL=3e5}register(e){const t=`${e.sourceFormat}→${e.targetFormat}`;this.converters.set(t,e)}findConverter(e,t){const r=`${e}→${t}`;return this.converters.get(r)||null}async convertEntity(e,t,r){const o=await this.detectFormatWithFallback(e,r);if(o===t)return e;const n=this.findConverter(o,t);if(!n)throw new Error(`No converter found for ${o} → ${t}`);if(!n.canConvert(e,r))throw new Error(`Converter cannot handle entity: ${e}`);return await n.convert(e,r)}async detectFormatWithFallback(e,t){if(e.startsWith("hcs://"))return E.HRL;if(/^0\.0\.\d+$/.test(e)){const o=this.getCachedFormat(e);if(o)return o;try{const r=await this.detectFormat(e,t||{});if(r!==E.ANY)return this.setCachedFormat(e,r),r}catch(r){this.logger.warn(`Entity detection failed for ${e}, using fallback: ${r.message}`)}return E.ANY}return E.ANY}async detectEntityFormat(e,t){return this.detectFormatWithFallback(e,t)}async detectFormat(e,t){const o=t.networkType||"testnet",n=new r.HederaMirrorNode(o,this.logger);n.configureRetry({maxRetries:3,maxDelayMs:1e3});const s=(await Promise.allSettled([n.getAccountBalance(e).then(e=>null!==e?E.ACCOUNT_ID:null).catch(()=>null),n.getTokenInfo(e).then(e=>null!==e?E.TOKEN_ID:null).catch(()=>null),n.getTopicInfo(e).then(e=>null!==e?E.TOPIC_ID:null).catch(()=>null),n.getContract(e).then(e=>null!==e?E.CONTRACT_ID:null).catch(()=>null)])).find(e=>"fulfilled"===e.status&&null!==e.value);return s&&"fulfilled"===s.status?s.value:E.ANY}getCachedFormat(e){const t=this.entityTypeCache.get(e);return!t||this.isCacheExpired(t)?(this.entityTypeCache.delete(e),null):t.format}setCachedFormat(e,t){this.entityTypeCache.set(e,{format:t,timestamp:Date.now(),ttl:this.defaultCacheTTL})}isCacheExpired(e){return Date.now()-e.timestamp>e.ttl}getRegisteredConverters(){return Array.from(this.converters.keys()).map(e=>{const[t,r]=e.split("→");return{source:t,target:r}})}hasConverter(e,t){return null!==this.findConverter(e,t)}clear(){this.converters.clear()}clearCache(){this.entityTypeCache.clear()}}class Fe{constructor(){this.sourceFormat=E.TOPIC_ID,this.targetFormat=E.HRL}canConvert(e,t){return/^0\.0\.\d+$/.test(e)}async convert(e,t){return`hcs://${"mainnet"===(t.networkType||"testnet")?"0":"1"}/${e}`}}const Ee=class{constructor(){this.sourceFormat=E.ANY,this.targetFormat=E.HRL}canConvert(e,t){if("string"!=typeof e)return!1;if(/^hcs:\/\/\d\/0\.0\.\d+$/i.test(e))return!1;if(/inscription-cdn\/(0\.0\.\d+)/i.test(e))return!0;if(/^content-ref:(0\.0\.\d+)$/i.test(e))return!0;if(/^0\.0\.\d+$/.test(e)){return Boolean("hrl"===t?.toolPreferences?.inscription||"hrl"===t?.toolPreferences?.topic)}return!1}async convert(e,t){const o=t.toolPreferences,n=o?.hrlStandard||o?.inscriptionHrlStandard||"1",s=t.networkType||"testnet",i=new r.HRLResolver,a=e.match(/inscription-cdn\/(0\.0\.\d+)/i);if(a&&a[1])try{const e=new r.HederaMirrorNode(s);e.configureRetry({maxRetries:3,maxDelayMs:1e3});const t=await e.getTopicInfo(a[1]),o=(t&&t.memo||"").match(/^hcs-(\d+)/);return`hcs://${o&&o[1]?o[1]:"1"}/${a[1]}`}catch{return`hcs://${n}/${a[1]}`}const c=e.match(/^content-ref:(0\.0\.\d+)$/i);if(c&&c[1])try{const e=await i.resolve(c[1],{network:s}),t=i.parseHRL(`hcs://1/${e.topicId}`);return`hcs://${t?.standard||n}/${e.topicId}`}catch{return`hcs://${n}/${c[1]}`}if(/^0\.0\.\d+$/.test(e))try{const t=await i.resolve(e,{network:s}),r=i.parseHRL(`hcs://1/${t.topicId}`);return`hcs://${r?.standard||n}/${t.topicId}`}catch{return`hcs://${n}/${e}`}return e}};Ee.standardCache=new Map;let Pe=Ee;class Oe{constructor(e,t){this.logger=new r.Logger({module:"ParameterService"}),this.formatConverterRegistry=e,this.networkType=t}async preprocessParameters(e,t,r=[],o){const n=o?.sessionId,s=o?.entityResolver,i=o?.preferences;let a={...t};if(s&&r.length>0)try{this.logger.info("AI-driven preprocessing phase",{toolName:e,entityCount:r.length,sessionId:n});const t={...a};for(const[e,o]of Object.entries(a))if("string"==typeof o){const n=await s.resolveReferences(o,r),a=await this.convertParameterEntities(n,r,i);t[e]=a}else if(Array.isArray(o)){const n=[];for(const e of o)if("string"==typeof e){const t=await s.resolveReferences(e,r),o=await this.convertParameterEntities(t,r,i);n.push(o)}else n.push(e);t[e]=n}a=t}catch(c){const t=c instanceof Error?c.message:"unknown";this.logger.warn("AI phase failed; continuing with deterministic pass",{toolName:e,error:t})}try{const e={...a};for(const[t,o]of Object.entries(a))if("string"==typeof o){const n=await this.convertParameterEntities(o,r,i);e[t]=n}else if(Array.isArray(o)){const n=[];for(const e of o)if("string"==typeof e){const t=await this.convertParameterEntities(e,r,i);n.push(t)}else n.push(e);e[t]=n}a=e}catch(l){this.logger.warn("Deterministic post-pass failed",{toolName:e,error:l instanceof Error?l.message:"unknown"})}return a}attachToAgent(e,t){const r=t?.getSessionId??(()=>null),o=t?.getEntities??(async()=>[]),n=t?.entityResolver,s=e,i=e=>{const t=e;return"function"==typeof t.setParameterPreprocessingCallback&&(t.setParameterPreprocessingCallback(async(e,t)=>{const s=r(),i=await o(s),a={};return n&&(a.entityResolver=n),s&&(a.sessionId=s),this.preprocessParameters(e,t,i,a)}),this.logger.info("Parameter preprocessing callback attached"),!0)};if(!i(e)&&"function"==typeof s.getAgent){const e=s.getAgent();e&&i(e)}}async preprocessToolParameters(e,t,r,o){try{if(!r||0===r.length)return this.logger.info("Tool parameter preprocessing skipped - no entities provided:",{toolName:e,originalParams:Object.keys(t)}),t;const n={...t},s=void 0;let i=!1;for(const[o,a]of Object.entries(t))if("string"==typeof a){const t=await this.convertParameterEntities(a,r,s);t!==a&&(n[o]=t,i=!0,this.logger.info("Parameter entity conversion applied:",{toolName:e,paramName:o,original:a,converted:t}))}else if(Array.isArray(a)){const t=a,c=[];let l=!1;for(const n of t)if("string"==typeof n){const t=await this.convertParameterEntities(n,r,s);c.push(t),t!==n&&(l=!0,this.logger.info("Parameter array item conversion applied:",{toolName:e,paramName:o,original:n,converted:t}))}else c.push(n);l&&(n[o]=c,i=!0)}return this.logger.info("Tool parameter preprocessing completed:",{toolName:e,originalParams:Object.keys(t),hasChanges:i,sessionId:o}),n}catch(n){return this.logger.warn("Tool parameter preprocessing failed:",{toolName:e,error:n instanceof Error?n.message:"Unknown error"}),t}}async convertParameterEntities(e,t,r){let o=e;for(const s of t){const e=o.includes(s.entityId),t=o.includes(s.entityName);if(!e&&!t)continue;let i=null;if(s.entityType===E.TOPIC_ID?"hrl"===r?.inscription||"hrl"===r?.topic?i=E.HRL:"topicId"!==r?.inscription&&"topicId"!==r?.topic||(i=E.TOPIC_ID):s.entityType===E.TOKEN_ID?"tokenId"===r?.token?i=E.TOKEN_ID:"symbol"===r?.token&&(i=E.SYMBOL):s.entityType===E.ACCOUNT_ID&&("accountId"===r?.account||"accountId"===r?.supplyKey||"accountId"===r?.adminKey?i=E.ACCOUNT_ID:"alias"===r?.account&&(i=E.ALIAS)),i)try{const n={networkType:this.networkType,sessionId:"unknown"};r&&(n.toolPreferences=r);const a=await this.formatConverterRegistry.convertEntity(s.entityId,i,n);e&&(o=o.replace(new RegExp(`\\b${s.entityId.replace(/\./g,"\\.")}\\b`,"g"),a)),t&&(o=o.replace(new RegExp(`\\b${s.entityName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"g"),a)),this.logger.info("Applied format conversion to parameter:",{entityId:s.entityId,entityType:s.entityType,targetFormat:i,convertedValue:a,parameterValue:o})}catch(n){this.logger.warn("Format conversion failed for parameter:",{entityId:s.entityId,targetFormat:i,error:n instanceof Error?n.message:"Unknown error"})}}return o}}const Ne="gpt-4o",Le="gpt-4o-mini",$e="claude-3-7-sonnet-latest",Be=.1,De="testnet",_e="autonomous",ze=class o{constructor(e){if(this.options=e,this.stateManager=e.stateManager||new t.OpenConvaiState,this.hcs10Plugin=new y,this.hcs2Plugin=new w,this.inscribePlugin=new S,this.hbarPlugin=new x,this.webBrowserPlugin=new we,this.logger=new r.Logger({module:"ConversationalAgent",silent:e.disableLogging||!1}),!1!==this.options.entityMemoryEnabled){if(!e.openAIApiKey)throw new Error("OpenAI/Anthropic API key is required when entity memory is enabled");this.memoryManager=new ne(this.options.entityMemoryConfig),this.logger.info("Entity memory initialized");const t=e.entityMemoryProvider||e.llmProvider||"openai";let r,o=e.entityMemoryModelName;if(o||(o="anthropic"===t?$e:"openrouter"===t?"openai/gpt-4o-mini":Le),"anthropic"===t)r=new f.ChatAnthropic({apiKey:e.openAIApiKey,model:o,temperature:0});else if("openrouter"===t){const t=e.openRouterBaseURL||"https://openrouter.ai/api/v1",n=e.openRouterApiKey||e.openAIApiKey;r=new g.ChatOpenAI({apiKey:n,model:o,temperature:0,configuration:{baseURL:t,defaultHeaders:{"HTTP-Referer":process.env.OPENROUTER_REFERRER||"https://hashgraphonline.com","X-Title":process.env.OPENROUTER_TITLE||"Hashgraph Online Conversational Agent"}}})}else r=new g.ChatOpenAI({apiKey:e.openAIApiKey,model:o,temperature:0});this.entityTools=Re(r),this.logger.info("LLM-based entity resolver tools initialized")}}async initialize(){const{accountId:r,privateKey:o,network:n=De,openAIApiKey:s,openAIModelName:i=Ne,llmProvider:a="openai"}=this.options;this.validateOptions(r,o);try{const h=this.options.operationalMode||_e,u="autonomous"!==h;let m,d;try{const e=t.InscriberBuilder;"function"==typeof e.setPreferWalletOnly&&e.setPreferWalletOnly(!1)}catch(c){this.logger.warn("Failed to set wallet-only preference",c)}if(u){const e="mainnet"===String(n||"testnet")?"mainnet":"testnet",t=this.options.userAccountId||r;m=new ue(t,e,this.options.walletExecutor)}else m=new e.ServerSigner(r,o,n);this.logger.info("Signer configured",{operationalMode:h,bytesMode:u,signerClass:Object.getPrototypeOf(m)?.constructor?.name||"unknown"});try{const e=pe();if(e){const r=t.InscriberBuilder;"function"==typeof r.setWalletInfoResolver&&r.setWalletInfoResolver(async()=>{const t=await e.status();return t.connected&&t.accountId&&t.network?{accountId:t.accountId,network:t.network}:null}),"function"==typeof r.setWalletExecutor&&r.setWalletExecutor(async(t,r)=>await e.executeBytes(t,r)),"function"==typeof r.setStartInscriptionDelegate&&e.startInscription&&r.setStartInscriptionDelegate(async(t,r)=>await e.startInscription(t,r));try{const r=await e.status(),o=!(!u||!r.connected);t.SignerProviderRegistry.setWalletInfoResolver(async()=>{const t=await e.status();return t.connected&&t.accountId&&t.network?{accountId:t.accountId,network:t.network}:null}),t.SignerProviderRegistry.setWalletExecutor(async(t,r)=>await e.executeBytes(t,r));const n=e;"function"==typeof n?.startHCS?t.SignerProviderRegistry.setStartHCSDelegate(async(e,t,r)=>await n.startHCS(e,t,r)):t.SignerProviderRegistry.setStartHCSDelegate(null),t.SignerProviderRegistry.setPreferWalletOnly(o);const s=t.InscriberBuilder;"function"==typeof s.setPreferWalletOnly&&s.setPreferWalletOnly(o)}catch(l){this.logger.warn("Failed to wire SAK SignerProviderRegistry wallet delegates",l)}}}catch(c){this.logger.warn("Failed to register wallet bridge providers",c)}let p={provider:a};if("anthropic"===a)d=new f.ChatAnthropic({apiKey:s,model:i||$e,temperature:Be}),p={...p,model:i||$e,keyPresent:!!s};else if("openrouter"===a){const e=this.options.openRouterBaseURL||"https://openrouter.ai/api/v1",t=this.options.openRouterApiKey||s,r=i||"anthropic/claude-3-haiku-20240307";d=new g.ChatOpenAI({apiKey:t,model:r,temperature:Be,configuration:{baseURL:e,defaultHeaders:{"HTTP-Referer":process.env.OPENROUTER_REFERRER||"https://hashgraphonline.com","X-Title":process.env.OPENROUTER_TITLE||"Hashgraph Online Conversational Agent"}}}),p={...p,model:r,baseURL:e,keyPresent:!!t}}else{const e=i||Le,t=e.toLowerCase().includes("gpt-5")||e.toLowerCase().includes("gpt5");d=new g.ChatOpenAI({apiKey:s,model:e,...t?{temperature:1}:{temperature:Be}}),p={...p,model:e,keyPresent:!!s}}this.logger.info("AI provider configured",p),this.logger.info("Preparing plugins...");const y=this.preparePlugins();this.logger.info("Creating agent config...");const w=this.createAgentConfig(m,d,y);if(this.logger.info("Creating agent..."),this.agent=he(w),this.logger.info("Agent created"),this.logger.info("Configuring HCS10 plugin..."),this.configureHCS10Plugin(y),this.logger.info("HCS10 plugin configured"),this.contentStoreManager=new Ce,await this.contentStoreManager.initialize(),this.logger.info("ContentStoreManager initialized for content reference support"),this.logger.info("About to call agent.boot()"),this.logger.info("🔥 About to call agent.boot()"),await this.agent.boot(),this.logger.info("agent.boot() completed"),this.logger.info("🔥 agent.boot() completed"),this.agent){try{const e=new Ae;e.register(new Fe),e.register(new Pe);new Oe(e,this.options.network||"testnet").attachToAgent(this.agent,{getEntities:async()=>this.memoryManager?.getEntityAssociations()||[]}),this.logger.info("Parameter preprocessing callback attached (internal)")}catch(c){this.logger.warn("Failed to attach internal parameter preprocessing callback",c)}const e=w;e.filtering=e.filtering||{};const t=e.filtering.toolPredicate,r=this.options.toolFilter;e.filtering.toolPredicate=e=>(!e||"hedera-account-transfer-hbar"!==e.name)&&((!e||"hedera-hts-airdrop-token"!==e.name)&&(!(t&&!t(e))&&!(r&&!r(e))))}this.options.mcpServers&&this.options.mcpServers.length>0&&this.connectMCP()}catch(h){throw this.logger.error("Failed to initialize ConversationalAgent:",h),h}}getPlugin(){return this.hcs10Plugin}getStateManager(){return this.stateManager}getAgent(){if(!this.agent)throw new Error(o.NOT_INITIALIZED_ERROR);return this.agent}getConversationalAgent(){return this.getAgent()}async processMessage(e,t=[]){if(!this.agent)throw new Error("Agent not initialized. Call initialize() first.");try{const r=e,o={messages:t.map(e=>{const t=e.content;return"system"===e.type?new m.SystemMessage(t):"human"===e.type?new m.HumanMessage(t):new m.AIMessage(t)})},n=await this.agent.chat(r,o);return this.memoryManager&&"returnBytes"!==this.options.operationalMode&&await this.extractAndStoreEntities(n,e),this.logger.info("Message processed successfully"),n}catch(r){throw this.logger.error("Error processing message:",r),r}}async processFormSubmission(e){if(!this.agent)throw new Error(o.NOT_INITIALIZED_ERROR);try{this.logger.info("Processing form submission:",{formId:e.formId,toolName:e.toolName,parameterKeys:Object.keys(e.parameters||{}),hasContext:!!e.context});const t=await this.agent.processFormSubmission(e);return this.logger.info("Form submission processed successfully"),t}catch(t){throw this.logger.error("Error processing form submission:",t),t}}validateOptions(e,t){const r="autonomous"!==(this.options.operationalMode||_e);if(!e)throw new Error("Account ID is required");if(!t&&!r)throw new Error("Private key is required in autonomous mode");if("string"!=typeof e)throw new Error("Account ID must be a string, received "+typeof e);if(!r&&"string"!=typeof t)throw new Error(`Private key must be a string, received ${typeof t}: ${JSON.stringify(t)}`);if(!r&&"string"==typeof t&&t.length<10)throw new Error("Private key appears to be invalid (too short)")}preparePlugins(){const{additionalPlugins:t=[],enabledPlugins:r,disabledPlugins:o}=this.options,n=[this.hcs10Plugin,this.hcs2Plugin,this.inscribePlugin,this.hbarPlugin];n.push(this.webBrowserPlugin);const s=e.getAllHederaCorePlugins();let i=[...n,...s];if(r){const e=new Set(r);i=i.filter(t=>e.has(t.id))}if(o&&o.length>0){const e=new Set(o);i=i.filter(t=>!e.has(t.id))}const a=o&&o.length>0?t.filter(e=>!o.includes(e.id)):t;return[...i,...a]}createAgentConfig(e,t,r){const{operationalMode:o=_e,userAccountId:n,scheduleUserTransactionsInBytesMode:s,customSystemMessagePreamble:i,customSystemMessagePostamble:a,verbose:c=!1,mirrorNodeConfig:l,disableLogging:g,accountId:h=""}=this.options;return{framework:"langchain",signer:e,execution:{mode:"autonomous"===o?"direct":"bytes",operationalMode:o,...n&&{userAccountId:n},...void 0!==s&&{scheduleUserTransactionsInBytesMode:s,scheduleUserTransactions:s}},ai:{provider:new me(t),temperature:Be},filtering:{toolPredicate:e=>"hedera-account-transfer-hbar"!==e.name&&!(this.options.toolFilter&&!this.options.toolFilter(e))},messaging:{systemPreamble:i||Te(h),...a&&{systemPostamble:a},conciseMode:!0},extensions:{plugins:r,...l&&{mirrorConfig:l}},...this.options.mcpServers&&{mcp:{servers:this.options.mcpServers,autoConnect:!1}},debug:{verbose:c,silent:g??!1}}}configureHCS10Plugin(e){const t=e.find(e=>"hcs-10"===e.id);t&&(t.appConfig={stateManager:this.stateManager})}static withPlugins(e,t){return new o({...e,enabledPlugins:t})}static withHTS(e){return this.withPlugins(e,["hts-token"])}static withHCS2(e){return this.withPlugins(e,["hcs-2"])}static withHCS10(e){return this.withPlugins(e,["hcs-10"])}static withInscribe(e){return this.withPlugins(e,["inscribe"])}static withAccount(e){return this.withPlugins(e,["account"])}static withFileService(e){return this.withPlugins(e,["file-service"])}static withConsensusService(e){return this.withPlugins(e,["consensus-service"])}static withSmartContract(e){return this.withPlugins(e,["smart-contract"])}static withAllStandards(e){return this.withPlugins(e,["hcs-10","hcs-2","inscribe"])}static minimal(e){return this.withPlugins(e,[])}static withMCP(e,t){return new o({...e,mcpServers:t})}async extractAndStoreEntities(e,t){if(this.memoryManager&&this.entityTools)try{this.logger.info("Starting LLM-based entity extraction");const o=this.extractResponseText(e),n=await this.entityTools.extractEntities.call({response:o,userMessage:t});try{const t=JSON.parse(n);for(const r of t)if(r&&"object"==typeof r&&"name"in r&&"type"in r&&"id"in r){this.logger.info(`Storing entity: ${r.name} (${r.type}) -> ${r.id}`);const t=this.extractTransactionId(e),o=String(r.id);/^0\.0\.[0-9]+$/.test(o)?this.memoryManager.storeEntityAssociation(o,String(r.name),String(r.type),t):this.logger.warn("Skipping non-ID entity from extraction",{id:o,name:String(r.name),type:String(r.type)})}t.length>0?this.logger.info(`Stored ${t.length} entities via LLM extraction`):this.logger.info("No entities found in response via LLM extraction")}catch(r){throw this.logger.error("Failed to parse extracted entities JSON:",r),r}}catch(o){throw this.logger.error("Entity extraction failed:",o),o}}extractTransactionId(e){try{if("object"==typeof e&&e&&"transactionId"in e){const t=e;return"string"==typeof t.transactionId?t.transactionId:void 0}if("string"==typeof e){const t=e.match(/transaction[\s\w]*ID[\s:"]*([0-9a-fA-F@._-]+)/i);return t?t[1]:void 0}return}catch{return}}connectMCP(){this.agent&&this.options.mcpServers&&this.agent.connectMCPServers().catch(e=>{this.logger.error("Failed to connect MCP servers:",e)}).then(()=>{this.logger.info("MCP servers connected successfully")})}getMCPConnectionStatus(){return this.agent?this.agent.getMCPConnectionStatus():new Map}isMCPServerConnected(e){if(this.agent){const t=this.agent.getMCPConnectionStatus().get(e);return t?.connected??!1}return!1}async cleanup(){try{if(this.logger.info("Cleaning up ConversationalAgent..."),this.memoryManager){try{this.memoryManager.dispose(),this.logger.info("Memory manager cleaned up successfully")}catch(e){this.logger.warn("Error cleaning up memory manager:",e)}this.memoryManager=void 0}this.contentStoreManager&&(await this.contentStoreManager.dispose(),this.logger.info("ContentStoreManager cleaned up")),this.logger.info("ConversationalAgent cleanup completed")}catch(e){this.logger.error("Error during cleanup:",e)}}switchMode(e){this.agent?.switchMode&&this.agent.switchMode(e||"autonomous")}getUsageStats(){return this.agent?.getUsageStats?.()??{}}clearUsageStats(){this.agent?.clearUsageStats&&this.agent.clearUsageStats()}shutdown(){return this.agent?.shutdown?.()??Promise.resolve()}extractResponseText(e){if("string"==typeof e)return e;if(e&&"object"==typeof e&&"output"in e){return String(e.output)}return JSON.stringify(e)}};ze.NOT_INITIALIZED_ERROR="Agent not initialized. Call initialize() first.";let He=ze;exports.AttachmentProcessor=class{constructor(){this.logger=new r.Logger({module:"AttachmentProcessor"})}async processAttachments(e,t,r){return 0===t.length?e:(this.logger.info("Processing attachments with content reference system:",{attachmentCount:t.length,totalSize:t.reduce((e,t)=>e+t.size,0)}),r&&r.isInitialized()?this.processWithContentStore(e,t,r):(this.logger.warn("Content storage not available, creating simple file references"),this.processWithSimpleReferences(e,t)))}async processWithContentStore(e,t,r){const o=[];for(const i of t)try{const e=i.data.includes("base64,")?i.data.split("base64,")[1]:i.data,t=globalThis.Buffer.from(e,"base64"),n=await r.storeContentIfLarge(t,{mimeType:i.type,source:"user_upload",fileName:i.name,tags:["attachment","user_file"]});n?i.type.startsWith("image/")?o.push(`[Image File: ${i.name}] (content-ref:${n.referenceId})`):o.push(`[File: ${i.name}] (content-ref:${n.referenceId})`):o.push(this.createInlineReference(i,e))}catch(s){this.logger.error("Failed to process attachment:",{fileName:i.name,error:s instanceof Error?s.message:"Unknown error"}),o.push(`[File: ${i.name} - Error processing file: ${s instanceof Error?s.message:"Unknown error"}]`)}const n=this.createFileList(t);return e?`${e}\n\nAttached files:\n${n}\n\n${o.join("\n")}`:`Attached files:\n${n}\n\n${o.join("\n")}`}processWithSimpleReferences(e,t){const r=t.map(e=>{const t=this.formatFileSize(e.size);return e.type.startsWith("image/")?`📎 Image: ${e.name} (${t}, ${e.type})`:`📎 File: ${e.name} (${t}, ${e.type})`});return e?`${e}\n\nAttached files:\n${r.join("\n")}`:`Attached files:\n${r.join("\n")}`}createInlineReference(e,t){return e.size<5e4?e.type.startsWith("image/")?``:`[File: ${e.name} (${this.formatFileSize(e.size)})]\nContent: ${t}`:`[File: ${e.name} (${this.formatFileSize(e.size)}) - Content too large to include inline]`}createFileList(e){return e.map(e=>{const t=this.formatFileSize(e.size);return`📎 ${e.name} (${t})`}).join("\n")}formatFileSize(e){return e>=1048576?`${(e/1048576).toFixed(1)}MB`:`${(e/1024).toFixed(1)}KB`}},exports.BaseAgent=H,exports.ContentStorage=te,exports.ContentStoreManager=Ce,exports.ConversationalAgent=He,exports.EntityFormat=E,exports.EntityResolver=class{constructor(e){this.llm=new g.ChatOpenAI({apiKey:e.apiKey,modelName:e.modelName||"gpt-4o-mini",temperature:0}),this.logger=new r.Logger({module:"EntityResolver"})}async resolveReferences(e,t){if(!t||0===t.length)return e;const r=t.reduce((e,t)=>(e[t.entityType]||(e[t.entityType]=[]),e[t.entityType].push(t),e),{});try{const t=Object.fromEntries(Object.entries(r).map(([e,t])=>[e,{count:t.length,mostRecent:t[0]?.entityId}]));this.logger.info("resolveReferences: input summary",{messagePreview:e.substring(0,200),entityStats:t})}catch{}let o="Available entities in memory:\n";for(const[s,i]of Object.entries(r)){const e=i[0];o+=`Most recent ${s}: "${e.entityName}" = ${e.entityId}\n`,i.length>1&&(o+=` (${i.length-1} other ${s}s in memory)\n`)}const n=`Task: Replace entity references with their IDs from memory. STRICT TYPE RULES:\n\n- For phrases referring to "${O}" or actions that clearly require a token (create/mint/airdrop/associate/etc.), resolve to the most recent TOKEN entity ID (never a topic or account).\n- For phrases referring to "${P}" or actions that clearly require a topic (inscribe/publish/consensus/etc.), resolve to the most recent TOPIC entity ID (never a token or account).\n- Do not infer or invent entity IDs. Only use those present in the provided context.\n\n${o}\n\nUser message: "${e}"\n\nInstructions:\n- If the user says "${P}" or "that topic" → replace with the most recent topic ID\n- If the user says "${O}" or "that token" → replace with the most recent token ID (never a topic)\n- If the user says "it" or "that" after an action verb → replace with the most recent entity ID\n- Examples:\n * "submit on ${P}" → "submit on 0.0.6543472"\n * "airdrop ${O}" → "airdrop 0.0.123456"\n * "send a message to it" → "send a message to 0.0.6543472"\n\nReturn ONLY the message with replacements made. Do not add any explanations.\nResolved message:`;try{const t=(await this.llm.invoke(n)).content.trim(),r=t!==e;try{this.logger.info("resolveReferences: resolution result",{changed:r,hasEntityId:/\b0\.0\.\d+\b/.test(t),resolvedPreview:t.substring(0,200)})}catch{}return r&&t.includes("0.0.")?t:e}catch{return e}}async extractEntities(e,t){const r=this.extractFromReceipt(e,t);return r.length>0?r:this.extractWithLLM(e,t)}extractFromReceipt(e,t){const r=[];let o;try{o="string"==typeof e?JSON.parse(e):e}catch{o=e}if(!o||!1===o.success)return r;const n=o.receipt||o.result?.receipt||o.data?.receipt;if(!n)return r;const s=this.extractNameFromMessage(t),i=o.transactionId||o.result?.transactionId||void 0,a=e=>"string"==typeof e?e:e&&"object"==typeof e&&"function"==typeof e.toString&&e.toString!==Object.prototype.toString?e.toString():String(e);if(n.tokenId){const e={id:a(n.tokenId),name:s,type:E.TOKEN_ID};i&&(e.transactionId=i),r.push(e)}if(n.topicId){const e={id:a(n.topicId),name:s,type:E.TOPIC_ID};i&&(e.transactionId=i),r.push(e)}if(n.accountId){const e={id:a(n.accountId),name:s,type:E.ACCOUNT_ID};i&&(e.transactionId=i),r.push(e)}if(n.contractId){const e={id:a(n.contractId),name:s,type:E.CONTRACT_ID};i&&(e.transactionId=i),r.push(e)}if(n.fileId){const e={id:a(n.fileId),name:s,type:E.FILE_ID};i&&(e.transactionId=i),r.push(e)}if(n.scheduleId){const e={id:a(n.scheduleId),name:s,type:E.SCHEDULE_ID};i&&(e.transactionId=i),r.push(e)}return r}extractNameFromMessage(e){const t=e.match(/"([^"]+)"/);if(t)return t[1];const r=e.match(/called\s+([A-Za-z0-9#\s_-]+?)(?:\s|$)/i);if(r)return r[1].trim();const o=e.match(/for\s+([A-Za-z0-9#\s_-]+)/i);if(o)return o[1].trim();const n=e.match(/(?:token|topic|account|contract)\s+([A-Za-z0-9#_-]+)/i);return n?n[1].trim():e.includes("new account")?"new account":"unnamed_entity"}async extractWithLLM(e,t){const r="string"==typeof e?e:JSON.stringify(e),o=`Analyze this agent response and extract ONLY newly created entities.\n\nUser asked: "${t.substring(0,200)}"\n\nAgent response: ${r.substring(0,3e3)}\n\nCRITICAL: Only extract Hedera entity IDs in the format 0.0.XXXXX (shard.realm.number).\nDO NOT extract:\n- Token symbols (e.g., "FOREV", "USDC", "HBAR")\n- Token names (e.g., "Forever", "My Token")\n- Transaction IDs (format: 0.0.XXX@timestamp)\n- Account aliases or mnemonics\n\nLook for:\n1. Success messages with entity IDs (e.g., "Successfully created topic 0.0.6543472")\n2. Transaction confirmations that created new entities\n3. Entity IDs that appear after words like "created", "new", "successfully"\n\nDO NOT include:\n- Token symbols or names (these are NOT entity IDs)\n- Account IDs that already existed (like sender/receiver accounts)\n- Entity IDs that were parameters to the operation\n- Failed operations\n- Anything that doesn't match the 0.0.XXXXX format\n\nReturn a JSON array of newly created entities:\n[{"id": "0.0.XXX", "name": "descriptive_name", "type": "topic|token|account"}]\n\nIf no entities were created, return: []\n\nJSON:`;try{const e=await this.llm.invoke(o),t=e.content.match(/\[[\s\S]*?\]/);if(t){return JSON.parse(t[0])}}catch{}return[]}validateEntityType(e,t,r){const o=r.find(t=>t.entityId===e);return!!o&&o.entityType===t}async resolveWithTypeValidation(e,t,r){return await this.resolveReferences(e,t),r?t.filter(e=>e.entityType===r):t}getEntitiesByType(e,t){return e.filter(e=>e.entityType===t)}getMostRecentEntityByType(e,t){const r=e.filter(e=>e.entityType===t);return 0===r.length?null:r.reduce((e,t)=>t.createdAt>e.createdAt?t:e)}},exports.ExtractEntitiesTool=Me,exports.FieldTypeRegistry=M,exports.FormAwareAgentExecutor=z,exports.FormEngine=B,exports.FormGenerator=$,exports.FormValidatingToolWrapper=se,exports.FormatConverterRegistry=Ae,exports.HCS10Plugin=y,exports.HCS2Plugin=w,exports.HbarPlugin=x,exports.InscribePlugin=S,exports.LangChainAgent=ge,exports.LangChainProvider=me,exports.MCPClientManager=U,exports.MCPContentProcessor=j,exports.MCPServers={filesystem:e=>({name:"filesystem",command:"npx",args:["-y","@modelcontextprotocol/server-filesystem",e],transport:"stdio",autoConnect:!0,additionalContext:"This server provides access to files and directories in the current working directory.",toolDescriptions:{list_directory:'Use this tool when users ask about files in the "current directory" or "working directory".',read_file:"Use this tool when users ask to see or check files in the current directory."}}),github:e=>({name:"github",command:"npx",args:["-y","@modelcontextprotocol/server-github"],...e&&{env:{GITHUB_TOKEN:e}},transport:"stdio",autoConnect:!0}),slack:e=>({name:"slack",command:"npx",args:["-y","@modelcontextprotocol/server-slack"],env:{SLACK_TOKEN:e},transport:"stdio",autoConnect:!0}),googleDrive:e=>({name:"google-drive",command:"npx",args:["-y","@modelcontextprotocol/server-google-drive"],env:{GOOGLE_CREDENTIALS:e},transport:"stdio",autoConnect:!0}),postgres:e=>({name:"postgres",command:"npx",args:["-y","@modelcontextprotocol/server-postgres",e],transport:"stdio",autoConnect:!0}),sqlite:e=>({name:"sqlite",command:"npx",args:["-y","@modelcontextprotocol/server-sqlite",e],transport:"stdio",autoConnect:!0}),custom:e=>e},exports.MemoryWindow=Z,exports.OpenConvAIPlugin=y,exports.ParameterService=Oe,exports.ReferenceIdGenerator=X,exports.ResolveEntitiesTool=xe,exports.ResponseFormatter=D,exports.SmartMemoryManager=ne,exports.StringNormalizationConverter=Pe,exports.TokenCounter=V,exports.TopicIdToHrlConverter=Fe,exports.convertMCPToolToLangChain=K,exports.createAgent=he,exports.createEntityTools=Re,exports.createMCPConfig=function(e,t=!0){return{mcpServers:e.map(e=>({...e,autoConnect:e.autoConnect??t}))}},exports.fieldGuidanceRegistry=T,exports.fieldTypeRegistry=R,exports.getWalletBridgeProvider=pe,exports.setWalletBridgeProvider=function(e){de=e},exports.validateServerConfig=function(e){const t=[];return e.name||t.push("Server name is required"),e.command||t.push("Server command is required"),e.args&&Array.isArray(e.args)||t.push("Server args must be an array"),e.transport&&!["stdio","http","websocket"].includes(e.transport)&&t.push("Invalid transport type. Must be stdio, http, or websocket"),t},exports.wrapToolWithFormValidation=ie,Object.keys(e).forEach(t=>{"default"===t||Object.prototype.hasOwnProperty.call(exports,t)||Object.defineProperty(exports,t,{enumerable:!0,get:()=>e[t]})});
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("hedera-agent-kit"),t=require("@hashgraphonline/standards-agent-kit"),r=require("@hashgraphonline/standards-sdk"),o=require("zod"),s=require("@hashgraph/sdk"),n=require("bignumber.js"),i=require("@langchain/core/tools"),a=require("@ethersphere/bee-js"),c=require("fs"),l=require("path"),g=require("util"),h=require("@ethereumjs/wallet"),u=require("crypto"),d=require("langchain/agents"),m=require("zod-to-json-schema"),p=require("@langchain/core/prompts"),f=require("@langchain/openai"),y=require("@modelcontextprotocol/sdk/client/index.js"),w=require("@modelcontextprotocol/sdk/client/stdio.js"),b=require("@langchain/core/messages"),T=require("tiktoken"),S=require("@langchain/anthropic");class v extends e.BasePlugin{constructor(){super(...arguments),this.id="hcs-10",this.name="HCS-10 Plugin",this.description="HCS-10 agent tools for decentralized agent registration, connections, and messaging on Hedera",this.version="1.0.0",this.author="Hashgraph Online",this.namespace="hcs10",this.tools=[]}async initialize(e){await super.initialize(e);const o=e.config.hederaKit;var s;if(o)try{this.stateManager=e.stateManager||e.config.stateManager||this.appConfig?.stateManager||new t.OpenConvaiState;const a=o.signer.getAccountId().toString(),c="returnBytes"===String(o.operationalMode||"returnBytes");let l,g="",h="",u=o.signer.getOperatorPrivateKey();try{l="function"==typeof u?.toString?u.toString():"";const e=new r.HCS10Client({network:o.network,operatorId:a,operatorPrivateKey:u,logLevel:"error"}),t=await e.retrieveProfile(a);t.success&&t.topicInfo&&(g=t.topicInfo.inboundTopic,h=t.topicInfo.outboundTopic)}catch(n){this.context.logger.warn("Skipping profile topic discovery",n)}const d={name:`Agent ${a}`,accountId:a,inboundTopicId:g,outboundTopicId:h};if(!c&&l&&(d.privateKey=l),this.stateManager.setCurrentAgent(d),this.context.logger.info(`Set current agent: ${a} with topics ${g}/${h}`),!c&&this.stateManager&&!this.stateManager.getConnectionsManager())try{const e=new r.HCS10Client({network:o.network,operatorId:a,operatorPrivateKey:u??"",logLevel:"error"});"object"==typeof(s=this.stateManager)&&null!==s&&"initializeConnectionsManager"in s&&"function"==typeof s.initializeConnectionsManager?this.stateManager.initializeConnectionsManager(e):this.context.logger.warn("StateManager does not support connection manager initialization"),this.context.logger.info("ConnectionsManager initialized in HCS10Plugin")}catch(i){this.context.logger.warn("Could not initialize ConnectionsManager:",i)}this.initializeTools(),this.context.logger.info("HCS-10 Plugin initialized successfully")}catch(a){this.context.logger.error("Failed to initialize HCS-10 plugin:",a)}else this.context.logger.warn("HederaKit not found in context. HCS-10 tools will not be available.")}initializeTools(){if(!this.stateManager)throw new Error("StateManager must be initialized before creating tools");const e=this.context.config.hederaKit;if(!e)throw new Error("HederaKit not found in context config");const r=new t.HCS10Builder(e,this.stateManager);this.tools=[new t.RegisterAgentTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger}),new t.FindRegistrationsTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger}),new t.RetrieveProfileTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger}),new t.InitiateConnectionTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger}),new t.ListConnectionsTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger}),new t.SendMessageToConnectionTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger}),new t.CheckMessagesTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger}),new t.ConnectionMonitorTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger}),new t.ManageConnectionRequestsTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger}),new t.AcceptConnectionRequestTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger}),new t.ListUnapprovedConnectionRequestsTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger})]}getTools(){return this.tools}getStateManager(){return this.stateManager}async cleanup(){this.tools=[],delete this.stateManager,this.context?.logger&&this.context.logger.info("HCS-10 Plugin cleaned up")}}class k extends e.BasePlugin{constructor(){super(...arguments),this.id="hcs-2",this.name="HCS-2 Plugin",this.description="HCS-2 registry management tools for decentralized registries on Hedera",this.version="1.0.0",this.author="Hashgraph Online",this.namespace="hcs2",this.tools=[]}async initialize(e){await super.initialize(e);if(e.config.hederaKit)try{this.initializeTools(),this.context.logger.info("HCS-2 Plugin initialized successfully")}catch(t){this.context.logger.error("Failed to initialize HCS-2 plugin:",t)}else this.context.logger.warn("HederaKit not found in context. HCS-2 tools will not be available.")}initializeTools(){const e=this.context.config.hederaKit;if(!e)throw new Error("HederaKit not found in context config");const r=new t.HCS2Builder(e);this.tools=[new t.CreateRegistryTool({hederaKit:e,hcs2Builder:r,logger:this.context.logger}),new t.RegisterEntryTool({hederaKit:e,hcs2Builder:r,logger:this.context.logger}),new t.UpdateEntryTool({hederaKit:e,hcs2Builder:r,logger:this.context.logger}),new t.DeleteEntryTool({hederaKit:e,hcs2Builder:r,logger:this.context.logger}),new t.MigrateRegistryTool({hederaKit:e,hcs2Builder:r,logger:this.context.logger}),new t.QueryRegistryTool({hederaKit:e,hcs2Builder:r,logger:this.context.logger})]}getTools(){return this.tools}async cleanup(){this.tools=[],this.context?.logger&&this.context.logger.info("HCS-2 Plugin cleaned up")}}const C=new class{constructor(){this.configurations=[],this.providers=[],this.registerOrderCounter=0,this.logger=new r.Logger({module:"FieldGuidanceRegistry"})}registerToolConfiguration(e){this.configurations.push(e)}registerToolProvider(e,t,r){const o=r?.id??`provider-${this.providers.length+1}`,s=r?.priority??0;if(this.providers.some(e=>e.id===o))throw this.logger.error("Duplicate provider id",{id:o}),new Error("DUPLICATE_PROVIDER_ID");return this.providers.push({id:o,priority:s,pattern:e,provider:t,order:this.registerOrderCounter++}),o}unregisterProvider(e){this.providers=this.providers.filter(t=>t.id!==e)}listProviders(){return this.providers.map(({id:e,priority:t,pattern:r})=>({id:e,priority:t,pattern:r}))}getFieldGuidance(e,t){if("false"===process.env.CA_FORM_GUIDANCE_ENABLED)return null;for(const o of this.configurations){if(("string"==typeof o.toolPattern?e.toLowerCase().includes(o.toolPattern.toLowerCase()):o.toolPattern.test(e))&&o.fields[t]){const r=o.fields[t],s=this.pickMatchingProviders(e);if(0===s.length)return r;let n={...r};for(const o of[...s].reverse()){const r=this.safeGetFieldGuidance(o,t,e);r&&(n=this.mergeGuidance(n,r))}return n}}const r=this.pickMatchingProviders(e);if(r.length>0){let o={};for(const s of[...r].reverse()){const r=this.safeGetFieldGuidance(s,t,e);r&&(o=this.mergeGuidance(o,r))}return Object.keys(o).length>0?o:null}return null}getGlobalGuidance(e){if("false"===process.env.CA_FORM_GUIDANCE_ENABLED)return null;for(const r of this.configurations){if(("string"==typeof r.toolPattern?e.toLowerCase().includes(r.toolPattern.toLowerCase()):r.toolPattern.test(e))&&r.globalGuidance){const t=r.globalGuidance,o=this.pickMatchingProviders(e);if(0===o.length)return t;let s=t.warnings,n=t.qualityStandards;for(const r of[...o].reverse()){const t=this.safeGetGlobalGuidance(r,e);t&&(s=t.warnings??s,n=t.qualityStandards??n)}const i={};return void 0!==s&&(i.warnings=s),void 0!==n&&(i.qualityStandards=n),i}}const t=this.pickMatchingProviders(e);if(t.length>0){let r,o;for(const n of[...t].reverse()){const t=this.safeGetGlobalGuidance(n,e);t&&(r=t.warnings??r,o=t.qualityStandards??o)}const s={};return void 0!==r&&(s.warnings=r),void 0!==o&&(s.qualityStandards=o),Object.keys(s).length>0?s:null}return null}validateFieldValue(e,t,r){const o=this.getFieldGuidance(e,t),s=[],n=[];if(!o||"string"!=typeof r)return{isValid:!0,warnings:s,errors:n};if(o.warnings)for(const i of o.warnings)i.pattern.test(r)&&s.push(i.message);if(o.validationRules){const{rejectPatterns:e,qualityChecks:t}=o.validationRules;if(e)for(const o of e)o.pattern.test(r)&&n.push(`Rejected: ${o.reason}`);if(t){if(t.forbidTechnicalTerms){const e=r.toLowerCase();for(const r of t.forbidTechnicalTerms)e.includes(r.toLowerCase())&&n.push(`Avoid technical terms like "${r}" in NFT metadata`)}if(t.requireSpecificTerms){const e=r.toLowerCase();t.requireSpecificTerms.some(t=>e.includes(t.toLowerCase()))||s.push(`Consider including terms like: ${t.requireSpecificTerms.join(", ")}`)}if(t.minNonTechnicalWords){r.split(/\s+/).filter(e=>e.length>2).length<t.minNonTechnicalWords&&s.push(`Consider providing more descriptive content (at least ${t.minNonTechnicalWords} meaningful words)`)}}}return{isValid:0===n.length,warnings:s,errors:n}}clear(){this.configurations=[],this.providers=[],this.registerOrderCounter=0}pickMatchingProviders(e){return this.providers.filter(t=>"string"==typeof t.pattern?e.toLowerCase().includes(t.pattern.toLowerCase()):t.pattern.test(e)).sort((e,t)=>t.priority!==e.priority?t.priority-e.priority:t.order-e.order).map(e=>({id:e.id,provider:e.provider,priority:e.priority,order:e.order}))}safeGetFieldGuidance(e,t,r){try{return e.provider.getFieldGuidance(t,{toolName:r})??null}catch(o){return this.logger.warn("Provider getFieldGuidance failed",{id:e.id,err:o}),null}}safeGetGlobalGuidance(e,t){try{return e.provider.getGlobalGuidance?.(t)??null}catch(r){return this.logger.warn("Provider getGlobalGuidance failed",{id:e.id,err:r}),null}}mergeGuidance(e,t){const r={},o=t.suggestions??e.suggestions;void 0!==o&&(r.suggestions=o);const s=t.predefinedOptions??e.predefinedOptions;void 0!==s&&(r.predefinedOptions=s);const n=t.warnings??e.warnings;void 0!==n&&(r.warnings=n);const i=t.validationRules??e.validationRules;void 0!==i&&(r.validationRules=i);const a=t.fieldTypeOverride??e.fieldTypeOverride;void 0!==a&&(r.fieldTypeOverride=a);const c=t.contextualHelpText??e.contextualHelpText;return void 0!==c&&(r.contextualHelpText=c),r}};class I extends e.BasePlugin{constructor(){super(...arguments),this.id="inscribe",this.name="Inscribe Plugin",this.description="Content inscription tools for storing data on Hedera Consensus Service",this.version="1.0.0",this.author="Hashgraph Online",this.namespace="inscribe",this.tools=[],this.providerId=null}async initialize(e){await super.initialize(e);if(e.config.hederaKit)try{this.initializeTools();try{const e={getFieldGuidance:e=>"name"===e?{suggestions:["Sunset Landscape #42","Digital Abstract Art"],contextualHelpText:"Create a distinctive name that collectors will find appealing"}:"description"===e?{fieldTypeOverride:"textarea",suggestions:["A beautiful piece representing..."]}:null,getGlobalGuidance:()=>({qualityStandards:["Use meaningful names that describe the artwork or content"]})};this.providerId=C.registerToolProvider(/hashinal/i,e,{id:"inscribe:hashinal:provider",priority:1})}catch(t){this.context.logger.warn("Could not register Inscribe field guidance provider")}this.context.logger.info("Inscribe Plugin initialized successfully")}catch(r){this.context.logger.error("Failed to initialize Inscribe plugin:",r)}else this.context.logger.warn("HederaKit not found in context. Inscription tools will not be available.")}initializeTools(){const e=this.context.config.hederaKit;if(!e)throw new Error("HederaKit not found in context config");const r=new t.InscriberBuilder(e);this.tools=[new t.InscribeFromUrlTool({hederaKit:e,inscriberBuilder:r,logger:this.context.logger}),new t.InscribeFromFileTool({hederaKit:e,inscriberBuilder:r,logger:this.context.logger}),new t.InscribeFromBufferTool({hederaKit:e,inscriberBuilder:r,logger:this.context.logger}),new t.InscribeHashinalTool({hederaKit:e,inscriberBuilder:r,logger:this.context.logger}),new t.RetrieveInscriptionTool({hederaKit:e,inscriberBuilder:r,logger:this.context.logger})]}getTools(){return this.tools}async cleanup(){if(this.tools=[],this.providerId){try{C.unregisterProvider(this.providerId)}catch{}this.providerId=null}this.context?.logger&&this.context.logger.info("Inscribe Plugin cleaned up")}}class x extends e.BaseServiceBuilder{constructor(e){super(e)}transferHbar(e,t=!0){this.clearNotes();const r=new s.TransferTransaction;if(!e.transfers||0===e.transfers.length)throw new Error("HbarTransferParams must include at least one transfer.");let o=new n(0),i=!1;if(t&&this.kit.userAccountId&&"provideBytes"===this.kit.operationalMode&&1===e.transfers.length){const t=e.transfers[0],o="string"==typeof t.amount||"number"==typeof t.amount?t.amount:t.amount.toString(),a=new n(o);if(a.isPositive()){const e="string"==typeof t.accountId?s.AccountId.fromString(t.accountId):t.accountId,o=a.toFixed(8,n.ROUND_DOWN),c=s.Hbar.fromString(o);this.logger.info(`[AccountBuilder.transferHbar] Configuring user-initiated scheduled transfer: ${c.toString()} from ${this.kit.userAccountId} to ${e.toString()}`),this.addNote(`Configured HBAR transfer from your account (${this.kit.userAccountId}) to ${e.toString()} for ${c.toString()}.`),r.addHbarTransfer(e,c),r.addHbarTransfer(s.AccountId.fromString(this.kit.userAccountId),c.negated()),i=!0}}if(!i){const t=[];for(const r of e.transfers){const e="string"==typeof r.accountId?s.AccountId.fromString(r.accountId):r.accountId,i="string"==typeof r.amount||"number"==typeof r.amount?r.amount:r.amount.toString(),a=new n(i),c=a.toFixed(8,n.ROUND_DOWN);this.logger.info(`Processing transfer: ${i} HBAR (rounded to ${c}) for account ${e.toString()}`);const l=s.Hbar.fromString(c);t.push({accountId:e,amount:a,hbar:l});const g=l.toTinybars();o=o.plus(g.toString())}if(!o.isZero()&&(this.logger.warn(`Transfer sum not zero: ${o.toString()} tinybars off. Adjusting last transfer.`),t.length>0)){const e=t[t.length-1],r=o.dividedBy(-1e8),i=e.amount.plus(r).toFixed(8,n.ROUND_DOWN);e.hbar=s.Hbar.fromString(i),this.logger.info(`Adjusted last transfer for ${e.accountId.toString()} to ${i} HBAR`)}for(const e of t)r.addHbarTransfer(e.accountId,e.hbar)}return void 0!==e.memo&&(null===e.memo?this.logger.warn("Received null for memo in transferHbar."):r.setTransactionMemo(e.memo)),this.setCurrentTransaction(r),this}}const M=o.z.object({accountId:o.z.string().describe('Account ID for the transfer (e.g., "0.0.xxxx").'),amount:o.z.union([o.z.number(),o.z.string()]).describe("HBAR amount in decimal format (e.g., 1 for 1 HBAR, 0.5 for 0.5 HBAR). Positive for credit, negative for debit. DO NOT multiply by 10^8 for tinybars - just use the HBAR amount directly.")}),E=o.z.object({transfers:o.z.array(M).min(1).describe('Array of transfers. For simple transfers from your operator account, just include the recipient with positive amount: [{accountId: "0.0.800", amount: 1}]. For complex multi-party transfers, include all parties with negative amounts for senders and positive for receivers.'),memo:o.z.string().optional().describe("Optional. Memo for the transaction.")});class A extends e.BaseHederaTransactionTool{constructor(){super(...arguments),this.name="hedera-account-transfer-hbar-v2",this.description='PRIMARY TOOL FOR HBAR TRANSFERS: Transfers HBAR between accounts. For simple transfers from the operator account, just specify the recipient with a positive amount (e.g., [{accountId: "0.0.800", amount: 1}] to send 1 HBAR to 0.0.800). The sender will be automatically added. For multi-party transfers (e.g., "A sends 5 HBAR to C and B sends 3 HBAR to C"), include ALL transfers with their amounts (negative for senders, positive for receivers).',this.specificInputSchema=E,this.namespace="account"}getServiceBuilder(){return new x(this.hederaKit)}async callBuilderMethod(e,t){await e.transferHbar(t)}}class F extends i.StructuredTool{constructor(e,t){super(),this.name="hedera-hts-airdrop-token",this.description="Airdrops fungible tokens to multiple recipients. Automatically converts human-readable amounts to smallest units based on token decimals.",this.schema=o.z.object({tokenId:o.z.string().describe('The ID of the fungible token to airdrop (e.g., "0.0.yyyy").'),recipients:o.z.array(o.z.object({accountId:o.z.string().describe('Recipient account ID (e.g., "0.0.xxxx").'),amount:o.z.union([o.z.number(),o.z.string()]).describe('Amount in human-readable format (e.g., "10" for 10 tokens).')})).min(1).describe("Array of recipient objects, each with accountId and amount."),memo:o.z.string().optional().describe("Optional. Memo for the transaction.")}),this.originalTool=e,this.agentKit=t,this.logger=new r.Logger({module:"AirdropToolWrapper"})}async _call(e){try{this.logger.info(`Processing airdrop request for token ${e.tokenId} with ${e.recipients.length} recipients`);const t=(await this.getTokenInfo(e.tokenId)).decimals||0;this.logger.info(`Token ${e.tokenId} has ${t} decimal places`);const r=e.recipients.map(e=>{const r="string"==typeof e.amount?parseFloat(e.amount):e.amount,o=this.convertToSmallestUnits(r,t);return this.logger.info(`Converting amount for ${e.accountId}: ${r} tokens → ${o} smallest units`),{...e,amount:o.toString()}}),o={...e,recipients:r};return this.logger.info("Calling original airdrop tool with converted amounts"),await this.originalTool._call(o)}catch(t){throw this.logger.error("Error in airdrop tool wrapper:",t),t}}convertToSmallestUnits(e,t){return Math.floor(e*Math.pow(10,t))}async getTokenInfo(e){try{return await this.queryTokenInfo(e)}catch(t){throw t}}async queryTokenInfo(e){try{this.logger.info("Querying token info using mirror node");const t=this.agentKit.mirrorNode;if(t){const r=await t.getTokenInfo(e);if(r&&void 0!==r.decimals){const t=parseInt(r.decimals.toString())||0;return this.logger.info(`Token ${e} found with ${t} decimals`),{...r,decimals:t}}}else{this.logger.info("MirrorNode not found in agentKit, attempting to access via fetch");const t="mainnet"===(this.agentKit.network||"testnet")?"https://mainnet.mirrornode.hedera.com":"https://testnet.mirrornode.hedera.com",r=await fetch(`${t}/api/v1/tokens/${e}`);if(r.ok){const t=await r.json(),o=parseInt(String(t.decimals||"0"));return this.logger.info(`Token ${e} found with ${o} decimals via API`),{...t,decimals:o}}}throw new Error("Token data not found or missing decimals field")}catch(t){return this.logger.warn(`Failed to query token info for ${e}:`,t),this.logger.info("Falling back to assumed 0 decimal places (smallest units)"),{decimals:0}}}}class R extends e.BasePlugin{constructor(){super(...arguments),this.id="hbar",this.name="HBAR Plugin",this.description="HBAR operations: transfer tool with robust decimal handling and compatibility with airdrop improvements",this.version="1.0.0",this.author="Hashgraph Online",this.namespace="account",this.tools=[],this.originalAirdropTool=null}async initialize(e){await super.initialize(e);if(e.config.hederaKit)try{this.initializeTools(),this.context.logger.info("HBAR Plugin initialized successfully")}catch(t){this.context.logger.error("Failed to initialize HBAR plugin:",t)}else this.context.logger.warn("HederaKit not found in context. HBAR tools will not be available.")}initializeTools(){const t=this.context.config.hederaKit;if(!t)throw new Error("HederaKit not found in context config");const r=new A({hederaKit:t,logger:this.context.logger});this.tools=[r];try{this.context.logger.info("Creating wrapper for passed original airdrop tool");const r=new e.HederaAirdropTokenTool({hederaKit:t,logger:this.context.logger}),o=new F(r,t);this.tools.push(o),this.context.logger.info("Added wrapped airdrop tool to HBAR Plugin")}catch(o){this.context.logger.error("Error creating airdrop tool wrapper:",o)}this.context.logger.info(`HBAR Plugin tools initialized with ${this.tools.length} tools`)}getTools(){return this.tools}async shutdown(){this.tools=[]}}const P=404,O=400,N="Endpoint not found. If using Swarm Gateway, postage stamp management endpoints are not available.",L="If using Swarm Gateway, tag endpoints are not available.";function $(e){const t=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=parseInt(e.slice(r,r+2),16);return t}const B=e=>({stampID:"string"==typeof e.batchID?e.batchID:e.batchID.toHex(),usage:e.usageText,capacity:`${e.remainingSize.toFormattedString()} remaining out of ${e.size.toFormattedString()}`,immutable:e.immutableFlag,ttl:`${e.duration.represent()} (${e.duration.toEndDate().toDateString()})`}),z=e=>({content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}),D=(e,t)=>"object"==typeof e&&null!==e&&"status"in e&&e.status===t,H=e=>"object"==typeof e&&null!==e&&"responseBody"in e&&"object"==typeof e.responseBody&&null!==e.responseBody&&"message"in e.responseBody?e.responseBody.message:"",j=async(e,t,r)=>{let o=e;const s=r.autoAssignStamp??!0;let n=0;if(!o&&!s)throw new Error("No postageBatchId was provided. Please repeat the prompt and also specify the usable postage batch id.");if(!o)try{(await t.getPostageBatches()).forEach(e=>{if(!e.usable)return;const t=e.remainingSize.toBytes();t>n&&(n=t,o=e.batchID.toHex())})}catch(i){if(!D(i,P))throw new Error("Retrieval of postage batches failed.");o="0000000000000000000000000000000000000000000000000000000000000000"}if(!o)throw new Error("There is no usable postage batch with capacity.");return o},_={ms:1,milli:1,millis:1,millisecond:1,milliseconds:1,s:1e3,sec:1e3,second:1e3,seconds:1e3,m:6e4,min:6e4,minute:6e4,minutes:6e4,h:36e5,hour:36e5,hours:36e5,d:864e5,day:864e5,days:864e5,w:6048e5,week:6048e5,weeks:6048e5,month:2592e6,months:2592e6,y:31536e6,year:31536e6,years:31536e6};function U(e){const t=parseFloat(e);if(isNaN(t))throw Error("makeDate got NaN for input");const r=e.replace(/^-?[0-9.]+/,"").trim().toLowerCase(),o=_[r];if(!o)throw Error(`Unknown unit: "${r}"`);return t*o}const q=o.z.object({leastUsed:o.z.boolean().optional(),limit:o.z.number().optional(),minUsage:o.z.number().optional(),maxUsage:o.z.number().optional()});class K extends e.BaseHederaQueryTool{constructor(e){const{bee:t,config:r,...o}=e;super(o),this.name="swarm-list-postage-stamps",this.description="\n List the available postage stamps.\n leastUsed: A boolean value that tells if stamps are sorted so least used comes first.\n limit: Limit is the maximum number of returned stamps.\n minUsage: Only list stamps with at least this usage percentage.\n maxUsage: Only list stamps with at most this usage percentage. \n ",this.namespace="swarm",this.specificInputSchema=q,this.bee=t,this.config=r}async executeQuery(e){const{leastUsed:t,limit:r,minUsage:o,maxUsage:s}=e;let n;try{n=await this.bee.getPostageBatches()}catch(c){let e="Retrieval of postage batches failed.";throw D(c,P)&&(e=N),this.logger.error(e,c),new Error(e)}let i=n.map(e=>({...e,batchID:e.batchID.toHex()})).filter(e=>{if(!e.usable)return!1;const t=100*e.usage;return!(void 0!==o&&t<o)&&!(void 0!==s&&t>s)});Boolean(t)&&i.length&&(i=i.sort((e,t)=>e.usage-t.usage)),void 0!==r&&r<i.length&&(i=i.slice(0,r));const a=i.map(e=>B(e));return z({raw:i,summary:a})}}const G=o.z.object({data:o.z.string(),redundancyLevel:o.z.number().optional(),postageBatchId:o.z.string().optional()});class W extends e.BaseHederaQueryTool{constructor(e){const{bee:t,config:r,...o}=e;super(o),this.name="swarm-upload-data",this.description="\n Upload text data to Swarm.\n data: Arbitrary string to upload.\n redundancyLevel: Redundancy level for fault tolerance: 0 - none, 1 - medium, 2 - strong, 3 - insane, 4 - paranoid (higher values provide better fault tolerance but increase storage overhead). Optional, value is 0 if not requested.\n postageBatchId: The postage stamp batch ID which will be used to perform the upload, if it is provided.\n ",this.namespace="swarm",this.specificInputSchema=G,this.bee=t,this.config=r}async executeQuery(e){const{data:t,redundancyLevel:r,postageBatchId:o}=e;if(!t)throw this.logger.error("Missing required parameter: data."),new Error("Missing required parameter: data.");let s="";try{s=await j(o,this.bee,this.config)}catch(c){let e="Upload data failed.";throw c instanceof Error&&(e=c.message),this.logger.error(e),new Error(e)}const n=globalThis.Buffer.from(t),i=r?{redundancyLevel:r}:void 0;let a;try{a=await this.bee.uploadData(s,n,i)}catch(c){let e="Unable to upload data.";throw D(c,O)&&(e=H(c)),this.logger.error(e,c),new Error(e)}return z({reference:a.reference.toString(),url:this.bee.url+"/bytes/"+a.reference.toString(),message:"Data successfully uploaded to Swarm"})}}const J=o.z.object({reference:o.z.string()});class V extends e.BaseHederaQueryTool{constructor(e){const{bee:t,config:r,...o}=e;super(o),this.name="swarm-download-data",this.description="\n Downloads immutable data from a Swarm content address hash.\n reference: Swarm reference hash.\n ",this.namespace="swarm",this.specificInputSchema=J,this.bee=t,this.config=r}async executeQuery(e){const{reference:t}=e;if(!t)throw this.logger.error("Missing required parameter: reference."),new Error("Missing required parameter: reference.");if(64!==t.length&&66!==t.length)throw this.logger.error("Invalid Swarm content address hash value for reference."),new Error("Invalid Swarm content address hash value for reference.");let r;try{r=await this.bee.downloadData(t)}catch(s){let e="Downloading data failed.";throw D(s,O)&&(e=H(s)),this.logger.error(e,s),new Error(e)}const o=r.toUtf8();return z({textData:o})}}const Z=o.z.object({size:o.z.number(),duration:o.z.string(),label:o.z.string().optional()});class X extends e.BaseHederaQueryTool{constructor(e){const{bee:t,config:r,...o}=e;super(o),this.name="swarm-create-postage-stamp",this.description="\n Buy postage stamp based on size in megabytes and duration.\n size: The storage size in MB (Megabytes). These other size units convert like this to MB: 1 byte = 0.000001 MB, 1 KB = 0.001 MB, 1GB= 1000MB.\n duration: Duration for which the data should be stored. Time to live of the postage stamp, e.g. 1d - 1 day, 1w - 1 week, 1month - 1 month.\n label: Sets label for the postage batch (omit if the user didn't ask for one). Do not set a label with with specific capacity values because they can get misleading.\n ",this.namespace="swarm",this.specificInputSchema=Z,this.bee=t,this.config=r}async executeQuery(e){const{size:t,duration:r,label:o}=e;if(!t)throw this.logger.error("Missing required parameter: size."),new Error("Missing required parameter: size.");if(!r)throw this.logger.error("Missing required parameter: duration."),new Error("Missing required parameter: duration.");let s,n;try{s=U(r)}catch(i){throw this.logger.error("Invalid parameter: duration."),new Error("Invalid parameter: duration.")}try{let e={};void 0!==o&&(e={label:o});const r=this.bee.buyStorage(a.Size.fromMegabytes(t),a.Duration.fromMilliseconds(s),e),[i,c]=await(async(e,t)=>{let r=!1;const o=new Promise(e=>setTimeout(()=>{r=!0,e(!0)},t));return[await Promise.race([e,o]),r]})(r,3e4);if(c)return JSON.stringify({content:[{type:"text",text:"Purchase of postage batch is in progress, it may take a few minutes. Please list you batches after a few minutes to find it."}]});n=i}catch(c){let e="Unable to buy storage.";throw D(c,P)?e=N:D(c,O)&&(e=H(c)),this.logger.error(e,c),new Error(e)}return{content:[{type:"text",text:`Postage batch ID: ${n.toHex()}`}]}}}const Y=o.z.object({postageBatchId:o.z.string(),duration:o.z.string().optional(),size:o.z.number().optional()});class Q extends e.BaseHederaQueryTool{constructor(e){const{bee:t,config:r,...o}=e;super(o),this.name="swarm-extend-postage-stamp",this.description="Increase the duration (relative to current duration) or size (in megabytes) of a postage stamp.\n postageBatchId: The id of the batch for which extend is performed.\n size: The storage size in MB (Megabytes). These other size units convert like this to MB: 1 byte = 0.000001 MB, 1 KB = 0.001 MB, 1GB= 1000MB.\n duration: Duration for which the data should be stored. Time to live of the postage stamp, e.g. 1d - 1 day, 1w - 1 week, 1month - 1 month.\n ",this.namespace="swarm",this.specificInputSchema=Y,this.bee=t,this.config=r}async executeQuery(e){const{postageBatchId:t,duration:r,size:o}=e;if(!t)throw this.logger.error("Missing required parameter: postageBatchId."),new Error("Missing required parameter: postageBatchId.");if(!r&&!o)throw this.logger.error("You need at least one parameter from duration and size."),new Error("You need at least one parameter from duration and size.");const s=o?a.Size.fromMegabytes(o):a.Size.fromBytes(1);let n,i=a.Duration.ZERO;try{r&&(i=a.Duration.fromMilliseconds(U(r)))}catch(c){throw this.logger.error("Invalid parameter: duration."),new Error("Invalid parameter: duration.")}try{n=await this.bee.extendStorage(t,s,i)}catch(l){let e="Extend failed.";throw D(l,P)?e=N:D(l,O)&&(e=H(l)),this.logger.error(e,l),new Error(e)}return z({postageBatchId:n.toHex()})}}const ee=o.z.object({tagId:o.z.string()});class te extends e.BaseHederaQueryTool{constructor(e){const{bee:t,config:r,...o}=e;super(o),this.name="swarm-query-upload-progress",this.description="Query upload progress for a specific upload session identified with the returned Tag ID.\n tagId: Tag ID returned by swarm-upload-file and swarm-upload-folder tools to track upload progress.\n ",this.namespace="swarm",this.specificInputSchema=ee,this.bee=t,this.config=r}async executeQuery(e){if(!e?.tagId)throw this.logger.error("Missing required parameter: tagId."),new Error("Missing required parameter: tagId.");const t=Number.parseInt(e.tagId,10);if(Number.isNaN(t))throw this.logger.error("Invalid tagId format. Expected a numeric string."),new Error("Invalid tagId format. Expected a numeric string.");try{const e=await this.bee.retrieveTag(t),r=e.synced??0,o=r+(e.seen??0),s=e.split??0,n=e.startedAt,i=s>0?Math.round(o/s*100):0,a=100===i;let c=!1;if(a)try{await this.bee.deleteTag(t),c=!0}catch{}return z({processedPercentage:i,message:a?"Upload completed successfully.":`Upload progress: ${i}% processed`,startedAt:n,tagAddress:e.address})}catch(r){let t=`Failed to retrieve upload progress: ${r?.message??"Unknown error"}`;throw 404===(r?.status??r?.response?.status)&&(t=`Tag with ID ${e.tagId} does not exist or has been deleted. `+L),this.logger.error(t,r),new Error(t)}}}const re=o.z.object({reference:o.z.string(),filePath:o.z.string().optional()});class oe extends e.BaseHederaQueryTool{constructor(e){const{bee:t,config:r,...o}=e;super(o),this.name="swarm-download-files",this.description="Download folder, files from a Swarm reference and save to file path or return file list of the reference.\n Prioritizes this tool over swarm-download-data if there is no assumption about the data type.\n reference: Swarm reference hash.\n filePath: Optional file path to save the downloaded content (only available in stdio mode). If not provided list of files in the manifest will be returned.\n ",this.namespace="swarm",this.specificInputSchema=re,this.bee=t,this.config=r}async executeQuery(e){const{reference:t,filePath:r}=e;if(!t)throw this.logger.error("Missing required parameter: reference."),new Error("Missing required parameter: reference.");this.logger.info(`[API] Downloading folder from Swarm with reference: ${t}.`);let o,s=!1;try{o=await a.MantarayNode.unmarshal(this.bee,t),await o.loadRecursively(this.bee),s=!0}catch(n){}if(s){if(r){const e=r;c.existsSync(e)||await g.promisify(c.mkdir)(e,{recursive:!0});const s=o.collect();if(1===s.length){const t=s[0],r=await this.bee.downloadData(t.targetAddress);await g.promisify(c.writeFile)(l.join(e,t.fullPathString.split("\\").slice(-1)[0]),r.toUint8Array())}else for(const t of s){const r=l.parse(t.fullPathString),o=l.join(e,r.dir);c.existsSync(o)||await g.promisify(c.mkdir)(o,{recursive:!0});const s=await this.bee.downloadData(t.targetAddress);await g.promisify(c.writeFile)(l.join(e,t.fullPathString),s.toUint8Array())}return{content:[{type:"text",text:JSON.stringify({reference:t,manifestNodeCount:s.length,savedTo:e,message:`Manifest content (${s.length} files) successfully downloaded to ${e}`},null,2)}]}}{const e=o.collect().map(e=>({path:e.fullPathString||"/",targetAddress:Array.from(e.targetAddress).map(e=>e.toString(16).padStart(2,"0")).join(""),metadata:e.metadata}));return{content:[{type:"text",text:JSON.stringify({reference:t,type:"manifest",files:e,message:"This is a manifest with multiple files. Provide a filePath to download all files or download individual files using their specific references."},null,2)}]}}}return"Try swarm-download-data tool instead since the given reference is not a manifest."}}const se=o.z.object({postageBatchId:o.z.string()});class ne extends e.BaseHederaQueryTool{constructor(e){const{bee:t,config:r,...o}=e;super(o),this.name="swarm-get-postage-stamp",this.description="Get a specific postage stamp based on postageBatchId.\n postageBatchId: The id of the stamp which is requested.\n ",this.namespace="swarm",this.specificInputSchema=se,this.bee=t,this.config=r}async executeQuery(e){const{postageBatchId:t}=e;if(!t)throw this.logger.error("Missing required parameter: postageBatchId."),new Error("Missing required parameter: postageBatchId.");let r;try{r=await this.bee.getPostageBatch(t)}catch(n){let e="Retrieval of postage batch failed.";throw D(n,P)&&(e=N),this.logger.error(e,n),new Error(e)}const o={...r,batchID:r.batchID.toHex()},s=B(r);return z({raw:o,summary:s})}}const ie=o.z.object({memoryTopic:o.z.string(),owner:o.z.string().optional()});class ae extends e.BaseHederaQueryTool{constructor(e){const{bee:t,config:r,...o}=e;super(o),this.name="swarm-read-feed",this.description="Retrieve the latest data from the feed of a given topic.\n memoryTopic: Feed topic.\n owner: When accessing external memory or feed, ethereum address of the owner must be set.\n ",this.namespace="swarm",this.specificInputSchema=ie,this.bee=t,this.config=r}async executeQuery(e){const{memoryTopic:t,owner:r}=e;if(!t)throw this.logger.error("Missing required parameter: memoryTopic."),new Error("Missing required parameter: memoryTopic.");if(this.logger.info(`[API] Downloading text from Swarm feed with topic: ${t}.`),!this.config.beeFeedPK)throw this.logger.error("Feed private key not configured."),new Error("Feed private key not configured.");let o=t;o.startsWith("0x")&&(o=o.slice(2));if(!/^[0-9a-fA-F]{64}$/.test(o)){o=u.createHash("sha256").update(t).digest("hex")}const s=$(o);let n,i=r;if(i){if(i.startsWith("0x")&&(i=i.slice(2)),40!==i.length)throw this.logger.error("Owner must be a valid Ethereum address."),new Error("Owner must be a valid Ethereum address.")}else{const e=$(this.config.beeFeedPK);i=new h.Wallet(e).getAddressString().slice(2)}try{const e=this.bee.makeFeedReader(s,i);n=(await e.downloadPayload()).payload.toUtf8()}catch(a){let e="Reading feed failed.";throw D(a,O)&&(e=H(a)),this.logger.error(e,a),new Error(e)}return z({textData:n})}}const ce=o.z.object({data:o.z.string(),memoryTopic:o.z.string(),postageBatchId:o.z.string().optional()});class le extends e.BaseHederaQueryTool{constructor(e){const{bee:t,config:r,...o}=e;super(o),this.name="swarm-update-feed",this.description="Update the feed of a given topic with new data.\n data: Arbitrary string to upload.\n memoryTopic: If provided, uploads the data to a feed with this topic. It is the label of the memory that can be used later to retrieve the data instead of its content hash. If not a hex string, it will be hashed to create a feed topic.\n postageBatchId: The postage stamp batch ID which will be used to perform the upload, if it is provided.",this.namespace="swarm",this.specificInputSchema=ce,this.bee=t,this.config=r}async executeQuery(e){const{data:t,memoryTopic:r,postageBatchId:o}=e;if(!t)throw this.logger.error("Missing required parameter: data."),new Error("Missing required parameter: data.");if(!r)throw this.logger.error("Missing required parameter: topic."),new Error("Missing required parameter: topic.");let s="";try{s=await j(o,this.bee,this.config)}catch(m){let e="Update feed failed.";throw m instanceof Error&&(e=m.message),this.logger.error(e),new Error(e)}const n=globalThis.Buffer.from(t);if(!this.config.beeFeedPK)throw this.logger.error("Feed private key not configured."),new Error("Feed private key not configured.");let i=r;i.startsWith("0x")&&(i=i.slice(2));if(!/^[0-9a-fA-F]{64}$/.test(r)){i=u.createHash("sha256").update(r).digest("hex")}const a=$(i),c=$(this.config.beeFeedPK),l=new h.Wallet(c).getAddressString().slice(2);let g;try{const e=this.bee.makeFeedWriter(a,c);g=await e.uploadPayload(s,n)}catch(m){let e="Unable to update feed.";throw D(m,O)&&(e=H(m)),this.logger.error(e,m),new Error(e)}const d=g.reference.toString();return z({reference:d,topicString:r,topic:i,feedUrl:`${this.bee.url}/feeds/${l}/${i}`,message:"Data successfully uploaded to Swarm and linked to feed."})}}const ge=o.z.object({data:o.z.string(),isPath:o.z.boolean(),redundancyLevel:o.z.number().optional(),postageBatchId:o.z.string().optional()});class he extends e.BaseHederaQueryTool{constructor(e){const{bee:t,config:r,...o}=e;super(o),this.name="swarm-upload-file",this.description="Upload a file to Swarm.\n data: base64 encoded file content or file path.\n isPath: Wether the data parameter is a path.\n redundancyLevel: Redundancy level for fault tolerance (higher values provide better fault tolerance but increase storage overhead). 0 - none, 1 - medium, 2 - strong, 3 - insane, 4 - paranoid.\n postageBatchId: The postage stamp batch ID which will be used to perform the upload, if it is provided.",this.namespace="swarm",this.specificInputSchema=ge,this.bee=t,this.config=r}async executeQuery(e){const{data:t,isPath:r,redundancyLevel:o,postageBatchId:s}=e;if(!t)throw this.logger.error("Missing required parameter: data."),new Error("Missing required parameter: data.");let n,i,a="";try{a=await j(s,this.bee,this.config)}catch(y){let e="Upload file failed.";throw y instanceof Error&&(e=y.message),this.logger.error(e),new Error(e)}if(r){try{n=await g.promisify(c.readFile)(t)}catch(w){throw this.logger.error(`Unable to read file at path: ${t}.`,w),new Error(`Unable to read file at path: ${t}.`)}i=t.split("/").pop()}else n=globalThis.Buffer.from(t,"base64");const l=o,h={},u=Number(this.config.deferredUploadSizeThresholdMB)||5,d=n.length>1024*u*1024;h.deferred=d,l&&(h.redundancyLevel=l);let m,p,f="File successfully uploaded to Swarm";if(d)try{const e=await this.bee.createTag();h.tag=e.uid,m=e.uid.toString(),f="File upload started in deferred mode. Use query_upload_progress to track progress."}catch(y){if(D(y,P))throw this.logger.error(L,y),new Error(L)}try{p=await this.bee.uploadFile(a,n,i,h)}catch(y){let e="Unable to upload file.";throw D(y,O)&&(e=H(y)),this.logger.error(e,y),new Error(e)}return z({reference:p.reference.toString(),url:this.bee.url+"/bzz/"+p.reference.toString(),message:f,tagId:m})}}const ue=o.z.object({folderPath:o.z.string(),redundancyLevel:o.z.number().optional(),postageBatchId:o.z.string().optional()});class de extends e.BaseHederaQueryTool{constructor(e){const{bee:t,config:r,...o}=e;super(o),this.name="swarm-upload-folder",this.description="Upload a folder to Swarm.\n folderPath: Path to the folder to upload. \n redundancyLevel: Redundancy level for fault tolerance (higher values provide better fault tolerance but increase storage overhead). 0 - none, 1 - medium, 2 - strong, 3 - insane, 4 - paranoid. \n postageBatchId: The postage stamp batch ID which will be used to perform the upload, if it is provided.",this.namespace="swarm",this.specificInputSchema=ue,this.bee=t,this.config=r}async executeQuery(e){const{folderPath:t,redundancyLevel:r,postageBatchId:o}=e;if(!t)throw this.logger.error("Missing required parameter: folderPath."),new Error("Missing required parameter: folderPath.");if(!(await g.promisify(c.stat)(t)).isDirectory())throw this.logger.error(`Path is not a directory: ${t}.`),new Error(`Path is not a directory: ${t}.`);let s="";try{s=await j(o,this.bee,this.config)}catch(u){let e="Upload folder failed.";throw u instanceof Error&&(e=u.message),this.logger.error(e),new Error(e)}const n=r,i={};n&&(i.redundancyLevel=n);i.deferred=!0;let a,l,h="Folder successfully uploaded to Swarm";try{const e=await this.bee.createTag();a=e.uid.toString(),i.tag=e.uid,h="Folder upload started in deferred mode. Use swarm-query-upload-progress to track progress."}catch(u){this.logger.error("Failed to create tag",u),i.deferred=!1}try{l=await this.bee.uploadFilesFromDirectory(s,t,i)}catch(u){let e="Unable to upload folder.";throw D(u,O)&&(e=H(u)),this.logger.error(e,u),new Error(e)}return z({reference:l.reference.toString(),url:this.bee.url+"/bzz/"+l.reference.toString(),message:h,tagId:a})}}class me extends e.BasePlugin{constructor(e){super(),this.id="swarm",this.name="Swarm Plugin",this.description="Swarm operations: tools for interacting with the Swarm decentralized storage.",this.version="1.0.0",this.author="Solar Punk",this.namespace="swarm",this.tools=[],this.config=e||null}async initialize(e){await super.initialize(e);const t=e.config.hederaKit;if(!t)return this.context.logger.warn("SwarmPlugin skipped because HederaAgentKit was not present in plugin context."),void(this.tools=[]);if(!this.config)return this.context.logger.warn("SwarmPlugin skipped because Swarm config was not present."),void(this.tools=[]);const r=this.config.beeApiUrl,o=new a.Bee(r),s=new X({hederaKit:t,bee:o,config:this.config,logger:this.context.logger}),n=new V({hederaKit:t,bee:o,config:this.config,logger:this.context.logger}),i=new oe({hederaKit:t,bee:o,config:this.config,logger:this.context.logger}),c=new Q({hederaKit:t,bee:o,config:this.config,logger:this.context.logger}),l=new ne({hederaKit:t,bee:o,config:this.config,logger:this.context.logger}),g=new K({hederaKit:t,bee:o,config:this.config,logger:this.context.logger}),h=new te({hederaKit:t,bee:o,config:this.config,logger:this.context.logger}),u=new ae({hederaKit:t,bee:o,config:this.config,logger:this.context.logger}),d=new le({hederaKit:t,bee:o,config:this.config,logger:this.context.logger}),m=new W({hederaKit:t,bee:o,config:this.config,logger:this.context.logger}),p=new he({hederaKit:t,bee:o,config:this.config,logger:this.context.logger}),f=new de({hederaKit:t,bee:o,config:this.config,logger:this.context.logger});this.tools=[s,n,i,c,l,g,h,u,d,m,p,f],this.context.logger.info("Swarm Plugin initialized.")}getTools(){return this.tools}async cleanup(){this.tools=[]}}class pe{constructor(){this.patterns=new Map,this.initializeDefaultPatterns()}static getInstance(){return pe.instance||(pe.instance=new pe),pe.instance}initializeDefaultPatterns(){this.register("numeric-supply-exact",{pattern:["maxSupply","minSupply","totalSupply"],type:"number",priority:15}),this.register("numeric-supply",{pattern:/supply$/i,type:"number",priority:10}),this.register("numeric-amounts",{pattern:/(?:amount|quantity|count|total|sum|value)$/i,type:"number",priority:8}),this.register("numeric-time",{pattern:/(?:period|duration|time|timeout|delay|interval)$/i,type:"number",priority:8}),this.register("numeric-limits",{pattern:/(?:limit|max|min|threshold|size|length)$/i,type:"number",priority:7}),this.register("currency",{pattern:/(?:price|cost|fee|payment|balance|amount)$/i,type:"currency",priority:9}),this.register("percentage",{pattern:/(?:percent|percentage|rate|ratio)$/i,type:"percentage",priority:9}),this.register("boolean-freeze",{pattern:["freezeDefault","freeze"],type:"checkbox",priority:10}),this.register("boolean-flags",{pattern:/(?:is|has|can|should|enable|disable|active|default|allow)(?:[A-Z]|$)/,type:"checkbox",priority:8}),this.register("textarea",{pattern:/(?:memo|description|notes|comment|message|content|body|text)$/i,type:"textarea",priority:8}),this.register("array-fees",{pattern:["customFees","fees"],type:"array",priority:10}),this.register("array-general",{pattern:/(?:list|items|array|collection)$/i,type:"array",priority:7}),this.register("object-options",{pattern:["metaOptions","options"],type:"object",priority:10}),this.register("object-config",{pattern:/(?:config|settings|configuration|metadata|data|info)$/i,type:"object",priority:7}),this.register("select-type",{pattern:/(?:type|kind|category|status|state|mode)$/i,type:"select",priority:7})}register(e,t){this.patterns.set(e,t)}unregister(e){return this.patterns.delete(e)}detectType(e){const t=[];for(const r of this.patterns.values()){let o=!1;Array.isArray(r.pattern)?o=r.pattern.some(t=>e===t||e.toLowerCase()===t.toLowerCase()):r.pattern instanceof RegExp&&(o=r.pattern.test(e)),o&&t.push({type:r.type,priority:r.priority??5})}return t.length>0?(t.sort((e,t)=>t.priority-e.priority),t[0].type):null}getPatterns(){return new Map(this.patterns)}clear(){this.patterns.clear()}reset(){this.clear(),this.initializeDefaultPatterns()}}const fe=pe.getInstance(),ye="Too many requests. Please wait a moment and try again.",we="I'm receiving too many requests right now. Please wait a moment and try again.";var be=(e=>(e.TOPIC_ID="topicId",e.HRL="hrl",e.SCHEDULE_ID="scheduleId",e.TOKEN_ID="tokenId",e.ADDRESS="address",e.SYMBOL="symbol",e.SERIAL_NUMBER="serialNumber",e.METADATA="metadata",e.ACCOUNT_ID="accountId",e.ALIAS="alias",e.EVM_ADDRESS="evmAddress",e.CONTRACT_ID="contractId",e.FILE_ID="fileId",e.ANY="any",e))(be||{});const Te="the topic",Se="the token";be.TOPIC_ID,be.TOKEN_ID,be.ACCOUNT_ID,be.CONTRACT_ID;const ve={ESSENTIAL:"essential",COMMON:"common",ADVANCED:"advanced",EXPERT:"expert"};function ke(e){return"object"==typeof e&&null!==e&&"shape"in e}class Ce{constructor(){this.logger=new r.Logger({module:"FormGenerator"})}generateFormFromError(e,t,r,o){const s=this.extractValidationErrors(e),n=this.identifyMissingFields(s,t),i=this.createFormConfig(t,n,r);return{type:"form",id:`form_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,formConfig:i,originalPrompt:o,toolName:r,validationErrors:s}}async generateFormFromSchema(e,t,r,o){let s;if(this.logger.info("🏁 FormGenerator.generateFormFromSchema starting",{toolName:r.toolName,partialInput:t,hasSchema:!!e,hasShape:!(!e||!ke(e)),hasPreCalculatedFields:void 0!==o,preCalculatedFieldsSize:o?.size||0}),void 0!==o)s=o,this.logger.info("📋 Using pre-calculated missing fields",{missingFieldsCount:s.size,missingFields:Array.from(s)});else{s=new Set;const t=this.extractZodObject(e);if(t){const e=t.shape;for(const t of Object.keys(e))s.add(t),this.logger.info(`⭐ Including all fields from focused schema: ${t}`)}this.logger.info("📋 Using ALL fields from focused schema",{totalFields:t?Object.keys(t.shape).length:0,missingFieldsCount:s.size,missingFields:Array.from(s)})}const n=this.createFormConfig(e,s,r.toolName,o);return{type:"form",id:`form_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,formConfig:n,originalPrompt:r.toolDescription||`Complete ${r.toolName}`,toolName:r.toolName,validationErrors:[]}}extractValidationErrors(e){return e.issues.map(e=>({path:e.path.map(e=>String(e)),message:e.message,code:e.code}))}identifyMissingFields(e,t){const r=new Set;return e.forEach(e=>{const t=e.path.join(".");t&&r.add(t)}),r}createFormConfig(e,t,r,o){const s=this.extractRenderConfigsSafely(e),n=this.generateFieldOrderingSafely(e),i=this.generateFormFields(e,s,t,n,o,r),a=C.getGlobalGuidance(r);let c=this.generateFormDescription(r,t.size);return a?.qualityStandards&&(c+="\n\nQuality Guidelines:\n"+a.qualityStandards.map(e=>`• ${e}`).join("\n")),{title:this.generateFormTitle(r),description:c,fields:i,submitLabel:"Continue",cancelLabel:"Cancel",metadata:{toolName:r,missingFieldCount:t.size,globalGuidance:a}}}extractRenderConfigsSafely(e){try{if("function"==typeof t.extractRenderConfigs)return t.extractRenderConfigs(e)}catch(r){this.logger.warn("Could not extract render configs:",r)}return{fields:{},groups:{},order:[],metadata:{}}}generateFieldOrderingSafely(e){try{if("function"==typeof t.generateFieldOrdering){const r=t.generateFieldOrdering(e);return{sections:Object.values(r.sections).map(e=>({fields:e.fields}))}}}catch(r){this.logger.warn("Could not generate field ordering:",r)}return{sections:[]}}getFieldPriority(e,t,r){if(t?.ui?.priority){const e=t.ui.priority;if(Object.values(ve).includes(e))return e}if(!0===r)return ve.ESSENTIAL;const o=t?.ui;return!0===o?.advanced?ve.ADVANCED:!0===o?.expert?ve.EXPERT:ve.COMMON}determineFieldsToInclude(e,t,r){const o=new Set;if(void 0===r){this.logger.info("⭐ Focused schema mode - including ALL fields from schema");this.extractFieldsFromSchema(e).forEach(e=>{o.add(e),this.logger.info(`✅ Including focused schema field: ${e}`)})}else r.size>0?(this.logger.info(`📋 Using ONLY pre-calculated missing fields (${r.size} fields)`,{fields:Array.from(r)}),r.forEach(e=>{o.add(e),this.logger.info(`✅ Including pre-calculated field: ${e}`)})):(this.logger.info("⚠️ No pre-calculated fields, falling back to schema analysis"),this.includeRequiredMissingFields(e,t,o));return o}includeRequiredMissingFields(e,t,r){this.extractFieldsFromSchema(e).forEach(o=>{const s=this.isFieldRequired(e,o),n=t.has(o),i=n&&s;this.logger.info(`🔍 FormGenerator field inclusion check: ${o}`,{isRequired:s,isMissing:n,shouldInclude:i}),i&&r.add(o)})}createOrderedFields(e,t,r,o,s){const n=[],i=new Set;if(t.sections.length>0){t.sections.flatMap(e=>e.fields).forEach(t=>{if(e.has(t)&&!i.has(t)){const e=this.createFormField(t,r.fields[t],o,t,s);e&&(n.push(e),i.add(t))}})}return e.forEach(e=>{if(!i.has(e)){const t=this.createFormField(e,r.fields[e],o,e,s);t&&n.push(t)}}),n}generateFormFields(e,t,r,o,s,n){const i=this.determineFieldsToInclude(e,r,s);let a=this.createOrderedFields(i,o,t,e,n);return 0===a.length&&r.size>0&&(a=Array.from(r).map(r=>this.createFormField(r,t.fields[r],e,r,n)).filter(e=>null!=e)),a}createFormField(e,t,r,o,s){const n=this.mapFieldType(t?.fieldType,r,o),i=this.isFieldRequired(r,o||e),a=s?C.getFieldGuidance(s,e):null,c=a?.fieldTypeOverride||n,l={name:e,label:t?.ui?.label||this.humanizeFieldName(e),type:c,required:i,priority:this.getFieldPriority(e,t,i)};if(a&&(a.suggestions&&a.suggestions.length>0&&(l.suggestions=a.suggestions,l.placeholder||(l.placeholder=`e.g., ${a.suggestions[0]}`)),a.predefinedOptions&&(l.options=[...l.options||[],...a.predefinedOptions]),a.contextualHelpText&&(l.helpText=a.contextualHelpText),a.warnings&&(l.warnings=a.warnings.map(e=>e.message)),a.validationRules)){const{qualityChecks:e}=a.validationRules;e&&(l.contextualGuidance={qualityStandards:[],examples:a.suggestions||[],avoidPatterns:e.forbidTechnicalTerms||[]},e.minNonTechnicalWords&&l.contextualGuidance.qualityStandards?.push(`Use at least ${e.minNonTechnicalWords} meaningful words`),e.forbidTechnicalTerms&&l.contextualGuidance.qualityStandards?.push(`Avoid technical terms like: ${e.forbidTechnicalTerms.join(", ")}`))}if(t&&(l.renderConfig=t),t?.ui?.placeholder&&(l.placeholder=t.ui.placeholder),t?.ui?.helpText&&(l.helpText=t.ui.helpText),t?.constraints){const e={};void 0!==t.constraints.min&&(e.min=t.constraints.min),void 0!==t.constraints.max&&(e.max=t.constraints.max),void 0!==t.constraints.minLength&&(e.minLength=t.constraints.minLength),void 0!==t.constraints.maxLength&&(e.maxLength=t.constraints.maxLength),void 0!==t.constraints.pattern&&(e.pattern=t.constraints.pattern),Object.keys(e).length>0&&(l.validation=e)}return t?.options&&(l.options=t.options.map(e=>({value:String(e.value),label:e.label,...void 0!==e.disabled&&{disabled:e.disabled}}))),l}mapFieldType(e,t,r){if(!e&&t&&r){const e=this.inferTypeFromSchema(t,r);if(e)return e}if(!e&&r){const e=fe.detectType(r);if(e)return e}if(!e)return"text";const o=e.toLowerCase();return["text","string"].includes(o)?"text":["number","integer","float","decimal"].includes(o)?"number":["select","enum","dropdown"].includes(o)?"select":["checkbox","boolean","bool"].includes(o)?"checkbox":["textarea","longtext","multiline"].includes(o)?"textarea":["file","upload","attachment"].includes(o)?"file":["array","list"].includes(o)?"array":["object","json"].includes(o)?"object":["currency","money","price"].includes(o)?"currency":["percentage","percent"].includes(o)?"percentage":"text"}humanizeFieldName(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\./g," ").trim().split(" ").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}generateFormTitle(e){return`Complete ${e.replace(/Tool$/,"").replace(/Hedera/g,"").replace(/([A-Z])/g," $1").trim()} Information`}extractZodObject(e){try{const t=e._def;if(t&&"ZodObject"===t.typeName)return e}catch(t){this.logger.debug("Could not extract ZodObject from schema:",t)}return null}extractFieldsFromSchema(e){const t=[],r=this.extractZodObject(e);if(r)return t.push(...Object.keys(r.shape)),t;try{const r=e._def;if(r&&"ZodUnion"===r.typeName&&r.options){const e=r.options[0],o=this.extractZodObject(e);o&&t.push(...Object.keys(o.shape))}}catch(o){this.logger.debug("Could not extract fields from schema structure:",o)}return t}inferTypeFromSchema(e,t){try{const r=this.extractZodObject(e);if(!r)return null;const o=r.shape;if(!o)return null;let s=o[t];if(!s)return null;const n=s._def;if(n&&"ZodOptional"===n.typeName&&n.innerType&&(s=n.innerType),!s||!s._def)return null;const i=s._def.typeName,a=t.toLowerCase();switch(i){case"ZodString":return a.includes("memo")||a.includes("description")?"textarea":"text";case"ZodNumber":return a.includes("percent")?"percentage":a.includes("price")||a.includes("cost")?"currency":"number";case"ZodBoolean":return"checkbox";case"ZodEnum":case"ZodNativeEnum":return"select";case"ZodArray":return"array";case"ZodObject":return"object";default:return"text"}}catch(r){this.logger.debug("Could not infer type from schema:",r)}return null}isFieldRequired(e,t){if(!e||!t)return!1;try{const r=this.extractZodObject(e);if(!r)return!1;const o=r.shape;if(!o||!o[t])return!1;const s=o[t];if(!s||!s._def)return!0;const n=s._def,i=n.typeName;return"ZodOptional"!==i&&("ZodDefault"!==i&&void 0===n.defaultValue)}catch(r){this.logger.debug(`Could not determine if field ${t} is required:`,r)}return!1}generateFormDescription(e,t){return 0===t?"Please provide the required information to continue with your request.":`Please provide the following ${t} required field${1!==t?"s":""} to continue with your request.`}generateJsonSchemaForm(e,t,r){const o=m.zodToJsonSchema(e,{target:"jsonSchema7"}),s={};let n=o;if(r&&r.size>0){const e=o;if(e.properties&&"object"==typeof e.properties){const t={...e,type:"object",properties:{},required:[]};let o=0;r.forEach(r=>{e.properties&&e.properties[r]&&(t.properties[r]=e.properties[r],o++)}),Array.isArray(e.required)&&(t.required=e.required.filter(e=>r.has(e))),o>0&&(n=t)}}return this.extractFieldsFromSchema(e).forEach(t=>{const r=this.isFieldRequired(e,t),o=this.getFieldPriority(t,void 0,r),n=t.toLowerCase();switch("attributes"!==n&&"metadata"!==n&&"properties"!==n||(s[t]={"ui:options":{collapsible:!0,collapsed:!0}}),o){case"essential":r&&(s[t]={...s[t],"ui:help":"Required field"});break;case"advanced":case"expert":s[t]={...s[t],"ui:options":{...s[t]?.["ui:options"],collapsed:!0}}}}),{jsonSchema:n,uiSchema:s}}}class Ie{constructor(e){this.formGenerator=new Ce,this.logger=e||new r.Logger({module:"FormEngine"})}async generateForm(e,r,s,n){const i={tool:r,input:s,...n};try{return t.isFormValidatable(r)?await this.generateFormValidatableForm(r,s,i):s instanceof o.ZodError?await this.generateErrorBasedForm(r,s,i):this.hasRenderConfig(r)?await this.generateRenderConfigForm(r,s,i):this.isZodObject(r.schema)?await this.generateSchemaBasedForm(r,s,i):null}catch(a){throw this.logger.error(`Failed to generate form for tool: ${e}`,{error:a instanceof Error?a.message:String(a)}),a}}async processSubmission(e,t){this.validateSubmission(e);const r=this.extractBaseToolInput(t),o=this.extractSubmissionData(e);return this.mergeInputData(r,o)}shouldGenerateForm(e,r){const o=r;if(!0===o?.__fromForm||!1===o?.renderForm)return!1;if(t.isFormValidatable(e))try{return e.shouldGenerateForm(r)}catch(s){return this.logger.error(`Error calling shouldGenerateForm() on ${e.name}:`,s),!1}return!this.validateInput(e,r).isValid}async generateFormFromError(e,t,r,o){return this.formGenerator.generateFormFromError(e,r,t,o)}async generateFormValidatableForm(e,t,r){const{schemaToUse:o,isFocusedSchema:s}=this.resolveFormSchema(e),n=this.determineMissingFields(e,t,o,s);return this.generateFormWithSchema(e,t,o,n)}async generateSchemaBasedForm(e,t,r){const o=e.schema,s=await this.formGenerator.generateFormFromSchema(o,t,{toolName:e.name,toolDescription:e.description},r.missingFields);if(this.isZodObject(o))try{const{jsonSchema:e,uiSchema:n}=this.formGenerator.generateJsonSchemaForm(o,t,r.missingFields||new Set);s.jsonSchema=e,s.uiSchema=n}catch(n){this.logger.warn("Failed to generate JSON Schema for schema-based tool:",n)}return s.partialInput=t,s}async generateRenderConfigForm(e,t,r){const o=e.schema,s=this.extractRenderConfig(e),n=await this.formGenerator.generateFormFromSchema(o,t,{toolName:e.name,toolDescription:e.description},r.missingFields);return s&&(n.formConfig.metadata={...n.formConfig.metadata,renderConfig:s}),n.partialInput=t,n}async generateErrorBasedForm(e,t,r){return this.formGenerator.generateFormFromError(t,e.schema,e.name,r.input?String(r.input):"")}validateInput(e,t){try{return e.schema.parse(t),{isValid:!0}}catch(r){if(r instanceof o.ZodError){return{isValid:!1,errors:r.errors.map(e=>`${e.path.join(".")}: ${e.message}`)}}return{isValid:!1,errors:["Validation failed"]}}}isZodObject(e){if(!e||"object"!=typeof e)return!1;const t=e;return Boolean(t._def&&"ZodObject"===t._def.typeName)}hasRenderConfig(e){const t=e.schema;return!(!t||!t._renderConfig)}extractRenderConfig(e){const t=e.schema;return t?._renderConfig}resolveFormSchema(e){const t=e;if(t.getFormSchema){const e=t.getFormSchema();if(e)return{schemaToUse:e,isFocusedSchema:!0}}return{schemaToUse:e.schema,isFocusedSchema:!1}}determineMissingFields(e,t,r,o){const s=new Set;if(!t||"object"!=typeof t)return s;const n=t,i=e;if(i.getEssentialFields){const e=i.getEssentialFields();for(const t of e)(!(t in n)||i.isFieldEmpty&&i.isFieldEmpty(t,n[t]))&&s.add(t)}return s}async generateFormWithSchema(e,t,r,o){const s=await this.formGenerator.generateFormFromSchema(r,t,{toolName:e.name,toolDescription:e.description},o);if(this.isZodObject(r))try{const{jsonSchema:e,uiSchema:n}=this.formGenerator.generateJsonSchemaForm(r,t,o);s.jsonSchema=e,s.uiSchema=n}catch(n){this.logger.warn("Failed to generate JSON Schema:",n)}return s.partialInput=t,s}validateSubmission(e){if(!e.toolName)throw new Error("Tool name is required in form submission");if(!e.parameters)throw new Error("Parameters are required in form submission")}extractBaseToolInput(e){return e?.originalInput||{}}extractSubmissionData(e){return{...e.parameters,__fromForm:!0}}mergeInputData(e,t){return{...e,...t}}getRegisteredStrategies(){return["FormValidatable","SchemaBased","RenderConfig","ZodErrorBased"]}getRegisteredMiddleware(){return["FormSubmissionValidator"]}}class xe{static isHashLinkResponse(e){if(!e||"object"!=typeof e)return!1;const t=e;return!(!0!==t.success||"inscription"!==t.type||!t.hashLinkBlock||"object"!=typeof t.hashLinkBlock)}static formatHashLinkResponse(e){const t=e.hashLinkBlock,r=e.metadata||{},o=e.inscription||{};let s="✅ Interactive content created successfully!\n\n";return r.name&&(s+=`**${r.name}**\n`),r.description&&(s+=`${r.description}\n\n`),(o.topicId||t.attributes.topicId)&&(s+=`📍 **Topic ID:** ${o.topicId||t.attributes.topicId}\n`),(o.hrl||t.attributes.hrl)&&(s+=`🔗 **HRL:** ${o.hrl||t.attributes.hrl}\n`),o.cdnUrl&&(s+=`🌐 **CDN URL:** ${o.cdnUrl}\n`),r.creator&&(s+=`👤 **Creator:** ${r.creator}\n`),s+="\n⚡ Interactive content will load below",s.trim()}static isInscriptionResponse(e){if(!e||"object"!=typeof e)return!1;const t=e;return!(!0!==t.success||"inscription"!==t.type||!t.inscription||"object"!=typeof t.inscription)}static formatInscriptionResponse(e){const t=e.inscription,r=e.metadata||{};let o=`✅ ${e.title||"Inscription Complete"}\n\n`;return r.name&&(o+=`**${r.name}**\n`),r.description&&(o+=`${r.description}\n\n`),t.topicId&&(o+=`📍 **Topic ID:** ${t.topicId}\n`),t.hrl&&(o+=`🔗 **HRL:** ${t.hrl}\n`),t.cdnUrl&&(o+=`🌐 **CDN URL:** ${t.cdnUrl}\n`),r.creator&&(o+=`👤 **Creator:** ${r.creator}\n`),o.trim()}static formatResponse(e){try{const t=JSON.parse(e);return xe.isHashLinkResponse(t)?xe.formatHashLinkResponse(t):xe.isInscriptionResponse(t)?xe.formatInscriptionResponse(t):e}catch{return e}}}const Me=new Map;class Ee extends d.AgentExecutor{constructor(...e){super(...e),this.pendingForms=new Map,this.formGenerator=new Ce,this.formEngine=new Ie(new r.Logger({module:"FormAwareAgentExecutor.FormEngine"})),this.formLogger=new r.Logger({module:"FormAwareAgentExecutor"}),this.parameterPreprocessingCallback=void 0}isZodObject(e){return e instanceof o.z.ZodObject}hasHashLinkBlock(e){return"object"==typeof e&&null!==e&&"hashLinkBlock"in e&&"object"==typeof e.hashLinkBlock&&null!==e.hashLinkBlock}setParameterPreprocessingCallback(e){this.parameterPreprocessingCallback=e}async _takeNextStep(e,r,o,s,n){this.formLogger.info("🛡️ BULLETPROOF INTERCEPTION: _takeNextStep called",{availableTools:Object.keys(e),inputKeys:Object.keys(r)});const i=await this.agent.plan(o,r,s?.getChild());if("returnValues"in i)return this.formLogger.info("Agent returned finish action, passing through"),i;const a=i,c=a.tool,l=a.toolInput;this.formLogger.info(`🎯 INTERCEPTING TOOL CALL: ${c}`,{toolInput:l,hasInNameToolMap:c in e,toolInputKeys:Object.keys(l||{})});const g=e[c]||this.tools.find(e=>e.name===c);if(!g)throw this.formLogger.error(`Tool ${c} not found in registry`),new Error(`Tool "${c}" not found`);let h=!1;if(t.isFormValidatable(g)){this.formLogger.info(`🔍 Tool ${c} implements FormValidatable, checking shouldGenerateForm()`,{toolInput:l});try{h=g.shouldGenerateForm(l),this.formLogger.info(`FormValidatable.shouldGenerateForm() result: ${h}`,{toolName:c,toolInput:l})}catch(u){this.formLogger.error(`Error calling shouldGenerateForm() on ${c}:`,u),h=!1}}if(h){this.formLogger.info(`🚨 FORM GENERATION TRIGGERED for ${c}`);try{let e,o=!1;if(t.isFormValidatable(g)){this.formLogger.info(`🎯 Tool ${c} is FormValidatable, attempting to get focused schema`);try{const t=g.getFormSchema();t?(e=t,o=!0,this.formLogger.info(`✅ Successfully obtained focused schema for ${c}`)):(this.formLogger.warn(`getFormSchema() returned null/undefined for ${c}, using default schema`),e=g.schema,o=!1)}catch(u){this.formLogger.error(`Failed to get focused schema from ${c}:`,u),this.formLogger.info(`Falling back to default schema for ${c}`),e=g.schema,o=!1}}else this.formLogger.info(`Tool ${c} is not FormValidatable, using default schema`),e=g.schema,o=!1;let s,n="unknown";try{if(this.isZodObject(e)){const t=e.shape;t&&"object"==typeof t&&(n=Object.keys(t).length.toString())}}catch{}if(this.formLogger.info(`📋 Generating form with ${o?"FOCUSED":"DEFAULT"} schema`,{toolName:c,schemaType:e?.constructor?.name,estimatedFieldCount:n,isFocusedSchema:o}),o)this.formLogger.info("⭐ Using focused schema - letting FormGenerator determine fields from schema"),s=void 0;else{if(s=new Set,this.isZodObject(e)){const r=e.shape||{};for(const o of Object.keys(r)){const r=(l||{})[o],n=t.isFormValidatable(g)&&g.isFieldEmpty?g.isFieldEmpty(o,r):void 0===r||""===r||null===r||Array.isArray(r)&&0===r.length,i=this.isFieldRequired(e,o),a=!(!t.isFormValidatable(g)||!g.getEssentialFields)&&g.getEssentialFields().includes(o);this.formLogger.info(`🔍 Field analysis: ${o}`,{value:r,isEmpty:n,isRequired:i,isEssential:a,willAddToMissingFields:n&&(i||a)}),n&&(i||a)&&s.add(o)}}this.formLogger.info("📋 Missing fields analysis complete",{totalFields:this.isZodObject(e)?Object.keys(e.shape).length:0,missingFieldsCount:s.size,missingFields:Array.from(s)})}const i=await this.formGenerator.generateFormFromSchema(e,l,{toolName:c,toolDescription:g.description},s);if(this.isZodObject(e))try{const{jsonSchema:t,uiSchema:r}=this.formGenerator.generateJsonSchemaForm(e,l,s);i.jsonSchema=t,i.uiSchema=r}catch(u){this.formLogger.warn("Failed to generate JSON Schema for RJSF:",u)}i.partialInput=l;const h={toolName:c,originalInput:r,originalToolInput:l,schema:e,toolRef:g,originalToolRef:g.originalTool};this.pendingForms.set(i.id,h),Me.set(i.id,h),this.formLogger.info(`✅ FORM INTERCEPT SUCCESS for ${c}`);const d={requiresForm:!0,formMessage:i};return[{action:a,observation:JSON.stringify(d)}]}catch(u){this.formLogger.error(`Form generation failed for ${c}:`,u)}}if(this.formLogger.info(`⚪ Passing through to normal tool execution for ${c}`),this.parameterPreprocessingCallback&&l){this.formLogger.info(`🔄 Applying parameter preprocessing for ${c}`);try{const e=await this.parameterPreprocessingCallback(c,l);if(e&&"object"==typeof e&&"__requestForm"in e){const o=e.__requestForm,s=o.id||`form_${Date.now()}_${Math.random().toString(36).slice(2)}`,n={type:"form",id:s,originalPrompt:"Parameter validation required",toolName:c,formConfig:{title:o.title||"Complete required parameters",description:o.description||"One or more parameters require confirmation. Please review and submit.",submitLabel:o.submitLabel||"Continue",fields:(o.fields||[]).map(e=>{const t=["text","number","select","checkbox","textarea"].includes(e.type)?e.type:"text";return{name:e.name,label:e.label,type:t,required:e.required??!0,options:e.options}})}},i=t.isFormValidatable(g)?(()=>{try{return g.getFormSchema()||g.schema}catch{return g.schema}})():g.schema;return this.pendingForms.set(s,{toolName:c,originalInput:r,originalToolInput:l,schema:i,toolRef:g,originalToolRef:g.originalTool}),Me.set(s,{toolName:c,originalInput:r,originalToolInput:l,schema:i}),[{action:a,observation:JSON.stringify({requiresForm:!0,formMessage:n})}]}if(JSON.stringify(e)!==JSON.stringify(l)){this.formLogger.info(`📝 Parameters preprocessed for ${c}:`,{original:Object.keys(l),preprocessed:Object.keys(e),hasChanges:!0});try{a.toolInput=e}catch{}}else this.formLogger.debug(`No parameter changes needed for ${c}`)}catch(d){this.formLogger.warn(`Parameter preprocessing failed for ${c}, using original parameters:`,d)}}return super._takeNextStep(e,r,o,s,n)}isFieldRequired(e,t){if(!e||!t)return!1;try{const r=e._def;if(!r||"ZodObject"!==r.typeName)return!1;const o="function"==typeof r.shape?r.shape():r.shape;if(!o||"object"!=typeof o)return!1;const s=o[t];if(!s)return!1;const n=(e=>{const t=e._def;return t&&"ZodOptional"===t.typeName&&t.innerType?t.innerType:e})(s)._def;return!n||"ZodOptional"!==n.typeName&&"ZodDefault"!==n.typeName&&void 0===n.defaultValue}catch(r){this.formLogger.debug(`Could not determine if field ${t} is required:`,r)}return!1}async _call(e){try{const t=await super._call(e);if(t.intermediateSteps&&Array.isArray(t.intermediateSteps))for(const r of t.intermediateSteps)if(r.observation)try{const o="string"==typeof r.observation?JSON.parse(r.observation):r.observation;if(o.requiresForm&&o.formMessage){this.formLogger.info("Tool requested form generation",{toolName:r.action?.tool,hasForm:!0});const s=r.action?.tool||"unknown",n=this.tools.find(e=>e.name===s),i=n||{},a={toolName:s,originalInput:e,originalToolInput:r.action?.toolInput,schema:null,toolRef:n,originalToolRef:i?.originalTool};return this.pendingForms.set(o.formMessage.id,a),Me.set(o.formMessage.id,a),{...t,requiresForm:!0,formMessage:o.formMessage,output:o.message||"Please complete the form to continue."}}if(o.hashLinkBlock||o.success&&o.inscription&&o.hashLinkBlock){this.formLogger.info("Tool returned HashLink blocks",{toolName:r.action?.tool,hasHashLink:!0,blockId:o.hashLinkBlock?.blockId});const e=this.processHashLinkResponse(o);return{...t,hasHashLinkBlocks:!0,hashLinkBlock:e.hashLinkBlock,output:e.message}}}catch{}return t}catch(t){if(t instanceof o.ZodError)return this.formLogger.info("Intercepted ZodError during agent execution"),this.handleValidationError(t,e,[]);throw t}}async handleValidationError(e,t,r){this.formLogger.info("Zod validation error detected, generating form",{errorIssues:e.issues.length,inputKeys:Object.keys(t)});let o=this.extractToolInfoFromError(e,t,r);if(!o){this.formLogger.warn("Could not extract tool info from validation error, trying fallback detection");const t=this.detectToolFromErrorContext(e);if(!t)throw this.formLogger.error("No tool detected for form generation, rethrowing error"),e;o=t}this.formLogger.info("Generating form for tool:",{toolName:o.toolName,hasSchema:!!o.schema});const s=this.formGenerator.generateFormFromError(e,o.schema,o.toolName,t.input||"");return this.pendingForms.set(s.id,{toolName:o.toolName,originalInput:t,schema:o.schema}),Me.set(s.id,{toolName:o.toolName,originalInput:t,schema:o.schema}),{output:this.formatFormResponse(s),formMessage:s,requiresForm:!0,intermediateSteps:r||[]}}getPendingForms(){return new Map(this.pendingForms)}restorePendingForms(e){for(const[t,r]of e)this.pendingForms.set(t,r)}async processFormSubmission(e){if(this.formLogger.info("🚀 FormAwareAgentExecutor.processFormSubmission called!",{submissionFormId:e.formId,submissionToolName:e.toolName}),!e)throw new Error("Form submission is null or undefined");if(!e.formId)throw new Error("Form submission missing formId");if(!e.parameters||null===e.parameters||"object"!=typeof e.parameters||Array.isArray(e.parameters))throw new Error(`Form submission parameters are invalid: ${typeof e.parameters}, isNull: ${null===e.parameters}, isArray: ${Array.isArray(e.parameters)}, parameters: ${JSON.stringify(e.parameters)}`);this.formLogger.info("Processing form submission:",{formId:e.formId,toolName:e.toolName,parameterKeys:Object.keys(e.parameters),parametersType:typeof e.parameters,parametersIsNull:null===e.parameters,parametersIsUndefined:void 0===e.parameters,hasContext:!!e.context});let t=this.pendingForms.get(e.formId);if(!t&&(t=Me.get(e.formId),!t))throw new Error(`No pending form found for ID: ${e.formId}`);this.pendingForms.delete(e.formId),Me.delete(e.formId);const r=t.toolRef||this.tools.find(e=>e.name===t.toolName);if(!r)throw new Error(`Tool not found for form submission: ${t.toolName}`);let s={};try{t.originalToolInput&&"object"==typeof t.originalToolInput&&(s={...t.originalToolInput})}catch(a){this.formLogger.warn("Failed to extract base tool input, using empty object:",a),s={}}let n={};try{e.parameters&&"object"==typeof e.parameters&&(n={...e.parameters})}catch(a){this.formLogger.warn("Failed to extract submission parameters, using empty object:",a),n={}}const i={};try{Object.keys(s).forEach(e=>{const t=s[e];null!=t&&(i[e]=t)}),Object.keys(n).forEach(e=>{const t=n[e];null!=t&&(i[e]=t)}),i.renderForm=!1,i.__fromForm=!0,this.formLogger.info("Successfully merged tool input:",{baseKeys:Object.keys(s),submissionKeys:Object.keys(n),mergedKeys:Object.keys(i)})}catch(a){throw this.formLogger.error("Failed to merge tool input data:",a),new Error(`Failed to merge tool input data: ${a instanceof Error?a.message:"Unknown error"}`)}try{const o=r;let s;if("function"==typeof o.executeOriginal)s=await o.executeOriginal(i);else if("function"==typeof o.getOriginalTool){const e=o.getOriginalTool(),t=e;if(e&&"function"==typeof t._call)s=await t._call(i);else if(e&&"function"==typeof t.call)s=await t.call(i);else{const e=r;if("function"!=typeof e.call)throw new Error("No callable tool implementation found for form submission");s=await e.call(i)}}else if(o.originalTool&&"function"==typeof o.originalTool._call)s=await o.originalTool._call(i);else if(o.originalTool&&"function"==typeof o.originalTool.call)s=await o.originalTool.call(i);else{if("function"!=typeof r.call)throw new Error("No callable tool implementation found for form submission");s=await r.call(i)}let n,c={};try{const e=JSON.parse(s);if(this.formLogger.info("✅ METADATA EXTRACTION: Successfully parsed JSON",{jsonKeys:Object.keys(e),hasHashLinkBlock:!!e.hashLinkBlock}),e&&"object"==typeof e)if(xe.isHashLinkResponse(e)){this.formLogger.info("🔗 HASHLINK DETECTED: Processing HashLink response separately to preserve metadata");const t=e;c={...c,hashLinkBlock:t.hashLinkBlock,...t},n=xe.formatHashLinkResponse(e),this.formLogger.info("🔗 METADATA PRESERVED: HashLink metadata extracted for component rendering",{blockId:this.hasHashLinkBlock(c)?c.hashLinkBlock.blockId:void 0,hasTemplate:!!this.hasHashLinkBlock(c)&&!!c.hashLinkBlock.template})}else n=xe.formatResponse(s),c={...c,hashLinkBlock:e.hashLinkBlock,...e};else n=xe.formatResponse(s)}catch(a){this.formLogger.warn("❌ METADATA EXTRACTION: Tool output is not JSON",{error:a instanceof Error?a.message:"unknown error",outputSample:"string"==typeof s?s.substring(0,200):"not-string"}),n=xe.formatResponse(s)}return{output:n,formCompleted:!0,originalFormId:e.formId,intermediateSteps:[],metadata:c,rawToolOutput:s,toolName:t.toolName}}catch(a){if(a instanceof o.ZodError)return this.handleValidationError(a,i,[]);throw a}}extractToolInfoFromError(e,t,r){try{if(r.length>0){const e=r[r.length-1];if(e.action&&e.action.tool){const t=this.tools.find(t=>t.name===e.action.tool);if(t&&"schema"in t)return this.formLogger.info("Found tool from intermediate steps:",e.action.tool),{toolName:e.action.tool,schema:t.schema}}}const e=t.intermediateSteps||[];if(e.length>0){const t=e[e.length-1];let r;if(r=Array.isArray(t)&&t.length>0?t[0]:t.action?t.action:t,r&&r.tool){const e=this.tools.find(e=>e.name===r.tool);if(e&&"schema"in e)return this.formLogger.info("Found tool from input steps:",r.tool),{toolName:r.tool,schema:e.schema}}}const o=this.findToolFromContext(t);return o?(this.formLogger.info("Found tool from context:",o.toolName),o):null}catch(o){return this.formLogger.error("Error extracting tool info:",o),null}}findToolFromContext(e){const t=e.input||"";for(const r of this.tools){if(this.extractToolKeywords(r.name).some(e=>t.toLowerCase().includes(e.toLowerCase()))&&"schema"in r)return{toolName:r.name,schema:r.schema}}return null}detectToolFromErrorContext(e){const t=e.issues.map(e=>e.path.join("."));for(const r of this.tools)if("schema"in r){const e=r.schema;if(this.schemaMatchesErrorPaths(e,t))return this.formLogger.info("Detected tool from error path analysis:",r.name),{toolName:r.name,schema:e}}return null}schemaMatchesErrorPaths(e,t){const r=e;if(!r||!r._def)return!1;try{const e=r._def;if("ZodObject"===e.typeName){const r=e.shape,o=Object.keys(r||{});return t.some(e=>{const t=e.split(".")[0];return o.includes(t)})}}catch(o){this.formLogger.debug("Error analyzing schema structure:",o)}return!1}extractToolKeywords(e){return[...e.replace(/([A-Z])/g," $1").toLowerCase().split(/[\s_-]+/).filter(e=>e.length>2),e.toLowerCase()]}formatFormResponse(e){const t=e.formConfig.fields.length,r=e.formConfig.fields.slice(0,3).map(e=>`• ${e.label}`).join("\n");return`I need some additional information to complete your request.\n\n${e.formConfig.description}\n\nRequired fields:\n${r}${t>3?`\n... and ${t-3} more`:""}\n\nPlease fill out the form below to continue.`}hasPendingForms(){return this.pendingForms.size>0}getPendingFormsInfo(){return Array.from(this.pendingForms.entries()).map(([e,t])=>({formId:e,toolName:t.toolName}))}processHashLinkResponse(e){try{let t;if((e.hashLinkBlock||e.success&&e.hashLinkBlock)&&(t=e.hashLinkBlock),!t)throw new Error("HashLink block data not found in response");if(!t.blockId||!t.hashLink||!t.attributes)throw new Error("Invalid HashLink block structure - missing required fields");let r="Content processed successfully!";if(e.success&&e.inscription){const t=e.inscription,o=e.metadata||{};r=`✅ ${t.standard} Hashinal inscription completed!\n\n`,o.name&&(r+=`**${o.name}**\n`),o.description&&(r+=`${o.description}\n\n`),r+=`📍 **Topic ID:** ${t.topicId}\n`,r+=`🔗 **HRL:** ${t.hrl}\n`,t.cdnUrl&&(r+=`🌐 **CDN URL:** ${t.cdnUrl}\n`),o.creator&&(r+=`👤 **Creator:** ${o.creator}\n`)}return this.formLogger.info("Processed HashLink response",{blockId:t.blockId,hashLink:t.hashLink,hasTemplate:!!t.template,attributeCount:Object.keys(t.attributes||{}).length}),{hasHashLinkBlocks:!0,hashLinkBlock:t,message:r}}catch(t){return this.formLogger.error("Error processing HashLink response:",t),{hasHashLinkBlocks:!1,message:"Content processed, but interactive display is not available."}}}getFormEngineStatistics(){return{strategies:this.formEngine.getRegisteredStrategies(),middleware:this.formEngine.getRegisteredMiddleware()}}}class Ae{constructor(e){this.config=e,this.tools=[],this.initialized=!1,this.logger=new r.Logger({module:"BaseAgent",silent:e.debug?.silent||!1})}getCore(){return this.agentKit}filterTools(e){let t=[...e];const r=this.config.filtering;return r?(r.namespaceWhitelist?.length&&(t=t.filter(e=>{const t=e.namespace;return!t||r.namespaceWhitelist.includes(t)})),r.toolBlacklist?.length&&(t=t.filter(e=>!r.toolBlacklist.includes(e.name))),r.toolPredicate&&(t=t.filter(r.toolPredicate)),this.logger.debug(`Filtered tools: ${e.length} → ${t.length}`),t):t}buildSystemPrompt(){const e=[],t=this.config.signer.getAccountId().toString(),r=this.config.execution?.userAccountId;this.config.messaging?.systemPreamble&&e.push(this.config.messaging.systemPreamble),e.push(`You are a helpful Hedera assistant. Your primary operator account is ${t}. You have tools to interact with the Hedera Hashgraph. When using any tool, provide all necessary parameters as defined by that tool's schema and description.`),e.push("\nMETADATA QUALITY PRINCIPLES: When collecting user input for metadata creation across any tool:\n• Prioritize meaningful, valuable content over technical file information\n• Focus on attributes that add value for end users and collectors\n• Avoid auto-generating meaningless technical attributes as user-facing metadata\n• When fields are missing or inadequate, use forms to collect quality metadata\n• Encourage descriptive names, collectible traits, and storytelling elements"),r&&e.push(`The user you are assisting has a personal Hedera account ID: ${r}. IMPORTANT: When the user says things like "I want to send HBAR" or "transfer my tokens", you MUST use ${r} as the sender/from account. For example, if user says "I want to send 2 HBAR to 0.0.800", you must set up a transfer where ${r} sends the HBAR, not your operator account.`);return"autonomous"===(this.config.execution?.operationalMode||"returnBytes")?e.push(`\nOPERATIONAL MODE: 'autonomous'. Your goal is to execute transactions directly using your tools. Your account ${t} will be the payer for these transactions. Even if the user's account (${r||"a specified account"}) is the actor in the transaction body (e.g., sender of HBAR), you (the agent with operator ${t}) 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.`):this.config.execution?.scheduleUserTransactionsInBytesMode&&r?e.push(`\nOPERATIONAL MODE: 'returnBytes' with scheduled transactions for user actions. When a user asks for a transaction to be prepared (e.g., creating a token, topic, transferring assets for them to sign, etc), you MUST default to creating a Scheduled Transaction using the appropriate tool with the metaOption 'schedule: true'. The user (with account ID ${r}) will be the one to ultimately pay for and (if needed) sign the inner transaction. Your operator account (${t}) will pay for creating the schedule entity itself. 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.`):e.push(`\nOPERATIONAL MODE: 'returnBytes'. Your goal is to provide transaction bytes when possible. When a user asks for a transaction to be prepared (e.g., for them to sign, or for scheduling without the default scheduling flow), you MUST call the appropriate tool. IMPORTANT: Only use metaOption 'returnBytes: true' for tools that explicitly support it (like HBAR transfers, token operations). Many tools (inscriptions, HCS-2, HCS-20, etc.) do NOT support returnBytes and will execute directly - this is expected behavior. For tools without returnBytes support, simply call them with their standard parameters. If you need raw bytes for the user to sign for their own account ${r||"if specified"}, ensure the tool constructs the transaction body accordingly when returnBytes IS supported.`),!1!==this.config.messaging?.conciseMode&&e.push("\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."),this.config.messaging?.systemPostamble&&e.push(this.config.messaging.systemPostamble),e.join("\n")}isReady(){return this.initialized}}class Fe{constructor(e,t){this.contentStorage=e,this.logger=t}analyzeResponse(e){const t=[];let r=0;this.extractContentFromResponse(e,t),r=t.reduce((e,t)=>e+t.sizeBytes,0);const o=t.reduce((e,t)=>Math.max(e,t.sizeBytes),0);return{shouldProcess:t.some(e=>this.contentStorage.shouldUseReference("string"==typeof e.content?e.content:JSON.stringify(e.content))),contents:t,totalSize:r,largestContentSize:o}}async processResponse(e,t,r){try{const o=this.analyzeResponse(e);if(!o.shouldProcess)return{content:e,wasProcessed:!1};return await this.createReferencedResponse(e,o,t,r)}catch(o){return this.logger.error("Error processing MCP response:",o),{content:e,wasProcessed:!1,errors:[o instanceof Error?o.message:"Unknown processing error"]}}}extractContentFromResponse(e,t){if(null!=e)if(Array.isArray(e))e.forEach(e=>this.extractContentFromResponse(e,t));else{if("object"==typeof e){const r=e;if("text"===r.type&&"string"==typeof r.text)return void t.push({content:r.text,type:"text",sizeBytes:globalThis.Buffer.byteLength(r.text,"utf8"),mimeType:this.detectMimeType(r.text)});if("image"===r.type&&"string"==typeof r.data)return void t.push({content:r.data,type:"image",sizeBytes:Math.ceil(.75*r.data.length),mimeType:r.mimeType||"image/jpeg"});if("resource"===r.type&&r.resource){const e=JSON.stringify(r.resource);return void t.push({content:e,type:"resource",sizeBytes:globalThis.Buffer.byteLength(e,"utf8"),mimeType:"application/json"})}return void Object.values(r).forEach(e=>this.extractContentFromResponse(e,t))}"string"==typeof e&&e.length>1e3&&t.push({content:e,type:"text",sizeBytes:globalThis.Buffer.byteLength(e,"utf8"),mimeType:this.detectMimeType(e)})}}async createReferencedResponse(e,t,r,o){const s=this.deepClone(e),n=[];let i=!1,a=0;for(const g of t.contents)if(this.contentStorage.shouldUseReference("string"==typeof g.content?g.content:JSON.stringify(g.content)))try{const e=globalThis.Buffer.from("string"==typeof g.content?g.content:JSON.stringify(g.content),"utf8"),t={contentType:this.mapMimeTypeToContentType(g.mimeType),source:"mcp_tool",mcpToolName:`${r}::${o}`,tags:["mcp_response",r,o]};void 0!==g.mimeType&&(t.mimeType=g.mimeType);const n=await this.contentStorage.storeContentIfLarge(e,t);n&&(this.replaceContentInResponse(s,g.content,this.createLightweightReference(n)),i=!0,a+=e.length)}catch(l){n.push(`Failed to create reference: ${l instanceof Error?l.message:"Unknown error"}`)}const c={content:s,wasProcessed:!0,referenceCreated:i,originalSize:a};return n.length>0&&(c.errors=n),c}createLightweightReference(e){return{type:"content_reference",referenceId:e.referenceId,preview:e.preview,size:e.metadata.sizeBytes,contentType:e.metadata.contentType,format:"ref://{id}",_isReference:!0}}replaceContentInResponse(e,t,r){if(null!=e)if(Array.isArray(e))for(let o=0;o<e.length;o++)e[o]===t?e[o]=r:this.replaceContentInResponse(e[o],t,r);else if("object"==typeof e){const o=e;if("text"===o.type&&o.text===t){for(const e of Object.keys(o))delete o[e];if("object"==typeof r&&null!==r){const e=r;for(const t of Object.keys(e))o[t]=e[t]}return}for(const e in o)o[e]===t?o[e]=r:this.replaceContentInResponse(o[e],t,r)}}detectMimeType(e){return e.trim().startsWith("{")||e.trim().startsWith("[")?"application/json":e.includes("<html>")||e.includes("<!DOCTYPE")?"text/html":e.includes("# ")||e.includes("## ")?"text/markdown":"text/plain"}mapMimeTypeToContentType(e){return e?e.startsWith("text/plain")?"text":"application/json"===e?"json":"text/html"===e?"html":"text/markdown"===e?"markdown":e.startsWith("text/")?"text":"binary":"text"}deepClone(e){if(null===e||"object"!=typeof e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e))return e.map(e=>this.deepClone(e));const t={};for(const r in e)e.hasOwnProperty(r)&&(t[r]=this.deepClone(e[r]));return t}}class Re{constructor(e,t){this.clients=new Map,this.tools=new Map,this.logger=e,t&&(this.contentProcessor=new Fe(t,e))}async connectServer(e){try{if(this.isServerConnected(e.name))return{serverName:e.name,connected:!1,error:`Server ${e.name} is already connected`,tools:[]};if(e.transport&&"stdio"!==e.transport)throw new Error(`Transport ${e.transport} not yet supported`);const t=new w.StdioClientTransport({command:e.command,args:e.args,...e.env&&{env:e.env}}),r=new y.Client({name:`conversational-agent-${e.name}`,version:"1.0.0"},{capabilities:{}});await r.connect(t),this.clients.set(e.name,r);const o=(await r.listTools()).tools.map(t=>{const r=t,{description:o,...s}=r;return{...void 0!==o&&"string"==typeof o?{...s,description:o}:{...s},serverName:e.name}});return this.tools.set(e.name,o),this.logger.info(`Connected to MCP server ${e.name} with ${o.length} tools`),{serverName:e.name,connected:!0,tools:o}}catch(t){return this.logger.error(`Failed to connect to MCP server ${e.name}:`,t),{serverName:e.name,connected:!1,error:t instanceof Error?t.message:"Unknown error",tools:[]}}}async executeTool(e,t,r){const o=this.clients.get(e);if(!o)throw new Error(`MCP server ${e} not connected`);this.logger.debug(`Executing MCP tool ${t} on server ${e}`,r);try{const s=await o.callTool({name:t,arguments:r});if(this.contentProcessor){const r=await this.contentProcessor.processResponse(s,e,t);return r.wasProcessed&&(this.logger.debug(`Processed MCP response from ${e}::${t}`,{referenceCreated:r.referenceCreated,originalSize:r.originalSize,errors:r.errors}),r.errors&&r.errors.length>0&&this.logger.warn(`Content processing warnings for ${e}::${t}:`,r.errors)),r.content}return s}catch(s){throw this.logger.error(`Error executing MCP tool ${t}:`,s),s}}async disconnectAll(){for(const[t,r]of this.clients)try{await r.close(),this.logger.info(`Disconnected from MCP server ${t}`)}catch(e){this.logger.error(`Error disconnecting MCP server ${t}:`,e)}this.clients.clear(),this.tools.clear()}getAllTools(){const e=[];for(const t of this.tools.values())e.push(...t);return e}getServerTools(e){return this.tools.get(e)||[]}isServerConnected(e){return this.clients.has(e)}getConnectedServers(){return Array.from(this.clients.keys())}enableContentProcessing(e){this.contentProcessor=new Fe(e,this.logger),this.logger.info("Content processing enabled for MCP responses")}disableContentProcessing(){delete this.contentProcessor,this.logger.info("Content processing disabled for MCP responses")}isContentProcessingEnabled(){return void 0!==this.contentProcessor}analyzeResponseContent(e){if(!this.contentProcessor)throw new Error("Content processing is not enabled");return this.contentProcessor.analyzeResponse(e)}}function Pe(e,t,o){const s=Oe(e.inputSchema),n=`${e.serverName}_${e.name}`.replace(/[^a-zA-Z0-9_]/g,"_");let a=e.description||`MCP tool ${e.name} from ${e.serverName}`;return o?.toolDescriptions?.[e.name]&&(a=`${a}\n\n${o.toolDescriptions[e.name]}`),o?.additionalContext&&(a=`${a}\n\nContext: ${o.additionalContext}`),new i.DynamicStructuredTool({name:n,description:a,schema:s,func:async o=>{try{const s=await t.executeTool(e.serverName,e.name,o);let n="";if("string"==typeof s)n=s;else if(s&&"object"==typeof s&&"content"in s){const e=s.content;if(Array.isArray(e)){n=e.filter(e=>"object"==typeof e&&null!==e&&"type"in e&&"text"===e.type&&"text"in e).map(e=>e.text).join("\n")}else n=JSON.stringify(e)}else n=JSON.stringify(s);const i=globalThis.Buffer.from(n,"utf8"),a=10240;if(i.length>a||r.shouldUseReference(i)){const t=r.ContentStoreService.getInstance();if(t)try{return`content-ref:${await t.storeContent(i,{contentType:"text",source:"mcp",mcpToolName:`${e.serverName}_${e.name}`,originalSize:i.length})}`}catch{}}return n}catch(s){const t=s instanceof Error?s.message:"Unknown error";return`Error executing MCP tool ${e.name}: ${t}`}}})}function Oe(e){if(!e||"object"!=typeof e)return o.z.object({});const t=e;if(t.type&&"object"!==t.type)return Ne(t);if(!t.properties||"object"!=typeof t.properties)return o.z.object({});const r={};for(const[o,s]of Object.entries(t.properties)){let e=Ne(s);Array.isArray(t.required)&&t.required.includes(o)||(e=e.optional()),r[o]=e}return o.z.object(r)}function Ne(e){if(!e||"object"!=typeof e||!("type"in e))return o.z.unknown();const t=e;let r;switch(t.type){case"string":r=o.z.string(),t.enum&&Array.isArray(t.enum)&&(r=o.z.enum(t.enum));break;case"number":r=o.z.number(),"minimum"in t&&"number"==typeof t.minimum&&(r=r.min(t.minimum)),"maximum"in t&&"number"==typeof t.maximum&&(r=r.max(t.maximum));break;case"integer":r=o.z.number().int(),"minimum"in t&&"number"==typeof t.minimum&&(r=r.min(t.minimum)),"maximum"in t&&"number"==typeof t.maximum&&(r=r.max(t.maximum));break;case"boolean":r=o.z.boolean();break;case"array":r=t.items?o.z.array(Ne(t.items)):o.z.array(o.z.unknown());break;case"object":r="properties"in t?Oe(t):o.z.object({}).passthrough();break;default:r=o.z.unknown()}return"description"in t&&"string"==typeof t.description&&(r=r.describe(t.description)),r}const Le=class e{constructor(e="gpt-4o"){this.modelName=String(e);try{this.encoding=T.encoding_for_model(e)}catch{this.encoding=T.encoding_for_model("gpt-4o"),this.modelName="gpt-4o"}}countTokens(e){if(!e||""===e.trim())return 0;try{return this.encoding.encode(e).length}catch{return Math.ceil(1.3*e.split(/\s+/).length)}}countMessageTokens(t){return this.countTokens(String(t.content??""))+this.countTokens(this.getMessageRole(t))+e.MESSAGE_OVERHEAD+e.ROLE_OVERHEAD}countMessagesTokens(e){if(!e||0===e.length)return 0;let t=0;for(const r of e)t+=this.countMessageTokens(r);return t}estimateSystemPromptTokens(t){if(!t||""===t.trim())return 0;return this.countTokens(t)+this.countTokens("system")+e.MESSAGE_OVERHEAD+e.ROLE_OVERHEAD}estimateContextSize(e,t){return this.estimateSystemPromptTokens(e)+this.countMessagesTokens(t)+10}getMessageRole(e){switch(e._getType()){case"human":default:return"user";case"ai":return"assistant";case"system":return"system";case"function":return"function";case"tool":return"tool"}}getModelName(){return this.modelName}dispose(){try{this.encoding.free()}catch{}}};Le.MESSAGE_OVERHEAD=3,Le.ROLE_OVERHEAD=1;let $e=Le;const Be=class e{constructor(t=e.DEFAULT_MAX_TOKENS,r=e.DEFAULT_RESERVE_TOKENS,o){if(this.messages=[],this.systemPrompt="",this.systemPromptTokens=0,r>=t)throw new Error("Reserve tokens must be less than max tokens");this.maxTokens=t,this.reserveTokens=r,this.tokenCounter=o||new $e}addMessage(e){this.tokenCounter.countMessageTokens(e),this.messages.push(e);let t=[];return this.getCurrentTokenCount()>this.maxTokens-this.reserveTokens&&(this.messages.pop(),t=this.pruneToFit(),this.messages.push(e)),{added:!0,prunedMessages:t,currentTokenCount:this.getCurrentTokenCount(),remainingCapacity:this.getRemainingTokenCapacity()}}pruneToFit(){const t=[],r=this.maxTokens-this.reserveTokens;for(;this.getCurrentTokenCount()>r&&this.messages.length>0;){const r=Math.min(e.PRUNING_BATCH_SIZE,this.messages.length);for(let e=0;e<r;e++){const e=this.messages.shift();e&&t.push(e)}if(t.length>1e3)break}return t}getCurrentTokenCount(){const e=this.tokenCounter.countMessagesTokens(this.messages);return this.systemPromptTokens+e}getRemainingTokenCapacity(){return Math.max(0,this.maxTokens-this.getCurrentTokenCount())}canAddMessage(e){const t=this.tokenCounter.countMessageTokens(e),r=this.getCurrentTokenCount()+t>this.maxTokens-this.reserveTokens;return!(t>this.maxTokens)&&(!r||this.messages.length>0)}getMessages(){return[...this.messages]}clear(){this.messages=[]}setSystemPrompt(e){this.systemPrompt=e,this.systemPromptTokens=this.tokenCounter.estimateSystemPromptTokens(e)}getSystemPrompt(){return this.systemPrompt}getConfig(){return{maxTokens:this.maxTokens,reserveTokens:this.reserveTokens,currentTokens:this.getCurrentTokenCount(),messageCount:this.messages.length,systemPromptTokens:this.systemPromptTokens}}updateLimits(e,t){if(void 0!==t&&t>=e)throw new Error("Reserve tokens must be less than max tokens");this.maxTokens=e,void 0!==t&&(this.reserveTokens=t),this.getCurrentTokenCount()>this.maxTokens-this.reserveTokens&&this.pruneToFit()}getStats(){const e=this.getCurrentTokenCount(),t=this.maxTokens,r=e/t*100;return{totalMessages:this.messages.length,currentTokens:e,maxTokens:t,reserveTokens:this.reserveTokens,systemPromptTokens:this.systemPromptTokens,usagePercentage:Math.round(100*r)/100,remainingCapacity:this.getRemainingTokenCapacity(),canAcceptMore:this.getRemainingTokenCapacity()>this.reserveTokens}}dispose(){this.clear(),this.tokenCounter.dispose()}};Be.DEFAULT_MAX_TOKENS=8e3,Be.DEFAULT_RESERVE_TOKENS=1e3,Be.PRUNING_BATCH_SIZE=2;let ze=Be;class De{static generateId(e){const t=u.createHash("sha256");return t.update(e),t.digest("hex")}static isValidReferenceId(e){return!(!e||"string"!=typeof e)&&(64===e.length&&/^[a-f0-9]+$/.test(e))}static extractReferenceId(e){if(!e||"string"!=typeof e)return null;const t=e.match(/^ref:\/\/([a-f0-9]{64})$/);return t?t[1]:this.isValidReferenceId(e)?e:null}static formatReference(e){return`ref://${e}`}static generateTestId(e){const t=globalThis.Buffer.from(`test-${e}-${Date.now()}`);return this.generateId(t)}}const He={sizeThresholdBytes:10240,maxAgeMs:36e5,maxReferences:100,maxTotalStorageBytes:104857600,enableAutoCleanup:!0,cleanupIntervalMs:3e5,enablePersistence:!1,storageBackend:"memory",cleanupPolicies:{recent:{maxAgeMs:18e5,priority:1},userContent:{maxAgeMs:72e5,priority:2},agentGenerated:{maxAgeMs:36e5,priority:3},default:{maxAgeMs:36e5,priority:4}}};class je extends Error{constructor(e,t,r,o){super(e),this.type=t,this.referenceId=r,this.suggestedActions=o,this.name="ContentReferenceError"}}const _e=class e{constructor(t=e.DEFAULT_MAX_STORAGE,r){this.messages=[],this.idCounter=0,this.contentStore=new Map,this.maxStorage=t,this.referenceConfig={...He,...r},this.referenceStats={activeReferences:0,totalStorageBytes:0,recentlyCleanedUp:0,totalResolutions:0,failedResolutions:0,averageContentSize:0,storageUtilization:0,performanceMetrics:{averageCreationTimeMs:0,averageResolutionTimeMs:0,averageCleanupTimeMs:0,creationTimes:[],resolutionTimes:[],cleanupTimes:[]}},this.referenceConfig.enableAutoCleanup&&this.startReferenceCleanupTimer()}storeMessages(e){if(0===e.length)return{stored:0,dropped:0};const t=new Date;let r=0;const o=e.map(e=>({message:e,storedAt:t,id:this.generateId()}));for(this.messages.push(...o);this.messages.length>this.maxStorage;)this.messages.shift(),r++;return{stored:o.length,dropped:r}}getRecentMessages(e){if(e<=0||0===this.messages.length)return[];const t=Math.max(0,this.messages.length-e);return this.messages.slice(t).map(e=>e.message)}searchMessages(e,t={}){if(!e||0===this.messages.length)return[];const{caseSensitive:r=!1,limit:o,useRegex:s=!1}=t;let n=[];if(s)try{const t=new RegExp(e,r?"g":"gi");n=this.messages.filter(e=>t.test(e.message.content)).map(e=>e.message)}catch{return[]}else{const t=r?e:e.toLowerCase();n=this.messages.filter(e=>{const o=e.message.content;return(r?o:o.toLowerCase()).includes(t)}).map(e=>e.message)}return o?n.slice(0,o):n}getMessagesFromTimeRange(e,t){return e>t||0===this.messages.length?[]:this.messages.filter(r=>r.storedAt>=e&&r.storedAt<=t).map(e=>e.message)}getStorageStats(){const e=this.messages.length,t=e>0?Math.round(e/this.maxStorage*100):0;let r,o;return e>0&&(r=this.messages[0].storedAt,o=this.messages[e-1].storedAt),{totalMessages:e,maxStorageLimit:this.maxStorage,usagePercentage:t,oldestMessageTime:r,newestMessageTime:o}}clear(){this.messages=[],this.idCounter=0}getTotalStoredMessages(){return this.messages.length}updateStorageLimit(e){if(e<=0)throw new Error("Storage limit must be greater than 0");for(this.maxStorage=e;this.messages.length>this.maxStorage;)this.messages.shift()}getMessagesByType(e,t){const r=this.messages.filter(t=>t.message._getType()===e).map(e=>e.message);return t?r.slice(0,t):r}getConfig(){return{maxStorage:this.maxStorage,currentUsage:this.messages.length,utilizationPercentage:this.messages.length/this.maxStorage*100}}generateId(){return`msg_${++this.idCounter}_${Date.now()}`}getRecentMessagesByTime(e){if(e<=0||0===this.messages.length)return[];const t=new Date(Date.now()-60*e*1e3);return this.messages.filter(e=>e.storedAt>=t).map(e=>e.message)}exportMessages(){return this.messages.map(e=>({content:"string"==typeof e.message.content?e.message.content:JSON.stringify(e.message.content),type:e.message._getType(),storedAt:e.storedAt.toISOString(),id:e.id}))}shouldUseReference(e){return(globalThis.Buffer.isBuffer(e)?e.length:globalThis.Buffer.byteLength(e,"utf8"))>this.referenceConfig.sizeThresholdBytes}async storeContentIfLarge(e,t){const r=globalThis.Buffer.isBuffer(e)?e:globalThis.Buffer.from(e,"utf8");if(!this.isImageContent(t.mimeType,t.fileName)&&!this.shouldUseReference(r))return null;const o={contentType:t.contentType||this.detectContentType(r,t.mimeType),sizeBytes:r.length,source:t.source,tags:[]};return void 0!==t.mimeType&&(o.mimeType=t.mimeType),void 0!==t.mcpToolName&&(o.mcpToolName=t.mcpToolName),void 0!==t.fileName&&(o.fileName=t.fileName),void 0!==t.tags&&(o.tags=t.tags),void 0!==t.customMetadata&&(o.customMetadata=t.customMetadata),await this.storeContent(r,o)}async storeContent(e,t){const r=Date.now();try{const o=new Date,s=De.generateId(e),n={...t,createdAt:o,lastAccessedAt:o,accessCount:0},i={content:e,metadata:n,state:"active"},a=this.calculateExpirationTime(t.source);void 0!==a&&(i.expiresAt=a),this.contentStore.set(s,i),this.updateStatsAfterStore(e.length),await this.enforceReferenceStorageLimits();const c=this.createContentPreview(e,n.contentType),l={contentType:n.contentType,sizeBytes:n.sizeBytes,source:n.source};void 0!==n.fileName&&(l.fileName=n.fileName),void 0!==n.mimeType&&(l.mimeType=n.mimeType);const g={referenceId:s,state:"active",preview:c,metadata:l,createdAt:o,format:"ref://{id}"},h=Date.now()-r;return this.recordPerformanceMetric("creation",h),g}catch(o){const e=Date.now()-r;throw this.recordPerformanceMetric("creation",e),new je(`Failed to store content: ${o instanceof Error?o.message:"Unknown error"}`,"system_error",void 0,["Try again","Check storage limits","Contact administrator"])}}async resolveReference(e){const t=Date.now();try{if(!De.isValidReferenceId(e))return this.referenceStats.failedResolutions++,{success:!1,error:"Invalid reference ID format",errorType:"not_found",suggestedActions:["Check the reference ID format","Ensure the reference ID is complete"]};const r=this.contentStore.get(e);if(!r)return this.referenceStats.failedResolutions++,{success:!1,error:"Reference not found",errorType:"not_found",suggestedActions:["Verify the reference ID","Check if the content has expired","Request fresh content"]};if(r.expiresAt&&r.expiresAt<new Date)return r.state="expired",this.referenceStats.failedResolutions++,{success:!1,error:"Reference has expired",errorType:"expired",suggestedActions:["Request fresh content","Use alternative content source"]};if("active"!==r.state)return this.referenceStats.failedResolutions++,{success:!1,error:`Reference is ${r.state}`,errorType:"expired"===r.state?"expired":"corrupted",suggestedActions:["Request fresh content","Check reference validity"]};r.metadata.lastAccessedAt=new Date,r.metadata.accessCount++,this.referenceStats.totalResolutions++;const o=Date.now()-t;return this.recordPerformanceMetric("resolution",o),{success:!0,content:r.content,metadata:r.metadata}}catch(r){const e=Date.now()-t;return this.recordPerformanceMetric("resolution",e),this.referenceStats.failedResolutions++,{success:!1,error:`System error resolving reference: ${r instanceof Error?r.message:"Unknown error"}`,errorType:"system_error",suggestedActions:["Try again","Contact administrator"]}}}async hasReference(e){if(!De.isValidReferenceId(e))return!1;const t=this.contentStore.get(e);return!!t&&(t.expiresAt&&t.expiresAt<new Date?(t.state="expired",!1):"active"===t.state)}async cleanupReference(e){const t=this.contentStore.get(e);return!!t&&(this.referenceStats.totalStorageBytes-=t.content.length,this.referenceStats.activeReferences--,this.referenceStats.recentlyCleanedUp++,this.contentStore.delete(e),!0)}async getStats(){return this.updateReferenceStorageStats(),{...this.referenceStats,performanceMetrics:{averageCreationTimeMs:this.calculateAverage(this.referenceStats.performanceMetrics.creationTimes),averageResolutionTimeMs:this.calculateAverage(this.referenceStats.performanceMetrics.resolutionTimes),averageCleanupTimeMs:this.calculateAverage(this.referenceStats.performanceMetrics.cleanupTimes)}}}async updateConfig(e){this.referenceConfig={...this.referenceConfig,...e},this.cleanupTimer&&(clearInterval(this.cleanupTimer),delete this.cleanupTimer),this.referenceConfig.enableAutoCleanup&&this.startReferenceCleanupTimer()}async performCleanup(){const e=Date.now(),t=[];let r=0;try{const s=new Date,n=[];for(const[e,t]of this.contentStore.entries()){let r=!1;t.expiresAt&&t.expiresAt<s&&(r=!0,t.state="expired");const o=s.getTime()-t.metadata.createdAt.getTime();o>this.getCleanupPolicy(t.metadata.source).maxAgeMs&&(r=!0),"cleanup_pending"===t.state&&(r=!0),r&&n.push(e)}n.sort((e,t)=>{const r=this.contentStore.get(e),o=this.contentStore.get(t),s=this.getCleanupPolicy(r.metadata.source).priority;return this.getCleanupPolicy(o.metadata.source).priority-s});for(const e of n)try{await this.cleanupReference(e)&&r++}catch(o){t.push(`Failed to cleanup ${e}: ${o instanceof Error?o.message:"Unknown error"}`)}if(this.contentStore.size>this.referenceConfig.maxReferences){const e=Array.from(this.contentStore.entries()).sort(([,e],[,t])=>e.metadata.lastAccessedAt.getTime()-t.metadata.lastAccessedAt.getTime()),s=this.contentStore.size-this.referenceConfig.maxReferences;for(let n=0;n<s&&n<e.length;n++){const[s]=e[n];try{await this.cleanupReference(s)&&r++}catch(o){t.push(`Failed to cleanup excess reference ${s}: ${o instanceof Error?o.message:"Unknown error"}`)}}}const i=Date.now()-e;return this.recordPerformanceMetric("cleanup",i),{cleanedUp:r,errors:t}}catch(o){const s=Date.now()-e;this.recordPerformanceMetric("cleanup",s);const n=`Cleanup process failed: ${o instanceof Error?o.message:"Unknown error"}`;return t.push(n),{cleanedUp:r,errors:t}}}getReferenceConfig(){return{...this.referenceConfig}}async enforceReferenceStorageLimits(){this.contentStore.size>=this.referenceConfig.maxReferences&&await this.performCleanup(),this.referenceStats.totalStorageBytes>=this.referenceConfig.maxTotalStorageBytes&&await this.performCleanup()}calculateExpirationTime(e){const t=this.getCleanupPolicy(e);return new Date(Date.now()+t.maxAgeMs)}getCleanupPolicy(e){switch(e){case"mcp_tool":return this.referenceConfig.cleanupPolicies.recent;case"user_upload":return this.referenceConfig.cleanupPolicies.userContent;case"agent_generated":return this.referenceConfig.cleanupPolicies.agentGenerated;default:return this.referenceConfig.cleanupPolicies.default}}detectContentType(e,t){if(t)return"text/html"===t?"html":"text/markdown"===t?"markdown":"application/json"===t?"json":t.startsWith("text/")?"text":"binary";const r=e.toString("utf8",0,Math.min(e.length,1e3));return r.startsWith("{")||r.startsWith("[")?"json":r.includes("<html>")||r.includes("<!DOCTYPE")?"html":r.includes("#")&&r.includes("\n")?"markdown":"text"}createContentPreview(e,t){let r=e.toString("utf8",0,Math.min(e.length,400));if("html"===t)r=r.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim();else if("json"===t)try{const e=JSON.parse(r);r=JSON.stringify(e,null,0)}catch{}return r=r.trim(),r.length>200&&(r=r.substring(0,200)+"..."),r||"[Binary content]"}updateStatsAfterStore(e){this.referenceStats.activeReferences++,this.referenceStats.totalStorageBytes+=e,this.updateReferenceStorageStats()}updateReferenceStorageStats(){let e;this.referenceStats.activeReferences>0&&(this.referenceStats.averageContentSize=this.referenceStats.totalStorageBytes/this.referenceStats.activeReferences),this.referenceStats.storageUtilization=this.referenceStats.totalStorageBytes/this.referenceConfig.maxTotalStorageBytes*100;let t=0;for(const[r,o]of this.contentStore.entries())o.metadata.accessCount>t&&(t=o.metadata.accessCount,e=r);void 0!==e?this.referenceStats.mostAccessedReferenceId=e:delete this.referenceStats.mostAccessedReferenceId}isImageContent(e,t){if(e&&e.startsWith("image/"))return!0;if(t){const e=t.toLowerCase();return[".png",".jpg",".jpeg",".gif",".bmp",".webp",".svg",".tiff",".ico"].some(t=>e.endsWith(t))}return!1}recordPerformanceMetric(e,t){const r=this.referenceStats.performanceMetrics;switch(e){case"creation":r.creationTimes.push(t),r.creationTimes.length>100&&r.creationTimes.shift();break;case"resolution":r.resolutionTimes.push(t),r.resolutionTimes.length>100&&r.resolutionTimes.shift();break;case"cleanup":r.cleanupTimes.push(t),r.cleanupTimes.length>100&&r.cleanupTimes.shift()}}calculateAverage(e){return 0===e.length?0:e.reduce((e,t)=>e+t,0)/e.length}startReferenceCleanupTimer(){this.cleanupTimer=setInterval(async()=>{try{await this.performCleanup()}catch{}},this.referenceConfig.cleanupIntervalMs)}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),delete this.cleanupTimer),this.contentStore.clear(),this.clear()}};_e.DEFAULT_MAX_STORAGE=1e3;let Ue=_e;const qe='"isEntityAssociation":true',Ke=class e{constructor(t={}){this.config={...e.DEFAULT_CONFIG,...t},this.logger=new r.Logger({module:"SmartMemoryManager"}),this.tokenCounter=new $e(this.config.modelName),this._contentStorage=new Ue(this.config.storageLimit),this.memoryWindow=new ze(this.config.maxTokens,this.config.reserveTokens,this.tokenCounter)}get contentStorage(){return this._contentStorage}addMessage(e){const t=this.memoryWindow.addMessage(e);t.prunedMessages.length>0&&this._contentStorage.storeMessages(t.prunedMessages)}getMessages(){return this.memoryWindow.getMessages()}clear(e=!1){this.memoryWindow.clear(),e&&this._contentStorage.clear()}setSystemPrompt(e){this.memoryWindow.setSystemPrompt(e)}getSystemPrompt(){return this.memoryWindow.getSystemPrompt()}searchHistory(e,t={}){return this._contentStorage.searchMessages(e,t)}getRecentHistory(e){return this._contentStorage.getRecentMessages(e)}canAddMessage(e){return this.memoryWindow.canAddMessage(e)}getMemoryStats(){const e=this.memoryWindow.getStats();return{totalActiveMessages:e.totalMessages,currentTokenCount:e.currentTokens,maxTokens:e.maxTokens,remainingCapacity:e.remainingCapacity,systemPromptTokens:e.systemPromptTokens,usagePercentage:e.usagePercentage}}getStorageStats(){return this._contentStorage.getStorageStats()}getOverallStats(){const e=this.getMemoryStats(),t=this.getStorageStats();return{activeMemory:e,storage:t,totalMessagesManaged:e.totalActiveMessages+t.totalMessages,activeMemoryUtilization:e.usagePercentage,storageUtilization:t.usagePercentage}}updateConfig(e){this.config={...this.config,...e},void 0===e.maxTokens&&void 0===e.reserveTokens||this.memoryWindow.updateLimits(this.config.maxTokens,this.config.reserveTokens),void 0!==e.storageLimit&&this._contentStorage.updateStorageLimit(this.config.storageLimit)}getConfig(){return{...this.config}}getHistoryFromTimeRange(e,t){return this._contentStorage.getMessagesFromTimeRange(e,t)}getHistoryByType(e,t){return this._contentStorage.getMessagesByType(e,t)}getRecentHistoryByTime(e){return this._contentStorage.getRecentMessagesByTime(e)}exportState(){return{config:this.config,activeMessages:this.memoryWindow.getMessages().map(e=>({content:e.content,type:e._getType()})),systemPrompt:this.memoryWindow.getSystemPrompt(),memoryStats:this.getMemoryStats(),storageStats:this.getStorageStats(),storedMessages:this._contentStorage.exportMessages()}}getContextSummary(e=!1){const t=this.getMessages(),r={activeMessageCount:t.length,systemPrompt:this.getSystemPrompt(),recentMessages:t.slice(-5),memoryUtilization:this.getMemoryStats().usagePercentage,hasStoredHistory:this.getStorageStats().totalMessages>0};return e?{...r,recentStoredMessages:this.getRecentHistory(10),storageStats:this.getStorageStats()}:r}performMaintenance(){}storeEntityAssociation(e,t,r,o,s){try{if(!e||"string"!=typeof e||0===e.trim().length)return;if(!t||"string"!=typeof t||0===t.trim().length)return;if(!r||"string"!=typeof r||0===r.trim().length)return;const n=e.trim(),i=t.trim().substring(0,100),a=this.normalizeEntityType(r);let c="";"tokenid"===a?c="Use this as tokenId for HTS operations":"topicid"===a?c="Can be used for HCS operations, HRLs for minting with the format hcs://1/<topicId>, etc.":"accountid"===a&&(c="Can be used for account based operations");const l={entityId:n,entityName:i,entityType:a,createdAt:new Date,isEntityAssociation:!0,...c?{usage:c}:{},..."topicId"===a?{hrl:`hcs://1/${n}`}:{},...null!=o&&""!==o.trim()?{transactionId:o.trim()}:{},...s&&""!==s.trim()?{sessionId:s.trim()}:{}},g=JSON.stringify(l),h={_getType:()=>"system",content:g,id:`entity_${n}_${Date.now()}`,name:"entity_association",additional_kwargs:{entityId:n,entityName:i,entityType:a,isEntityAssociation:!0,...s&&""!==s.trim()?{sessionId:s.trim()}:{}}};try{this.memoryWindow.addMessage(new b.SystemMessage(g))}catch{}this._contentStorage.storeMessages([h])}catch(n){this.logger.error("Failed to store entity association",{entityId:e,entityName:t,entityType:r,error:n instanceof Error?n.message:String(n)})}}normalizeEntityType(e){const t=(e||"").trim();if(0===t.length)return"";const r=t.replace(/[^a-z]/gi,"").toLowerCase(),o={topic:"topicId",topicid:"topicId",token:"tokenId",tokenid:"tokenId",account:"accountId",accountid:"accountId",contract:"contractId",contractid:"contractId",file:"fileId",fileid:"fileId",schedule:"scheduleId",scheduleid:"scheduleId"};return Object.prototype.hasOwnProperty.call(o,r)?o[r]:(/^[a-z]+Id$/.test(t),t)}resolveEntityReference(e,t={}){try{if(!e||"string"!=typeof e)return[];const r=e.trim();if(0===r.length)return[];r.length;const{entityType:o,limit:s=10,fuzzyMatch:n=!0}=t,i=Math.max(1,Math.min(s||10,100)),a=/^0\.0\.\d+$/.test(r),c=this._contentStorage.searchMessages(r.substring(0,200),{caseSensitive:!1,limit:2*i}),l=[];for(const e of c)try{const t=e.content;if(t.includes(qe)||t.includes("entityId")){const e=JSON.parse(t);if(e.entityId&&e.entityName&&e.entityType){if(o&&e.entityType!==o)continue;if(a&&e.entityId!==r)continue;l.push(e)}}}catch{continue}if(n&&0===l.length&&!a){const t=[e.toLowerCase(),"token","account",o||""].filter(Boolean);for(const r of t){if(r===e.toLowerCase())continue;const t=this._contentStorage.searchMessages(r,{caseSensitive:!1,limit:s});for(const e of t)try{const t=e.content;if(t.includes(qe)){const e=JSON.parse(t);if(e.entityId&&e.entityName&&e.entityType){if(o&&e.entityType!==o)continue;l.push(e)}}}catch{continue}}}const g=l.filter((e,t,r)=>r.findIndex(t=>t.entityId===e.entityId)===t).sort((e,t)=>new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime());return g.slice(0,i)}catch(r){return this.logger.error("Failed to resolve entity reference",{query:e,options:t,error:r instanceof Error?r.message:String(r)}),[]}}getEntityAssociations(e){try{const r=e?e.trim():void 0,o=r?this.normalizeEntityType(r):void 0;if(e&&(!r||0===r.length))return[];const s=o||"entityId",n=this._contentStorage.searchMessages(s,{caseSensitive:!1,limit:100}),i=[];for(const e of n)try{const t=e.content;if(t.includes(qe)){const e=JSON.parse(t);if(e.entityId&&e.entityName&&e.entityType){if(o&&e.entityType!==o)continue;e.createdAt&&"string"==typeof e.createdAt&&(e.createdAt=new Date(e.createdAt)),i.push(e)}}}catch(t){this.logger.warn("Failed to parse entity association from message",{messageContent:"string"==typeof e.content?e.content.substring(0,100):"non-string",error:t instanceof Error?t.message:String(t)});continue}const a=new Map,c=e=>e instanceof Date?e.getTime():new Date(e).getTime();for(const e of i){const t=a.get(e.entityId);if(!t){a.set(e.entityId,e);continue}const r=c(t.createdAt),o=c(e.createdAt);(o>r||!!e.transactionId&&!t.transactionId)&&a.set(e.entityId,{...t,...e})}return Array.from(a.values()).sort((e,t)=>c(t.createdAt)-c(e.createdAt))}catch(r){return this.logger.error("Failed to get entity associations",{entityType:e,error:r instanceof Error?r.message:String(r)}),[]}}dispose(){this.memoryWindow.dispose(),this._contentStorage.dispose(),this.tokenCounter.dispose()}};Ke.DEFAULT_CONFIG={maxTokens:8e3,reserveTokens:1e3,modelName:"gpt-4o",storageLimit:1e3};let Ge=Ke;class We extends i.StructuredTool{constructor(e,t,o={}){super(),this.originalTool=e,this.formGenerator=t,this.validationConfig=o,this.logger=new r.Logger({module:"FormValidatingToolWrapper"}),this.name=e.name,this.description=e.description,this.schema=e.schema,this.logger.info(`🔧 FormValidatingToolWrapper created for tool: ${this.name}`,{originalToolName:e.name,originalToolType:e.constructor.name,wrapperType:this.constructor.name})}validateInput(e){try{return this.schema.parse(e),{isValid:!0}}catch(t){if(t instanceof o.z.ZodError){return{isValid:!1,errors:t.errors.filter(e=>{const t=e.path[0];return!this.validationConfig.skipFields?.includes(t)}).map(e=>`${e.path.join(".")}: ${e.message}`)}}return{isValid:!1,errors:["Validation failed"]}}}getSchemaShape(){return this.isZodObject(this.schema)?Object.keys(this.schema.shape):[]}async executeOriginal(e,t){const r=this.originalTool;if("_call"in r&&"function"==typeof r._call)return r._call(e,t);if("call"in r&&"function"==typeof r.call)return r.call(e,t);throw new Error("Original tool has no callable implementation")}getOriginalTool(){return this.originalTool}hasFormValidatableMethod(e,t){return null!==e&&"object"==typeof e&&t in e&&"function"==typeof e[t]}getFormSchema(){return this.hasFormValidatableMethod(this.originalTool,"getFormSchema")?this.originalTool.getFormSchema():this.schema}getEssentialFields(){return this.hasFormValidatableMethod(this.originalTool,"getEssentialFields")?this.originalTool.getEssentialFields():[]}isFieldEmpty(e,t){return this.hasFormValidatableMethod(this.originalTool,"isFieldEmpty")?this.originalTool.isFieldEmpty(e,t):null==t||""===t||!(!Array.isArray(t)||0!==t.length)}calculateMissingFields(e,t){const r=new Set;if(!t)return r;const o=this.getEssentialFields();for(const s of o){const t=e[s];this.isFieldEmpty(s,t)&&r.add(s)}return r}async createFormMessage(e,t,r){let o=await this.formGenerator.generateFormFromSchema(e,t,{toolName:this.name,toolDescription:this.description},r);if(this.isZodObject(e))try{const{jsonSchema:s,uiSchema:n}=this.formGenerator.generateJsonSchemaForm(e,t,r);o={...o,jsonSchema:s,uiSchema:n}}catch(s){this.logger.warn("Failed to generate JSON Schema for RJSF:",s)}return o.partialInput=t,o}isZodObject(e){const t=e._def;return!(!t||"ZodObject"!==t.typeName)}shouldGenerateForm(e){if(this.logger.info(`shouldGenerateForm called for ${this.name}/${this.originalTool.name}`,{input:e,hasCustomValidation:!!this.validationConfig.customValidation}),this.validationConfig.customValidation){const t=!this.validationConfig.customValidation(e);return this.logger.info(`Custom validation result: ${t}`),t}if(t.isFormValidatable(this.originalTool))return this.logger.info(`Tool ${this.originalTool.name} implements FormValidatable, using custom logic`),this.originalTool.shouldGenerateForm(e);this.logger.info(`Tool ${this.originalTool.name} using schema validation only`);const r=this.validateInput(e);return this.logger.info(`Schema validation for ${this.originalTool.name}:`,{isValid:r.isValid,errors:r.errors}),!r.isValid}hasFormBypassFlags(e){return!0===e.__fromForm||!1===e.renderForm}async _call(e,r){this.logger.info(`🚨🚨🚨 FormValidatingToolWrapper._call INTERCEPTING ${this.name} 🚨🚨🚨`,{input:e,inputKeys:Object.keys(e),schemaShape:this.getSchemaShape(),stackTrace:(new Error).stack?.split("\n").slice(0,5)});const o=e;if(this.hasFormBypassFlags(o))return this.logger.info("Bypassing form generation and executing original tool due to submission flags"),this.executeOriginal(o,r);const s=this.shouldGenerateForm(e);if(this.logger.info(`FormValidatingToolWrapper decision for ${this.name}:`,{shouldGenerateForm:s,toolName:this.name,originalToolName:this.originalTool.name}),s){this.logger.info(`Generating form for incomplete input in ${this.name}`);try{const r=t.isFormValidatable(this.originalTool),o=r?this.getFormSchema():this.schema,s=this.calculateMissingFields(e,r),n=this.isZodObject(o)?Object.keys(o.shape):[];this.logger.info(`Using ${r?"CUSTOM":"DEFAULT"} schema for form generation`,{toolName:this.originalTool.name,schemaType:o.constructor?.name,schemaFields:n,isCustomSchema:r});const i={requiresForm:!0,formMessage:await this.createFormMessage(o,e,s),message:`Please complete the form to provide the required information for ${this.name}.`};return this.logger.info(`FormValidatingToolWrapper returning form result for ${this.name}`),JSON.stringify(i)}catch(n){this.logger.error("Failed to generate form:",n)}}return this.logger.info(`FormValidatingToolWrapper passing through to original tool ${this.name}`),this.executeOriginal(e,r)}}function Je(e,t,r={}){return new We(e,t,r)}class Ve{constructor(e){this.tools=new Map,this.formGenerator=new Ce,this.logger=e||new r.Logger({module:"ToolRegistry"})}registerTool(e,t={}){const r=this.analyzeToolCapabilities(e),o={name:e.name,version:"1.0.0",category:t.metadata?.category||"core",description:e.description,capabilities:r,dependencies:[],schema:e.schema,...t.metadata};try{if(!o.entityResolutionPreferences){const t=e.schema,r=t&&"object"==typeof t&&t._entityResolutionPreferences;r&&"object"==typeof r&&(o.entityResolutionPreferences=r)}}catch{}try{const t=e.schema,r=t&&t._def;if("ZodObject"===r?.typeName){const t=("function"==typeof r.shape?r.shape?.()||{}:r.shape||{}).metadata;if(!!t&&"ZodArray"===t._def?.typeName&&"ZodString"===t._def?.type?._def?.typeName&&"string"==typeof e.description){o.entityResolutionPreferences||(o.entityResolutionPreferences={inscription:"hrl"});const t=" NOTE: When referencing inscriptions or media, provide canonical Hashlink Resource Locators (e.g., hcs://<standard>/<topicId>) rather than external URLs or embedded JSON.";e.description.includes("Hashlink Resource Locators")||(e.description=`${e.description}${t}`)}}}catch{}let s,n=e;this.shouldWrapTool(e,r,t)&&(s=Je(e,this.formGenerator,{requireAllFields:!1,skipFields:["metaOptions"],...t.wrapperConfig}),n=s);try{o.entityResolutionPreferences&&(n.entityResolutionPreferences=o.entityResolutionPreferences)}catch{}const i={tool:n,metadata:o,wrapper:s,originalTool:e,options:{priority:r.priority,capability:"basic",enabled:!0,namespace:o.category}};this.tools.set(e.name,i);try{const t=o.fieldGuidance;t&&C.registerToolConfiguration(t);const r=o.fieldGuidanceProvider;if(r){const o=t?.toolPattern??e.name;C.registerToolProvider(o,r,{id:`${e.name}:field-guidance-provider`,priority:0})}}catch{}}getTool(e){return this.tools.get(e)||null}getToolsByCapability(e,t){const r=[];for(const o of this.tools.values())void 0!==t?o.metadata.capabilities[e]===t&&r.push(o):o.metadata.capabilities[e]&&r.push(o);return r}getToolsByQuery(e){const t=[];for(const r of this.tools.values()){let o=!0;if(e.name&&r.metadata.name!==e.name&&(o=!1),e.category&&r.metadata.category!==e.category&&(o=!1),e.capabilities)for(const[t,s]of Object.entries(e.capabilities))if(r.metadata.capabilities[t]!==s){o=!1;break}o&&t.push(r)}return t}getAllTools(){return Array.from(this.tools.values()).map(e=>e.tool)}getAllRegistryEntries(){return Array.from(this.tools.values())}getToolNames(){return Array.from(this.tools.keys())}getToolsByPriority(e){return this.getToolsByCapability("priority",e)}getEnabledTools(){return this.getAllRegistryEntries()}getToolsByNamespace(e){return e?this.getToolsByQuery({category:e}):this.getAllRegistryEntries()}hasCapability(e){for(const t of this.tools.values())if(t.metadata.capabilities[e])return!0;return!1}updateToolOptions(e,t){const r=this.tools.get(e);return!!r&&(r.metadata={...r.metadata,...t},!0)}hasTool(e){return this.tools.has(e)}unregisterTool(e){return this.tools.delete(e)}clear(){this.tools.clear()}analyzeToolCapabilities(e){const r=t.isFormValidatable(e),o=this.hasRenderConfig(e),s=this.isZodObjectLike(e.schema),n=r||o,i=n&&s;let a="medium",c="core";n&&i?a="critical":n?a="high":(e.description?.toLowerCase().includes("query")||e.description?.toLowerCase().includes("search"))&&(a="low");const l=e;return e.constructor.name.includes("MCP")||l.isMCPTool?c="mcp":(l.isExtension||e.constructor.name.includes("Extension"))&&(c="extension"),{supportsFormValidation:n,requiresWrapper:i,priority:a,category:c}}hasRenderConfig(e){const t=e.schema;return!(!t||!t._renderConfig)}shouldWrapTool(e,t,r){return!r.skipWrapper&&(!!r.forceWrapper||t.requiresWrapper)}isZodObjectLike(e){if(!e||"object"!=typeof e)return!1;const t=e,r=t._def;return e instanceof o.z.ZodObject||"ZodObject"===r?.typeName||"shape"in t&&"object"==typeof t.shape}getStatistics(){const e={totalTools:this.tools.size,wrappedTools:0,unwrappedTools:0,categoryCounts:{core:0,extension:0,mcp:0},priorityCounts:{low:0,medium:0,high:0,critical:0}};for(const t of this.tools.values())t.wrapper?e.wrappedTools++:e.unwrappedTools++,e.categoryCounts[t.metadata.category]++,e.priorityCounts[t.metadata.capabilities.priority]++;return e}}class Ze{constructor(e,t,o,s){this.toolRegistry=e,this.formEngine=t,this.memory=o,this.logger=s||new r.Logger({module:"ExecutionPipeline"})}async execute(e,t,r){const o=`trace-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,s=Date.now(),n=this.toolRegistry.getTool(e);if(!n)throw new Error(`Tool not found in registry: ${e}`);const i={toolName:e,input:t,session:r||this.buildDefaultSession(),memory:this.memory,traceId:o,toolEntry:n};try{const e=await this.checkFormGeneration(i);if(e.requiresForm&&e.formMessage)return{success:!1,output:"Form generation required",requiresForm:!0,formMessage:e.formMessage,traceId:o,executionTime:Date.now()-s};return{success:!0,output:await this.executeToolDirect(i),traceId:o,executionTime:Date.now()-s}}catch(a){return this.handleExecutionError(a,i,o,Date.now()-s)}}async executeWithValidation(e,t,r){return this.execute(e,t,r)}async processFormSubmission(e,t,r,o){const s=`form-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,n=Date.now();try{const s={formId:t,toolName:e,parameters:r,timestamp:Date.now()},n=await this.formEngine.processSubmission(s);return this.execute(e,n,o)}catch(i){return{success:!1,output:"Form submission processing failed",error:i instanceof Error?i.message:String(i),traceId:s,executionTime:Date.now()-n}}}async checkFormGeneration(e){const t=e.input;if(!0===t?.__fromForm||!1===t?.renderForm)return{requiresForm:!1};if(!this.formEngine.shouldGenerateForm(e.toolEntry.tool,e.input))return{requiresForm:!1};const r=await this.formEngine.generateForm(e.toolName,e.toolEntry.tool,e.input);return r?{requiresForm:!0,formMessage:r}:{requiresForm:!1}}async executeToolDirect(e){const{toolEntry:t,input:r}=e,o={...r||{},renderForm:!1};return t.wrapper?this.executeWrappedTool(t,o):await t.tool.call(o)}async executeWrappedTool(e,t){const r=e.wrapper;if(!r)throw new Error("Tool wrapper not found");const o=r;return o.executeOriginal?await o.executeOriginal(t):o.originalTool?.call?await o.originalTool.call(t):await e.originalTool.call(t)}handleExecutionError(e,t,r,s){const n=e instanceof Error?e.message:String(e);return e instanceof o.ZodError?{success:!1,output:"Validation error occurred",error:n,traceId:r,executionTime:s}:(this.logger.error(`Tool execution failed: ${t.toolName}`,{traceId:r,error:n}),{success:!1,output:"Tool execution failed",error:n,traceId:r,executionTime:s})}buildDefaultSession(){return{sessionId:`session-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,timestamp:Date.now()}}getStatistics(){return{totalMiddleware:0,registeredMiddleware:[]}}}function Xe(e){if(!e||"object"!=typeof e)return!1;const t=e;if(!("hashLinkBlock"in t)||!t.hashLinkBlock||"object"!=typeof t.hashLinkBlock)return!1;const r=t.hashLinkBlock;return"blockId"in r&&"hashLink"in r&&"template"in r&&"attributes"in r&&"string"==typeof r.blockId&&"string"==typeof r.hashLink&&"string"==typeof r.template&&"object"==typeof r.attributes}class Ye extends Ae{constructor(){super(...arguments),this.systemMessage="",this.mcpConnectionStatus=new Map}addToolRawToMemory(e,t){try{const r=`[tool-raw:${e}] ${t}`;this.smartMemory.addMessage(new b.SystemMessage(r))}catch{}}persistToolRaw(e,t){try{let r="";if("string"==typeof t)r=this.isJSON(t)?t:JSON.stringify({output:t});else if(void 0!==t)try{r=JSON.stringify(t)}catch{r=String(t)}else r=JSON.stringify({observation:null});this.addToolRawToMemory(e,r)}catch{}}persistIntermediateSteps(e){if(e&&Array.isArray(e))try{for(const t of e){const e=t?.action?.tool||"unknown",r=t?.observation;this.persistToolRaw(e,r)}}catch{}}getInscriptionTool(){const e=this.toolRegistry.getToolsByCapability("priority","critical");for(const r of e){const e=r.tool,t=e.name.toLowerCase(),o=e.description?.toLowerCase()||"";if(t.includes("inscribe")||t.includes("hashinal")||o.includes("inscribe")||o.includes("hashinal"))return e}const t=this.toolRegistry.getAllRegistryEntries();for(const r of t){const e=r.tool,t=e.name.toLowerCase(),o=e.description?.toLowerCase()||"";if(t.includes("inscribe")||t.includes("hashinal")||o.includes("inscribe")||o.includes("hashinal"))return e}return null}async executeToolDirect(e,t,r=!1){if(r&&this.executionPipeline&&this.smartMemory){const r={sessionId:`session-${Date.now()}`,timestamp:Date.now()},o=await this.executionPipeline.execute(e,t,r);if(!o.success)throw new Error(o.error||"Pipeline execution failed");return o.output}const o=this.toolRegistry.getTool(e);if(!o)throw new Error(`Tool not found: ${e}`);let s={...t};if(this.pendingParameterPreprocessingCallback){this.logger.info("Applying parameter preprocessing in executeToolDirect",{toolName:e,hasCallback:!0,parameterKeys:Object.keys(t)});try{s=await this.pendingParameterPreprocessingCallback(e,t),JSON.stringify(s)!==JSON.stringify(t)&&this.logger.info("Parameters preprocessed successfully",{toolName:e,originalKeys:Object.keys(t),processedKeys:Object.keys(s),changes:Object.keys(s).filter(e=>s[e]!==t[e])})}catch(i){this.logger.warn("Parameter preprocessing failed, using original parameters",{toolName:e,error:i instanceof Error?i.message:"Unknown error"}),s=t}}const n={...s,renderForm:!1};if(o.wrapper){const e=o.tool;if(e.originalTool?.call)return await e.originalTool.call(n)}return await o.tool.call(n)}createToolResponse(e){return{output:e,message:e,notes:[]}}async handleToolExecution(e,t){let r=!1,o=null;try{if(e.includes("TOOL_EXECUTION")){const t=JSON.parse(e);"TOOL_EXECUTION"===t.type&&(r=!0,o=t)}}catch{}if(!r||!o?.formId)return null;try{const e=o.parameters||{},t=o.toolName;if(t){const r=await this.executeToolDirect(t,e);try{const e=this.isJSON(r)?r:JSON.stringify({output:r});this.addToolRawToMemory(t,e)}catch{}return this.createToolResponse(r)}}catch{}const s={formId:o.formId,toolName:o.toolName||"",parameters:o.parameters||{},timestamp:Date.now()};return this.executor&&"processFormSubmission"in this.executor&&"function"==typeof this.executor.processFormSubmission?this.processFormSubmission(s,t):null}async handleDirectToolExecution(e){if("string"!=typeof e||!e.includes("Please execute the following tool:"))return null;try{const t=e.match(/Tool:\s*(.+)/),r=e.indexOf("Arguments:");if(t&&-1!==r){const o=t[1].trim(),s=e.slice(r+10).trim();let n={};try{n=JSON.parse(s)}catch{}const i=await this.executeToolDirect(o,n);try{const e=this.isJSON(i)?i:JSON.stringify({output:i});this.addToolRawToMemory(o,e)}catch{}return this.createToolResponse(i)}}catch{}return null}async handleJsonToolCalls(e,t){if("string"!=typeof e)return null;try{const r=e.trim();if(!(r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]")))return null;const o=JSON.parse(r),s=o.formId,n=o.toolName||"",i=o.parameters||{};if(s&&this.executor&&"processFormSubmission"in this.executor&&"function"==typeof this.executor.processFormSubmission)return this.processFormSubmission({formId:s,toolName:n,parameters:i,timestamp:Date.now()},t);if(n){const e=await this.executeToolDirect(n,i);try{const t=this.isJSON(e)?e:JSON.stringify({output:e});this.addToolRawToMemory(n,t)}catch{}return this.createToolResponse(e)}}catch{}return null}async handleContentRefMessages(e){if("string"!=typeof e||!e.includes("content-ref:"))return null;try{const t=this.getInscriptionTool();if(!t)return null;const r=e.match(/content-ref:([A-Za-z0-9_\-]+)/i)||e.match(/content-ref:([^\s)]+)/i),o=r&&r[1]?`content-ref:${r[1]}`:e.match(/content-ref:[^\s)]+/i)?.[0]||void 0,s=o?{contentRef:o,renderForm:!0,withHashLinkBlocks:!0}:{renderForm:!0,withHashLinkBlocks:!0},n=await t.call(s);let i;try{i="string"==typeof n?JSON.parse(n):n}catch{}if(i&&i.requiresForm&&i.formMessage){const r=new Map,o={input:e,chat_history:this.smartMemory.getMessages()},n=i.formMessage;r.set(n.id,{toolName:t.name,originalInput:o,originalToolInput:s,schema:null});const a=this.executor;"function"==typeof a.restorePendingForms&&a.restorePendingForms(r);const c=i.message||"Please complete the form to continue.";return{output:c,message:c,notes:[],requiresForm:!0,formMessage:n}}}catch{}return null}async processExecutorResult(t){let r="";if("string"==typeof t.output)r=t.output;else if(t.output)try{r=JSON.stringify(t.output)}catch{r=String(t.output)}let o={output:r,message:r,notes:[],intermediateSteps:t.intermediateSteps};if(t.requiresForm&&t.formMessage&&(o.formMessage=t.formMessage,o.requiresForm=!0),t.intermediateSteps&&Array.isArray(t.intermediateSteps)){const e=t.intermediateSteps.map((e,t)=>({id:`call_${t}`,name:e.action?.tool||"unknown",args:e.action?.toolInput||{},output:"string"==typeof e.observation?e.observation:JSON.stringify(e.observation)}));e.length>0&&(o.tool_calls=e),this.persistIntermediateSteps(t.intermediateSteps)}const s=t?.intermediateSteps||[],n=[...s].reverse().find(e=>"string"==typeof e?.observation&&this.isJSON(e.observation))?.observation;if(n)try{const e=JSON.parse(n);if(xe.isInscriptionResponse(e)){const t=xe.formatInscriptionResponse(e);o.output=t,o.message=t,e.inscription&&(o.inscription=e.inscription),e.metadata&&(o.metadata={...o.metadata,...e.metadata})}else"string"==typeof e.message&&e.message.trim().length>0&&(o.message=e.message,o.output=e.message),!0===e.success&&delete o.error,"string"==typeof e.transactionBytes&&(o.metadata={...o.metadata,transactionBytes:e.transactionBytes}),"string"==typeof e.scheduleId&&(o.scheduleId=e.scheduleId);const t=this.processHashLinkBlocks(e);t.hashLinkBlock&&(o.metadata={...o.metadata,...t})}catch(a){this.logger.error("Error parsing intermediate steps:",a)}if(o.output&&""!==o.output.trim()||(o.output="Agent action complete."),o.output&&this.smartMemory.addMessage(new b.AIMessage(o.output)),this.tokenTracker){const t=this.tokenTracker.getLatestTokenUsage();t&&(o.tokenUsage=t,o.cost=e.calculateTokenCostSync(t))}const i=this.smartMemory.getMemoryStats();return o.metadata={...o.metadata,memoryStats:{activeMessages:i.totalActiveMessages,tokenUsage:i.currentTokenCount,maxTokens:i.maxTokens,usagePercentage:i.usagePercentage}},this.logger.info("LangChainAgent.chat returning response:",o),o}loadContextMessages(e){if(!this.smartMemory||!e?.messages||0===e.messages.length)return;const t=this.smartMemory.getMessages(),r=new Set(t.map(e=>`${e.constructor.name}:${e.content}`));for(const o of e.messages){let e,t;if(o instanceof b.HumanMessage||o instanceof b.AIMessage||o instanceof b.SystemMessage)e=o.constructor,t=o.content;else{if(!(o&&"object"==typeof o&&"content"in o&&"type"in o))continue;{t=String(o.content);const r=String(o.type);if("human"===r)e=b.HumanMessage;else if("ai"===r)e=b.AIMessage;else{if("system"!==r)continue;e=b.SystemMessage}}}const s=`${e.name}:${t}`;r.has(s)||(this.smartMemory.addMessage(new e(t)),r.add(s))}}async boot(){if(this.logger.info("🚨🚨🚨 LANGCHAIN AGENT BOOT METHOD CALLED 🚨🚨🚨"),this.initialized)this.logger.warn("Agent already initialized");else try{this.agentKit=await this.createAgentKit(),await this.agentKit.initialize();const t=this.config.ai?.modelName||process.env.OPENAI_MODEL_NAME||"gpt-4o-mini";try{"function"==typeof e.TokenUsageCallbackHandler?this.tokenTracker=new e.TokenUsageCallbackHandler(t):this.logger.warn("TokenUsageCallbackHandler unavailable or not a constructor; skipping token tracking")}catch{this.logger.warn("TokenUsageCallbackHandler threw; skipping token tracking")}this.toolRegistry=new Ve(this.logger);const r=this.agentKit.getAggregatedLangChainTools();this.logger.info("=== TOOL REGISTRATION START ==="),this.logger.info("All tools from agentKit:",r.map(e=>e.name));const o=this.filterTools(r);this.logger.info("Filtered tools for registration:",o.map(e=>e.name));for(const e of o){this.logger.info(`🔧 Registering tool: ${e.name}`);const t={},r=e.name.toLowerCase(),o=e.description?.toLowerCase()||"";if("hedera-hts-mint-nft"===e.name){const t=e.call.bind(e);e.call=async e=>{if(e.metaOptions&&"object"==typeof e.metaOptions){const t=e.metaOptions;t.transactionMemo&&(this.logger.warn("🚨 WORKAROUND: Stripping transactionMemo from hedera-hts-mint-nft to avoid bug",{originalMemo:t.transactionMemo}),delete t.transactionMemo)}return t(e)}}(r.includes("inscribe")||r.includes("hashinal")||o.includes("inscribe")||o.includes("hashinal"))&&(t.forceWrapper=!0,t.metadata={category:"core",version:"1.0.0",dependencies:[]},this.logger.info(`🎯 CRITICAL TOOL DEBUG - ${e.name} schema:`,{hasSchema:!!e.schema,schemaType:e.schema?.constructor?.name,hasRenderConfig:!!e.schema?._renderConfig,renderConfig:e.schema?._renderConfig})),this.toolRegistry.registerTool(e,t)}this.tools=this.toolRegistry.getAllTools(),this.logger.info(`🚀 TOOLS REGISTERED: ${this.tools.length} tools`);const s=this.toolRegistry.getStatistics();this.logger.info("📊 Tool Registry Statistics:",{total:s.totalTools,wrapped:s.wrappedTools,unwrapped:s.unwrappedTools,categories:s.categoryCounts,priorities:s.priorityCounts});const n=this.getInscriptionTool();if(n){this.toolRegistry.getTool(n.name)&&this.logger.info(`✅ Inscription tool registered: ${n.name}`)}const i=this.toolRegistry.getToolNames(),a=new Set(i);if(i.length!==a.size){this.logger.error("DUPLICATE TOOL NAMES DETECTED in registry!");const e=i.filter((e,t)=>i.indexOf(e)!==t);throw new Error(`Duplicate tool names detected: ${e.join(", ")}`)}this.config.mcp?.servers&&this.config.mcp.servers.length>0&&(!1!==this.config.mcp.autoConnect?await this.initializeMCP():(this.logger.info("MCP servers configured but autoConnect=false, skipping synchronous connection"),this.mcpManager=new Re(this.logger))),this.smartMemory=new Ge({modelName:t,maxTokens:9e4,reserveTokens:1e4,storageLimit:1e3}),this.logger.info("SmartMemoryManager initialized:",{modelName:t,toolsCount:this.tools.length,maxTokens:9e4,reserveTokens:1e4}),this.formEngine=new Ie(this.logger),this.executionPipeline=new Ze(this.toolRegistry,this.formEngine,this.smartMemory,this.logger),this.systemMessage=this.buildSystemPrompt(),this.smartMemory.setSystemPrompt(this.systemMessage),await this.createExecutor(),this.initialized=!0,this.logger.info("LangChain Hedera agent initialized with ToolRegistry")}catch(t){throw this.logger.error("Failed to initialize agent:",t),t}}async chat(e,t){if(!this.initialized||!this.executor||!this.smartMemory)throw new Error("Agent not initialized. Call boot() first.");try{const r=await this.handleToolExecution(e,t);if(r)return r;const o=await this.handleDirectToolExecution(e);if(o)return o;const s=await this.handleJsonToolCalls(e,t);if(s)return s;const n=await this.handleContentRefMessages(e);if(n)return n;this.logger.info("LangChainAgent.chat called with:",{message:e,contextLength:t?.messages?.length||0}),this.loadContextMessages(t),this.smartMemory.addMessage(new b.HumanMessage(e));const i=this.smartMemory.getMemoryStats();this.logger.info("Memory stats before execution:",{totalMessages:i.totalActiveMessages,currentTokens:i.currentTokenCount,maxTokens:i.maxTokens,usagePercentage:i.usagePercentage,toolsCount:this.tools.length});const a=this.smartMemory.getMessages();this.logger.info("Current messages in memory:",{count:a.length});try{const e=a.map(e=>String(e.content||"")).filter(e=>"string"==typeof e&&(e.includes("[instruction:")||e.includes("[tool-next-steps:")));e.length>0&&this.logger.info("Instruction/next-steps messages in memory:",{messages:e})}catch{}const c=await this.executor.invoke({input:e,chat_history:a});return this.logger.info("LangChainAgent executor result:",c),this.processExecutorResult(c)}catch(r){return this.logger.error("LangChainAgent.chat error:",r),this.handleError(r)}}async shutdown(){this.mcpManager&&await this.mcpManager.disconnectAll(),this.smartMemory&&(this.smartMemory.dispose(),this.smartMemory=void 0),this.toolRegistry&&this.toolRegistry.clear(),this.executor=void 0,this.agentKit=void 0,this.tools=[],this.initialized=!1,this.logger.info("Agent cleaned up")}switchMode(e){this.config.execution?this.config.execution.operationalMode=e:this.config.execution={operationalMode:e},this.agentKit&&(this.agentKit.operationalMode=e),this.systemMessage=this.buildSystemPrompt(),this.logger.info(`Operational mode switched to: ${e}`)}getUsageStats(){if(!this.tokenTracker)return{promptTokens:0,completionTokens:0,totalTokens:0,cost:{totalCost:0}};const t=this.tokenTracker.getTotalTokenUsage(),r=e.calculateTokenCostSync(t);return{...t,cost:r}}getUsageLog(){return this.tokenTracker?this.tokenTracker.getTokenUsageHistory().map(t=>({...t,cost:e.calculateTokenCostSync(t)})):[]}clearUsageStats(){this.tokenTracker&&(this.tokenTracker.reset(),this.logger.info("Usage statistics cleared"))}getMCPConnectionStatus(){return new Map(this.mcpConnectionStatus)}async processFormSubmission(t,r){if(!this.initialized||!this.executor||!this.smartMemory)throw new Error("Agent not initialized. Call boot() first.");try{if(!t.parameters||"object"!=typeof t.parameters){this.logger.error("Invalid form submission parameters:",{parameters:t.parameters,type:typeof t.parameters});const e=JSON.stringify(t,null,2);return this.handleError(new Error(`Invalid form submission parameters: ${e}`))}this.loadContextMessages(r);const s={...t,parameters:t.parameters||{}},n=await this.executor.processFormSubmission(s),i=n?.metadata?{...n.metadata}:{};try{const e=n.rawToolOutput,t=n.toolName||"unknown";if("string"==typeof e&&e.trim().length>0){const r=this.isJSON(e)?e:JSON.stringify({output:e});this.addToolRawToMemory(t,r)}}catch{}let a="Form processed successfully.";if("string"==typeof n.output)a=n.output;else if(n.output)try{a=JSON.stringify(n.output)}catch{a=String(n.output)}let c={output:a,message:a,notes:[],intermediateSteps:n.intermediateSteps};if(n.metadata&&(c.metadata={...c.metadata,...n.metadata},this.logger.info("🔍 DEBUG: Metadata after merge from result:",{hasMetadata:!!c.metadata,metadataKeys:c.metadata?Object.keys(c.metadata):[],hasHashLinkBlock:Xe(c.metadata),hashLinkBlockContent:Xe(c.metadata)?c.metadata.hashLinkBlock:void 0})),n.requiresForm&&n.formMessage&&(c.formMessage=n.formMessage,c.requiresForm=!0),n.intermediateSteps&&Array.isArray(n.intermediateSteps)){const e=n.intermediateSteps.map((e,t)=>{const r=e?.action?.tool||"unknown",o=e?.action?.toolInput||{},s=e?.observation;let n="";if("string"==typeof s)n=s;else if(s&&"object"==typeof s)try{n=JSON.stringify(s)}catch{n=String(s)}else void 0!==s&&(n=String(s));return{id:`call_${t}`,name:r,args:o,output:n}});e.length>0&&(c.tool_calls=e),this.persistIntermediateSteps(n.intermediateSteps)}const l=n?.intermediateSteps?.[0]?.observation;if(l&&"string"==typeof l&&this.isJSON(l))try{const e=JSON.parse(l);c={...c,...e};const t=this.processHashLinkBlocks(e);t.hashLinkBlock&&(c.metadata={...c.metadata,...t})}catch(o){this.logger.error("Error parsing intermediate steps:",o)}if(c.output&&this.smartMemory.addMessage(new b.AIMessage(c.output)),this.tokenTracker){const t=this.tokenTracker.getLatestTokenUsage();t&&(c.tokenUsage=t,c.cost=e.calculateTokenCostSync(t))}const g=this.smartMemory.getMemoryStats();return this.logger.info("🔍 DEBUG: Metadata before memoryStats merge:",{hasMetadata:!!c.metadata,metadataKeys:c.metadata?Object.keys(c.metadata):[],hasHashLinkBlock:Xe(c.metadata)}),c.metadata={...i,...c.metadata,memoryStats:{activeMessages:g.totalActiveMessages,tokenUsage:g.currentTokenCount,maxTokens:g.maxTokens,usagePercentage:g.usagePercentage}},this.logger.info("🔍 DEBUG: Final response metadata before return:",{hasMetadata:!!c.metadata,metadataKeys:c.metadata?Object.keys(c.metadata):[],hasHashLinkBlock:Xe(c.metadata),fullMetadata:c.metadata}),Xe(i)&&!Xe(c.metadata)&&(this.logger.error("❌ CRITICAL: HashLink metadata was lost during processing!"),this.logger.error("Original metadata had hashLinkBlock:",i.hashLinkBlock),this.logger.error("Final metadata missing hashLinkBlock")),c}catch(o){return this.logger.error("Form submission processing error:",o),this.handleError(o)}}hasPendingForms(){return!!this.executor&&this.executor.hasPendingForms()}getPendingFormsInfo(){return this.executor?this.executor.getPendingFormsInfo():[]}async createAgentKit(){const t=[...e.getAllHederaCorePlugins(),...this.config.extensions?.plugins||[]],r=this.config.execution?.operationalMode||"returnBytes",o=this.config.ai?.modelName||"gpt-4o";return new e.HederaAgentKit(this.config.signer,{plugins:t},r,this.config.execution?.userAccountId,this.config.execution?.scheduleUserTransactionsInBytesMode??!1,void 0,o,this.config.extensions?.mirrorConfig,this.config.debug?.silent??!1)}async createExecutor(){const e=this.executor?.getPendingForms()||new Map;let t;if(this.config.ai?.provider&&this.config.ai.provider.getModel)t=this.config.ai.provider.getModel();else if(this.config.ai?.llm)t=this.config.ai.llm;else{const e=this.config.ai?.apiKey||process.env.OPENAI_API_KEY;if(!e)throw new Error("OpenAI API key required");const r=this.config.ai?.modelName||"gpt-4o-mini",o=r.toLowerCase().includes("gpt-5")||r.toLowerCase().includes("gpt5");t=new f.ChatOpenAI({apiKey:e,modelName:r,callbacks:this.tokenTracker?[this.tokenTracker]:[],...o?{temperature:1}:{}})}const r=p.ChatPromptTemplate.fromMessages([["system",this.systemMessage],new p.MessagesPlaceholder("chat_history"),["human","{input}"],new p.MessagesPlaceholder("agent_scratchpad")]),o=this.tools,s=this.getInscriptionTool();if(s){this.toolRegistry.getTool(s.name)&&this.logger.info(`✅ Inscription tool registered: ${s.name}`)}const n=this.toolRegistry.getStatistics();this.logger.info("🛡️ TOOL SECURITY REPORT:",{totalTools:n.totalTools,wrappedTools:n.wrappedTools,unwrappedTools:n.unwrappedTools,categories:n.categoryCounts,priorities:n.priorityCounts}),this.logger.info(`📊 Tool Security Summary: ${n.wrappedTools} wrapped, ${n.unwrappedTools} unwrapped`);const i=await d.createOpenAIToolsAgent({llm:t,tools:o,prompt:r});this.executor=new Ee({agent:i,tools:o,verbose:this.config.debug?.verbose??!1,returnIntermediateSteps:!0}),this.pendingParameterPreprocessingCallback&&(this.executor.setParameterPreprocessingCallback(this.pendingParameterPreprocessingCallback),this.logger.info("Parameter preprocessing callback re-applied to new executor",{hasCallback:!0})),e.size>0&&(this.logger.info(`Restoring ${e.size} pending forms to new executor`),this.executor.restorePendingForms(e)),this.logger.info("FormAwareAgentExecutor initialization complete")}setParameterPreprocessingCallback(e){this.pendingParameterPreprocessingCallback=e,this.executor?(this.executor.setParameterPreprocessingCallback(e),this.logger.info("Parameter preprocessing callback configured",{hasCallback:!!e})):this.logger.warn("Cannot set parameter preprocessing callback: executor not initialized")}handleError(t){const r=t instanceof Error?t.message:"Unknown error";let o,s;this.logger.error("Chat error:",t),this.tokenTracker&&(o=this.tokenTracker.getLatestTokenUsage(),o&&(s=e.calculateTokenCostSync(o)));let n=r,i=r;r.includes("429")?r.includes("quota")?(n="API quota exceeded. Please check your OpenAI billing and usage limits.",i="I'm currently unable to respond because the API quota has been exceeded. Please check your OpenAI account billing and usage limits, then try again."):(n=ye,i=we):r.includes("401")||r.includes("unauthorized")?(n="API authentication failed. Please check your API key configuration.",i="There's an issue with the API authentication. Please check your OpenAI API key configuration in settings."):r.includes("timeout")?(n="Request timed out. Please try again.",i="The request took too long to process. Please try again."):r.includes("network")||r.includes("fetch")?(n="Network error. Please check your internet connection and try again.",i="There was a network error. Please check your internet connection and try again."):r.includes("400")&&(n=r,i=r);const a={output:i,message:n,error:r,notes:[]};return o&&(a.tokenUsage=o),s&&(a.cost=s),a}async initializeMCP(){this.mcpManager=new Re(this.logger);for(const e of this.config.mcp.servers){if(!1===e.autoConnect){this.logger.info(`Skipping MCP server ${e.name} (autoConnect=false)`);continue}const t=await this.mcpManager.connectServer(e);if(t.connected){this.logger.info(`Connected to MCP server ${t.serverName} with ${t.tools.length} tools`);for(const r of t.tools){const t=Pe(r,this.mcpManager,e);this.toolRegistry.registerTool(t,{metadata:{category:"mcp",version:"1.0.0",dependencies:[e.name]}})}this.tools=this.toolRegistry.getAllTools()}else this.logger.error(`Failed to connect to MCP server ${t.serverName}: ${t.error}`)}}async connectMCPServers(){this.config.mcp?.servers&&0!==this.config.mcp.servers.length&&(this.mcpManager||(this.mcpManager=new Re(this.logger)),this.logger.info(`Starting background MCP server connections for ${this.config.mcp.servers.length} servers...`),this.config.mcp.servers.forEach(e=>{this.connectServerInBackground(e)}),this.logger.info("MCP server connections initiated in background"))}connectServerInBackground(e){const t=e.name;setTimeout(async()=>{try{this.logger.info(`Background connecting to MCP server: ${t}`);const r=await this.mcpManager.connectServer(e);if(this.mcpConnectionStatus.set(t,r),r.connected){this.logger.info(`Successfully connected to MCP server ${r.serverName} with ${r.tools.length} tools`);for(const t of r.tools){const r=Pe(t,this.mcpManager,e);this.toolRegistry.registerTool(r,{metadata:{category:"mcp",version:"1.0.0",dependencies:[e.name]}})}this.tools=this.toolRegistry.getAllTools(),this.initialized&&this.executor&&(this.logger.info(`Recreating executor with ${this.tools.length} total tools`),await this.createExecutor())}else this.logger.error(`Failed to connect to MCP server ${r.serverName}: ${r.error}`)}catch(r){this.logger.error(`Background connection failed for MCP server ${t}:`,r),this.mcpConnectionStatus.set(t,{connected:!1,serverName:t,tools:[],error:r instanceof Error?r.message:"Connection failed"})}},1e3)}processHashLinkBlocks(e){try{const t=e;if(e&&"object"==typeof e&&t.hashLinkBlock&&"object"==typeof t.hashLinkBlock){const e=t.hashLinkBlock;if(e.blockId&&e.hashLink&&e.template&&e.attributes&&"string"==typeof e.blockId&&"string"==typeof e.hashLink&&"string"==typeof e.template&&"object"==typeof e.attributes)return this.logger.info("HashLink block detected:",{blockId:e.blockId,hashLink:e.hashLink,template:e.template,attributeKeys:Object.keys(e.attributes)}),{hashLinkBlock:{blockId:e.blockId,hashLink:e.hashLink,template:e.template,attributes:e.attributes}};this.logger.warn("Invalid HashLink block structure detected:",e)}}catch(t){this.logger.error("Error processing HashLink blocks:",t)}return{}}isJSON(e){if("string"!=typeof e)return!1;const t=e.trim();if(!t)return!1;if(!(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")))return!1;try{return JSON.parse(t),!0}catch{return!1}}}function Qe(e){const t=e.framework||"langchain";switch(t){case"langchain":return new Ye(e);case"vercel":throw new Error("Vercel AI SDK support coming soon");case"baml":throw new Error("BAML support coming soon");default:throw new Error(`Unknown framework: ${t}`)}}class et extends e.AbstractSigner{getAccountId(){return this.account}getNetwork(){return this.network}constructor(e,t,r){super(),this.account=s.AccountId.fromString(e),this.network=t,this.client="mainnet"===t?s.Client.forMainnet():s.Client.forTestnet(),this.exec=r??null,this.ephemeralKey=s.PrivateKey.generateED25519()}getOperatorPrivateKey(){return this.ephemeralKey}getClient(){return this.client}async signAndExecuteTransaction(e){if(!this.exec)throw new Error("BrowserSigner executor not available");e.isFrozen()||await e.freezeWith(this.client);const t=globalThis.Buffer.from(e.toBytes()).toString("base64"),{transactionId:o}=await this.exec(t,this.network),n=new r.HederaMirrorNode(this.network),i=Date.now()+6e4;for(;Date.now()<i;){try{const e=await n.getTransaction(o);if(e&&e.result)return s.TransactionReceipt.fromBytes(globalThis.Buffer.from(e.result,"base64"))}catch{}await new Promise(e=>setTimeout(e,1200))}return s.TransactionReceipt.fromBytes(globalThis.Buffer.from(""))}async getPublicKey(){const e="mainnet"===this.network?"mainnet":"testnet",t=new r.HederaMirrorNode(e,new r.Logger({module:"BrowserSigner"})),o=await t.getPublicKey(this.account.toString()),n="function"==typeof o?.toString?o.toString():String(o);return s.PublicKey.fromString(n)}}class tt{constructor(e){this.model=e}async generate(e,t){const r=await this.model.invoke(e,t);return"string"==typeof r?r:r.toString()}async*stream(e,t){const r=await this.model.stream(e,t);for await(const o of r)yield"string"==typeof o?o:o.toString()}getModel(){return this.model}}let rt=null;function ot(){return rt}const st=o.z.object({url:o.z.string().url(),maxCharacters:o.z.number().int().min(256,"Minimum length is 256 characters").max(8e3,"Maximum length is 8000 characters").optional().default(3e3)});class nt extends e.BaseHederaQueryTool{constructor(e){const{fetchImpl:t,...r}=e;super(r),this.name="web_page_snapshot",this.description="Fetches the visible text content of a web page for analysis.",this.namespace="browser",this.specificInputSchema=st,this.fetchImpl=t??fetch}async executeQuery(e){const t=e.maxCharacters??3e3;try{const r=await this.fetchImpl(e.url,{redirect:"follow"});if(!r.ok)return`Failed to load ${e.url}: HTTP ${r.status}`;const o=await r.text(),s=this.normalizeHtml(o);return s?s.length>t?`${s.slice(0,t)}…`:s:"The fetched page did not contain readable text."}catch(r){return this.logger.error("WebPageSnapshotTool failed",r),`Failed to fetch content for ${e.url}: ${r instanceof Error?r.message:String(r)}`}}normalizeHtml(e){return e.replace(/<script[\s\S]*?<\/script>/gi," ").replace(/<style[\s\S]*?<\/style>/gi," ").replace(/<!--([\s\S]*?)-->/g," ").replace(/<[^>]+>/g," ").replace(/ /gi," ").replace(/&/gi,"&").replace(/</gi,"<").replace(/>/gi,">").replace(/"/gi,'"').replace(/'/gi,"'").replace(/\s+/g," ").trim()}}class it extends e.BasePlugin{constructor(){super(...arguments),this.id="web-browser",this.name="Web Browser Plugin",this.description="Provides tools for fetching live web page content to enrich assistant understanding.",this.version="0.1.0",this.author="Hashgraph Online",this.namespace="browser",this.tools=[]}async initialize(e){await super.initialize(e);const t=e.config.hederaKit;if(!t)return this.context.logger.warn("WebBrowserPlugin skipped because HederaAgentKit was not present in plugin context."),void(this.tools=[]);const r=new nt({hederaKit:t,logger:this.context.logger});this.tools=[r],this.context.logger.info("Web Browser Plugin initialized with snapshot tool")}getTools(){return this.tools}async cleanup(){this.tools=[]}}const at=e=>`You are a helpful assistant managing Hashgraph Online HCS-10 connections, messages, HCS-2 registries, content inscription, and Hedera Hashgraph operations.\n\nYou have access to tools for:\n- HCS-10: registering agents, finding registered agents, initiating connections, listing active connections, sending messages over connections, and checking for new messages\n- HCS-2: creating registries, registering entries, updating entries, deleting entries, migrating registries, and querying registry contents\n- Inscription: inscribing content from URLs, files, or buffers, creating Hashinal NFTs, and retrieving inscriptions\n- Hedera Token Service (HTS): creating tokens, transferring tokens, airdropping tokens, and managing token operations\n\n\n*** IMPORTANT CONTEXT ***\nYou are currently operating as agent: ${e||"unknown"} on the Hedera Hashgraph\nWhen users ask about "my profile", "my account", "my connections", etc., use this account ID: ${e||"unknown"}\n\n*** CRITICAL ENTITY HANDLING RULES ***\n- When users refer to entities (tokens, topics, accounts) with pronouns like "it", "that", "the token/topic", etc., ALWAYS use the most recently created entity of that type\n- Entity IDs look like "0.0.XXXXXX" and are stored in memory after creation\n- NEVER use example or placeholder IDs like "0.0.123456" - always use actual created entity IDs\n- Account ID ${e} is NOT a token - tokens and accounts are different entities\n\n Remember the connection numbers when listing connections, as users might refer to them.`;class ct{constructor(e){this.storage=e}async storeContent(e,t){const r={contentType:"binary",sizeBytes:e.length,source:"system",...t};return(await this.storage.storeContent(e,r)).referenceId}async resolveReference(e){const t=await this.storage.resolveReference(e);if(t.success&&t.content){const e={content:t.content};return t.metadata&&(e.metadata={...void 0!==t.metadata.mimeType&&{mimeType:t.metadata.mimeType},...void 0!==t.metadata.fileName&&{fileName:t.metadata.fileName},originalSize:t.metadata.sizeBytes}),e}throw new Error(t.error||"Reference not found")}async hasReference(e){return await this.storage.hasReference(e)}async cleanupReference(e){await this.storage.cleanupReference(e)}async getStats(){return await this.storage.getStats()}async updateConfig(e){const t={sizeThresholdBytes:e.maxSize||10240,enableAutoCleanup:e.enableCompression||!0,...e};return await this.storage.updateConfig(t)}async performCleanup(){await this.storage.performCleanup()}async dispose(){return Promise.resolve(this.storage.dispose())}}class lt{constructor(e){this.adapter=e}async resolveReference(e){return await this.adapter.resolveReference(e)}shouldUseReference(e){return r.shouldUseReference(e)}extractReferenceId(e){return r.extractReferenceId(e)}}class gt{constructor(e=1e3,t,o){this.isRegistered=!1,this.logger=o||new r.Logger({module:"ContentStoreManager"}),this.contentStorage=new Ue(e,t),this.adapter=new ct(this.contentStorage),this.resolver=new lt(this.adapter)}async initialize(){if(this.isRegistered)this.logger.warn("ContentStoreManager is already initialized");else try{r.ContentStoreService&&"function"==typeof r.ContentStoreService.setInstance?await r.ContentStoreService.setInstance(this.adapter):this.logger.warn("ContentStoreService.setInstance is unavailable; skipping registration"),r.ContentResolverRegistry&&"function"==typeof r.ContentResolverRegistry.register?r.ContentResolverRegistry.register(this.resolver):this.logger.warn("ContentResolverRegistry.register is unavailable; skipping registration"),this.isRegistered=!0,this.logger.info("ContentStoreManager initialized and registered for cross-package access")}catch(e){throw this.logger.error("Failed to initialize ContentStoreManager:",e),e}}getContentStorage(){return this.contentStorage}async getStats(){return await this.contentStorage.getStats()}async updateConfig(e){return await this.contentStorage.updateConfig(e)}async performCleanup(){return await this.contentStorage.performCleanup()}shouldUseReference(e){return this.contentStorage.shouldUseReference(e)}async storeContentIfLarge(e,t){const r={source:"system",contentType:"binary",...t};return await this.contentStorage.storeContentIfLarge(e,r)}async dispose(){this.isRegistered&&(this.contentStorage.dispose(),r.ContentStoreService&&"function"==typeof r.ContentStoreService.dispose&&r.ContentStoreService.dispose(),r.ContentResolverRegistry&&"function"==typeof r.ContentResolverRegistry.unregister&&r.ContentResolverRegistry.unregister(),this.isRegistered=!1,this.logger.info("ContentStoreManager disposed and unregistered"))}isInitialized(){return this.isRegistered}}const ht=new r.Logger({module:"EntityResolverTool"}),ut=o.z.object({message:o.z.string().describe("The message containing entity references to resolve"),entities:o.z.array(o.z.object({entityId:o.z.string(),entityName:o.z.string(),entityType:o.z.string()})).describe("Available entities in memory")}),dt=o.z.object({response:o.z.string().describe("Agent response text to extract entities from"),userMessage:o.z.string().describe("Original user message for context")});class mt extends i.StructuredTool{constructor(e){super(),this.name="resolve_entities",this.description='Resolves entity references like "the topic", "it", "that" to actual entity IDs',this.schema=ut,this.llm=e}async _call(e){const{message:t,entities:r}=e;if(!r||0===r.length)return t;const o=this.groupEntitiesByType(r),s=`Task: Replace entity references with IDs.\n\n${this.buildEntityContext(o)}\n\nMessage: "${t}"\n\nRules:\n- "the topic" or "that topic" → replace with most recent topic ID\n- "the token" or "that token" → replace with most recent token ID\n- "it" or "that" after action verb → replace with most recent entity ID\n- "airdrop X" without token ID → add most recent token ID as first parameter\n- Token operations without explicit token → use most recent token ID\n\nExamples:\n- "submit on the topic" → "submit on 0.0.6543472"\n- "airdrop the token" → "airdrop 0.0.123456"\n- "airdrop 10 to 0.0.5842697" → "airdrop 0.0.123456 10 to 0.0.5842697"\n- "mint 100" → "mint 0.0.123456 100"\n\nReturn ONLY the resolved message:`;try{return(await this.llm.invoke(s)).content.trim()}catch(n){return ht.error("ResolveEntitiesTool failed:",n),t}}groupEntitiesByType(e){return e.reduce((e,t)=>(e[t.entityType]||(e[t.entityType]=[]),e[t.entityType].push(t),e),{})}buildEntityContext(e){let t="Available entities:\n";for(const[r,o]of Object.entries(e)){const e=o[0];t+=`- Most recent ${r}: "${e.entityName}" = ${e.entityId}\n`}return t}}class pt extends i.StructuredTool{constructor(e){super(),this.name="extract_entities",this.description="Extracts newly created entities from agent responses",this.schema=dt,this.llm=e}async _call(e){const{response:t,userMessage:r}=e,o=`Extract ONLY newly created entities from this response.\n\nUser asked: "${r.substring(0,200)}"\nResponse: ${t.substring(0,3e3)}\n\nLook for:\n- Success messages with new entity IDs\n- Words like "created", "new", "successfully" followed by entity IDs\n\nReturn JSON array of created entities:\n[{"id": "0.0.XXX", "name": "name", "type": "topic|token|account"}]\n\nIf none created, return: []\n\nJSON:`;try{const e=await this.llm.invoke(o),t=e.content.match(/\[[\s\S]*?\]/);return t?t[0]:"[]"}catch(s){return ht.error("ExtractEntitiesTool failed:",s),"[]"}}}function ft(e){return{resolveEntities:new mt(e),extractEntities:new pt(e)}}class yt{constructor(){this.converters=new Map,this.entityTypeCache=new Map,this.logger=new r.Logger({module:"FormatConverterRegistry"}),this.defaultCacheTTL=3e5}register(e){const t=`${e.sourceFormat}→${e.targetFormat}`;this.converters.set(t,e)}findConverter(e,t){const r=`${e}→${t}`;return this.converters.get(r)||null}async convertEntity(e,t,r){const o=await this.detectFormatWithFallback(e,r);if(o===t)return e;const s=this.findConverter(o,t);if(!s)throw new Error(`No converter found for ${o} → ${t}`);if(!s.canConvert(e,r))throw new Error(`Converter cannot handle entity: ${e}`);return await s.convert(e,r)}async detectFormatWithFallback(e,t){if(e.startsWith("hcs://"))return be.HRL;if(/^0\.0\.\d+$/.test(e)){const o=this.getCachedFormat(e);if(o)return o;try{const r=await this.detectFormat(e,t||{});if(r!==be.ANY)return this.setCachedFormat(e,r),r}catch(r){this.logger.warn(`Entity detection failed for ${e}, using fallback: ${r.message}`)}return be.ANY}return be.ANY}async detectEntityFormat(e,t){return this.detectFormatWithFallback(e,t)}async detectFormat(e,t){const o=t.networkType||"testnet",s=new r.HederaMirrorNode(o,this.logger);s.configureRetry({maxRetries:3,maxDelayMs:1e3});const n=(await Promise.allSettled([s.getAccountBalance(e).then(e=>null!==e?be.ACCOUNT_ID:null).catch(()=>null),s.getTokenInfo(e).then(e=>null!==e?be.TOKEN_ID:null).catch(()=>null),s.getTopicInfo(e).then(e=>null!==e?be.TOPIC_ID:null).catch(()=>null),s.getContract(e).then(e=>null!==e?be.CONTRACT_ID:null).catch(()=>null)])).find(e=>"fulfilled"===e.status&&null!==e.value);return n&&"fulfilled"===n.status?n.value:be.ANY}getCachedFormat(e){const t=this.entityTypeCache.get(e);return!t||this.isCacheExpired(t)?(this.entityTypeCache.delete(e),null):t.format}setCachedFormat(e,t){this.entityTypeCache.set(e,{format:t,timestamp:Date.now(),ttl:this.defaultCacheTTL})}isCacheExpired(e){return Date.now()-e.timestamp>e.ttl}getRegisteredConverters(){return Array.from(this.converters.keys()).map(e=>{const[t,r]=e.split("→");return{source:t,target:r}})}hasConverter(e,t){return null!==this.findConverter(e,t)}clear(){this.converters.clear()}clearCache(){this.entityTypeCache.clear()}}class wt{constructor(){this.sourceFormat=be.TOPIC_ID,this.targetFormat=be.HRL}canConvert(e,t){return/^0\.0\.\d+$/.test(e)}async convert(e,t){return`hcs://${"mainnet"===(t.networkType||"testnet")?"0":"1"}/${e}`}}const bt=class{constructor(){this.sourceFormat=be.ANY,this.targetFormat=be.HRL}canConvert(e,t){if("string"!=typeof e)return!1;if(/^hcs:\/\/\d\/0\.0\.\d+$/i.test(e))return!1;if(/inscription-cdn\/(0\.0\.\d+)/i.test(e))return!0;if(/^content-ref:(0\.0\.\d+)$/i.test(e))return!0;if(/^0\.0\.\d+$/.test(e)){return Boolean("hrl"===t?.toolPreferences?.inscription||"hrl"===t?.toolPreferences?.topic)}return!1}async convert(e,t){const o=t.toolPreferences,s=o?.hrlStandard||o?.inscriptionHrlStandard||"1",n=t.networkType||"testnet",i=new r.HRLResolver,a=e.match(/inscription-cdn\/(0\.0\.\d+)/i);if(a&&a[1])try{const e=new r.HederaMirrorNode(n);e.configureRetry({maxRetries:3,maxDelayMs:1e3});const t=await e.getTopicInfo(a[1]),o=(t&&t.memo||"").match(/^hcs-(\d+)/);return`hcs://${o&&o[1]?o[1]:"1"}/${a[1]}`}catch{return`hcs://${s}/${a[1]}`}const c=e.match(/^content-ref:(0\.0\.\d+)$/i);if(c&&c[1])try{const e=await i.resolve(c[1],{network:n}),t=i.parseHRL(`hcs://1/${e.topicId}`);return`hcs://${t?.standard||s}/${e.topicId}`}catch{return`hcs://${s}/${c[1]}`}if(/^0\.0\.\d+$/.test(e))try{const t=await i.resolve(e,{network:n}),r=i.parseHRL(`hcs://1/${t.topicId}`);return`hcs://${r?.standard||s}/${t.topicId}`}catch{return`hcs://${s}/${e}`}return e}};bt.standardCache=new Map;let Tt=bt;class St{constructor(e,t){this.logger=new r.Logger({module:"ParameterService"}),this.formatConverterRegistry=e,this.networkType=t}async preprocessParameters(e,t,r=[],o){const s=o?.sessionId,n=o?.entityResolver,i=o?.preferences;let a={...t};if(n&&r.length>0)try{this.logger.info("AI-driven preprocessing phase",{toolName:e,entityCount:r.length,sessionId:s});const t={...a};for(const[e,o]of Object.entries(a))if("string"==typeof o){const s=await n.resolveReferences(o,r),a=await this.convertParameterEntities(s,r,i);t[e]=a}else if(Array.isArray(o)){const s=[];for(const e of o)if("string"==typeof e){const t=await n.resolveReferences(e,r),o=await this.convertParameterEntities(t,r,i);s.push(o)}else s.push(e);t[e]=s}a=t}catch(c){const t=c instanceof Error?c.message:"unknown";this.logger.warn("AI phase failed; continuing with deterministic pass",{toolName:e,error:t})}try{const e={...a};for(const[t,o]of Object.entries(a))if("string"==typeof o){const s=await this.convertParameterEntities(o,r,i);e[t]=s}else if(Array.isArray(o)){const s=[];for(const e of o)if("string"==typeof e){const t=await this.convertParameterEntities(e,r,i);s.push(t)}else s.push(e);e[t]=s}a=e}catch(l){this.logger.warn("Deterministic post-pass failed",{toolName:e,error:l instanceof Error?l.message:"unknown"})}return a}attachToAgent(e,t){const r=t?.getSessionId??(()=>null),o=t?.getEntities??(async()=>[]),s=t?.entityResolver,n=e,i=e=>{const t=e;return"function"==typeof t.setParameterPreprocessingCallback&&(t.setParameterPreprocessingCallback(async(e,t)=>{const n=r(),i=await o(n),a={};return s&&(a.entityResolver=s),n&&(a.sessionId=n),this.preprocessParameters(e,t,i,a)}),this.logger.info("Parameter preprocessing callback attached"),!0)};if(!i(e)&&"function"==typeof n.getAgent){const e=n.getAgent();e&&i(e)}}async preprocessToolParameters(e,t,r,o){try{if(!r||0===r.length)return this.logger.info("Tool parameter preprocessing skipped - no entities provided:",{toolName:e,originalParams:Object.keys(t)}),t;const s={...t},n=void 0;let i=!1;for(const[o,a]of Object.entries(t))if("string"==typeof a){const t=await this.convertParameterEntities(a,r,n);t!==a&&(s[o]=t,i=!0,this.logger.info("Parameter entity conversion applied:",{toolName:e,paramName:o,original:a,converted:t}))}else if(Array.isArray(a)){const t=a,c=[];let l=!1;for(const s of t)if("string"==typeof s){const t=await this.convertParameterEntities(s,r,n);c.push(t),t!==s&&(l=!0,this.logger.info("Parameter array item conversion applied:",{toolName:e,paramName:o,original:s,converted:t}))}else c.push(s);l&&(s[o]=c,i=!0)}return this.logger.info("Tool parameter preprocessing completed:",{toolName:e,originalParams:Object.keys(t),hasChanges:i,sessionId:o}),s}catch(s){return this.logger.warn("Tool parameter preprocessing failed:",{toolName:e,error:s instanceof Error?s.message:"Unknown error"}),t}}async convertParameterEntities(e,t,r){let o=e;for(const n of t){const e=o.includes(n.entityId),t=o.includes(n.entityName);if(!e&&!t)continue;let i=null;if(n.entityType===be.TOPIC_ID?"hrl"===r?.inscription||"hrl"===r?.topic?i=be.HRL:"topicId"!==r?.inscription&&"topicId"!==r?.topic||(i=be.TOPIC_ID):n.entityType===be.TOKEN_ID?"tokenId"===r?.token?i=be.TOKEN_ID:"symbol"===r?.token&&(i=be.SYMBOL):n.entityType===be.ACCOUNT_ID&&("accountId"===r?.account||"accountId"===r?.supplyKey||"accountId"===r?.adminKey?i=be.ACCOUNT_ID:"alias"===r?.account&&(i=be.ALIAS)),i)try{const s={networkType:this.networkType,sessionId:"unknown"};r&&(s.toolPreferences=r);const a=await this.formatConverterRegistry.convertEntity(n.entityId,i,s);e&&(o=o.replace(new RegExp(`\\b${n.entityId.replace(/\./g,"\\.")}\\b`,"g"),a)),t&&(o=o.replace(new RegExp(`\\b${n.entityName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"g"),a)),this.logger.info("Applied format conversion to parameter:",{entityId:n.entityId,entityType:n.entityType,targetFormat:i,convertedValue:a,parameterValue:o})}catch(s){this.logger.warn("Format conversion failed for parameter:",{entityId:n.entityId,targetFormat:i,error:s instanceof Error?s.message:"Unknown error"})}}return o}}const vt="gpt-4o",kt="gpt-4o-mini",Ct="claude-3-7-sonnet-latest",It=.1,xt="testnet",Mt="autonomous",Et=class o{constructor(e){if(this.options=e,this.stateManager=e.stateManager||new t.OpenConvaiState,this.hcs10Plugin=new v,this.hcs2Plugin=new k,this.inscribePlugin=new I,this.hbarPlugin=new R,this.webBrowserPlugin=new it,this.logger=new r.Logger({module:"ConversationalAgent",silent:e.disableLogging||!1}),!1!==this.options.entityMemoryEnabled){if(!e.openAIApiKey)throw new Error("OpenAI/Anthropic API key is required when entity memory is enabled");this.memoryManager=new Ge(this.options.entityMemoryConfig),this.logger.info("Entity memory initialized");const t=e.entityMemoryProvider||e.llmProvider||"openai";let r,o=e.entityMemoryModelName;if(o||(o="anthropic"===t?Ct:"openrouter"===t?"openai/gpt-4o-mini":kt),"anthropic"===t)r=new S.ChatAnthropic({apiKey:e.openAIApiKey,model:o,temperature:0});else if("openrouter"===t){const t=e.openRouterBaseURL||"https://openrouter.ai/api/v1",s=e.openRouterApiKey||e.openAIApiKey;r=new f.ChatOpenAI({apiKey:s,model:o,temperature:0,configuration:{baseURL:t,defaultHeaders:{"HTTP-Referer":process.env.OPENROUTER_REFERRER||"https://hashgraphonline.com","X-Title":process.env.OPENROUTER_TITLE||"Hashgraph Online Conversational Agent"}}})}else r=new f.ChatOpenAI({apiKey:e.openAIApiKey,model:o,temperature:0});this.entityTools=ft(r),this.logger.info("LLM-based entity resolver tools initialized")}}async initialize(){const{accountId:r,privateKey:o,network:s=xt,openAIApiKey:n,openAIModelName:i=vt,llmProvider:a="openai"}=this.options;this.validateOptions(r,o);try{const g=this.options.operationalMode||Mt,h="autonomous"!==g;let u,d;try{const e=t.InscriberBuilder;"function"==typeof e.setPreferWalletOnly&&e.setPreferWalletOnly(!1)}catch(c){this.logger.warn("Failed to set wallet-only preference",c)}if(h){const e="mainnet"===String(s||"testnet")?"mainnet":"testnet",t=this.options.userAccountId||r;u=new et(t,e,this.options.walletExecutor)}else u=new e.ServerSigner(r,o,s);this.logger.info("Signer configured",{operationalMode:g,bytesMode:h,signerClass:Object.getPrototypeOf(u)?.constructor?.name||"unknown"});try{const e=ot();if(e){const r=t.InscriberBuilder;"function"==typeof r.setWalletInfoResolver&&r.setWalletInfoResolver(async()=>{const t=await e.status();return t.connected&&t.accountId&&t.network?{accountId:t.accountId,network:t.network}:null}),"function"==typeof r.setWalletExecutor&&r.setWalletExecutor(async(t,r)=>await e.executeBytes(t,r)),"function"==typeof r.setStartInscriptionDelegate&&e.startInscription&&r.setStartInscriptionDelegate(async(t,r)=>await e.startInscription(t,r));try{const r=await e.status(),o=!(!h||!r.connected);t.SignerProviderRegistry.setWalletInfoResolver(async()=>{const t=await e.status();return t.connected&&t.accountId&&t.network?{accountId:t.accountId,network:t.network}:null}),t.SignerProviderRegistry.setWalletExecutor(async(t,r)=>await e.executeBytes(t,r));const s=e;"function"==typeof s?.startHCS?t.SignerProviderRegistry.setStartHCSDelegate(async(e,t,r)=>await s.startHCS(e,t,r)):t.SignerProviderRegistry.setStartHCSDelegate(null),t.SignerProviderRegistry.setPreferWalletOnly(o);const n=t.InscriberBuilder;"function"==typeof n.setPreferWalletOnly&&n.setPreferWalletOnly(o)}catch(l){this.logger.warn("Failed to wire SAK SignerProviderRegistry wallet delegates",l)}}}catch(c){this.logger.warn("Failed to register wallet bridge providers",c)}let m={provider:a};if("anthropic"===a)d=new S.ChatAnthropic({apiKey:n,model:i||Ct,temperature:It}),m={...m,model:i||Ct,keyPresent:!!n};else if("openrouter"===a){const e=this.options.openRouterBaseURL||"https://openrouter.ai/api/v1",t=this.options.openRouterApiKey||n,r=i||"anthropic/claude-3-haiku-20240307";d=new f.ChatOpenAI({apiKey:t,model:r,temperature:It,configuration:{baseURL:e,defaultHeaders:{"HTTP-Referer":process.env.OPENROUTER_REFERRER||"https://hashgraphonline.com","X-Title":process.env.OPENROUTER_TITLE||"Hashgraph Online Conversational Agent"}}}),m={...m,model:r,baseURL:e,keyPresent:!!t}}else{const e=i||kt,t=e.toLowerCase().includes("gpt-5")||e.toLowerCase().includes("gpt5");d=new f.ChatOpenAI({apiKey:n,model:e,...t?{temperature:1}:{temperature:It}}),m={...m,model:e,keyPresent:!!n}}this.logger.info("AI provider configured",m),this.logger.info("Preparing plugins...");const p=this.preparePlugins();this.logger.info("Creating agent config...");const y=this.createAgentConfig(u,d,p);if(this.logger.info("Creating agent..."),this.agent=Qe(y),this.logger.info("Agent created"),this.logger.info("Configuring HCS10 plugin..."),this.configureHCS10Plugin(p),this.logger.info("HCS10 plugin configured"),this.contentStoreManager=new gt,await this.contentStoreManager.initialize(),this.logger.info("ContentStoreManager initialized for content reference support"),this.logger.info("About to call agent.boot()"),this.logger.info("🔥 About to call agent.boot()"),await this.agent.boot(),this.logger.info("agent.boot() completed"),this.logger.info("🔥 agent.boot() completed"),this.agent){try{const e=new yt;e.register(new wt),e.register(new Tt);new St(e,this.options.network||"testnet").attachToAgent(this.agent,{getEntities:async()=>this.memoryManager?.getEntityAssociations()||[]}),this.logger.info("Parameter preprocessing callback attached (internal)")}catch(c){this.logger.warn("Failed to attach internal parameter preprocessing callback",c)}const e=y;e.filtering=e.filtering||{};const t=e.filtering.toolPredicate,r=this.options.toolFilter;e.filtering.toolPredicate=e=>(!e||"hedera-account-transfer-hbar"!==e.name)&&((!e||"hedera-hts-airdrop-token"!==e.name)&&(!(t&&!t(e))&&!(r&&!r(e))))}this.options.mcpServers&&this.options.mcpServers.length>0&&this.connectMCP()}catch(g){throw this.logger.error("Failed to initialize ConversationalAgent:",g),g}}getPlugin(){return this.hcs10Plugin}getStateManager(){return this.stateManager}getAgent(){if(!this.agent)throw new Error(o.NOT_INITIALIZED_ERROR);return this.agent}getConversationalAgent(){return this.getAgent()}async processMessage(e,t=[]){if(!this.agent)throw new Error("Agent not initialized. Call initialize() first.");try{const r=e,o={messages:t.map(e=>{const t=e.content;return"system"===e.type?new b.SystemMessage(t):"human"===e.type?new b.HumanMessage(t):new b.AIMessage(t)})},s=await this.agent.chat(r,o);return this.memoryManager&&"returnBytes"!==this.options.operationalMode&&await this.extractAndStoreEntities(s,e),this.logger.info("Message processed successfully"),s}catch(r){throw this.logger.error("Error processing message:",r),r}}async processFormSubmission(e){if(!this.agent)throw new Error(o.NOT_INITIALIZED_ERROR);try{this.logger.info("Processing form submission:",{formId:e.formId,toolName:e.toolName,parameterKeys:Object.keys(e.parameters||{}),hasContext:!!e.context});const t=await this.agent.processFormSubmission(e);return this.logger.info("Form submission processed successfully"),t}catch(t){throw this.logger.error("Error processing form submission:",t),t}}validateOptions(e,t){const r="autonomous"!==(this.options.operationalMode||Mt);if(!e)throw new Error("Account ID is required");if(!t&&!r)throw new Error("Private key is required in autonomous mode");if("string"!=typeof e)throw new Error("Account ID must be a string, received "+typeof e);if(!r&&"string"!=typeof t)throw new Error(`Private key must be a string, received ${typeof t}: ${JSON.stringify(t)}`);if(!r&&"string"==typeof t&&t.length<10)throw new Error("Private key appears to be invalid (too short)")}preparePlugins(){const{additionalPlugins:t=[],enabledPlugins:r,disabledPlugins:o}=this.options,s=[this.hcs10Plugin,this.hcs2Plugin,this.inscribePlugin,this.hbarPlugin];s.push(this.webBrowserPlugin);const n=e.getAllHederaCorePlugins();let i=[...s,...n];if(r){const e=new Set(r);i=i.filter(t=>e.has(t.id))}if(o&&o.length>0){const e=new Set(o);i=i.filter(t=>!e.has(t.id))}const a=o&&o.length>0?t.filter(e=>!o.includes(e.id)):t;return[...i,...a]}createAgentConfig(e,t,r){const{operationalMode:o=Mt,userAccountId:s,scheduleUserTransactionsInBytesMode:n,customSystemMessagePreamble:i,customSystemMessagePostamble:a,verbose:c=!1,mirrorNodeConfig:l,disableLogging:g,accountId:h=""}=this.options;return{framework:"langchain",signer:e,execution:{mode:"autonomous"===o?"direct":"bytes",operationalMode:o,...s&&{userAccountId:s},...void 0!==n&&{scheduleUserTransactionsInBytesMode:n,scheduleUserTransactions:n}},ai:{provider:new tt(t),temperature:It},filtering:{toolPredicate:e=>"hedera-account-transfer-hbar"!==e.name&&!(this.options.toolFilter&&!this.options.toolFilter(e))},messaging:{systemPreamble:i||at(h),...a&&{systemPostamble:a},conciseMode:!0},extensions:{plugins:r,...l&&{mirrorConfig:l}},...this.options.mcpServers&&{mcp:{servers:this.options.mcpServers,autoConnect:!1}},debug:{verbose:c,silent:g??!1}}}configureHCS10Plugin(e){const t=e.find(e=>"hcs-10"===e.id);t&&(t.appConfig={stateManager:this.stateManager})}static withPlugins(e,t){return new o({...e,enabledPlugins:t})}static withHTS(e){return this.withPlugins(e,["hts-token"])}static withHCS2(e){return this.withPlugins(e,["hcs-2"])}static withHCS10(e){return this.withPlugins(e,["hcs-10"])}static withInscribe(e){return this.withPlugins(e,["inscribe"])}static withAccount(e){return this.withPlugins(e,["account"])}static withFileService(e){return this.withPlugins(e,["file-service"])}static withConsensusService(e){return this.withPlugins(e,["consensus-service"])}static withSmartContract(e){return this.withPlugins(e,["smart-contract"])}static withAllStandards(e){return this.withPlugins(e,["hcs-10","hcs-2","inscribe"])}static minimal(e){return this.withPlugins(e,[])}static withMCP(e,t){return new o({...e,mcpServers:t})}async extractAndStoreEntities(e,t){if(this.memoryManager&&this.entityTools)try{this.logger.info("Starting LLM-based entity extraction");const o=this.extractResponseText(e),s=await this.entityTools.extractEntities.call({response:o,userMessage:t});try{const t=JSON.parse(s);for(const r of t)if(r&&"object"==typeof r&&"name"in r&&"type"in r&&"id"in r){this.logger.info(`Storing entity: ${r.name} (${r.type}) -> ${r.id}`);const t=this.extractTransactionId(e),o=String(r.id);/^0\.0\.[0-9]+$/.test(o)?this.memoryManager.storeEntityAssociation(o,String(r.name),String(r.type),t):this.logger.warn("Skipping non-ID entity from extraction",{id:o,name:String(r.name),type:String(r.type)})}t.length>0?this.logger.info(`Stored ${t.length} entities via LLM extraction`):this.logger.info("No entities found in response via LLM extraction")}catch(r){throw this.logger.error("Failed to parse extracted entities JSON:",r),r}}catch(o){throw this.logger.error("Entity extraction failed:",o),o}}extractTransactionId(e){try{if("object"==typeof e&&e&&"transactionId"in e){const t=e;return"string"==typeof t.transactionId?t.transactionId:void 0}if("string"==typeof e){const t=e.match(/transaction[\s\w]*ID[\s:"]*([0-9a-fA-F@._-]+)/i);return t?t[1]:void 0}return}catch{return}}connectMCP(){this.agent&&this.options.mcpServers&&this.agent.connectMCPServers().catch(e=>{this.logger.error("Failed to connect MCP servers:",e)}).then(()=>{this.logger.info("MCP servers connected successfully")})}getMCPConnectionStatus(){return this.agent?this.agent.getMCPConnectionStatus():new Map}isMCPServerConnected(e){if(this.agent){const t=this.agent.getMCPConnectionStatus().get(e);return t?.connected??!1}return!1}async cleanup(){try{if(this.logger.info("Cleaning up ConversationalAgent..."),this.memoryManager){try{this.memoryManager.dispose(),this.logger.info("Memory manager cleaned up successfully")}catch(e){this.logger.warn("Error cleaning up memory manager:",e)}this.memoryManager=void 0}this.contentStoreManager&&(await this.contentStoreManager.dispose(),this.logger.info("ContentStoreManager cleaned up")),this.logger.info("ConversationalAgent cleanup completed")}catch(e){this.logger.error("Error during cleanup:",e)}}switchMode(e){this.agent?.switchMode&&this.agent.switchMode(e||"autonomous")}getUsageStats(){return this.agent?.getUsageStats?.()??{}}clearUsageStats(){this.agent?.clearUsageStats&&this.agent.clearUsageStats()}shutdown(){return this.agent?.shutdown?.()??Promise.resolve()}extractResponseText(e){if("string"==typeof e)return e;if(e&&"object"==typeof e&&"output"in e){return String(e.output)}return JSON.stringify(e)}};Et.NOT_INITIALIZED_ERROR="Agent not initialized. Call initialize() first.";let At=Et;exports.AttachmentProcessor=class{constructor(){this.logger=new r.Logger({module:"AttachmentProcessor"})}async processAttachments(e,t,r){return 0===t.length?e:(this.logger.info("Processing attachments with content reference system:",{attachmentCount:t.length,totalSize:t.reduce((e,t)=>e+t.size,0)}),r&&r.isInitialized()?this.processWithContentStore(e,t,r):(this.logger.warn("Content storage not available, creating simple file references"),this.processWithSimpleReferences(e,t)))}async processWithContentStore(e,t,r){const o=[];for(const i of t)try{const e=i.data.includes("base64,")?i.data.split("base64,")[1]:i.data,t=globalThis.Buffer.from(e,"base64"),s=await r.storeContentIfLarge(t,{mimeType:i.type,source:"user_upload",fileName:i.name,tags:["attachment","user_file"]});s?i.type.startsWith("image/")?o.push(`[Image File: ${i.name}] (content-ref:${s.referenceId})`):o.push(`[File: ${i.name}] (content-ref:${s.referenceId})`):o.push(this.createInlineReference(i,e))}catch(n){this.logger.error("Failed to process attachment:",{fileName:i.name,error:n instanceof Error?n.message:"Unknown error"}),o.push(`[File: ${i.name} - Error processing file: ${n instanceof Error?n.message:"Unknown error"}]`)}const s=this.createFileList(t);return e?`${e}\n\nAttached files:\n${s}\n\n${o.join("\n")}`:`Attached files:\n${s}\n\n${o.join("\n")}`}processWithSimpleReferences(e,t){const r=t.map(e=>{const t=this.formatFileSize(e.size);return e.type.startsWith("image/")?`📎 Image: ${e.name} (${t}, ${e.type})`:`📎 File: ${e.name} (${t}, ${e.type})`});return e?`${e}\n\nAttached files:\n${r.join("\n")}`:`Attached files:\n${r.join("\n")}`}createInlineReference(e,t){return e.size<5e4?e.type.startsWith("image/")?``:`[File: ${e.name} (${this.formatFileSize(e.size)})]\nContent: ${t}`:`[File: ${e.name} (${this.formatFileSize(e.size)}) - Content too large to include inline]`}createFileList(e){return e.map(e=>{const t=this.formatFileSize(e.size);return`📎 ${e.name} (${t})`}).join("\n")}formatFileSize(e){return e>=1048576?`${(e/1048576).toFixed(1)}MB`:`${(e/1024).toFixed(1)}KB`}},exports.BaseAgent=Ae,exports.ContentStorage=Ue,exports.ContentStoreManager=gt,exports.ConversationalAgent=At,exports.EntityFormat=be,exports.EntityResolver=class{constructor(e){this.llm=new f.ChatOpenAI({apiKey:e.apiKey,modelName:e.modelName||"gpt-4o-mini",temperature:0}),this.logger=new r.Logger({module:"EntityResolver"})}async resolveReferences(e,t){if(!t||0===t.length)return e;const r=t.reduce((e,t)=>(e[t.entityType]||(e[t.entityType]=[]),e[t.entityType].push(t),e),{});try{const t=Object.fromEntries(Object.entries(r).map(([e,t])=>[e,{count:t.length,mostRecent:t[0]?.entityId}]));this.logger.info("resolveReferences: input summary",{messagePreview:e.substring(0,200),entityStats:t})}catch{}let o="Available entities in memory:\n";for(const[n,i]of Object.entries(r)){const e=i[0];o+=`Most recent ${n}: "${e.entityName}" = ${e.entityId}\n`,i.length>1&&(o+=` (${i.length-1} other ${n}s in memory)\n`)}const s=`Task: Replace entity references with their IDs from memory. STRICT TYPE RULES:\n\n- For phrases referring to "${Se}" or actions that clearly require a token (create/mint/airdrop/associate/etc.), resolve to the most recent TOKEN entity ID (never a topic or account).\n- For phrases referring to "${Te}" or actions that clearly require a topic (inscribe/publish/consensus/etc.), resolve to the most recent TOPIC entity ID (never a token or account).\n- Do not infer or invent entity IDs. Only use those present in the provided context.\n\n${o}\n\nUser message: "${e}"\n\nInstructions:\n- If the user says "${Te}" or "that topic" → replace with the most recent topic ID\n- If the user says "${Se}" or "that token" → replace with the most recent token ID (never a topic)\n- If the user says "it" or "that" after an action verb → replace with the most recent entity ID\n- Examples:\n * "submit on ${Te}" → "submit on 0.0.6543472"\n * "airdrop ${Se}" → "airdrop 0.0.123456"\n * "send a message to it" → "send a message to 0.0.6543472"\n\nReturn ONLY the message with replacements made. Do not add any explanations.\nResolved message:`;try{const t=(await this.llm.invoke(s)).content.trim(),r=t!==e;try{this.logger.info("resolveReferences: resolution result",{changed:r,hasEntityId:/\b0\.0\.\d+\b/.test(t),resolvedPreview:t.substring(0,200)})}catch{}return r&&t.includes("0.0.")?t:e}catch{return e}}async extractEntities(e,t){const r=this.extractFromReceipt(e,t);return r.length>0?r:this.extractWithLLM(e,t)}extractFromReceipt(e,t){const r=[];let o;try{o="string"==typeof e?JSON.parse(e):e}catch{o=e}if(!o||!1===o.success)return r;const s=o.receipt||o.result?.receipt||o.data?.receipt;if(!s)return r;const n=this.extractNameFromMessage(t),i=o.transactionId||o.result?.transactionId||void 0,a=e=>"string"==typeof e?e:e&&"object"==typeof e&&"function"==typeof e.toString&&e.toString!==Object.prototype.toString?e.toString():String(e);if(s.tokenId){const e={id:a(s.tokenId),name:n,type:be.TOKEN_ID};i&&(e.transactionId=i),r.push(e)}if(s.topicId){const e={id:a(s.topicId),name:n,type:be.TOPIC_ID};i&&(e.transactionId=i),r.push(e)}if(s.accountId){const e={id:a(s.accountId),name:n,type:be.ACCOUNT_ID};i&&(e.transactionId=i),r.push(e)}if(s.contractId){const e={id:a(s.contractId),name:n,type:be.CONTRACT_ID};i&&(e.transactionId=i),r.push(e)}if(s.fileId){const e={id:a(s.fileId),name:n,type:be.FILE_ID};i&&(e.transactionId=i),r.push(e)}if(s.scheduleId){const e={id:a(s.scheduleId),name:n,type:be.SCHEDULE_ID};i&&(e.transactionId=i),r.push(e)}return r}extractNameFromMessage(e){const t=e.match(/"([^"]+)"/);if(t)return t[1];const r=e.match(/called\s+([A-Za-z0-9#\s_-]+?)(?:\s|$)/i);if(r)return r[1].trim();const o=e.match(/for\s+([A-Za-z0-9#\s_-]+)/i);if(o)return o[1].trim();const s=e.match(/(?:token|topic|account|contract)\s+([A-Za-z0-9#_-]+)/i);return s?s[1].trim():e.includes("new account")?"new account":"unnamed_entity"}async extractWithLLM(e,t){const r="string"==typeof e?e:JSON.stringify(e),o=`Analyze this agent response and extract ONLY newly created entities.\n\nUser asked: "${t.substring(0,200)}"\n\nAgent response: ${r.substring(0,3e3)}\n\nCRITICAL: Only extract Hedera entity IDs in the format 0.0.XXXXX (shard.realm.number).\nDO NOT extract:\n- Token symbols (e.g., "FOREV", "USDC", "HBAR")\n- Token names (e.g., "Forever", "My Token")\n- Transaction IDs (format: 0.0.XXX@timestamp)\n- Account aliases or mnemonics\n\nLook for:\n1. Success messages with entity IDs (e.g., "Successfully created topic 0.0.6543472")\n2. Transaction confirmations that created new entities\n3. Entity IDs that appear after words like "created", "new", "successfully"\n\nDO NOT include:\n- Token symbols or names (these are NOT entity IDs)\n- Account IDs that already existed (like sender/receiver accounts)\n- Entity IDs that were parameters to the operation\n- Failed operations\n- Anything that doesn't match the 0.0.XXXXX format\n\nReturn a JSON array of newly created entities:\n[{"id": "0.0.XXX", "name": "descriptive_name", "type": "topic|token|account"}]\n\nIf no entities were created, return: []\n\nJSON:`;try{const e=await this.llm.invoke(o),t=e.content.match(/\[[\s\S]*?\]/);if(t){return JSON.parse(t[0])}}catch{}return[]}validateEntityType(e,t,r){const o=r.find(t=>t.entityId===e);return!!o&&o.entityType===t}async resolveWithTypeValidation(e,t,r){return await this.resolveReferences(e,t),r?t.filter(e=>e.entityType===r):t}getEntitiesByType(e,t){return e.filter(e=>e.entityType===t)}getMostRecentEntityByType(e,t){const r=e.filter(e=>e.entityType===t);return 0===r.length?null:r.reduce((e,t)=>t.createdAt>e.createdAt?t:e)}},exports.ExtractEntitiesTool=pt,exports.FieldTypeRegistry=pe,exports.FormAwareAgentExecutor=Ee,exports.FormEngine=Ie,exports.FormGenerator=Ce,exports.FormValidatingToolWrapper=We,exports.FormatConverterRegistry=yt,exports.HCS10Plugin=v,exports.HCS2Plugin=k,exports.HbarPlugin=R,exports.InscribePlugin=I,exports.LangChainAgent=Ye,exports.LangChainProvider=tt,exports.MCPClientManager=Re,exports.MCPContentProcessor=Fe,exports.MCPServers={filesystem:e=>({name:"filesystem",command:"npx",args:["-y","@modelcontextprotocol/server-filesystem",e],transport:"stdio",autoConnect:!0,additionalContext:"This server provides access to files and directories in the current working directory.",toolDescriptions:{list_directory:'Use this tool when users ask about files in the "current directory" or "working directory".',read_file:"Use this tool when users ask to see or check files in the current directory."}}),github:e=>({name:"github",command:"npx",args:["-y","@modelcontextprotocol/server-github"],...e&&{env:{GITHUB_TOKEN:e}},transport:"stdio",autoConnect:!0}),slack:e=>({name:"slack",command:"npx",args:["-y","@modelcontextprotocol/server-slack"],env:{SLACK_TOKEN:e},transport:"stdio",autoConnect:!0}),googleDrive:e=>({name:"google-drive",command:"npx",args:["-y","@modelcontextprotocol/server-google-drive"],env:{GOOGLE_CREDENTIALS:e},transport:"stdio",autoConnect:!0}),postgres:e=>({name:"postgres",command:"npx",args:["-y","@modelcontextprotocol/server-postgres",e],transport:"stdio",autoConnect:!0}),sqlite:e=>({name:"sqlite",command:"npx",args:["-y","@modelcontextprotocol/server-sqlite",e],transport:"stdio",autoConnect:!0}),custom:e=>e},exports.MemoryWindow=ze,exports.OpenConvAIPlugin=v,exports.ParameterService=St,exports.ReferenceIdGenerator=De,exports.ResolveEntitiesTool=mt,exports.ResponseFormatter=xe,exports.SmartMemoryManager=Ge,exports.StringNormalizationConverter=Tt,exports.SwarmPlugin=me,exports.TokenCounter=$e,exports.TopicIdToHrlConverter=wt,exports.convertMCPToolToLangChain=Pe,exports.createAgent=Qe,exports.createEntityTools=ft,exports.createMCPConfig=function(e,t=!0){return{mcpServers:e.map(e=>({...e,autoConnect:e.autoConnect??t}))}},exports.fieldGuidanceRegistry=C,exports.fieldTypeRegistry=fe,exports.getWalletBridgeProvider=ot,exports.setWalletBridgeProvider=function(e){rt=e},exports.validateServerConfig=function(e){const t=[];return e.name||t.push("Server name is required"),e.command||t.push("Server command is required"),e.args&&Array.isArray(e.args)||t.push("Server args must be an array"),e.transport&&!["stdio","http","websocket"].includes(e.transport)&&t.push("Invalid transport type. Must be stdio, http, or websocket"),t},exports.wrapToolWithFormValidation=Je,Object.keys(e).forEach(t=>{"default"===t||Object.prototype.hasOwnProperty.call(exports,t)||Object.defineProperty(exports,t,{enumerable:!0,get:()=>e[t]})});
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|