@hashgraphonline/standards-agent-kit 0.0.37 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (251) hide show
  1. package/dist/cjs/builders/hcs10/hcs10-builder.d.ts +262 -0
  2. package/dist/cjs/builders/index.d.ts +2 -0
  3. package/dist/cjs/builders/types.d.ts +10 -0
  4. package/dist/cjs/index.d.ts +3 -1
  5. package/dist/cjs/init/init.d.ts +21 -22
  6. package/dist/cjs/plugins/PluginInterface.d.ts +4 -80
  7. package/dist/cjs/plugins/PluginRegistry.d.ts +1 -47
  8. package/dist/cjs/plugins/defi/index.d.ts +7 -4
  9. package/dist/cjs/plugins/hedera/HbarPricePlugin.d.ts +7 -35
  10. package/dist/cjs/plugins/index.d.ts +0 -5
  11. package/dist/cjs/plugins/weather/index.d.ts +6 -5
  12. package/dist/cjs/standards-agent-kit.cjs +1 -1
  13. package/dist/cjs/standards-agent-kit.cjs.map +1 -1
  14. package/dist/cjs/state/state-types.d.ts +8 -8
  15. package/dist/cjs/tools/hcs10/AcceptConnectionRequestTool.d.ts +40 -0
  16. package/dist/cjs/tools/hcs10/CheckMessagesTool.d.ts +40 -0
  17. package/dist/cjs/tools/hcs10/ConnectionMonitorTool.d.ts +134 -0
  18. package/dist/cjs/tools/hcs10/FindRegistrationsTool.d.ts +34 -0
  19. package/dist/cjs/tools/hcs10/InitiateConnectionTool.d.ts +43 -0
  20. package/dist/cjs/tools/hcs10/ListConnectionsTool.d.ts +34 -0
  21. package/dist/cjs/tools/hcs10/ListUnapprovedConnectionRequestsTool.d.ts +15 -0
  22. package/dist/cjs/tools/hcs10/ManageConnectionRequestsTool.d.ts +34 -0
  23. package/dist/cjs/tools/hcs10/RegisterAgentTool.d.ts +218 -0
  24. package/dist/cjs/tools/hcs10/RetrieveProfileTool.d.ts +33 -0
  25. package/dist/cjs/tools/hcs10/SendMessageToConnectionTool.d.ts +40 -0
  26. package/dist/cjs/tools/hcs10/base-hcs10-tools.d.ts +28 -0
  27. package/dist/cjs/tools/hcs10/hcs10-tool-params.d.ts +18 -0
  28. package/dist/cjs/tools/hcs10/index.d.ts +13 -0
  29. package/dist/cjs/tools/index.d.ts +1 -13
  30. package/dist/es/builders/hcs10/hcs10-builder.d.ts +262 -0
  31. package/dist/es/builders/index.d.ts +2 -0
  32. package/dist/es/builders/types.d.ts +10 -0
  33. package/dist/es/index.d.ts +3 -1
  34. package/dist/es/init/init.d.ts +21 -22
  35. package/dist/es/plugins/PluginInterface.d.ts +4 -80
  36. package/dist/es/plugins/PluginRegistry.d.ts +1 -47
  37. package/dist/es/plugins/defi/index.d.ts +7 -4
  38. package/dist/es/plugins/hedera/HbarPricePlugin.d.ts +7 -35
  39. package/dist/es/plugins/index.d.ts +0 -5
  40. package/dist/es/plugins/weather/index.d.ts +6 -5
  41. package/dist/es/standards-agent-kit.es.js +10 -18
  42. package/dist/es/standards-agent-kit.es.js.map +1 -1
  43. package/dist/es/standards-agent-kit.es10.js +29 -76
  44. package/dist/es/standards-agent-kit.es10.js.map +1 -1
  45. package/dist/es/standards-agent-kit.es11.js +61 -384
  46. package/dist/es/standards-agent-kit.es11.js.map +1 -1
  47. package/dist/es/standards-agent-kit.es12.js +22 -190
  48. package/dist/es/standards-agent-kit.es12.js.map +1 -1
  49. package/dist/es/standards-agent-kit.es13.js +26 -138
  50. package/dist/es/standards-agent-kit.es13.js.map +1 -1
  51. package/dist/es/standards-agent-kit.es14.js +35 -59
  52. package/dist/es/standards-agent-kit.es14.js.map +1 -1
  53. package/dist/es/standards-agent-kit.es15.js +11 -117
  54. package/dist/es/standards-agent-kit.es15.js.map +1 -1
  55. package/dist/es/standards-agent-kit.es16.js +1 -1
  56. package/dist/es/standards-agent-kit.es16.js.map +1 -1
  57. package/dist/es/standards-agent-kit.es17.js +63 -46
  58. package/dist/es/standards-agent-kit.es17.js.map +1 -1
  59. package/dist/es/standards-agent-kit.es18.js +25 -74
  60. package/dist/es/standards-agent-kit.es18.js.map +1 -1
  61. package/dist/es/standards-agent-kit.es19.js +22 -13
  62. package/dist/es/standards-agent-kit.es19.js.map +1 -1
  63. package/dist/es/standards-agent-kit.es2.js +1381 -188
  64. package/dist/es/standards-agent-kit.es2.js.map +1 -1
  65. package/dist/es/standards-agent-kit.es20.js +3 -67
  66. package/dist/es/standards-agent-kit.es20.js.map +1 -1
  67. package/dist/es/standards-agent-kit.es3.js +285 -347
  68. package/dist/es/standards-agent-kit.es3.js.map +1 -1
  69. package/dist/es/standards-agent-kit.es4.js +22 -74
  70. package/dist/es/standards-agent-kit.es4.js.map +1 -1
  71. package/dist/es/standards-agent-kit.es5.js +127 -154
  72. package/dist/es/standards-agent-kit.es5.js.map +1 -1
  73. package/dist/es/standards-agent-kit.es6.js +21 -88
  74. package/dist/es/standards-agent-kit.es6.js.map +1 -1
  75. package/dist/es/standards-agent-kit.es7.js +28 -86
  76. package/dist/es/standards-agent-kit.es7.js.map +1 -1
  77. package/dist/es/standards-agent-kit.es8.js +27 -100
  78. package/dist/es/standards-agent-kit.es8.js.map +1 -1
  79. package/dist/es/standards-agent-kit.es9.js +35 -117
  80. package/dist/es/standards-agent-kit.es9.js.map +1 -1
  81. package/dist/es/state/state-types.d.ts +8 -8
  82. package/dist/es/tools/hcs10/AcceptConnectionRequestTool.d.ts +40 -0
  83. package/dist/es/tools/hcs10/CheckMessagesTool.d.ts +40 -0
  84. package/dist/es/tools/hcs10/ConnectionMonitorTool.d.ts +134 -0
  85. package/dist/es/tools/hcs10/FindRegistrationsTool.d.ts +34 -0
  86. package/dist/es/tools/hcs10/InitiateConnectionTool.d.ts +43 -0
  87. package/dist/es/tools/hcs10/ListConnectionsTool.d.ts +34 -0
  88. package/dist/es/tools/hcs10/ListUnapprovedConnectionRequestsTool.d.ts +15 -0
  89. package/dist/es/tools/hcs10/ManageConnectionRequestsTool.d.ts +34 -0
  90. package/dist/es/tools/hcs10/RegisterAgentTool.d.ts +218 -0
  91. package/dist/es/tools/hcs10/RetrieveProfileTool.d.ts +33 -0
  92. package/dist/es/tools/hcs10/SendMessageToConnectionTool.d.ts +40 -0
  93. package/dist/es/tools/hcs10/base-hcs10-tools.d.ts +28 -0
  94. package/dist/es/tools/hcs10/hcs10-tool-params.d.ts +18 -0
  95. package/dist/es/tools/hcs10/index.d.ts +13 -0
  96. package/dist/es/tools/index.d.ts +1 -13
  97. package/dist/umd/builders/hcs10/hcs10-builder.d.ts +262 -0
  98. package/dist/umd/builders/index.d.ts +2 -0
  99. package/dist/umd/builders/types.d.ts +10 -0
  100. package/dist/umd/index.d.ts +3 -1
  101. package/dist/umd/init/init.d.ts +21 -22
  102. package/dist/umd/plugins/PluginInterface.d.ts +4 -80
  103. package/dist/umd/plugins/PluginRegistry.d.ts +1 -47
  104. package/dist/umd/plugins/defi/index.d.ts +7 -4
  105. package/dist/umd/plugins/hedera/HbarPricePlugin.d.ts +7 -35
  106. package/dist/umd/plugins/index.d.ts +0 -5
  107. package/dist/umd/plugins/weather/index.d.ts +6 -5
  108. package/dist/umd/standards-agent-kit.umd.js +1 -164
  109. package/dist/umd/standards-agent-kit.umd.js.map +1 -1
  110. package/dist/umd/state/state-types.d.ts +8 -8
  111. package/dist/umd/tools/hcs10/AcceptConnectionRequestTool.d.ts +40 -0
  112. package/dist/umd/tools/hcs10/CheckMessagesTool.d.ts +40 -0
  113. package/dist/umd/tools/hcs10/ConnectionMonitorTool.d.ts +134 -0
  114. package/dist/umd/tools/hcs10/FindRegistrationsTool.d.ts +34 -0
  115. package/dist/umd/tools/hcs10/InitiateConnectionTool.d.ts +43 -0
  116. package/dist/umd/tools/hcs10/ListConnectionsTool.d.ts +34 -0
  117. package/dist/umd/tools/hcs10/ListUnapprovedConnectionRequestsTool.d.ts +15 -0
  118. package/dist/umd/tools/hcs10/ManageConnectionRequestsTool.d.ts +34 -0
  119. package/dist/umd/tools/hcs10/RegisterAgentTool.d.ts +218 -0
  120. package/dist/umd/tools/hcs10/RetrieveProfileTool.d.ts +33 -0
  121. package/dist/umd/tools/hcs10/SendMessageToConnectionTool.d.ts +40 -0
  122. package/dist/umd/tools/hcs10/base-hcs10-tools.d.ts +28 -0
  123. package/dist/umd/tools/hcs10/hcs10-tool-params.d.ts +18 -0
  124. package/dist/umd/tools/hcs10/index.d.ts +13 -0
  125. package/dist/umd/tools/index.d.ts +1 -13
  126. package/package.json +41 -41
  127. package/src/builders/hcs10/hcs10-builder.ts +2108 -0
  128. package/src/builders/index.ts +2 -0
  129. package/src/builders/types.ts +11 -0
  130. package/src/hcs10/HCS10Client.ts +3 -2
  131. package/src/index.ts +4 -2
  132. package/src/init/init.ts +85 -63
  133. package/src/plugins/PluginInterface.ts +15 -94
  134. package/src/plugins/PluginRegistry.ts +2 -98
  135. package/src/plugins/defi/index.ts +31 -118
  136. package/src/plugins/hedera/HbarPricePlugin.ts +19 -100
  137. package/src/plugins/index.ts +0 -5
  138. package/src/plugins/weather/index.ts +56 -40
  139. package/src/state/state-types.ts +9 -11
  140. package/src/tools/hcs10/AcceptConnectionRequestTool.ts +56 -0
  141. package/src/tools/hcs10/CheckMessagesTool.ts +73 -0
  142. package/src/tools/hcs10/ConnectionMonitorTool.ts +111 -0
  143. package/src/tools/hcs10/FindRegistrationsTool.ts +64 -0
  144. package/src/tools/hcs10/InitiateConnectionTool.ts +66 -0
  145. package/src/tools/hcs10/ListConnectionsTool.ts +58 -0
  146. package/src/tools/hcs10/ListUnapprovedConnectionRequestsTool.ts +26 -0
  147. package/src/tools/hcs10/ManageConnectionRequestsTool.ts +48 -0
  148. package/src/tools/hcs10/RegisterAgentTool.ts +213 -0
  149. package/src/tools/hcs10/RetrieveProfileTool.ts +61 -0
  150. package/src/tools/hcs10/SendMessageToConnectionTool.ts +45 -0
  151. package/src/tools/hcs10/base-hcs10-tools.ts +65 -0
  152. package/src/tools/hcs10/hcs10-tool-params.ts +21 -0
  153. package/src/tools/hcs10/index.ts +13 -0
  154. package/src/tools/index.ts +2 -13
  155. package/src/utils/HederaClient.ts +2 -2
  156. package/src/utils/ensure-agent-has-hbar.ts +3 -4
  157. package/dist/cjs/agents/index.d.ts +0 -0
  158. package/dist/cjs/plugins/BasePlugin.d.ts +0 -28
  159. package/dist/cjs/plugins/GenericPlugin.d.ts +0 -17
  160. package/dist/cjs/plugins/HCS10Plugin.d.ts +0 -13
  161. package/dist/cjs/plugins/PluginLoader.d.ts +0 -38
  162. package/dist/cjs/plugins/openconvai/OpenConvAIPlugin.d.ts +0 -23
  163. package/dist/cjs/plugins/openconvai/index.d.ts +0 -1
  164. package/dist/cjs/tools/AcceptConnectionRequestTool.d.ts +0 -33
  165. package/dist/cjs/tools/CheckMessagesTool.d.ts +0 -34
  166. package/dist/cjs/tools/ConnectionMonitorTool.d.ts +0 -100
  167. package/dist/cjs/tools/ConnectionTool.d.ts +0 -40
  168. package/dist/cjs/tools/FindRegistrationsTool.d.ts +0 -28
  169. package/dist/cjs/tools/InitiateConnectionTool.d.ts +0 -30
  170. package/dist/cjs/tools/ListConnectionsTool.d.ts +0 -33
  171. package/dist/cjs/tools/ListUnapprovedConnectionRequestsTool.d.ts +0 -41
  172. package/dist/cjs/tools/ManageConnectionRequestsTool.d.ts +0 -38
  173. package/dist/cjs/tools/RegisterAgentTool.d.ts +0 -188
  174. package/dist/cjs/tools/RetrieveProfileTool.d.ts +0 -34
  175. package/dist/cjs/tools/SendMessageToConnectionTool.d.ts +0 -34
  176. package/dist/cjs/tools/SendMessageTool.d.ts +0 -40
  177. package/dist/es/agents/index.d.ts +0 -0
  178. package/dist/es/plugins/BasePlugin.d.ts +0 -28
  179. package/dist/es/plugins/GenericPlugin.d.ts +0 -17
  180. package/dist/es/plugins/HCS10Plugin.d.ts +0 -13
  181. package/dist/es/plugins/PluginLoader.d.ts +0 -38
  182. package/dist/es/plugins/openconvai/OpenConvAIPlugin.d.ts +0 -23
  183. package/dist/es/plugins/openconvai/index.d.ts +0 -1
  184. package/dist/es/standards-agent-kit.es21.js +0 -92
  185. package/dist/es/standards-agent-kit.es21.js.map +0 -1
  186. package/dist/es/standards-agent-kit.es22.js +0 -7
  187. package/dist/es/standards-agent-kit.es22.js.map +0 -1
  188. package/dist/es/standards-agent-kit.es23.js +0 -106
  189. package/dist/es/standards-agent-kit.es23.js.map +0 -1
  190. package/dist/es/standards-agent-kit.es24.js +0 -7
  191. package/dist/es/standards-agent-kit.es24.js.map +0 -1
  192. package/dist/es/standards-agent-kit.es25.js +0 -7
  193. package/dist/es/standards-agent-kit.es25.js.map +0 -1
  194. package/dist/es/standards-agent-kit.es26.js +0 -85
  195. package/dist/es/standards-agent-kit.es26.js.map +0 -1
  196. package/dist/es/standards-agent-kit.es27.js +0 -28
  197. package/dist/es/standards-agent-kit.es27.js.map +0 -1
  198. package/dist/es/tools/AcceptConnectionRequestTool.d.ts +0 -33
  199. package/dist/es/tools/CheckMessagesTool.d.ts +0 -34
  200. package/dist/es/tools/ConnectionMonitorTool.d.ts +0 -100
  201. package/dist/es/tools/ConnectionTool.d.ts +0 -40
  202. package/dist/es/tools/FindRegistrationsTool.d.ts +0 -28
  203. package/dist/es/tools/InitiateConnectionTool.d.ts +0 -30
  204. package/dist/es/tools/ListConnectionsTool.d.ts +0 -33
  205. package/dist/es/tools/ListUnapprovedConnectionRequestsTool.d.ts +0 -41
  206. package/dist/es/tools/ManageConnectionRequestsTool.d.ts +0 -38
  207. package/dist/es/tools/RegisterAgentTool.d.ts +0 -188
  208. package/dist/es/tools/RetrieveProfileTool.d.ts +0 -34
  209. package/dist/es/tools/SendMessageToConnectionTool.d.ts +0 -34
  210. package/dist/es/tools/SendMessageTool.d.ts +0 -40
  211. package/dist/umd/agents/index.d.ts +0 -0
  212. package/dist/umd/plugins/BasePlugin.d.ts +0 -28
  213. package/dist/umd/plugins/GenericPlugin.d.ts +0 -17
  214. package/dist/umd/plugins/HCS10Plugin.d.ts +0 -13
  215. package/dist/umd/plugins/PluginLoader.d.ts +0 -38
  216. package/dist/umd/plugins/openconvai/OpenConvAIPlugin.d.ts +0 -23
  217. package/dist/umd/plugins/openconvai/index.d.ts +0 -1
  218. package/dist/umd/tools/AcceptConnectionRequestTool.d.ts +0 -33
  219. package/dist/umd/tools/CheckMessagesTool.d.ts +0 -34
  220. package/dist/umd/tools/ConnectionMonitorTool.d.ts +0 -100
  221. package/dist/umd/tools/ConnectionTool.d.ts +0 -40
  222. package/dist/umd/tools/FindRegistrationsTool.d.ts +0 -28
  223. package/dist/umd/tools/InitiateConnectionTool.d.ts +0 -30
  224. package/dist/umd/tools/ListConnectionsTool.d.ts +0 -33
  225. package/dist/umd/tools/ListUnapprovedConnectionRequestsTool.d.ts +0 -41
  226. package/dist/umd/tools/ManageConnectionRequestsTool.d.ts +0 -38
  227. package/dist/umd/tools/RegisterAgentTool.d.ts +0 -188
  228. package/dist/umd/tools/RetrieveProfileTool.d.ts +0 -34
  229. package/dist/umd/tools/SendMessageToConnectionTool.d.ts +0 -34
  230. package/dist/umd/tools/SendMessageTool.d.ts +0 -40
  231. package/src/agents/index.ts +0 -1
  232. package/src/plugins/BasePlugin.ts +0 -37
  233. package/src/plugins/GenericPlugin.ts +0 -19
  234. package/src/plugins/HCS10Plugin.ts +0 -14
  235. package/src/plugins/PluginLoader.ts +0 -121
  236. package/src/plugins/README.md +0 -113
  237. package/src/plugins/openconvai/OpenConvAIPlugin.ts +0 -124
  238. package/src/plugins/openconvai/index.ts +0 -1
  239. package/src/tools/AcceptConnectionRequestTool.ts +0 -196
  240. package/src/tools/CheckMessagesTool.ts +0 -194
  241. package/src/tools/ConnectionMonitorTool.ts +0 -550
  242. package/src/tools/ConnectionTool.ts +0 -231
  243. package/src/tools/FindRegistrationsTool.ts +0 -114
  244. package/src/tools/InitiateConnectionTool.ts +0 -137
  245. package/src/tools/ListConnectionsTool.ts +0 -158
  246. package/src/tools/ListUnapprovedConnectionRequestsTool.ts +0 -173
  247. package/src/tools/ManageConnectionRequestsTool.ts +0 -275
  248. package/src/tools/RegisterAgentTool.ts +0 -590
  249. package/src/tools/RetrieveProfileTool.ts +0 -94
  250. package/src/tools/SendMessageToConnectionTool.ts +0 -142
  251. package/src/tools/SendMessageTool.ts +0 -116
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("@hashgraphonline/standards-sdk"),t=require("@hashgraph/sdk"),n=require("@langchain/core/tools"),o=require("zod"),i=require("fs"),r=require("path"),s=require("axios");function a(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const n in e)if("default"!==n){const o=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,o.get?o:{enumerable:!0,get:()=>e[n]})}return t.default=e,Object.freeze(t)}const c=a(i),g=a(r);class l{constructor(t,n,o,i){this.standardClient=new e.HCS10Client({network:o,operatorId:t,operatorPrivateKey:n,guardedRegistryBaseUrl:i?.registryUrl,logLevel:i?.logLevel}),this.guardedRegistryBaseUrl=i?.registryUrl||"",this.useEncryption=i?.useEncryption||!1;const r="true"===process.env.DISABLE_LOGGING;this.logger=new e.Logger({level:i?.logLevel||"info",silent:r})}getOperatorId(){const e=this.standardClient.getClient().operatorAccountId;if(!e)throw new Error("Operator Account ID not configured in standard client.");return e.toString()}getNetwork(){return this.standardClient.getNetwork()}async handleConnectionRequest(e,t,n,o){try{return await this.standardClient.handleConnectionRequest(e,t,n,o)}catch(i){throw this.logger.error(`Error handling connection request #${n} for topic ${e}:`,i),new Error(`Failed to handle connection request: ${i instanceof Error?i.message:String(i)}`)}}async getAgentProfile(e){return this.standardClient.retrieveProfile(e)}async submitConnectionRequest(e,t){return this.standardClient.submitConnectionRequest(e,t)}async waitForConnectionConfirmation(e,t,n=60,o=2e3){return this.standardClient.waitForConnectionConfirmation(e,t,n,o)}async createAndRegisterAgent(t){const n=(new e.AgentBuilder).setName(t.name).setBio(t.description||"").setCapabilities(t.capabilities?t.capabilities:[e.AIAgentCapability.TEXT_GENERATION]).setType(t.type||"autonomous").setModel(t.model||"agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(e.InboundTopicType.PUBLIC);t?.feeConfig&&(n.setInboundTopicType(e.InboundTopicType.FEE_BASED),n.setFeeConfig(t.feeConfig)),t.pfpBuffer&&t.pfpFileName?0===t.pfpBuffer.byteLength?this.logger.warn("Provided PFP buffer is empty. Skipping profile picture."):(this.logger.info(`Setting profile picture: ${t.pfpFileName} (${t.pfpBuffer.byteLength} bytes)`),n.setProfilePicture(t.pfpBuffer,t.pfpFileName)):this.logger.warn("Profile picture not provided in metadata. Agent creation might fail if required by the underlying SDK builder."),t.social&&Object.entries(t.social).forEach((([e,t])=>{n.addSocial(e,t)})),t.properties&&Object.entries(t.properties).forEach((([e,t])=>{n.addProperty(e,t)}));try{const e=Boolean(t?.feeConfig),o=await this.standardClient.createAndRegisterAgent(n,{initialBalance:e?50:void 0});return o?.metadata?.inboundTopicId&&o?.metadata?.outboundTopicId&&(this.agentChannels={inboundTopicId:o.metadata.inboundTopicId,outboundTopicId:o.metadata.outboundTopicId}),o}catch(o){throw this.logger.error("Error during agent creation/registration:",o),new Error(`Failed to create/register agent: ${o instanceof Error?o.message:String(o)}`)}}async sendMessage(e,t,n,o){this.useEncryption;try{const i=await this.standardClient.sendMessage(e,t,n,o);return i.topicSequenceNumber?.toNumber()}catch(i){throw this.logger.error(`Error sending message to topic ${e}:`,i),new Error(`Failed to send message: ${i instanceof Error?i.message:String(i)}`)}}async getMessages(e){try{const t=(await this.standardClient.getMessages(e)).messages.map((e=>{const t=e?.created?.getTime()||0;return{...e,timestamp:t,data:e.data,sequence_number:e.sequence_number}}));return t.sort(((e,t)=>e.timestamp-t.timestamp)),{messages:t}}catch(t){return this.logger.error(`Error getting messages from topic ${e}:`,t),{messages:[]}}}async getMessageStream(e){return this.standardClient.getMessageStream(e)}async getMessageContent(e){try{return await this.standardClient.getMessageContent(e)}catch(t){throw this.logger.error(`Error retrieving message content for: ${e}`,t),new Error(`Failed to retrieve message content: ${t instanceof Error?t.message:String(t)}`)}}async getInboundTopicId(){try{const e=this.getOperatorId();this.logger.info(`[HCS10Client] Retrieving profile for operator ${e} to find inbound topic...`);const t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.inboundTopic)return this.logger.info(`[HCS10Client] Found inbound topic for operator ${e}: ${t.topicInfo.inboundTopic}`),t.topicInfo.inboundTopic;throw new Error(`Could not retrieve inbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}catch(e){this.logger.error(`[HCS10Client] Error fetching operator's inbound topic ID (${this.getOperatorId()}):`,e);const t=this.getOperatorId();let n=`Failed to get inbound topic ID for operator ${t}.`;throw e instanceof Error&&e.message.includes("does not have a valid HCS-11 memo")?n+=` The account profile may not exist or is invalid. Please ensure this operator account (${t}) is registered as an HCS-10 agent. You might need to register it first (e.g., using the 'register_agent' tool or SDK function).`:e instanceof Error?n+=` Reason: ${e.message}`:n+=` Unexpected error: ${String(e)}`,new Error(n)}}getAccountAndSigner(){const e=this.standardClient.getAccountAndSigner();return{accountId:e.accountId,signer:e.signer}}async getOutboundTopicId(){const e=this.getOperatorId(),t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.outboundTopic)return t.topicInfo.outboundTopic;throw new Error(`Could not retrieve outbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}setClient(t,n){return this.standardClient=new e.HCS10Client({network:this.getNetwork(),operatorId:t,operatorPrivateKey:n,guardedRegistryBaseUrl:this.guardedRegistryBaseUrl}),this.standardClient}async validateOperator(e){try{this.setClient(e.accountId,e.privateKey);return{isValid:!0,operator:{accountId:this.getOperatorId()}}}catch(t){return this.logger.error(`Validation error: ${t}`),{isValid:!1,error:t instanceof Error?t.message:String(t)}}}async initializeWithValidation(e){const t=await this.validateOperator(e);return t.isValid&&e.stateManager&&e.stateManager.initializeConnectionsManager(this.standardClient),t}}class u extends n.StructuredTool{constructor(e,t){super(),this.name="register_agent",this.description="Creates and registers the AI agent on the Hedera network. Returns JSON string with agent details (accountId, privateKey, topics) on success. Optionally supports fee configuration for the agent's inbound topic using HBAR or specific tokens.",this.schema=o.z.object({name:o.z.string().describe("The name of the agent to register"),description:o.z.string().optional().describe("Optional description of the agent"),type:o.z.enum(["autonomous","manual"]).optional().describe("Optional agent type (default: autonomous)"),model:o.z.string().optional().describe("Optional model identifier for the agent"),capabilities:o.z.array(o.z.number()).optional().describe("Optional array of AIAgentCapability enum values (0-18). If not provided, defaults to just TEXT_GENERATION (0)"),profilePicture:o.z.union([o.z.string().describe("Path to a local image file or URL to an image"),o.z.object({url:o.z.string().describe("URL to an image file"),filename:o.z.string().describe("Filename to use for the image")}),o.z.object({path:o.z.string().describe("Path to a local image file"),filename:o.z.string().optional().describe("Optional custom filename")})]).optional().describe("Optional profile picture for the agent (local file path or URL)"),feeCollectorAccountId:o.z.string().optional().describe("The account ID to collect fees. If not specified, the new agent's account ID will be used. Required if any fee is specified."),hbarFee:o.z.number().optional().describe("Optional: The fee amount in HBAR to charge per message on the inbound topic (e.g., 0.5). If specified, inboundTopicType will be set to FEE_BASED."),tokenFee:o.z.object({amount:o.z.number(),tokenId:o.z.string()}).optional().describe('Optional: The fee amount and token ID to charge per message on the inbound topic (e.g., { amount: 10, tokenId: "0.0.12345" }). If specified, inboundTopicType will be set to FEE_BASED.'),hbarFees:o.z.array(o.z.object({amount:o.z.number(),collectorAccount:o.z.string().optional()})).optional().describe("Optional: Array of HBAR fees with different collectors. If specified, inboundTopicType will be set to FEE_BASED."),tokenFees:o.z.array(o.z.object({amount:o.z.number(),tokenId:o.z.string(),collectorAccount:o.z.string().optional()})).optional().describe("Optional: Array of token fees with different collectors. If specified, inboundTopicType will be set to FEE_BASED."),exemptAccountIds:o.z.array(o.z.string()).optional().describe("Optional: Array of account IDs to exempt from ALL fees set for this agent."),setAsCurrent:o.z.boolean().optional().describe("Optional: Whether to set the newly registered agent as the current active agent in the state manager. Default: true"),persistence:o.z.object({prefix:o.z.string().optional()}).optional().describe("Optional: Configuration for persisting agent data to environment variables. The prefix will determine the environment variable names (e.g., PREFIX_ACCOUNT_ID). Defaults to TODD if not specified.")}),this.client=e,this.stateManager=t}async loadProfilePicture(t){const n=e.Logger.getInstance({level:"debug"});try{if(!t)return null;if("string"==typeof t){if(t.startsWith("http://")||t.startsWith("https://")){n.info(`Loading profile picture from URL: ${t}`);const e=await s.get(t,{responseType:"arraybuffer"}),o=globalThis.Buffer.from(e.data),i=new URL(t).pathname;return{buffer:o,filename:r.basename(i)||"profile.png"}}{if(!i.existsSync(t))return n.warn(`Profile picture file not found: ${t}`),null;n.info(`Loading profile picture from file: ${t}`);const e=i.readFileSync(t);return{buffer:e,filename:r.basename(t)}}}if("url"in t){n.info(`Loading profile picture from URL: ${t.url}`);const e=await s.get(t.url,{responseType:"arraybuffer"}),o=globalThis.Buffer.from(e.data);return{buffer:o,filename:t.filename||"profile.png"}}if("path"in t){if(!i.existsSync(t.path))return n.warn(`Profile picture file not found: ${t.path}`),null;n.info(`Loading profile picture from file: ${t.path}`);const e=i.readFileSync(t.path);return{buffer:e,filename:t.filename||r.basename(t.path)}}return null}catch(o){return n.error("Failed to load profile picture:",o),null}}async _call(t){const n=e.Logger.getInstance({level:"debug"}),o={name:t.name,description:t.description,type:t.type,model:t.model,capabilities:t.capabilities||[e.AIAgentCapability.TEXT_GENERATION],properties:{}};let i="";if(t.profilePicture){const e=await this.loadProfilePicture(t.profilePicture);if(e){const{buffer:n,filename:r}=e;o.pfpBuffer=n,o.pfpFileName=r,"string"==typeof t.profilePicture?i=t.profilePicture:"url"in t.profilePicture?i=t.profilePicture.url:"path"in t.profilePicture&&(i=t.profilePicture.path)}}const r=void 0!==t.hbarFee&&t.hbarFee>0,s=this.hasValidTokenFee(t.tokenFee),a=t.hbarFees&&t.hbarFees.length>0,c=t.tokenFees&&t.tokenFees.length>0;if(r||s||a||c){const{accountId:i}=this.client.getAccountAndSigner(),l=t.feeCollectorAccountId||i;if(!l)return"Error: Fee collector account ID is required when specifying fees and could not be determined.";const u=new e.FeeConfigBuilder({network:this.client.getNetwork(),logger:n});try{const e=t.exemptAccountIds?.filter((e=>e!==l&&e.startsWith("0.0")))||[];let i=u;if(r&&(n.info(`Adding HBAR fee: ${t.hbarFee} HBAR to be collected by ${l}`),i=i.addHbarFee(t.hbarFee,l,e)),a)for(const o of t.hbarFees){const t=o.collectorAccount||l;n.info(`Adding HBAR fee: ${o.amount} HBAR to be collected by ${t}`),i=i.addHbarFee(o.amount,t,e)}if(s&&(n.info(`Adding token fee: ${t.tokenFee.amount} of token ${t.tokenFee.tokenId} to be collected by ${l}`),i=await i.addTokenFee(t.tokenFee.amount,t.tokenFee.tokenId,l,void 0,e)),c)for(const o of t.tokenFees){const t=o.collectorAccount||l;n.info(`Adding token fee: ${o.amount} of token ${o.tokenId} to be collected by ${t}`),i=await i.addTokenFee(o.amount,o.tokenId,t,void 0,e)}o.feeConfig=i,n.info("FeeConfigBuilder created successfully")}catch(g){return`Error: Failed to configure fees. Reason: ${g instanceof Error?g.message:String(g)}`}}try{n.info("Registering agent with metadata");const e=await this.client.createAndRegisterAgent(o);return this.processRegistrationResult(e,t,i)}catch(g){return`Error: Failed to create/register agent "${t.name}". Reason: ${g instanceof Error?g.message:String(g)}`}}hasValidTokenFee(e){return!!(e&&e.amount>0&&e.tokenId&&""!==e.tokenId.trim())}async processRegistrationResult(t,n,o=""){const i=t?.metadata?.accountId||"",r=t?.metadata?.inboundTopicId||"",s=t?.metadata?.outboundTopicId||"",a=t?.metadata?.profileTopicId||"",c=t?.metadata?.privateKey||"",g=t?.metadata?.pfpTopicId;if(this.validateRegistrationResult(i,r,s,c),this.stateManager&&c&&i&&r&&s&&(void 0===n.setAsCurrent||n.setAsCurrent)){const t={name:n.name,accountId:i,inboundTopicId:r,outboundTopicId:s,profileTopicId:a,privateKey:c,pfpTopicId:g};if(this.stateManager.setCurrentAgent(t),this.stateManager.persistAgentData&&n.persistence)try{const e={type:"env-file",prefix:n.persistence.prefix};await this.stateManager.persistAgentData(t,e)}catch(h){e.Logger.getInstance().warn("Failed to persist agent data",h)}}await this.ensureAgentHasFunds(i,n.name);const l=this.createFeeDescription(n),u=l?` with ${l} fee on inbound topic`:"",d={success:!0,message:`Successfully registered agent '${n.name}'${u}.`,name:n.name,accountId:i,privateKey:c,inboundTopicId:r,outboundTopicId:s,profileTopicId:a||"N/A",capabilities:n.capabilities||[e.AIAgentCapability.TEXT_GENERATION],hasFees:!(!n.hbarFee&&!this.hasValidTokenFee(n.tokenFee)),hbarFee:n.hbarFee||0,tokenFee:n.tokenFee||null};return(g||o)&&(d.profilePicture={source:o,topicId:g}),JSON.stringify(d)}async ensureAgentHasFunds(n,o){try{await async function(n,o,i,r){try{const c=(await o.requestAccount(i)).balance.balance/1e8;n.info(`${r} account ${i} has ${c} HBAR`);try{const a=new e.HederaMirrorNode("testnet",n),g=await a.getHBARPrice(new Date);if(g){const e=c*g;if(n.info(`${r} balance in USD: $${e.toFixed(2)}`),e<2){n.warn(`${r} account ${i} has less than $2 (${e.toFixed(2)}). Attempting to fund.`);try{const e=o.getAccountAndSigner(),s=10/g,a=Math.max(0,s-c);if(a>0){const s=(new t.TransferTransaction).addHbarTransfer(e.accountId,t.Hbar.fromTinybars(Math.round(-1e8*a))).addHbarTransfer(i,t.Hbar.fromTinybars(Math.round(1e8*a)));n.info(`Funding ${r} account ${i} with ${a.toFixed(2)} HBAR from ${e.accountId}`);const c=await s.execute(o.getClient());await c.getReceipt(o.getClient()),n.info(`Successfully funded ${r} account ${i}.`)}else n.info(`${r} account ${i} does not require additional funding.`)}catch(s){n.error(`Failed to automatically fund ${r} account ${i}:`,s),n.warn(`Please fund the account ${i} manually with at least ${(10/g).toFixed(2)} HBAR.`)}}}else n.warn("Failed to get HBAR price from Mirror Node. Please ensure the account has enough HBAR.")}catch(a){n.warn("Failed to check USD balance. Please ensure the account has enough HBAR.")}}catch(a){n.error(`Failed to check ${r} account balance:`,a)}}(e.Logger.getInstance({module:"RegisterAgentTool"}),this.client.standardClient,n,o)}catch(i){e.Logger.getInstance().error("Failed to auto fund agent",i)}}validateRegistrationResult(e,t,n,o){if(!(e&&t&&n&&o)){const i=[!e&&"accountId",!t&&"inboundTopicId",!n&&"outboundTopicId",!o&&"privateKey"].filter(Boolean).join(", ");throw new Error(`Registration failed. The HCS client returned incomplete details (Missing: ${i}).`)}}createFeeDescription(e){const t=e.hbarFee&&e.hbarFee>0,n=this.hasValidTokenFee(e.tokenFee);if(!t&&!n)return"";let o="";if(t&&(o+=`${e.hbarFee} HBAR`),n&&e.tokenFee){const t=`${e.tokenFee.amount} of token ${e.tokenFee.tokenId}`;o+=o?` and ${t}`:t}return o}}class d extends n.StructuredTool{constructor(t){super(),this.name="send_message",this.description="Sends a message to a specified Hedera topic using HCS-10 and monitors for responses.",this.lastProcessedTimestamp=0,this.schema=o.z.object({topicId:o.z.string().describe("The Hedera topic ID to send the message to"),message:o.z.string().describe("The message content to send"),disableMonitoring:o.z.boolean().optional().describe("Whether to disable monitoring for responses")}),this.client=t,this.logger=e.Logger.getInstance({module:"SendMessageTool"})}async _call(e){try{const t=await this.client.sendMessage(e.topicId,e.message);if(!t)throw new Error("Failed to send message");if(this.logger.info(`Message sent with sequence number ${t}`),e.disableMonitoring)return`Successfully sent message to topic ${e.topicId}`;{const n=await this.monitorResponses(e.topicId,t);return`Successfully sent message to topic ${e.topicId}${n?`\nResponse: ${n}`:""}`}}catch(t){throw new Error(`Failed to send message: ${t instanceof Error?t.message:String(t)}`)}}async monitorResponses(e,t){let n=0;for(;n<10;){try{const n=await this.client.getMessageStream(e);for(const e of n.messages)if(e.created&&e.created.getTime()>this.lastProcessedTimestamp){this.lastProcessedTimestamp=e.created.getTime();const n=await this.client.getMessageContent(e.data||"");let i;try{i=JSON.parse(n)}catch(o){this.logger.error(`Error parsing message content: ${o}`);continue}if(e.sequence_number>t)return i&&"string"==typeof i.data?i.data:JSON.stringify(i)}}catch(o){this.logger.error(`Error monitoring responses: ${o}`)}n++,await new Promise((e=>setTimeout(e,1e3)))}return null}}class h extends n.StructuredTool{constructor({client:t,stateManager:n,...i}){super(i),this.name="monitor_connections",this.description="Starts passively LISTENING on the current agent's own inbound topic for INCOMING HCS-10 connection requests. Handles received requests automatically. Takes NO arguments. DO NOT use this to start a new connection TO someone else.",this.isMonitoring=!1,this.monitoringTopic=null,this.schema=o.z.object({}),this.client=t,this.stateManager=n,this.logger=e.Logger.getInstance({module:"ConnectionTool",level:"info"})}async _call(){let e;try{e=await this.client.getInboundTopicId()}catch(t){const e=`Error getting inbound topic ID for monitoring: ${t instanceof Error?t.message:String(t)}`;return this.logger.error(e),e}return e?this.isMonitoring?this.monitoringTopic===e?`Already monitoring topic ${e}.`:`Error: Already monitoring a different topic (${this.monitoringTopic}). Stop the current monitor first.`:(this.isMonitoring=!0,this.monitoringTopic=e,this.logger.info(`Initiating connection request monitoring for topic ${e}...`),this.monitorIncomingRequests(e).catch((t=>{this.logger.error(`Monitoring loop for ${e} encountered an unrecoverable error:`,t),this.isMonitoring=!1,this.monitoringTopic=null})),`Started monitoring inbound topic ${e} for connection requests in the background.`):"Error: Could not determine the inbound topic ID for the current agent."}async monitorIncomingRequests(e){this.logger.info(`Monitoring inbound topic ${e}...`);let t=0;const n=new Set;for(;this.isMonitoring&&this.monitoringTopic===e;){try{const i=(await this.client.getMessages(e)).messages,r=i.filter((e=>"connection_request"===e.op&&"number"==typeof e.sequence_number));for(const s of r){t=Math.max(t,s.sequence_number||0);const r=s.sequence_number;if(!r)continue;if(i.some((e=>"connection_created"===e.op&&e.connection_id===r))){this.logger.debug(`Connection request #${r} already handled (found connection_created). Skipping.`);continue}const a=s.operator_id||"",c=a.split("@")[1]||null;if(c)if(n.has(r))this.logger.info(`Connection request #${r} already processed in this session. Skipping.`);else{this.logger.info(`Processing connection request #${r} from account ${c}...`);try{const t=await this.client.handleConnectionRequest(e,c,r);n.add(r),this.logger.info(`Connection confirmed for request #${r}. New connection topic: ${t.connectionTopicId}`);const o={targetAccountId:c,targetAgentName:`Agent ${c}`,targetInboundTopicId:"N/A",connectionTopicId:t.connectionTopicId};this.stateManager.addActiveConnection(o),this.logger.info(`Added new active connection to ${c} state.`)}catch(o){this.logger.error(`Error handling connection request #${r} from ${c}:`,o)}}else this.logger.warn(`Could not determine requesting account ID from operator_id '${a}' for request #${r}. Skipping.`)}}catch(i){this.logger.error(`Error fetching or processing messages for topic ${e}:`,i)}await new Promise((e=>setTimeout(e,5e3)))}this.logger.info(`Monitoring loop stopped for topic ${e}.`),this.isMonitoring=!1,this.monitoringTopic=null}stopMonitoring(){this.isMonitoring?(this.logger.info(`Stopping monitoring for topic ${this.monitoringTopic}...`),this.isMonitoring=!1,this.monitoringTopic=null):this.logger.info("Monitor is not currently running.")}}class f extends n.StructuredTool{constructor({hcsClient:t,stateManager:n,...i}){super(i),this.name="send_message_to_connection",this.description="Sends a text message to another agent using an existing active connection. Identify the target agent using their account ID (e.g., 0.0.12345) or the connection number shown in 'list_connections'. Return back the reply from the target agent if possible",this.schema=o.z.object({targetIdentifier:o.z.string().describe("The account ID (e.g., 0.0.12345) of the target agent OR the connection number (e.g., '1', '2') from the 'list_connections' tool."),message:o.z.string().describe("The text message content to send."),disableMonitoring:o.z.boolean().optional().default(!1)}),this.hcsClient=t,this.stateManager=n,this.logger=e.Logger.getInstance({module:"SendMessageToConnectionTool"})}async _call({targetIdentifier:e,message:t,disableMonitoring:n}){const o=this.stateManager.getCurrentAgent();if(!o)return"Error: Cannot send message. No agent is currently active. Please register or select an agent first.";const i=this.stateManager.getConnectionByIdentifier(e);if(!i)return`Error: Could not find an active connection matching identifier "${e}". Use 'list_connections' to see active connections.`;const r=i.connectionTopicId,s=i.targetAgentName,a=`${o.inboundTopicId}@${o.accountId}`;this.logger.info(`Sending message from ${a} to ${s} (${i.targetAccountId}) via connection topic ${r}`);try{const e=await this.hcsClient.sendMessage(r,t,`Agent message from ${o.name}`);if(!e)throw new Error("Failed to send message");if(!n)return`Message sent to ${s} (${i.targetAccountId}) via connection ${r}. Sequence Number: ${e}`;const c=await this.monitorResponses(r,a,e);return c?(this.logger.info(`Got reply from ${s}`,c),`Received reply from ${s}: ${c}`):`Message sent to ${s} (${i.targetAccountId}) via connection ${r}. Sequence Number: ${e}`}catch(c){return this.logger.error(`Failed to send message via connection ${r}: ${c}`),`Error sending message to ${s}: ${c instanceof Error?c.message:String(c)}`}}async monitorResponses(e,t,n){for(;;){try{const o=await this.hcsClient.getMessageStream(e);for(const e of o.messages){if(e.sequence_number<n||e.operator_id===t)continue;return await this.hcsClient.getMessageContent(e.data||"")}}catch(o){this.logger.error(`Error monitoring responses: ${o}`)}await new Promise((e=>setTimeout(e,4e3)))}return null}}class p extends n.StructuredTool{constructor({hcsClient:t,stateManager:n,...i}){super(i),this.name="initiate_connection",this.description="Actively STARTS a NEW HCS-10 connection TO a specific target agent identified by their account ID. Requires the targetAccountId parameter. Use this ONLY to INITIATE an OUTGOING connection request.",this.schema=o.z.object({targetAccountId:o.z.string().describe("The Hedera account ID (e.g., 0.0.12345) of the agent you want to connect with.")}),this.hcsClient=t,this.stateManager=n,this.logger=e.Logger.getInstance({module:"InitiateConnectionTool"})}async _call({targetAccountId:e}){const t=this.stateManager.getCurrentAgent();if(!t)return"Error: Cannot initiate connection. No agent is currently active. Please register or select an agent first.";this.logger.info(`Attempting connection from ${t.accountId} to ${e}`);try{this.logger.debug(`Retrieving profile for ${e}...`);const o=await this.hcsClient.getAgentProfile(e);if(!o?.topicInfo?.inboundTopic)return`Error: Could not retrieve profile or find inbound topic ID for target agent ${e}. They might not be registered or have a public profile.`;const i=o.topicInfo.inboundTopic,r=o.profile.name||`Agent ${e}`,s=await this.hcsClient.submitConnectionRequest(i,t.name),a=s?.topicSequenceNumber;if(!a)throw new Error("Connection request sequence number not found.");let c;try{if(c=a.toNumber(),isNaN(c))throw new Error("Converted sequence number is NaN.")}catch(n){throw new Error(`Failed to convert connection request sequence number: ${n}`)}const g=6e4,l=2e3,u=Math.ceil(g/l),d=await this.hcsClient.waitForConnectionConfirmation(i,c,u,l);if(!d?.connectionTopicId)return`Error: Connection confirmation not received from ${e} (for request ${c}) within ${g/1e3} seconds.`;const h=d.connectionTopicId;this.logger.info(`Connection confirmed! Topic ID: ${h}`);const f={targetAccountId:e,targetAgentName:r,targetInboundTopicId:i,connectionTopicId:h};this.stateManager.addActiveConnection(f);const p=this.stateManager.listConnections(),m=p.find((e=>e.connectionTopicId===h)),I=m?p.indexOf(m)+1:null;return`Successfully established connection ${I?`#${I}`:""} with ${r} (${e}). Connection Topic: ${h}. You can now send messages using this connection.`}catch(o){return this.logger.error(`Connection initiation failed: ${o}`),`Error initiating connection with ${e}: ${o instanceof Error?o.message:String(o)}`}}}class m extends n.StructuredTool{constructor({stateManager:t,hcsClient:n,...i}){super(i),this.name="list_connections",this.description="Lists the currently active HCS-10 connections with detailed information. Shows connection status, agent details, and recent activity. Use this to get a comprehensive view of all active connections.",this.schema=o.z.object({includeDetails:o.z.boolean().optional().describe("Whether to include detailed information about each connection"),showPending:o.z.boolean().optional().describe("Whether to include pending connection requests")}),this.stateManager=t,this.hcsClient=n,this.logger=new e.Logger({module:"ListConnectionsTool"})}async _call(e){const t=e.includeDetails??!0,n=e.showPending??!0,o=await this.getEnhancedConnections();if(0===o.length)return"There are currently no active connections.";const i=o.filter((e=>"established"===e.status)),r=o.filter((e=>e.isPending)),s=o.filter((e=>e.needsConfirmation));let a="";return i.length>0&&(a+=`🟢 Active Connections (${i.length}):\n`,i.forEach(((e,n)=>{a+=this.formatConnection(e,n,t)})),a+="\n"),n&&s.length>0&&(a+=`🟠 Connections Needing Confirmation (${s.length}):\n`,s.forEach(((e,n)=>{a+=this.formatConnection(e,n,t)})),a+="\n"),n&&r.length>0&&(a+=`⚪ Pending Connection Requests (${r.length}):\n`,r.forEach(((e,n)=>{a+=this.formatConnection(e,n,t)}))),a.trim()}formatConnection(e,t,n){let o=`${t+1}. ${e.profileInfo?.display_name||e.targetAgentName||"Unknown Agent"} (${e.targetAccountId})\n`;o+=` Topic: ${e.isPending?"(Pending Request)":e.connectionTopicId}\n`;if(o+=` Status: ${e.status||"unknown"}\n`,n){if(e.profileInfo?.bio&&(o+=` Bio: ${e.profileInfo.bio.substring(0,100)}${e.profileInfo.bio.length>100?"...":""}\n`),e.created){o+=` ${e.isPending?"Request sent":"Connection established"}: ${e.created.toLocaleString()}\n`}e.lastActivity&&(o+=` Last activity: ${e.lastActivity.toLocaleString()}\n`)}return o}async getEnhancedConnections(){if(!this.hcsClient)return this.stateManager.listConnections();try{const{accountId:e}=this.hcsClient.getAccountAndSigner();if(!e)return this.stateManager.listConnections();const t=this.stateManager.getConnectionsManager();if(!t)return this.logger.error("ConnectionsManager not initialized"),this.stateManager.listConnections();const n=await t.fetchConnectionData(e);for(const o of n)this.stateManager.updateOrAddConnection(o);return n}catch(e){return console.error("Error fetching connection data:",e),this.stateManager.listConnections()}}}class I extends n.StructuredTool{constructor({hcsClient:t,stateManager:n,...i}){super(i),this.name="check_messages",this.description="Checks for and retrieves messages from an active connection. \nIdentify the target agent using their account ID (e.g., 0.0.12345) or the connection number shown in 'list_connections'. \nBy default, it only retrieves messages newer than the last check. \nUse 'fetchLatest: true' to get the most recent messages regardless of when they arrived. \nUse 'lastMessagesCount' to specify how many latest messages to retrieve (default 1 when fetchLatest is true).",this.schema=o.z.object({targetIdentifier:o.z.string().describe("The account ID (e.g., 0.0.12345) of the target agent OR the connection number (e.g., '1', '2') from the 'list_connections' tool to check messages for."),fetchLatest:o.z.boolean().optional().default(!1).describe("Set to true to fetch the latest messages even if they have been seen before, ignoring the last checked timestamp. Defaults to false (fetching only new messages)."),lastMessagesCount:o.z.number().int().positive().optional().describe("When fetchLatest is true, specifies how many of the most recent messages to retrieve. Defaults to 1.")}),this.hcsClient=t,this.stateManager=n,this.logger=e.Logger.getInstance({module:"CheckMessagesTool"})}async _call({targetIdentifier:e,fetchLatest:t,lastMessagesCount:n}){const o=this.stateManager.getConnectionByIdentifier(e);if(!o)return`Error: Could not find an active connection matching identifier "${e}". Use 'list_connections' to see active connections.`;const i=o.connectionTopicId,r=o.targetAgentName,s=this.stateManager.getLastTimestamp(i);this.logger.info(`Checking messages for connection with ${r} (${o.targetAccountId}) on topic ${i} (fetchLatest: ${t}, lastCount: ${n}, since: ${s})`);try{const e=(await this.hcsClient.getMessages(i)).messages;if(!e||0===e.length)return`No messages found on connection topic ${i}.`;let o=[],g=s;const l=!0===t;if(l){this.logger.info("Fetching latest messages regardless of timestamp.");const t=n??1;o=e.slice(-t)}else this.logger.info(`Filtering for messages newer than ${s}`),o=e.filter((e=>1e6*e.timestamp>s)),o.length>0&&(g=o.reduce(((e,t)=>Math.max(e,1e6*t.timestamp)),s));if(0===o.length)return l?`Could not retrieve the latest message(s). No messages found on topic ${i}.`:`No new messages found for connection with ${r} since last check.`;this.logger.info(`Processing ${o.length} message(s).`);let u=l?`Latest message(s) from ${r}:\n`:`New messages from ${r}:\n`;for(const t of o){let e=t.data;try{"string"==typeof e&&e.startsWith("hcs://")&&(this.logger.debug(`Resolving inscribed message: ${e}`),e=await this.hcsClient.getMessageContent(e),this.logger.debug(`Resolved content length: ${e?.length}`));let n=e;try{const t=JSON.parse(e||"{}");if("hcs-10"===t.p&&"message"===t.op&&t.data){n=`[${t.operator_id||"unknown_sender"}]: ${t.data}`}else n=e}catch(a){n=e}u+=`\n[${new Date(t.timestamp).toLocaleString()}] (Seq: ${t.sequence_number})\n${n}\n`}catch(c){const e=`Error processing message (Seq: ${t.sequence_number}): ${c instanceof Error?c.message:String(c)}`;this.logger.error(e),u+=`\n[Error processing message Seq: ${t.sequence_number}]\n`}}return!l&&g>s&&(this.logger.debug(`Updating timestamp for topic ${i} to ${g}`),this.stateManager.updateTimestamp(i,g)),u.trim()}catch(c){return this.logger.error(`Failed to check messages for topic ${i}: ${c}`),`Error checking messages for ${r}: ${c instanceof Error?c.message:String(c)}`}}}class C extends n.StructuredTool{constructor({hcsClient:t,...n}){super(n),this.name="find_registrations",this.description="Searches the configured agent registry for HCS-10 agents. You can filter by account ID or tags. Returns basic registration info.",this.schema=o.z.object({accountId:o.z.string().optional().describe("Optional: Filter registrations by a specific Hedera account ID (e.g., 0.0.12345)."),tags:o.z.array(o.z.nativeEnum(e.AIAgentCapability)).optional().describe("Optional: Filter registrations by a list of tags (API filter only).")}),this.hcsClient=t,this.logger=e.Logger.getInstance({module:"FindRegistrationsTool"})}async _call({accountId:e,tags:t}){this.logger.info("Searching registrations with filters - Account ID",JSON.stringify({accountId:e,tags:t}));const n={};e&&(n.accountId=e),t&&t.length>0&&(n.tags=t),n.network=this.hcsClient.getNetwork();try{if(!this.hcsClient.standardClient)throw new Error("Standard SDK client instance is not available in HCS10Client wrapper.");const e=await this.hcsClient.standardClient.findRegistrations(n);if(!e.success||e.error)return`Error finding registrations: ${e.error||"Unknown error"}`;if(!e.registrations||0===e.registrations.length)return"No registrations found matching the criteria.";let t=`Found ${e.registrations.length} registration(s):\n`;return e.registrations.forEach(((e,n)=>{const o=e.metadata;t+=`${n+1}. Name: ${o.alias||"N/A"}\n`,t+=`Description: ${o.bio||"N/A"}\n`,t+=` Account ID: ${e.accountId}\n`,t+=` Status: ${e.status}\n`,t+=` Model: ${o.properties?.model||"N/A"}\n`,o.properties?.capabilities&&o.properties.capabilities.length>0&&(t+=` Capabilities: ${o.properties.capabilities.join(", ")}\n`),o.properties&&(t+=` Properties: ${JSON.stringify(o.properties)}\n`),t+=` Inbound Topic: ${e.inboundTopicId}\n`,t+=` Outbound Topic: ${e.outboundTopicId}\n`,t+=` Created At: ${e.createdAt}\n`})),t.trim()}catch(o){return this.logger.error(`Failed to execute findRegistrations: ${o}`),`Error searching registrations: ${o instanceof Error?o.message:String(o)}`}}}class b extends n.StructuredTool{constructor({hcsClient:t,stateManager:n,...i}){super(i),this.name="monitor_connections",this.description="Monitors for incoming connection requests and accepts them with optional fee settings. Use this to watch for connection requests and accept them, optionally setting HBAR or token fees on the connection.",this.schema=o.z.object({acceptAll:o.z.boolean().optional().describe("Whether to automatically accept all incoming connection requests. Default is false."),targetAccountId:o.z.string().optional().describe("If provided, only accept connection requests from this specific account ID."),hbarFees:o.z.array(o.z.object({amount:o.z.number(),collectorAccount:o.z.string().optional()})).optional().describe("Array of HBAR fee amounts to charge per message (with optional collector accounts)."),tokenFees:o.z.array(o.z.object({amount:o.z.number(),tokenId:o.z.string(),collectorAccount:o.z.string().optional()})).optional().describe("Array of token fee amounts and IDs to charge per message (with optional collector accounts)."),exemptAccountIds:o.z.array(o.z.string()).optional().describe("Array of account IDs to exempt from ALL fees set in this request."),monitorDurationSeconds:o.z.number().optional().describe("How long to monitor for incoming requests in seconds. Default is 60."),defaultCollectorAccount:o.z.string().optional().describe("Default account to collect fees if not specified at the fee level. Defaults to the agent account.")}),this.isMonitoring=!1,this.hcsClient=t,this.stateManager=n,this.logger=e.Logger.getInstance({module:"ConnectionMonitorTool",level:"error"}),this.listConnectionsTool=new m({stateManager:n,hcsClient:t,...i})}updateClient(e){this.hcsClient=e,this.logger.info("Updated HCS10Client instance for ConnectionMonitorTool"),this.listConnectionsTool=new m({stateManager:this.stateManager,hcsClient:e})}async _call({acceptAll:e=!1,targetAccountId:t,hbarFees:n=[],tokenFees:o=[],exemptAccountIds:i,monitorDurationSeconds:r=60,defaultCollectorAccount:s}){if(!this.stateManager.getCurrentAgent())return"Error: Cannot monitor for connections. No agent is currently active. Please register or select an agent first.";if(this.isMonitoring)return"Already monitoring for connection requests. Please wait for the current monitoring session to complete.";try{this.isMonitoring=!0;const c=await this.hcsClient.getInboundTopicId();if(!c)return this.isMonitoring=!1,"Error: Could not find inbound topic ID for the current agent.";this.logger.info(`Starting to monitor inbound topic ${c} for connection requests...`);const g=this.createFeeConfig(n,o,i,t,s),l=Date.now()+1e3*r,u=3e3;let d=0,h=0,f=0,p=0;for(;Date.now()<l;)try{await this.listConnectionsTool.invoke({includeDetails:!1,showPending:!1});const n=this.stateManager.listConnections(),o=new Map;n.filter((e=>"established"===e.status&&!e.isPending)).forEach((e=>{o.has(e.targetAccountId)||o.set(e.targetAccountId,new Set),e.connectionRequestId&&o.get(e.targetAccountId)?.add(String(e.connectionRequestId))}));const i=(await this.hcsClient.getMessages(c)).messages.filter((e=>!(!e.sequence_number||e.sequence_number<=d)&&(d=Math.max(d,e.sequence_number),"connection_request"===e.op)));for(const r of i){const n=r.sequence_number;if(!n)continue;h++;const i=await this.hcsClient.getInboundTopicId()||"",s=this.stateManager.getConnectionsManager();if(!s){this.logger.error("ConnectionsManager not initialized in state manager");continue}if(s.isConnectionRequestProcessed(i,n)){this.logger.info(`Request #${n} already processed, skipping`),p++;continue}const a=this.extractAccountId(r);if(!a){s.markConnectionRequestProcessed(i,n);continue}if(t&&a!==t){this.logger.info(`Request #${n} doesn't match target ${t}`);continue}const c=o.get(a);if(c?.has(String(n)))this.logger.info(`Already processed connection request #${n} from ${a}, skipping`),s.markConnectionRequestProcessed(i,n),p++;else if(e){const e=await this.acceptConnectionRequest(n,a,g);s.markConnectionRequestProcessed(i,n),e.success&&(f++,this.logger.info(`Successfully accepted connection with ${a} for request #${n}`))}else this.logger.info(`Found request #${n} from ${a} (not auto-accepting)`)}await new Promise((e=>setTimeout(e,u)))}catch(a){this.logger.error(`Error polling for messages: ${a}`),await new Promise((e=>setTimeout(e,u)))}return this.isMonitoring=!1,0===h?`No connection requests received during the ${r} second monitoring period.`:e?`Monitored for ${r} seconds. Found ${h} connection requests, accepted ${f} connections, skipped ${p} existing connections${this.formatFeeString(n,o)}.`:`Monitored for ${r} seconds. Found ${h} connection requests. To accept them, call this tool again with acceptAll=true.`}catch(a){return this.isMonitoring=!1,this.logger.error(`Connection monitoring failed: ${a}`),`Error monitoring for connections: ${a instanceof Error?a.message:String(a)}`}}createFeeConfig(t=[],n=[],o,i,r){if(0!==t.length||0!==n.length)try{const s=this.hcsClient.getAccountAndSigner().accountId,a=r||s,c=new e.FeeConfigBuilder({network:this.hcsClient.getNetwork(),logger:this.logger,defaultCollectorAccountId:a}),g=[...o||[]];i&&!g.includes(i)&&g.push(i);for(const e of t)if(e.amount>0){const t=e.collectorAccount||a;c.addHbarFee(e.amount,t,g),this.logger.info(`Added HBAR fee: ${e.amount} HBAR to be collected by ${t}`)}for(const e of n)if(e.amount>0&&e.tokenId){const t=e.collectorAccount||a;c.addTokenFee(e.amount,e.tokenId,t,void 0,g),this.logger.info(`Added token fee: ${e.amount} of token ${e.tokenId} to be collected by ${t}`)}return c}catch(s){return void this.logger.error(`Error creating fee configuration: ${s}`)}}extractAccountId(e){if(e.operator_id)return this.hcsClient.standardClient.extractAccountFromOperatorId(e.operator_id)}async acceptConnectionRequest(e,t,n){try{const i=await this.hcsClient.getInboundTopicId();this.logger.info(`Accepting connection request #${e} from ${t}`);const r=await this.hcsClient.handleConnectionRequest(i,t,e,n);if(!r?.connectionTopicId)return{success:!1,error:"Connection acceptance returned no connection topic ID"};const s=r.connectionTopicId;let a;this.logger.info(`Connection established! Topic ID: ${s}`);try{const e=await this.hcsClient.getAgentProfile(t);e.success&&e.profile&&(a=e.profile)}catch(o){this.logger.warn(`Could not fetch profile for ${t}: ${o}`)}const c=(await this.hcsClient.getAgentProfile(t))?.topicInfo?.inboundTopic||"",g={targetAccountId:t,targetAgentName:a?.display_name||`Agent ${t}`,targetInboundTopicId:c,connectionTopicId:s,profileInfo:a,created:new Date,status:"established",metadata:{requestId:e}};return this.stateManager.addActiveConnection(g),{success:!0,connectionTopicId:s}}catch(i){return this.logger.error(`Error accepting connection request: ${i}`),{success:!1,error:i instanceof Error?i.message:String(i)}}}formatFeeString(e=[],t=[]){if(0===e.length&&0===t.length)return"";let n=" with fees: ";if(e.length>0){const t=e.filter((e=>e.amount>0)).map((e=>{const t=e.collectorAccount?` to ${e.collectorAccount}`:"";return`${e.amount} HBAR${t}`})).join(", ");t&&(n+=t)}if(t.length>0){e.length>0&&(n+=" and ");const o=t.filter((e=>e.amount>0&&e.tokenId)).map((e=>{const t=e.collectorAccount?` to ${e.collectorAccount}`:"";return`${e.amount} of token ${e.tokenId}${t}`})).join(", ");o&&(n+=o)}return" with fees: "===n?"":n}update(){this.listConnectionsTool.invoke({includeDetails:!0,showPending:!0}).catch((e=>{this.logger.error(`Error updating connections: ${e}`)}))}}class $ extends n.StructuredTool{constructor({hcsClient:t,stateManager:n,...i}){super(i),this.name="manage_connection_requests",this.description='Manage incoming connection requests. List pending requests, view details about requesting agents, and reject connection requests. Use the separate "accept_connection_request" tool to accept.',this.schema=o.z.object({action:o.z.enum(["list","view","reject"]).describe("The action to perform: list all requests, view details of a specific request, or reject a request"),requestKey:o.z.string().optional().describe("The unique request key to view or reject (required for view and reject actions)")}),this.lastRefreshTime=0,this.refreshIntervalMs=3e4,this.hcsClient=t,this.stateManager=n,this.logger=e.Logger.getInstance({module:"ManageConnectionRequestsTool",level:"debug"})}async _call({action:e,requestKey:t}){if(!this.stateManager.getCurrentAgent())return"Error: Cannot manage connection requests. No agent is currently active. Please register or select an agent first.";if(("view"===e||"reject"===e)&&void 0===t)return`Error: Request key is required for the "${e}" action. Use the "list" action first to see available requests.`;try{switch(await this.refreshRequestsIfNeeded(),e){case"list":return this.listRequests();case"view":return this.viewRequest(t);case"reject":return this.rejectRequest(t);default:return`Error: Unsupported action: ${e}`}}catch(n){return this.logger.error(`Error in ManageConnectionRequestsTool: ${n}`),`Error managing connection requests: ${n instanceof Error?n.message:String(n)}`}}async refreshRequestsIfNeeded(){const e=Date.now();e-this.lastRefreshTime>this.refreshIntervalMs&&(await this.refreshRequests(),this.lastRefreshTime=e)}async refreshRequests(){try{const{accountId:e}=this.hcsClient.getAccountAndSigner();if(!e)throw new Error("Could not determine account ID for current agent");const t=this.stateManager.getConnectionsManager();if(!t)throw new Error("ConnectionsManager not initialized");await t.fetchConnectionData(e)}catch(e){throw this.logger.error(`Error refreshing connection requests: ${e}`),e}}listRequests(){const e=this.stateManager.getConnectionsManager();if(!e)return"Error: ConnectionsManager not initialized";const t=[...e.getPendingRequests(),...e.getConnectionsNeedingConfirmation()];if(0===t.length)return console.log("No pending connection requests found.",t),"No pending connection requests found.";let n=`Found ${t.length} pending connection request(s):\n\n`;return[...t].sort(((e,t)=>t.created.getTime()-e.created.getTime())).forEach(((e,t)=>{const o=e.needsConfirmation?"🟠 Incoming":"⚪️ Outgoing",i=e.uniqueRequestKey||`${e.connectionRequestId||e.inboundRequestId||"unknown"}`;n+=`${t+1}. ${o} - Key: ${i}\n`,n+=` ${e.needsConfirmation?"From":"To"}: ${e.targetAgentName||`Agent ${e.targetAccountId}`} (${e.targetAccountId})\n`,n+=` Sent/Rcvd: ${e.created.toLocaleString()}\n`,e.memo&&(n+=` Memo: ${e.memo}\n`),e.profileInfo&&e.profileInfo.bio&&(n+=` Bio: ${e.profileInfo.bio}\n`),n+="\n"})),n+='To view more details about a request, use action="view" with the specific requestKey.\n',n+='To reject a request, use action="reject" with the specific requestKey.',n}viewRequest(e){const t=this.stateManager.getConnectionsManager();if(!t)return"Error: ConnectionsManager not initialized";const n=[...t.getPendingRequests(),...t.getConnectionsNeedingConfirmation()].find((t=>t.uniqueRequestKey===e||t.connectionRequestId?.toString()===e||t.inboundRequestId?.toString()===e));if(!n)return`Error: Request with key ${e} not found or no longer pending.`;const o=n.needsConfirmation?"Incoming":"Outgoing",i=n.uniqueRequestKey||`${n.connectionRequestId||n.inboundRequestId||"unknown"}`;let r=`Details for ${o} connection request: ${i}\n\n`;return r+=`${n.needsConfirmation?"Requestor":"Target"} ID: ${n.targetAccountId}\n`,r+=`${n.needsConfirmation?"Requestor":"Target"} Name: ${n.targetAgentName||`Agent ${n.targetAccountId}`}\n`,r+=`Received: ${n.created.toLocaleString()}\n`,n.memo&&(r+=`Memo: ${n.memo}\n`),n.profileInfo&&(r+="\nAgent Profile Information:\n",(n.profileInfo.display_name||n.profileInfo.alias)&&(r+=`Name: ${n.profileInfo.display_name||n.profileInfo.alias}\n`),void 0!==n.profileInfo.type&&(r+=`Type: ${n.profileInfo.type}\n`),n.profileInfo.bio&&(r+=`Bio: ${n.profileInfo.bio}\n`)),r+="\nActions:\n",r+=`- To reject this request: action="reject", requestKey="${i}"\n`,r+='Use the separate "accept_connection_request" tool to accept requests.',r}async rejectRequest(e){const t=this.stateManager.getConnectionsManager();if(!t)return"Error: ConnectionsManager not initialized";const n=[...t.getPendingRequests(),...t.getConnectionsNeedingConfirmation()].find((t=>t.uniqueRequestKey===e||t.connectionRequestId?.toString()===e||t.inboundRequestId?.toString()===e));return n?(n.inboundRequestId?t.markConnectionRequestProcessed(n.targetInboundTopicId||"",n.inboundRequestId):n.connectionRequestId&&t.markConnectionRequestProcessed(n.originTopicId||"",n.connectionRequestId),`Connection request from ${n.targetAgentName||`Agent ${n.targetAccountId}`} was rejected.`):`Error: Request with key ${e} not found or no longer pending.`}}class w extends n.StructuredTool{constructor({hcsClient:t,stateManager:n,...i}){super(i),this.name="accept_connection_request",this.description="Accepts a specific pending connection request from another agent, establishing a communication channel.",this.schema=o.z.object({requestKey:o.z.string().describe('The unique request key of the specific request to accept. Use the "manage_connection_requests" tool with action="list" first to get valid keys.'),hbarFee:o.z.number().optional().describe("Optional HBAR fee amount to charge the connecting agent per message on the new connection topic."),exemptAccountIds:o.z.array(o.z.string()).optional().describe("Optional list of account IDs to exempt from any configured fees on the new connection topic.")}),this.hcsClient=t,this.stateManager=n,this.logger=e.Logger.getInstance({module:"AcceptConnectionRequestTool"})}async _call({requestKey:t,hbarFee:n,exemptAccountIds:o}){const i=this.stateManager.getCurrentAgent();if(!i)return"Error: Cannot accept connection request. No agent is currently active. Please register or select an agent first.";const r=this.stateManager.getConnectionsManager();if(!r)return"Error: ConnectionsManager not initialized";await r.fetchConnectionData(i.accountId);const s=[...r.getPendingRequests(),...r.getConnectionsNeedingConfirmation()].find((e=>e.uniqueRequestKey===t||e.connectionRequestId?.toString()===t||e.inboundRequestId?.toString()===t));if(!s)return`Error: Request with key ${t} not found or no longer pending. Use the manage_connection_requests tool with action="list" to verify.`;const a=s.connectionRequestId||s.inboundRequestId;if(!a)return`Error: Could not determine a valid request ID for the request with key ${t}.`;try{const l=await this.hcsClient.getInboundTopicId();let u;if(n&&n>0){const t=this.hcsClient.getAccountAndSigner().accountId;try{u=new e.FeeConfigBuilder({network:this.hcsClient.getNetwork(),logger:this.logger,defaultCollectorAccountId:t});const r=[...o||[],i.accountId];u.addHbarFee(n,t,r),this.logger.info(`Setting HBAR fee: ${n} HBAR to be collected by ${t}`)}catch(c){this.logger.error(`Error creating fee configuration: ${c}`),u=void 0,this.logger.warn("Proceeding to accept request without fees due to configuration error.")}}this.logger.info(`Attempting to accept request Key: ${t} (ID: ${a}) from ${s.targetAccountId}`);const d=await this.hcsClient.handleConnectionRequest(l,s.targetAccountId,a,u);if(!d?.connectionTopicId)return`Error: Failed to accept connection request with key ${t}. The SDK did not return a connection topic ID.`;this.logger.info(`Successfully created connection topic: ${d.connectionTopicId}`);const h=d.connectionTopicId;let f="";try{const e=await this.hcsClient.standardClient.retrieveProfile(s.targetAccountId);f=e?.topicInfo?.inboundTopic||"",f||this.logger.warn(`Could not resolve target inbound topic for ${s.targetAccountId}`)}catch(g){this.logger.warn(`Error fetching target profile/topic for ${s.targetAccountId}: ${g}`)}const p=s.profileInfo?.display_name||s.profileInfo?.alias||`Agent ${s.targetAccountId}`,m={targetAccountId:s.targetAccountId,targetAgentName:p,targetInboundTopicId:f,connectionTopicId:h,profileInfo:s.profileInfo,created:new Date,status:"established"};this.stateManager.addActiveConnection(m),r.fetchConnectionData(s.targetAccountId),this.logger.info(`Removed request ${t} from pending requests`);let I="";n&&n>0&&u&&(I=` with a ${n} HBAR fee per message`);return`Successfully accepted connection request ${s.uniqueRequestKey||t} from ${p} ${I}. Connection established on topic: ${h}.`}catch(l){return this.logger.error(`Error accepting connection request ${t}: ${l}`),`Error accepting connection request ${t}: ${l instanceof Error?l.message:String(l)}`}}}class y extends n.StructuredTool{constructor(t){super(),this.name="retrieve_profile",this.description="Retrieves the HCS-11 profile data associated with a given Hedera account ID. If no account ID is provided, it defaults to the current operator account ID. Returns the profile object as a JSON string on success.",this.schema=o.z.object({accountId:o.z.string().optional().describe("The Hedera account ID (e.g., 0.0.12345) to retrieve the profile for. If omitted, defaults to the current operator account ID."),disableCache:o.z.boolean().optional().describe("Optional: Set to true to bypass the cache and fetch fresh profile data.")}),this.client=t,this.logger=e.Logger.getInstance({module:this.name})}async _call(e){let t;try{if(e.accountId?t=e.accountId:(this.logger.info("accountId not provided, defaulting to operator ID."),t=this.client.getOperatorId()),!t)throw new Error("Could not determine target account ID.");this.logger.info(`Attempting to retrieve profile for account: ${t}, Disable Cache: ${!!e.disableCache}`);const n=await this.client.standardClient.retrieveProfile(t,e.disableCache);if(n.success&&n.profile)return this.logger.info(`Successfully retrieved profile for ${t}.`),JSON.stringify(n.profile,null,2);{const e=`Error retrieving profile for ${t}: ${n.error||"Profile not found or invalid."}`;return this.logger.error(e),e}}catch(n){const t=`Unexpected error retrieving profile for ${e.accountId||"operator default"}: ${n instanceof Error?n.message:String(n)}`;return this.logger.error(t,n),t}}}class T extends n.StructuredTool{constructor({hcsClient:t,stateManager:n,...i}){super(i),this.name="list_unapproved_connection_requests",this.description="Lists all connection requests that are not fully established, including incoming requests needing approval and outgoing requests waiting for confirmation.",this.schema=o.z.object({sortBy:o.z.enum(["time_asc","time_desc","name_asc","name_desc"]).optional().describe("Optional sorting criteria for the requests list (default: time_desc, newest first)"),limit:o.z.number().optional().describe("Optional limit on the number of requests to return (default: all)")}),this.hcsClient=t,this.stateManager=n,this.logger=e.Logger.getInstance({module:"ListPendingRequestsTool",level:"debug"})}async _call({sortBy:e="time_desc",limit:t}){if(!this.stateManager.getCurrentAgent())return"Error: Cannot list pending requests. No agent is currently active. Please register or select an agent first.";try{const n=await this.findAllPendingRequests();return this.formatRequestsList(n,e,t)}catch(n){return this.logger.error(`Error in ${this.name}: ${n}`),`Error listing pending requests: ${n instanceof Error?n.message:String(n)}`}}async findAllPendingRequests(){const e=this.stateManager.getConnectionsManager();if(!e)return[];const t=this.stateManager.getCurrentAgent();if(!t)return[];await e.fetchConnectionData(t.accountId);return[...e.getPendingRequests(),...e.getConnectionsNeedingConfirmation()]}formatRequestsList(e,t,n){if(0===e.length)return"No pending connection requests found (incoming or outgoing).";const o=this.sortRequests(e,t),i=n?o.slice(0,n):o;let r=`Found ${e.length} pending connection request(s):\n\n`;return i.forEach(((e,t)=>{const n="needs_confirmation"===e.status?"🟠 Incoming":"⚪️ Outgoing";r+=`${t+1}. ${n} - ID: ${e.uniqueRequestKey}\n`,r+=` ${"needs_confirmation"===e.status?"From:":"To: "} ${e.targetAgentName} (${e.targetAccountId})\n`,r+=` Sent/Rcvd: ${e.created.toLocaleString()}\n`,e.memo&&(r+=` Memo: ${e.memo}\n`),e.profileInfo?.bio&&(r+=` Bio: ${e.profileInfo.bio.substring(0,100)}${e.profileInfo.bio.length>100?"...":""}\n`),r+="\n"})),r+="Use related tools (manage_requests, accept_request) to handle these items.",r}sortRequests(e,t){const n=[...e];switch(t){case"time_asc":return n.sort(((e,t)=>e.created.getTime()-t.created.getTime()));case"time_desc":default:return n.sort(((e,t)=>t.created.getTime()-e.created.getTime()));case"name_asc":return n.sort(((e,t)=>e.targetAgentName?.localeCompare(t?.targetAgentName||"")||0));case"name_desc":return n.sort(((e,t)=>t.targetAgentName?.localeCompare(e?.targetAgentName||"")||0))}}}const A=r.join(process.cwd(),".env");class q{constructor(t){this.currentAgent=null,this.connectionMessageTimestamps={},this.connectionsManager=null,this.defaultEnvFilePath=t?.defaultEnvFilePath,this.defaultPrefix=t?.defaultPrefix??"TODD";const n=t?.disableLogging||"true"===process.env.DISABLE_LOGGING;this.logger=new e.Logger({module:"OpenConvaiState",silent:n}),t?.baseClient&&this.initializeConnectionsManager(t.baseClient)}initializeConnectionsManager(t){return this.connectionsManager?this.logger.debug("ConnectionsManager already initialized"):(this.logger.debug("Initializing ConnectionsManager"),this.connectionsManager=new e.ConnectionsManager({baseClient:t,logLevel:"error"})),this.connectionsManager}getConnectionsManager(){return this.connectionsManager}setCurrentAgent(e){this.currentAgent=e,this.connectionMessageTimestamps={},this.connectionsManager&&this.connectionsManager.clearAll()}getCurrentAgent(){return this.currentAgent}addActiveConnection(e){if(!this.connectionsManager)throw this.logger.error("ConnectionsManager not initialized. Call initializeConnectionsManager before adding connections."),new Error("ConnectionsManager not initialized. Call initializeConnectionsManager before adding connections.");const t={connectionTopicId:e.connectionTopicId,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName,targetInboundTopicId:e.targetInboundTopicId,status:this.convertConnectionStatus(e.status||"established"),isPending:e.isPending||!1,needsConfirmation:e.needsConfirmation||!1,created:e.created||new Date,lastActivity:e.lastActivity,profileInfo:e.profileInfo,connectionRequestId:e.connectionRequestId,processed:!0};this.connectionsManager.updateOrAddConnection(t),this.initializeTimestampIfNeeded(e.connectionTopicId)}updateOrAddConnection(e){this.addActiveConnection(e)}listConnections(){return this.connectionsManager?this.connectionsManager.getAllConnections().map((e=>this.convertToActiveConnection(e))):(this.logger.debug("ConnectionsManager not initialized, returning empty connections list"),[])}getConnectionByIdentifier(e){if(!this.connectionsManager)return;const t=this.listConnections(),n=parseInt(e)-1;if(!isNaN(n)&&n>=0&&n<t.length)return t[n];const o=this.connectionsManager.getConnectionByTopicId(e);if(o)return this.convertToActiveConnection(o);const i=this.connectionsManager.getConnectionByAccountId(e);return i?this.convertToActiveConnection(i):void 0}getLastTimestamp(e){return this.connectionMessageTimestamps[e]||0}updateTimestamp(e,t){if(!(e in this.connectionMessageTimestamps))return void(this.connectionMessageTimestamps[e]=t);t>this.connectionMessageTimestamps[e]&&(this.connectionMessageTimestamps[e]=t)}initializeTimestampIfNeeded(e){e in this.connectionMessageTimestamps||(this.connectionMessageTimestamps[e]=1e6*Date.now())}convertConnectionStatus(e){switch(e){case"pending":return"pending";case"established":default:return"established";case"needs confirmation":return"needs_confirmation"}}convertToActiveConnection(e){return{targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName||`Agent ${e.targetAccountId}`,targetInboundTopicId:e.targetInboundTopicId||"",connectionTopicId:e.connectionTopicId,status:this.convertToStateStatus(e.status),created:e.created,lastActivity:e.lastActivity,isPending:e.isPending,needsConfirmation:e.needsConfirmation,profileInfo:e.profileInfo,connectionRequestId:e.connectionRequestId}}convertToStateStatus(e){switch(e){case"pending":return"pending";case"established":case"closed":return"established";case"needs_confirmation":return"needs confirmation";default:return"unknown"}}async persistAgentData(e,t){if(t?.type&&"env-file"!==t.type)throw new Error(`Unsupported persistence type: ${t.type}. Only 'env-file' is supported.`);const n=t?.envFilePath||this.defaultEnvFilePath||process.env.ENV_FILE_PATH||".env",o=t?.prefix||this.defaultPrefix;if(!e.accountId||!e.inboundTopicId||!e.outboundTopicId)throw new Error("Agent data incomplete, cannot persist to environment");const r={[`${o}_ACCOUNT_ID`]:e.accountId,[`${o}_INBOUND_TOPIC_ID`]:e.inboundTopicId,[`${o}_OUTBOUND_TOPIC_ID`]:e.outboundTopicId};e.privateKey&&(r[`${o}_PRIVATE_KEY`]=e.privateKey),e.profileTopicId&&(r[`${o}_PROFILE_TOPIC_ID`]=e.profileTopicId),await async function(e,t){let n="";i.existsSync(e)&&(n=i.readFileSync(e,"utf8"));const o=[...n.split("\n")];for(const[i,r]of Object.entries(t)){const e=o.findIndex((e=>e.startsWith(`${i}=`)));-1!==e?o[e]=`${i}=${r}`:o.push(`${i}=${r}`)}i.writeFileSync(e,o.join("\n"))}(n,r)}}class v{async initialize(e){this.context=e}async cleanup(){}}const M=o.z.object({current_rate:o.z.object({cent_equivalent:o.z.number(),hbar_equivalent:o.z.number(),expiration_time:o.z.number()}),next_rate:o.z.object({cent_equivalent:o.z.number(),hbar_equivalent:o.z.number(),expiration_time:o.z.number()}),timestamp:o.z.string()});class E extends n.StructuredTool{constructor(){super(...arguments),this.name="getHbarPrice",this.description="Retrieves the current price of HBAR in USD from the Hedera Mirror Node.",this.schema=o.z.object({})}async _call(){try{const e=(await s.get("https://mainnet.mirrornode.hedera.com/api/v1/network/exchangerate")).data,t=M.safeParse(e);if(!t.success)throw console.error("Failed to parse exchange rate response:",t.error),new Error("Invalid API response format");const{current_rate:n}=t.data;return`The current price of HBAR is $${(n.cent_equivalent/n.hbar_equivalent/100).toFixed(6)} USD.`}catch(e){console.error("Error fetching HBAR price:",e);let t="An unknown error occurred";return s.isAxiosError(e)?(t=e.message,e.response&&(t+=` (Status: ${e.response.status})`)):e instanceof Error&&(t=e.message),`Failed to retrieve HBAR price: ${t}`}}}class R extends v{}exports.AcceptConnectionRequestTool=w,exports.BasePlugin=v,exports.CheckMessagesTool=I,exports.ConnectionMonitorTool=b,exports.ConnectionTool=h,exports.FindRegistrationsTool=C,exports.GenericPlugin=R,exports.GetHbarPriceTool=E,exports.HCS10Client=l,exports.HCS10Plugin=class extends v{},exports.HbarPricePlugin=class{constructor(){this.id="hedera-hbar-price",this.name="Hedera HBAR Price Plugin",this.description="Provides tools to interact with Hedera network data, specifically HBAR price.",this.version="1.0.0",this.author="Hedera Agent",this.tools=[new E]}async initialize(){return Promise.resolve()}getTools(){return this.tools}async cleanup(){return Promise.resolve()}},exports.InitiateConnectionTool=p,exports.ListConnectionsTool=m,exports.ListUnapprovedConnectionRequestsTool=T,exports.ManageConnectionRequestsTool=$,exports.OpenConvAIPlugin=class extends R{constructor(){super(...arguments),this.id="openconvai-standards-agent-kit",this.name="OpenConvAI Standards Agent Kit Plugin",this.description="Comprehensive plugin providing all HCS-10 agent tools for registration, connections, and messaging",this.version="1.0.0",this.author="Hashgraph Online",this.namespace="openconvai",this.tools=[]}async initialize(e){if(await super.initialize(e),!(e.client instanceof l))throw new Error("OpenConvAIPlugin requires an HCS10Client instance");this.hcs10Client=e.client,this.stateManager=e.stateManager||new q,this.initializeTools(),this.context.logger.info("OpenConvAI Standards Agent Kit Plugin initialized successfully")}initializeTools(){if(!this.hcs10Client||!this.stateManager)throw new Error("HCS10Client and StateManager must be initialized before creating tools");this.tools=[new u(this.hcs10Client,this.stateManager),new d(this.hcs10Client),new h({client:this.hcs10Client,stateManager:this.stateManager}),new C({hcsClient:this.hcs10Client}),new y(this.hcs10Client),new p({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new m({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new f({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new I({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new b({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new $({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new w({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new T({stateManager:this.stateManager,hcsClient:this.hcs10Client})]}getTools(){return this.tools}async cleanup(){this.tools=[],this.hcs10Client=void 0,this.stateManager=void 0,this.context.logger.info("OpenConvAI Standards Agent Kit Plugin cleaned up")}},exports.OpenConvaiState=q,exports.PluginLoader=class{static async loadFromDirectory(e,t,n={initialize:!0}){const o=g.join(e,"plugin.json");if(!c.existsSync(o))throw new Error(`Plugin manifest not found at ${o}`);try{const i=c.readFileSync(o,"utf8"),r=JSON.parse(i);if(!r.id||!r.main)throw new Error("Invalid plugin manifest: missing required fields (id, main)");const s=g.join(e,r.main);if(!c.existsSync(s))throw new Error(`Plugin main file not found at ${s}`);const a=await import(s),l=a.default||a[r.id];if(!l)throw new Error(`Could not find plugin class in ${s}`);const u=new l;if(!this.isValidPlugin(u))throw new Error("Plugin does not implement the IPlugin interface correctly");return n.initialize&&await u.initialize(t),u}catch(i){throw new Error(`Failed to load plugin from directory ${e}: ${i instanceof Error?i.message:String(i)}`)}}static async loadFromPackage(e,t,n={initialize:!0}){try{const o=require.resolve(e),i=g.dirname(o);return this.loadFromDirectory(i,t,n)}catch(o){throw new Error(`Failed to load plugin from package ${e}: ${o instanceof Error?o.message:String(o)}`)}}static isValidPlugin(e){return e&&"string"==typeof e.id&&"string"==typeof e.name&&"string"==typeof e.description&&"string"==typeof e.version&&"string"==typeof e.author&&"function"==typeof e.initialize&&"function"==typeof e.getTools}},exports.PluginRegistry=class{constructor(e){this.plugins=new Map,this.context=e,this.logger=e.logger}async registerPlugin(e){if(this.plugins.has(e.id))throw new Error(`Plugin with ID ${e.id} is already registered`);await e.initialize(this.context),this.plugins.set(e.id,e),this.logger.info(`Plugin registered: ${e.name} (${e.id}) v${e.version}`)}getPlugin(e){return this.plugins.get(e)}getAllPlugins(){return Array.from(this.plugins.values())}getAllTools(){return this.getAllPlugins().flatMap((e=>e.getTools()))}async unregisterPlugin(e){const t=this.plugins.get(e);if(!t)return!1;if(t.cleanup)try{await t.cleanup()}catch(o){this.logger.error(`Error during plugin cleanup: ${o}`)}const n=this.plugins.delete(e);return n&&this.logger.info(`Plugin unregistered: ${t.name} (${t.id})`),n}async unregisterAllPlugins(){const e=Array.from(this.plugins.keys());for(const t of e)await this.unregisterPlugin(t)}},exports.RegisterAgentTool=u,exports.RetrieveProfileTool=y,exports.SendMessageToConnectionTool=f,exports.SendMessageTool=d,exports.initializeStandardsAgentKit=t=>{const n=t?.clientConfig||{},o=n.operatorId||process.env.HEDERA_OPERATOR_ID,i=n.operatorKey||process.env.HEDERA_OPERATOR_KEY,r=n.network||process.env.HEDERA_NETWORK||"testnet";let s;if("mainnet"===r?s="mainnet":("testnet"===r||console.warn(`Unsupported network specified: '${r}'. Defaulting to 'testnet'.`),s="testnet"),!o||!i)throw new Error("Operator ID and private key must be provided either through options or environment variables.");const a="true"===process.env.DISABLE_LOGGING,c=e.Logger.getInstance({level:n.logLevel||"info",silent:a}),g=t?.stateManager||new q({defaultEnvFilePath:A,defaultPrefix:"TODD"});c.info("State manager initialized");const v=new l(o,i,s,{useEncryption:n.useEncryption,registryUrl:n.registryUrl});let M;c.info(`HCS10Client initialized for ${o} on ${s}`),t?.monitoringClient&&(M=new l(o,i,s,{useEncryption:n.useEncryption,registryUrl:n.registryUrl,logLevel:"error"}),c.info("Monitoring client initialized"));const E={};return E.registerAgentTool=new u(v,g),E.sendMessageTool=new d(v),E.connectionTool=new h({client:M||v,stateManager:g}),t?.createAllTools&&(E.findRegistrationsTool=new C({hcsClient:v}),E.retrieveProfileTool=new y(v),E.initiateConnectionTool=new p({hcsClient:v,stateManager:g}),E.listConnectionsTool=new m({hcsClient:v,stateManager:g}),E.sendMessageToConnectionTool=new f({hcsClient:v,stateManager:g}),E.checkMessagesTool=new I({hcsClient:v,stateManager:g}),E.connectionMonitorTool=new b({hcsClient:M||v,stateManager:g}),E.manageConnectionRequestsTool=new $({hcsClient:v,stateManager:g}),E.acceptConnectionRequestTool=new w({hcsClient:v,stateManager:g}),E.listUnapprovedConnectionRequestsTool=new T({stateManager:g,hcsClient:v}),c.info("All tools initialized")),{hcs10Client:v,monitoringClient:M,tools:E,stateManager:g}};
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("hedera-agent-kit"),t=require("@hashgraphonline/standards-sdk"),n=require("fs"),o=require("path"),i=require("axios"),r=require("zod");class s extends e.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}class a extends e.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}const c=r.z.object({name:r.z.string().min(1).max(50).describe("A unique name for the agent (1-50 characters)"),description:r.z.string().max(500).optional().describe("Optional bio description for the agent (max 500 characters)"),alias:r.z.string().optional().describe("Optional custom username/alias for the agent"),type:r.z.enum(["autonomous","manual"]).optional().describe("Agent type (default: autonomous)"),model:r.z.string().optional().describe("AI model identifier (default: agent-model-2024)"),capabilities:r.z.array(r.z.nativeEnum(t.AIAgentCapability)).optional().describe("Array of agent capabilities (default: [TEXT_GENERATION])"),creator:r.z.string().optional().describe("Creator attribution for the agent"),socials:r.z.record(r.z.enum(["twitter","github","discord","telegram","linkedin","youtube","website","x"]),r.z.string()).optional().describe('Social media links (e.g., {"twitter": "@handle", "discord": "username"})'),properties:r.z.record(r.z.unknown()).optional().describe("Custom metadata properties for the agent"),profilePicture:r.z.union([r.z.string().describe("URL or local file path to profile picture"),r.z.object({url:r.z.string().optional(),path:r.z.string().optional(),filename:r.z.string().optional()})]).optional().describe("Optional profile picture as URL, file path, or object with url/path/filename"),existingProfilePictureTopicId:r.z.string().optional().describe("Topic ID of an existing profile picture to reuse (e.g., 0.0.12345)"),initialBalance:r.z.number().positive().optional().describe("Optional initial HBAR balance for the new agent account (will create new account if provided)"),userAccountId:r.z.string().optional().describe("Optional account ID (e.g., 0.0.12345) to use as the agent account instead of creating a new one"),hbarFee:r.z.number().positive().optional().describe("Optional HBAR fee amount to charge per message on the inbound topic"),tokenFees:r.z.array(r.z.object({amount:r.z.number().positive(),tokenId:r.z.string()})).optional().describe("Optional token fees to charge per message"),exemptAccountIds:r.z.array(r.z.string()).optional().describe("Optional account IDs to exempt from fees"),setAsCurrent:r.z.boolean().optional().describe("Whether to set as current agent (default: true)"),persistence:r.z.object({prefix:r.z.string().optional()}).optional().describe("Optional persistence configuration")});class u extends s{constructor(e){super(e),this.name="register_agent",this.description="Creates and registers the AI agent on the Hedera network. Returns JSON string with agent details (accountId, privateKey, topics) on success. Note: This tool requires multiple transactions and cannot be used in returnBytes mode.",this.specificInputSchema=c,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const n=e,o={name:t.name};if(void 0!==t.description&&(o.bio=t.description),void 0!==t.alias&&(o.alias=t.alias),void 0!==t.type&&(o.type=t.type),void 0!==t.model&&(o.model=t.model),void 0!==t.capabilities&&(o.capabilities=t.capabilities),void 0!==t.creator&&(o.creator=t.creator),void 0!==t.socials&&(o.socials=t.socials),void 0!==t.properties&&(o.properties=t.properties),void 0!==t.profilePicture)if("string"==typeof t.profilePicture)o.profilePicture=t.profilePicture;else{const e={};void 0!==t.profilePicture.url&&(e.url=t.profilePicture.url),void 0!==t.profilePicture.path&&(e.path=t.profilePicture.path),void 0!==t.profilePicture.filename&&(e.filename=t.profilePicture.filename),o.profilePicture=e}void 0!==t.existingProfilePictureTopicId&&(o.existingProfilePictureTopicId=t.existingProfilePictureTopicId),void 0!==t.userAccountId&&(o.userAccountId=t.userAccountId),void 0!==t.hbarFee&&(o.hbarFee=t.hbarFee),void 0!==t.tokenFees&&(o.tokenFees=t.tokenFees),void 0!==t.exemptAccountIds&&(o.exemptAccountIds=t.exemptAccountIds),void 0!==t.initialBalance&&(o.initialBalance=t.initialBalance),await n.registerAgent(o)}}const d=r.z.object({targetIdentifier:r.z.string().describe("The request key (e.g., 'req-1:0.0.6155171@0.0.6154875'), account ID (e.g., 0.0.12345) of the target agent, OR the connection number (e.g., '1', '2') from the 'list_connections' tool. Request key is most deterministic."),message:r.z.string().describe("The text message content to send."),disableMonitoring:r.z.boolean().optional().default(!1)});class l extends s{constructor(e){super(e),this.name="send_message_to_connection",this.description="Sends a text message to another agent using an existing active connection. Identify the target agent using their account ID (e.g., 0.0.12345) or the connection number shown in 'list_connections'. Return back the reply from the target agent if possible",this.specificInputSchema=d,this.requiresMultipleTransactions=!0,this.neverScheduleThisTool=!0}async callBuilderMethod(e,t){const n=e;await n.sendMessageToConnection({targetIdentifier:t.targetIdentifier,message:t.message,disableMonitoring:t.disableMonitoring})}}const g=r.z.object({targetAccountId:r.z.string().describe("The Hedera account ID (e.g., 0.0.12345) of the agent you want to connect with."),disableMonitor:r.z.boolean().optional().describe("If true, does not wait for connection confirmation. Returns immediately after sending the request."),memo:r.z.string().optional().describe('Optional memo to include with the connection request (e.g., "Hello from Alice"). If not provided, defaults to "true" or "false" based on monitoring preference.')});class h extends s{constructor(e){super(e),this.name="initiate_connection",this.description="Actively STARTS a NEW HCS-10 connection TO a specific target agent identified by their account ID. Requires the targetAccountId parameter. Use this ONLY to INITIATE an OUTGOING connection request.",this.specificInputSchema=g,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const n=e,o={targetAccountId:t.targetAccountId};void 0!==t.disableMonitor&&(o.disableMonitor=t.disableMonitor),void 0!==t.memo&&(o.memo=t.memo),await n.initiateConnection(o)}}const p=r.z.object({includeDetails:r.z.boolean().optional().describe("Whether to include detailed information about each connection"),showPending:r.z.boolean().optional().describe("Whether to include pending connection requests")});class f extends a{constructor(e){super(e),this.name="list_connections",this.description="Lists the currently active HCS-10 connections with detailed information. Shows connection status, agent details, and recent activity. Use this to get a comprehensive view of all active connections.",this.specificInputSchema=p}async executeQuery(e){const t=this.hcs10Builder,n={};void 0!==e.includeDetails&&(n.includeDetails=e.includeDetails),void 0!==e.showPending&&(n.showPending=e.showPending),await t.listConnections(n);const o=await t.execute();if(o.success&&"rawResult"in o&&o.rawResult){const e=o.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Connections listed"}}return o}}const m=r.z.object({targetIdentifier:r.z.string().describe("The account ID (e.g., 0.0.12345) of the target agent OR the connection number (e.g., '1', '2') from the 'list_connections' tool to check messages for."),fetchLatest:r.z.boolean().optional().default(!1).describe("Set to true to fetch the latest messages even if they have been seen before, ignoring the last checked timestamp. Defaults to false (fetching only new messages)."),lastMessagesCount:r.z.number().int().positive().optional().describe("When fetchLatest is true, specifies how many of the most recent messages to retrieve. Defaults to 1.")});class I extends a{constructor(e){super(e),this.name="check_messages",this.description="Checks for and retrieves messages from an active connection.\nIdentify the target agent using their account ID (e.g., 0.0.12345) or the connection number shown in 'list_connections'.\nBy default, it only retrieves messages newer than the last check.\nUse 'fetchLatest: true' to get the most recent messages regardless of when they arrived.\nUse 'lastMessagesCount' to specify how many latest messages to retrieve (default 1 when fetchLatest is true).",this.specificInputSchema=m}async executeQuery({targetIdentifier:e,fetchLatest:t,lastMessagesCount:n}){const o=this.hcs10Builder;await o.checkMessages({targetIdentifier:e,fetchLatest:t,lastMessagesCount:n||1});const i=await o.execute();if(i.success&&"rawResult"in i&&i.rawResult){const e=i.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Messages checked"}}return i}}const w=r.z.object({accountId:r.z.string().optional().describe("Optional: Filter registrations by a specific Hedera account ID (e.g., 0.0.12345)."),tags:r.z.array(r.z.nativeEnum(t.AIAgentCapability)).optional().describe("Optional: Filter registrations by a list of tags (API filter only).")});class b extends a{constructor(e){super(e),this.name="find_registrations",this.description="Searches the configured agent registry for HCS-10 agents. You can filter by account ID or tags. Returns basic registration info.",this.specificInputSchema=w}async executeQuery({accountId:e,tags:t}){const n=this.hcs10Builder,o={};e&&(o.accountId=e),t&&(o.tags=t),await n.findRegistrations(o);const i=await n.execute();if(i.success&&"rawResult"in i&&i.rawResult){const e=i.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Registrations searched"}}return i}}const y=r.z.object({acceptAll:r.z.boolean().optional().describe("Whether to automatically accept all incoming connection requests. Default is false."),targetAccountId:r.z.string().optional().describe("If provided, only accept connection requests from this specific account ID."),hbarFees:r.z.array(r.z.object({amount:r.z.number(),collectorAccount:r.z.string().optional()})).optional().describe("Array of HBAR fee amounts to charge per message (with optional collector accounts)."),tokenFees:r.z.array(r.z.object({amount:r.z.number(),tokenId:r.z.string(),collectorAccount:r.z.string().optional()})).optional().describe("Array of token fee amounts and IDs to charge per message (with optional collector accounts)."),exemptAccountIds:r.z.array(r.z.string()).optional().describe("Array of account IDs to exempt from ALL fees set in this request."),monitorDurationSeconds:r.z.number().optional().describe("How long to monitor for incoming requests in seconds. Default is 120."),defaultCollectorAccount:r.z.string().optional().describe("Default account to collect fees if not specified at the fee level. Defaults to the agent account.")});class C extends s{constructor(e){super(e),this.name="monitor_connections",this.description="Monitors for incoming connection requests and accepts them with optional fee settings. Use this to watch for connection requests and accept them, optionally setting HBAR or token fees on the connection. Note: When acceptAll=true, this tool requires multiple transactions and cannot be used in returnBytes mode.",this.specificInputSchema=y,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const n=e;await n.monitorConnections({...void 0!==t.acceptAll&&{acceptAll:t.acceptAll},...void 0!==t.targetAccountId&&{targetAccountId:t.targetAccountId},...void 0!==t.monitorDurationSeconds&&{monitorDurationSeconds:t.monitorDurationSeconds},hbarFees:t.hbarFees||[],tokenFees:t.tokenFees||[],...void 0!==t.exemptAccountIds&&{exemptAccountIds:t.exemptAccountIds},...void 0!==t.defaultCollectorAccount&&{defaultCollectorAccount:t.defaultCollectorAccount}})}}const v=r.z.object({action:r.z.enum(["list","view","reject"]).describe("The action to perform: list all requests, view details of a specific request, or reject a request"),requestKey:r.z.string().optional().describe("The unique request key to view or reject (required for view and reject actions)")});class A extends a{constructor(e){super(e),this.name="manage_connection_requests",this.description='Manage incoming connection requests. List pending requests, view details about requesting agents, and reject connection requests. Use the separate "accept_connection_request" tool to accept.',this.specificInputSchema=v}async executeQuery({action:e,requestKey:t}){const n=this.hcs10Builder,o={action:e};void 0!==t&&(o.requestKey=t),await n.manageConnectionRequests(o);const i=await n.execute();return"rawResult"in i?i.rawResult:i}}const T=r.z.object({requestKey:r.z.string().describe('The unique request key of the specific request to accept. Use the "manage_connection_requests" tool with action="list" first to get valid keys.'),hbarFee:r.z.number().optional().describe("Optional HBAR fee amount to charge the connecting agent per message on the new connection topic."),exemptAccountIds:r.z.array(r.z.string()).optional().describe("Optional list of account IDs to exempt from any configured fees on the new connection topic.")});class q extends s{constructor(e){super(e),this.name="accept_connection_request",this.description="Accepts a pending HCS-10 connection request from another agent. Use list_unapproved_connection_requests to see pending requests.",this.specificInputSchema=T,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const n=e;await n.acceptConnection({requestKey:t.requestKey,hbarFee:t.hbarFee,exemptAccountIds:t.exemptAccountIds})}}const R=r.z.object({accountId:r.z.string().describe("The Hedera account ID of the agent whose profile you want to retrieve (e.g., 0.0.12345)."),disableCache:r.z.boolean().optional().describe("Optional: Force refresh from the network instead of using cache.")});class S extends a{constructor(e){super(e),this.name="retrieve_profile",this.description="Gets the detailed profile information for a specific HCS-10 agent by their account ID. Returns name, bio, capabilities, topics, and other metadata.",this.specificInputSchema=R}async executeQuery({accountId:e,disableCache:t}){const n=this.hcs10Builder,o={accountId:e};void 0!==t&&(o.disableCache=t),await n.retrieveProfile(o);const i=await n.execute();if(i.success&&"rawResult"in i&&i.rawResult){const e=i.rawResult;return{success:!0,data:e.profileDetails||"Profile retrieved",rawProfile:e.rawProfile}}return i}}const $=r.z.object({});class M extends a{constructor(e){super(e),this.name="list_unapproved_connection_requests",this.description="Lists all connection requests that are not fully established, including incoming requests needing approval and outgoing requests waiting for confirmation.",this.specificInputSchema=$}async executeQuery(){const e=this.hcs10Builder;await e.listUnapprovedConnectionRequests();const t=await e.execute();return"rawResult"in t?t.rawResult:t}}const E=o.join(process.cwd(),".env");class P{constructor(e){this.currentAgent=null,this.connectionMessageTimestamps={},this.connectionsManager=null,this.defaultEnvFilePath=e?.defaultEnvFilePath,this.defaultPrefix=e?.defaultPrefix??"TODD";const n=e?.disableLogging||"true"===process.env.DISABLE_LOGGING;this.logger=new t.Logger({module:"OpenConvaiState",silent:n}),e?.baseClient&&this.initializeConnectionsManager(e.baseClient)}initializeConnectionsManager(e){return this.connectionsManager?this.logger.debug("ConnectionsManager already initialized"):(this.logger.debug("Initializing ConnectionsManager"),this.connectionsManager=new t.ConnectionsManager({baseClient:e,logLevel:"error"})),this.connectionsManager}getConnectionsManager(){return this.connectionsManager}setCurrentAgent(e){this.currentAgent=e,this.connectionMessageTimestamps={},this.connectionsManager&&this.connectionsManager.clearAll()}getCurrentAgent(){return this.currentAgent}addActiveConnection(e){if(!this.connectionsManager)throw this.logger.error("ConnectionsManager not initialized. Call initializeConnectionsManager before adding connections."),new Error("ConnectionsManager not initialized. Call initializeConnectionsManager before adding connections.");const t={connectionTopicId:e.connectionTopicId,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName,targetInboundTopicId:e.targetInboundTopicId,status:this.convertConnectionStatus(e.status||"established"),isPending:e.isPending||!1,needsConfirmation:e.needsConfirmation||!1,created:e.created||new Date,lastActivity:e.lastActivity,profileInfo:e.profileInfo,connectionRequestId:e.connectionRequestId,processed:!0};this.connectionsManager.updateOrAddConnection(t),this.initializeTimestampIfNeeded(e.connectionTopicId)}updateOrAddConnection(e){this.addActiveConnection(e)}listConnections(){return this.connectionsManager?this.connectionsManager.getAllConnections().map(e=>this.convertToActiveConnection(e)):(this.logger.debug("ConnectionsManager not initialized, returning empty connections list"),[])}getConnectionByIdentifier(e){if(!this.connectionsManager)return;const t=this.listConnections(),n=parseInt(e)-1;if(!isNaN(n)&&n>=0&&n<t.length)return t[n];const o=this.connectionsManager.getConnectionByTopicId(e);if(o)return this.convertToActiveConnection(o);const i=this.connectionsManager.getConnectionByAccountId(e);return i?this.convertToActiveConnection(i):void 0}getLastTimestamp(e){return this.connectionMessageTimestamps[e]||0}updateTimestamp(e,t){if(!(e in this.connectionMessageTimestamps))return void(this.connectionMessageTimestamps[e]=t);t>this.connectionMessageTimestamps[e]&&(this.connectionMessageTimestamps[e]=t)}initializeTimestampIfNeeded(e){e in this.connectionMessageTimestamps||(this.connectionMessageTimestamps[e]=1e6*Date.now())}convertConnectionStatus(e){switch(e){case"pending":return"pending";case"established":default:return"established";case"needs confirmation":return"needs_confirmation"}}convertToActiveConnection(e){return{targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName||`Agent ${e.targetAccountId}`,targetInboundTopicId:e.targetInboundTopicId||"",connectionTopicId:e.connectionTopicId,status:this.convertToStateStatus(e.status),created:e.created,lastActivity:e.lastActivity,isPending:e.isPending,needsConfirmation:e.needsConfirmation,profileInfo:e.profileInfo,connectionRequestId:e.connectionRequestId}}convertToStateStatus(e){switch(e){case"pending":return"pending";case"established":case"closed":return"established";case"needs_confirmation":return"needs confirmation";default:return"unknown"}}async persistAgentData(e,t){if(t?.type&&"env-file"!==t.type)throw new Error(`Unsupported persistence type: ${t.type}. Only 'env-file' is supported.`);const o=t?.envFilePath||this.defaultEnvFilePath||process.env.ENV_FILE_PATH||".env",i=t?.prefix||this.defaultPrefix;if(!e.accountId||!e.inboundTopicId||!e.outboundTopicId)throw new Error("Agent data incomplete, cannot persist to environment");const r={[`${i}_ACCOUNT_ID`]:e.accountId,[`${i}_INBOUND_TOPIC_ID`]:e.inboundTopicId,[`${i}_OUTBOUND_TOPIC_ID`]:e.outboundTopicId};e.privateKey&&(r[`${i}_PRIVATE_KEY`]=e.privateKey),e.profileTopicId&&(r[`${i}_PROFILE_TOPIC_ID`]=e.profileTopicId),await async function(e,t){let o="";n.existsSync(e)&&(o=n.readFileSync(e,"utf8"));const i=[...o.split("\n")];for(const[n,r]of Object.entries(t)){const e=i.findIndex(e=>e.startsWith(`${n}=`));-1!==e?i[e]=`${n}=${r}`:i.push(`${n}=${r}`)}n.writeFileSync(e,i.join("\n"))}(o,r)}}const x="ConnectionsManager not initialized";class N extends e.BaseServiceBuilder{constructor(e,n,o){super(e),this.stateManager=n,this.useEncryption=o?.useEncryption||!1,this.guardedRegistryBaseUrl=o?.registryUrl||"";const i=this.hederaKit.client.network;this.network=i.toString().includes("mainnet")?"mainnet":"testnet";const r=this.hederaKit.signer.getAccountId().toString(),s=this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"";this.sdkLogger=new t.Logger({module:"HCS10Builder",level:o?.logLevel||"info"}),this.standardClient=new t.HCS10Client({network:this.network,operatorId:r,operatorPrivateKey:s,guardedRegistryBaseUrl:this.guardedRegistryBaseUrl,logLevel:o?.logLevel||"info"}),this.stateManager&&this.stateManager.initializeConnectionsManager(this.standardClient)}getOperatorId(){const e=this.standardClient.getClient().operatorAccountId;if(!e)throw new Error("Operator Account ID not configured in standard client.");return e.toString()}getNetwork(){return this.network}getAccountAndSigner(){const e=this.standardClient.getAccountAndSigner();return{accountId:e.accountId,signer:e.signer}}async getInboundTopicId(){try{const e=this.getOperatorId();this.logger.info(`[HCS10Builder] Retrieving profile for operator ${e} to find inbound topic...`);const t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.inboundTopic)return this.logger.info(`[HCS10Builder] Found inbound topic for operator ${e}: ${t.topicInfo.inboundTopic}`),t.topicInfo.inboundTopic;throw new Error(`Could not retrieve inbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}catch(e){this.logger.error(`[HCS10Builder] Error fetching operator's inbound topic ID (${this.getOperatorId()}):`,e);const t=this.getOperatorId();let n=`Failed to get inbound topic ID for operator ${t}.`;throw e instanceof Error&&e.message.includes("does not have a valid HCS-11 memo")?n+=` The account profile may not exist or is invalid. Please ensure this operator account (${t}) is registered as an HCS-10 agent. You might need to register it first (e.g., using the 'register_agent' tool or SDK function).`:e instanceof Error?n+=` Reason: ${e.message}`:n+=` Unexpected error: ${String(e)}`,new Error(n)}}async getAgentProfile(e){try{return await this.standardClient.retrieveProfile(e)}catch(t){throw this.logger.error(`[HCS10Builder] Error retrieving agent profile for account ${e}:`,t),t}}async submitConnectionRequest(e,t){return this.standardClient.submitConnectionRequest(e,t)}async handleConnectionRequest(e,t,n,o){try{const i=await this.standardClient.handleConnectionRequest(e,t,n,o);return i&&i.connectionTopicId&&"object"==typeof i.connectionTopicId&&"toString"in i.connectionTopicId&&(i.connectionTopicId=i.connectionTopicId.toString()),i}catch(i){throw this.logger.error(`Error handling connection request #${n} for topic ${e}:`,i),new Error(`Failed to handle connection request: ${i instanceof Error?i.message:String(i)}`)}}async sendMessage(e,t,n){if(e&&"object"==typeof e&&"toString"in e&&(e=e?.toString()),!e||"string"!=typeof e)throw new Error(`Invalid topic ID provided to sendMessage: ${JSON.stringify(e)}`);try{const o=await this.standardClient.sendMessage(e,t,n,void 0);return{sequenceNumber:o.topicSequenceNumber?.toNumber(),receipt:o,transactionId:"transactionId"in o?o.transactionId?.toString():void 0}}catch(o){throw this.logger.error(`Error sending message to topic ${e}:`,o),new Error(`Failed to send message: ${o instanceof Error?o.message:String(o)}`)}}async getMessages(e){if(e&&"object"==typeof e&&"toString"in e&&(e=e?.toString()),!e||"string"!=typeof e)throw new Error(`Invalid topic ID provided to getMessages: ${JSON.stringify(e)}`);try{const t=(await this.standardClient.getMessages(e)).messages.map(e=>{const t=e?.created?.getTime()||0;return{...e,timestamp:t,data:e.data||"",sequence_number:e.sequence_number,p:"hcs-10"}});return t.sort((e,t)=>e.timestamp-t.timestamp),{messages:t}}catch(t){return this.logger.error(`Error getting messages from topic ${e}:`,t),{messages:[]}}}async getMessageStream(e){if(e&&"object"==typeof e&&"toString"in e&&(e=e?.toString()),!e||"string"!=typeof e)throw new Error(`Invalid topic ID provided to getMessageStream: ${JSON.stringify(e)}`);return this.standardClient.getMessageStream(e)}async getMessageContent(e){try{return await this.standardClient.getMessageContent(e)}catch(t){throw this.logger.error(`Error retrieving message content for: ${e}`,t),new Error(`Failed to retrieve message content: ${t instanceof Error?t.message:String(t)}`)}}getStandardClient(){return this.standardClient}async loadProfilePicture(e){try{if(!e)return null;if("string"==typeof e){if(e.startsWith("http://")||e.startsWith("https://")){this.logger.info(`Loading profile picture from URL: ${e}`);const t=await i.get(e,{responseType:"arraybuffer"}),n=globalThis.Buffer.from(t.data),r=new URL(e).pathname;return{buffer:n,filename:o.basename(r)||"profile.png"}}{if(!n.existsSync(e))return this.logger.warn(`Profile picture file not found: ${e}`),null;this.logger.info(`Loading profile picture from file: ${e}`);const t=n.readFileSync(e);return{buffer:t,filename:o.basename(e)}}}if(e.url){this.logger.info(`Loading profile picture from URL: ${e.url}`);const t=await i.get(e.url,{responseType:"arraybuffer"}),n=globalThis.Buffer.from(t.data);return{buffer:n,filename:e.filename||"profile.png"}}if(e.path){if(!n.existsSync(e.path))return this.logger.warn(`Profile picture file not found: ${e.path}`),null;this.logger.info(`Loading profile picture from file: ${e.path}`);const t=n.readFileSync(e.path);return{buffer:t,filename:e.filename||o.basename(e.path)}}return null}catch(t){return this.logger.error("Failed to load profile picture:",t),null}}async createAndRegisterAgent(e){const n=(new t.AgentBuilder).setName(e.name).setBio(e.bio||"").setCapabilities(e.capabilities||[t.AIAgentCapability.TEXT_GENERATION]).setType(e.type||"autonomous").setModel(e.model||"agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(t.InboundTopicType.PUBLIC);e.alias&&n.setAlias(e.alias),e.creator&&n.setCreator(e.creator),e?.feeConfig&&(n.setInboundTopicType(t.InboundTopicType.FEE_BASED),n.setFeeConfig(e.feeConfig)),e.existingProfilePictureTopicId?n.setExistingProfilePicture(e.existingProfilePictureTopicId):e.pfpBuffer&&e.pfpFileName?0===e.pfpBuffer.byteLength?this.logger.warn("Provided PFP buffer is empty. Skipping profile picture."):(this.logger.info(`Setting profile picture: ${e.pfpFileName} (${e.pfpBuffer.byteLength} bytes)`),n.setProfilePicture(e.pfpBuffer,e.pfpFileName)):this.logger.warn("Profile picture not provided. Agent creation might fail if required by the underlying SDK builder."),e.socials&&Object.entries(e.socials).forEach(([e,t])=>{n.addSocial(e,t)}),e.properties&&Object.entries(e.properties).forEach(([e,t])=>{n.addProperty(e,t)});try{const t=Boolean(e?.feeConfig);return await this.standardClient.createAndRegisterAgent(n,{initialBalance:t?50:10})}catch(o){throw this.logger.error("Error during agent creation/registration:",o),new Error(`Failed to create/register agent: ${o instanceof Error?o.message:String(o)}`)}}async registerAgent(e){if(this.clearNotes(),"returnBytes"===this.hederaKit.operationalMode)throw new Error("Agent registration requires multiple transactions and cannot be performed in returnBytes mode. Please use autonomous mode.");try{let n=null;e.profilePicture&&(n=await this.loadProfilePicture(e.profilePicture));const o={name:e.name,...void 0!==e.bio&&{bio:e.bio},...void 0!==e.alias&&{alias:e.alias},...void 0!==e.type&&{type:e.type},...void 0!==e.model&&{model:e.model},...void 0!==e.capabilities&&{capabilities:e.capabilities},...void 0!==e.creator&&{creator:e.creator},...void 0!==e.socials&&{socials:e.socials},...void 0!==e.properties&&{properties:e.properties},...void 0!==e.existingProfilePictureTopicId&&{existingProfilePictureTopicId:e.existingProfilePictureTopicId},...void 0!==n?.buffer&&{pfpBuffer:n.buffer},...void 0!==n?.filename&&{pfpFileName:n.filename}};if(e.hbarFee&&e.hbarFee>0){const n=new t.FeeConfigBuilder({network:this.network,logger:this.sdkLogger}),{accountId:i}=this.getAccountAndSigner();if(!i)throw new Error("Could not determine account ID for fee collection.");this.addNote(`Setting the operator account (${i}) as the fee collector since no specific collector was provided.`);const r=e.exemptAccountIds?.filter(e=>e!==i&&e.startsWith("0.0"))||[];o.feeConfig=n.addHbarFee(e.hbarFee,i,r)}const i=await this.createAndRegisterAgent(o);this.executeResult={success:!0,transactionId:i.transactionId,receipt:void 0,scheduleId:void 0,rawResult:{...i,name:e.name,accountId:i?.metadata?.accountId||i.state?.agentMetadata?.accountId}}}catch(n){throw this.logger.error("Failed to register agent:",n),n}return this}async initiateConnection(e){this.clearNotes();try{const t=await this.getAgentProfile(e.targetAccountId);if(!t.success||!t.topicInfo?.inboundTopic)throw new Error(`Could not retrieve inbound topic for target account ${e.targetAccountId}`);const n=t.topicInfo.inboundTopic;let o;void 0!==e.memo?o=e.memo:(o=e.disableMonitor?"false":"true",this.addNote(`No custom memo was provided. Using default memo '${o}' based on monitoring preference.`)),e.disableMonitor||this.addNote("Monitoring will be enabled for this connection request as disableMonitor was not specified.");const i=await this.submitConnectionRequest(n,o);this.executeResult={success:!0,transactionId:"transactionId"in i?i.transactionId?.toString():void 0,receipt:i,scheduleId:void 0,rawResult:{targetAccountId:e.targetAccountId,targetInboundTopicId:n,connectionRequestSent:!0,monitoringEnabled:!e.disableMonitor,...i}}}catch(t){throw this.logger.error("Failed to initiate connection:",t),t}return this}async acceptConnection(e){if(this.clearNotes(),"returnBytes"===this.hederaKit.operationalMode)throw new Error("Accepting connections requires multiple transactions and cannot be performed in returnBytes mode. Please use autonomous mode.");try{const o=this.stateManager?.getCurrentAgent();if(!o)throw new Error("Cannot accept connection request. No agent is currently active. Please register or select an agent first.");const i=this.stateManager?.getConnectionsManager();if(!i)throw new Error(x);await i.fetchConnectionData(o.accountId);const r=[...i.getPendingRequests(),...i.getConnectionsNeedingConfirmation()].find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!r)throw new Error(`Request with key ${e.requestKey} not found or no longer pending.`);if(!r.needsConfirmation||!r.inboundRequestId)throw new Error(`Request with key ${e.requestKey} is not an inbound request that can be accepted.`);const s=r.targetAccountId,a=r.inboundRequestId;let c;if(e.hbarFee&&e.hbarFee>0){const n=new t.FeeConfigBuilder({network:this.network,logger:this.sdkLogger}),{accountId:o}=this.getAccountAndSigner();if(!o)throw new Error("Could not determine account ID for fee collection.");this.addNote(`Setting the operator account (${o}) as the fee collector since no specific collector was provided.`);const i=e.exemptAccountIds?.filter(e=>e!==o&&e.startsWith("0.0"))||[];c=n.addHbarFee(e.hbarFee,o,i)}const u=await this.getInboundTopicId(),d=await this.handleConnectionRequest(u,s,a,c);let l=d?.connectionTopicId;if(l&&"object"==typeof l&&"toString"in l&&(l=l?.toString()),!l||"string"!=typeof l)throw new Error(`Failed to create connection topic. Got: ${JSON.stringify(l)}`);if(this.stateManager){const e=r.targetAgentName||`Agent ${s}`;r.targetAgentName||this.addNote(`No agent name was provided in the connection request, using default name 'Agent ${s}'.`);let t=r.targetInboundTopicId||"";if(!t)try{const e=await this.getAgentProfile(s);e.success&&e.topicInfo?.inboundTopic&&(t=e.topicInfo.inboundTopic)}catch(n){this.logger.warn(`Could not fetch profile for ${s}:`,n)}const o={connectionId:`conn-${Date.now()}`,targetAccountId:s,targetAgentName:e,targetInboundTopicId:t,connectionTopicId:l,status:"established",created:new Date};this.stateManager.addActiveConnection(o),i.markConnectionRequestProcessed(r.targetInboundTopicId||"",a)}this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{targetAccountId:s,connectionTopicId:l,feeConfigured:!!e.hbarFee,hbarFee:e.hbarFee||0,confirmationResult:d}}}catch(o){throw this.logger.error("Failed to accept connection:",o),o}return this}async sendHCS10Message(e){this.clearNotes();try{const t=await this.sendMessage(e.topicId,e.message);this.executeResult={success:!0,transactionId:t.transactionId,receipt:t.receipt,scheduleId:void 0,rawResult:t},this.addNote(`Message sent to topic ${e.topicId}.`)}catch(t){throw this.logger.error("Failed to send message:",t),t}return this}async sendMessageToConnection(e){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required to send messages to connections");try{const t=this.stateManager.getCurrentAgent();if(!t)throw new Error("Cannot send message. No agent is currently active. Please register or select an agent first.");let n;if(e.targetIdentifier.includes("@")){const t=e.targetIdentifier.split("@");if(2===t.length){const o=t[1];n=this.stateManager.getConnectionByIdentifier(o),n||this.addNote(`Could not find connection using request key '${e.targetIdentifier}', extracted account ID '${o}'.`)}}if(n||(n=this.stateManager.getConnectionByIdentifier(e.targetIdentifier)),!n){const t=this.stateManager.listConnections().map(e=>`${e.targetAccountId} (${e.connectionTopicId})`);throw new Error(`Connection not found for identifier: ${e.targetIdentifier}. Available connections: ${t.join(", ")||"none"}. Use 'list_connections' to see details.`)}let o=n.connectionTopicId;if(o&&"object"==typeof o&&"toString"in o&&(o=o?.toString()),!o||"string"!=typeof o)throw new Error(`Invalid connection topic ID for ${n.targetAccountId}: ${JSON.stringify(o)} (type: ${typeof o})`);const i=n.targetAgentName,r=`${t.inboundTopicId}@${t.accountId}`,s=await this.sendMessage(o,e.message,`Agent message from ${t.name}`);if(!s.sequenceNumber)throw new Error("Failed to send message");let a=null;e.disableMonitoring?this.addNote("Message sent successfully. Response monitoring was disabled."):a=await this.monitorResponses(o,r,s.sequenceNumber),this.executeResult={success:!0,transactionId:s.transactionId,receipt:s.receipt,scheduleId:void 0,rawResult:{targetAgentName:i,targetAccountId:n.targetAccountId,connectionTopicId:o,sequenceNumber:s.sequenceNumber,reply:a,monitoringEnabled:!e.disableMonitoring,message:e.message,messageResult:s}}}catch(t){throw this.logger.error("Failed to send message to connection:",t),t}return this}async monitorResponses(e,t,n){let o=0;for(;o<30;){try{const o=await this.getMessageStream(e);for(const e of o.messages){if(e.sequence_number<n||e.operator_id===t)continue;return await this.getMessageContent(e.data||"")}}catch(i){this.logger.error(`Error monitoring responses: ${i}`)}await new Promise(e=>setTimeout(e,4e3)),o++}return null}async startPassiveConnectionMonitoring(){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required for passive monitoring");const e=await this.getInboundTopicId();return this.logger.info(`Starting passive connection monitoring on topic ${e}...`),this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{inboundTopicId:e,message:`Started monitoring inbound topic ${e} for connection requests in the background.`}},this}async monitorConnections(e){this.clearNotes();const{acceptAll:n=!1,targetAccountId:o,monitorDurationSeconds:i=120,hbarFees:r=[],tokenFees:s=[],exemptAccountIds:a=[],defaultCollectorAccount:c}=e;if(!this.stateManager)throw new Error("StateManager is required for connection monitoring");if(!this.stateManager.getCurrentAgent())throw new Error("Cannot monitor for connections. No agent is currently active.");const u=await this.getInboundTopicId(),d=Date.now()+1e3*i;let l=0,g=0;const h=new Set;for(;Date.now()<d;){try{const e=(await this.getMessages(u)).messages.filter(e=>"connection_request"===e.op&&"number"==typeof e.sequence_number);for(const i of e){const e=i.sequence_number;if(!e||h.has(e))continue;const d=i.operator_id?.split("@")[1];if(d)if(l++,o&&d!==o)this.logger.info(`Skipping request from ${d} (not target account)`);else if(n||o===d){let n;if(this.logger.info(`Accepting connection request from ${d}`),r.length>0||s.length>0){const e=new t.FeeConfigBuilder({network:this.network,logger:this.sdkLogger});for(const t of r){const n=t.collectorAccount||c||this.getOperatorId();e.addHbarFee(t.amount,n,a)}for(const t of s){const n=t.collectorAccount||c||this.getOperatorId();e.addTokenFee(t.amount,t.tokenId,n,void 0,a)}n=e}await this.handleConnectionRequest(u,d,e,n),h.add(e),g++}}}catch(p){this.logger.error("Error during connection monitoring:",p)}await new Promise(e=>setTimeout(e,3e3))}return this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{connectionRequestsFound:l,acceptedConnections:g,monitorDurationSeconds:i,processedRequestIds:Array.from(h)}},this.addNote(`Monitoring completed. Found ${l} requests, accepted ${g}.`),this}async manageConnectionRequests(e){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required for managing connection requests");if(!this.stateManager.getCurrentAgent())throw new Error("Cannot manage connection requests. No agent is currently active.");const t=this.stateManager.getConnectionsManager();if(!t)throw new Error(x);try{const{accountId:n}=this.getAccountAndSigner();await t.fetchConnectionData(n);const o=t.getPendingRequests(),i=t.getConnectionsNeedingConfirmation(),r=[...o,...i];switch(e.action){case"list":this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{requests:r.map((e,t)=>({index:t+1,type:e.needsConfirmation?"incoming":"outgoing",requestKey:e.uniqueRequestKey||`${e.connectionRequestId||e.inboundRequestId||"unknown"}`,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName||`Agent ${e.targetAccountId}`,created:e.created.toISOString(),memo:e.memo,bio:e.profileInfo?.bio}))}};break;case"view":{if(!e.requestKey)throw new Error("Request key is required for viewing a request");const t=r.find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!t)throw new Error(`Request with key ${e.requestKey} not found`);this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{request:{type:t.needsConfirmation?"incoming":"outgoing",requestKey:t.uniqueRequestKey||`${t.connectionRequestId||t.inboundRequestId||"unknown"}`,targetAccountId:t.targetAccountId,targetAgentName:t.targetAgentName||`Agent ${t.targetAccountId}`,created:t.created.toISOString(),memo:t.memo,profileInfo:t.profileInfo}}};break}case"reject":{if(!e.requestKey)throw new Error("Request key is required for rejecting a request");const n=r.find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!n)throw new Error(`Request with key ${e.requestKey} not found`);n.inboundRequestId?t.markConnectionRequestProcessed(n.targetInboundTopicId||"",n.inboundRequestId):n.connectionRequestId&&t.markConnectionRequestProcessed(n.originTopicId||"",n.connectionRequestId),this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{rejectedRequest:{requestKey:e.requestKey,targetAccountId:n.targetAccountId,targetAgentName:n.targetAgentName||`Agent ${n.targetAccountId}`}}};break}}}catch(n){throw this.logger.error("Failed to manage connection requests:",n),n}return this}async listUnapprovedConnectionRequests(){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required for listing connection requests");if(!this.stateManager.getCurrentAgent())throw new Error("Cannot list connection requests. No agent is currently active.");try{const e=await this.getInboundTopicId(),t=(await this.getMessages(e)).messages.filter(e=>"connection_request"===e.op).map(e=>({requestId:e.sequence_number,fromAccountId:e.operator_id?.split("@")[1]||"unknown",timestamp:e.timestamp||new Date(e?.created||"").getTime(),memo:e.m||"",data:e.data})).filter(e=>"unknown"!==e.fromAccountId);this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{requests:t,count:t.length}},0===t.length?this.addNote("No unapproved connection requests found."):this.addNote(`Found ${t.length} unapproved connection request(s).`)}catch(e){throw this.logger.error("Failed to list unapproved connection requests:",e),e}return this}async listConnections(e={}){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required to list connections");const t=e.includeDetails??!0,n=e.showPending??!0;try{const e=await this.getEnhancedConnections();if(0===e.length)return this.executeResult={success:!0,rawResult:{connections:[],message:"There are currently no active connections."}},this;const o=e.filter(e=>"established"===e.status),i=e.filter(e=>e.isPending),r=e.filter(e=>e.needsConfirmation);let s="";o.length>0&&(s+=`🟢 Active Connections (${o.length}):\n`,o.forEach((e,n)=>{s+=this.formatConnection(e,n,t)}),s+="\n"),n&&r.length>0&&(s+=`🟠 Connections Needing Confirmation (${r.length}):\n`,r.forEach((e,n)=>{s+=this.formatConnection(e,n,t)}),s+="\n"),n&&i.length>0&&(s+=`⚪ Pending Connection Requests (${i.length}):\n`,i.forEach((e,n)=>{s+=this.formatConnection(e,n,t)})),this.executeResult={success:!0,rawResult:{connections:e,formattedOutput:s.trim(),activeCount:o.length,pendingCount:i.length,needsConfirmationCount:r.length}}}catch(o){this.logger.error("Failed to list connections:",o),this.executeResult={success:!1,error:`Failed to list connections: ${o instanceof Error?o.message:String(o)}`}}return this}formatConnection(e,t,n){const o=e;let i=`${t+1}. ${o.profileInfo?.display_name||o.targetAgentName||"Unknown Agent"} (${o.targetAccountId})\n`;i+=` Topic: ${o.isPending?"(Pending Request)":o.connectionTopicId}\n`;if(i+=` Status: ${o.status||"unknown"}\n`,n){if(o.profileInfo?.bio&&(i+=` Bio: ${o.profileInfo.bio.substring(0,100)}${o.profileInfo.bio.length>100?"...":""}\n`),o.created){i+=` ${o.isPending?"Request sent":"Connection established"}: ${o.created.toLocaleString()}\n`}o.lastActivity&&(i+=` Last activity: ${o.lastActivity.toLocaleString()}\n`)}return i}async getEnhancedConnections(){try{const{accountId:e}=this.getAccountAndSigner();if(!e)return this.stateManager.listConnections();const t=this.stateManager.getConnectionsManager();if(!t)return this.logger.error(x),this.stateManager.listConnections();const n=await t.fetchConnectionData(e);for(const o of n)this.stateManager.addActiveConnection(o);return n}catch(e){return this.logger.error("Failed to get enhanced connections:",e),this.stateManager.listConnections()}}async checkMessages(e){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required to check messages");const t=this.stateManager.getConnectionByIdentifier(e.targetIdentifier);if(!t)return this.executeResult={success:!1,error:`Could not find an active connection matching identifier "${e.targetIdentifier}". Use 'list_connections' to see active connections.`},this;const n=t.connectionTopicId||"";if(!n||!n.match(/^\d+\.\d+\.\d+$/))return this.logger.error(`Invalid connection topic ID format: ${n}`),this.executeResult={success:!1,error:`Invalid connection topic ID format: ${n}. Expected format: 0.0.XXXXX`},this;const o=t.targetAgentName,i=this.stateManager.getLastTimestamp(n);this.logger.info(`Checking messages for connection with ${o} (${t.targetAccountId}) on topic ${n} (fetchLatest: ${e.fetchLatest}, lastCount: ${e.lastMessagesCount}, since: ${i})`);try{const t=(await this.getMessages(n)).messages;if(!t||0===t.length)return this.executeResult={success:!0,rawResult:{messages:[],message:`No messages found on connection topic ${n}.`}},this;let s=[],a=i;const c=!0===e.fetchLatest;if(c){this.logger.info("Fetching latest messages regardless of timestamp.");const n=e.lastMessagesCount??1;s=t.slice(-n)}else this.logger.info(`Filtering for messages newer than ${i}`),s=t.filter(e=>1e6*e.timestamp>i),s.length>0&&(a=s.reduce((e,t)=>Math.max(e,1e6*t.timestamp),i));if(0===s.length){const e=c?`Could not retrieve the latest message(s). No messages found on topic ${n}.`:`No new messages found for connection with ${o} since last check.`;return this.executeResult={success:!0,rawResult:{messages:[],message:e}},this}this.logger.info(`Processing ${s.length} message(s).`);let u=c?`Latest message(s) from ${o}:\n`:`New messages from ${o}:\n`;const d=[];for(const e of s){let t=e.data;try{"string"==typeof t&&t.startsWith("hcs://")&&(this.logger.debug(`Resolving inscribed message: ${t}`),t=await this.getMessageContent(t),this.logger.debug(`Resolved content length: ${t?.length}`));let n=t;try{const e=JSON.parse(t||"{}");if("hcs-10"===e.p&&"message"===e.op&&e.data){n=`[${e.operator_id||"unknown_sender"}]: ${e.data}`}else n=t}catch{n=t}u+=`\n[${new Date(e.timestamp).toLocaleString()}] (Seq: ${e.sequence_number})\n${n}\n`,d.push({timestamp:e.timestamp,sequenceNumber:e.sequence_number,content:n,raw:e})}catch(r){const t=`Error processing message (Seq: ${e.sequence_number}): ${r instanceof Error?r.message:String(r)}`;this.logger.error(t),u+=`\n[Error processing message Seq: ${e.sequence_number}]\n`}}!c&&a>i&&(this.logger.debug(`Updating timestamp for topic ${n} to ${a}`),this.stateManager.updateTimestamp(n,a)),this.executeResult={success:!0,rawResult:{messages:d,formattedOutput:u.trim(),targetAgentName:o,connectionTopicId:n}}}catch(r){this.logger.error(`Failed to check messages for topic ${n}: ${r}`),this.executeResult={success:!1,error:`Error checking messages for ${o}: ${r instanceof Error?r.message:String(r)}`}}return this}async findRegistrations(e){this.clearNotes();try{const t={network:this.network};e.accountId&&(t.accountId=e.accountId),e.tags&&e.tags.length>0&&(t.tags=e.tags);const n=await this.standardClient.findRegistrations(t);if(!n.success||n.error)return this.executeResult={success:!1,error:`Error finding registrations: ${n.error||"Unknown error"}`},this;if(!n.registrations||0===n.registrations.length)return this.executeResult={success:!0,rawResult:{registrations:[],message:"No registrations found matching the criteria."}},this;const o=n.registrations.map(e=>{const t=e;return`Agent: ${t.agent?.name||"Unknown Agent"} (${t.accountId||"Unknown Account"}), Capabilities: ${t.agent?.capabilities?.join(", ")||"None"}`}).join("\\n");this.executeResult={success:!0,rawResult:{registrations:n.registrations,formattedOutput:`Found ${n.registrations.length} registration(s):\\n${o}`}}}catch(t){this.logger.error("Error during FindRegistrations execution:",t),this.executeResult={success:!1,error:`Failed to search registrations: ${t instanceof Error?t.message:String(t)}`}}return this}async retrieveProfile(e){this.clearNotes();try{const t=await this.standardClient.retrieveProfile(e.accountId,e.disableCache||!1);if(!t.success)return this.executeResult={success:!1,error:`Failed to retrieve profile: ${t.error||"Unknown error"}`},this;const n=t.profile,o=t.topicInfo;let i=`Profile for ${e.accountId}:\n`;i+=`Name: ${n.name||"Unknown"}\n`,i+=`Bio: ${n.bio||"No bio provided"}\n`,i+=`Type: ${n.type||"Unknown"}\n`,i+=`Model: ${n.model||"Unknown"}\n`,n.capabilities&&n.capabilities.length>0?i+=`Capabilities: ${n.capabilities.join(", ")}\n`:i+="Capabilities: None listed\n",o&&(i+=`Inbound Topic: ${o.inboundTopic||"Unknown"}\n`,i+=`Outbound Topic: ${o.outboundTopic||"Unknown"}\n`,i+=`Profile Topic: ${o.profileTopicId||"Unknown"}\n`),n.social&&Object.keys(n.social).length>0&&(i+=`Social: ${Object.entries(n.social).map(([e,t])=>`${e}: ${t}`).join(", ")}\n`),n.properties&&Object.keys(n.properties).length>0&&(i+=`Properties: ${JSON.stringify(n.properties)}\n`),this.executeResult={success:!0,rawResult:{profileDetails:i,rawProfile:t}}}catch(t){this.logger.error(`Unexpected error retrieving profile for ${e.accountId}:`,t),this.executeResult={success:!1,error:`Unexpected error retrieving profile for ${e.accountId}: ${t instanceof Error?t.message:String(t)}`}}return this}async execute(){return this.executeResult?{success:this.executeResult.success,transactionId:this.executeResult.transactionId,receipt:this.executeResult.receipt,scheduleId:this.executeResult.scheduleId,error:this.executeResult.error,rawResult:this.executeResult.rawResult,notes:this.notes}:{success:!1,error:"No operation result available. Call a builder method first."}}}class k extends e.BasePlugin{constructor(){super(...arguments),this.id="hedera-hbar-price",this.name="Hedera HBAR Price Plugin",this.description="Provides tools to interact with Hedera network data, specifically HBAR price.",this.version="1.0.0",this.author="Hashgraph Online",this.tools=[]}async initialize(e){await super.initialize(e),this.initializeTools()}initializeTools(){this.tools=[new e.HederaGetHbarPriceTool({hederaKit:this.context.config.hederaKit,logger:this.context.logger})]}getTools(){return this.tools}}Object.defineProperty(exports,"BasePlugin",{enumerable:!0,get:()=>e.BasePlugin}),Object.defineProperty(exports,"GetHbarPriceTool",{enumerable:!0,get:()=>e.HederaGetHbarPriceTool}),Object.defineProperty(exports,"PluginRegistry",{enumerable:!0,get:()=>e.PluginRegistry}),exports.AcceptConnectionRequestTool=q,exports.BaseHCS10QueryTool=a,exports.BaseHCS10TransactionTool=s,exports.CheckMessagesTool=I,exports.ConnectionMonitorTool=C,exports.FindRegistrationsTool=b,exports.HCS10Builder=N,exports.HCS10Client=class{constructor(e,n,o,i){this.standardClient=new t.HCS10Client({network:o,operatorId:e,operatorPrivateKey:n,guardedRegistryBaseUrl:i?.registryUrl,logLevel:i?.logLevel}),this.guardedRegistryBaseUrl=i?.registryUrl||"",this.useEncryption=i?.useEncryption||!1;const r="true"===process.env.DISABLE_LOGGING;this.logger=new t.Logger({level:i?.logLevel||"info",silent:r})}getOperatorId(){const e=this.standardClient.getClient().operatorAccountId;if(!e)throw new Error("Operator Account ID not configured in standard client.");return e.toString()}getNetwork(){return this.standardClient.getNetwork()}async handleConnectionRequest(e,t,n,o){try{return await this.standardClient.handleConnectionRequest(e,t,n,o)}catch(i){throw this.logger.error(`Error handling connection request #${n} for topic ${e}:`,i),new Error(`Failed to handle connection request: ${i instanceof Error?i.message:String(i)}`)}}async getAgentProfile(e){return this.standardClient.retrieveProfile(e)}async submitConnectionRequest(e,t){return this.standardClient.submitConnectionRequest(e,t)}async waitForConnectionConfirmation(e,t,n=60,o=2e3){return this.standardClient.waitForConnectionConfirmation(e,t,n,o)}async createAndRegisterAgent(e){const n=(new t.AgentBuilder).setName(e.name).setBio(e.description||"").setCapabilities(e.capabilities?e.capabilities:[t.AIAgentCapability.TEXT_GENERATION]).setType(e.type||"autonomous").setModel(e.model||"agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(t.InboundTopicType.PUBLIC);e?.feeConfig&&(n.setInboundTopicType(t.InboundTopicType.FEE_BASED),n.setFeeConfig(e.feeConfig)),e.pfpBuffer&&e.pfpFileName?0===e.pfpBuffer.byteLength?this.logger.warn("Provided PFP buffer is empty. Skipping profile picture."):(this.logger.info(`Setting profile picture: ${e.pfpFileName} (${e.pfpBuffer.byteLength} bytes)`),n.setProfilePicture(e.pfpBuffer,e.pfpFileName)):this.logger.warn("Profile picture not provided in metadata. Agent creation might fail if required by the underlying SDK builder."),e.social&&Object.entries(e.social).forEach(([e,t])=>{n.addSocial(e,t)}),e.properties&&Object.entries(e.properties).forEach(([e,t])=>{n.addProperty(e,t)});try{const t=Boolean(e?.feeConfig),o=await this.standardClient.createAndRegisterAgent(n,{initialBalance:t?50:void 0});return o?.metadata?.inboundTopicId&&o?.metadata?.outboundTopicId&&(this.agentChannels={inboundTopicId:o.metadata.inboundTopicId,outboundTopicId:o.metadata.outboundTopicId}),o}catch(o){throw this.logger.error("Error during agent creation/registration:",o),new Error(`Failed to create/register agent: ${o instanceof Error?o.message:String(o)}`)}}async sendMessage(e,t,n,o){this.useEncryption;try{const i=await this.standardClient.sendMessage(e,t,n,o);return i.topicSequenceNumber?.toNumber()}catch(i){throw this.logger.error(`Error sending message to topic ${e}:`,i),new Error(`Failed to send message: ${i instanceof Error?i.message:String(i)}`)}}async getMessages(e){try{const t=(await this.standardClient.getMessages(e)).messages.map(e=>{const t=e?.created?.getTime()||0;return{...e,timestamp:t,data:e.data,sequence_number:e.sequence_number}});return t.sort((e,t)=>e.timestamp-t.timestamp),{messages:t}}catch(t){return this.logger.error(`Error getting messages from topic ${e}:`,t),{messages:[]}}}async getMessageStream(e){return this.standardClient.getMessageStream(e)}async getMessageContent(e){try{return await this.standardClient.getMessageContent(e)}catch(t){throw this.logger.error(`Error retrieving message content for: ${e}`,t),new Error(`Failed to retrieve message content: ${t instanceof Error?t.message:String(t)}`)}}async getInboundTopicId(){try{const e=this.getOperatorId();this.logger.info(`[HCS10Client] Retrieving profile for operator ${e} to find inbound topic...`);const t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.inboundTopic)return this.logger.info(`[HCS10Client] Found inbound topic for operator ${e}: ${t.topicInfo.inboundTopic}`),t.topicInfo.inboundTopic;throw new Error(`Could not retrieve inbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}catch(e){this.logger.error(`[HCS10Client] Error fetching operator's inbound topic ID (${this.getOperatorId()}):`,e);const t=this.getOperatorId();let n=`Failed to get inbound topic ID for operator ${t}.`;throw e instanceof Error&&e.message.includes("does not have a valid HCS-11 memo")?n+=` The account profile may not exist or is invalid. Please ensure this operator account (${t}) is registered as an HCS-10 agent. You might need to register it first (e.g., using the 'register_agent' tool or SDK function).`:e instanceof Error?n+=` Reason: ${e.message}`:n+=` Unexpected error: ${String(e)}`,new Error(n)}}getAccountAndSigner(){const e=this.standardClient.getAccountAndSigner();return{accountId:e.accountId,signer:e.signer}}async getOutboundTopicId(){const e=this.getOperatorId(),t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.outboundTopic)return t.topicInfo.outboundTopic;throw new Error(`Could not retrieve outbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}setClient(e,n){return this.standardClient=new t.HCS10Client({network:this.getNetwork(),operatorId:e,operatorPrivateKey:n,guardedRegistryBaseUrl:this.guardedRegistryBaseUrl}),this.standardClient}async validateOperator(e){try{this.setClient(e.accountId,e.privateKey);return{isValid:!0,operator:{accountId:this.getOperatorId()}}}catch(t){return this.logger.error(`Validation error: ${t}`),{isValid:!1,error:t instanceof Error?t.message:String(t)}}}async initializeWithValidation(e){const t=await this.validateOperator(e);return t.isValid&&e.stateManager&&e.stateManager.initializeConnectionsManager(this.standardClient),t}},exports.HbarPricePlugin=k,exports.InitiateConnectionTool=h,exports.ListConnectionsTool=f,exports.ListUnapprovedConnectionRequestsTool=M,exports.ManageConnectionRequestsTool=A,exports.OpenConvaiState=P,exports.RegisterAgentTool=u,exports.RetrieveProfileTool=S,exports.SendMessageToConnectionTool=l,exports.initializeStandardsAgentKit=async n=>{const o=n?.clientConfig||{},i=o.operatorId||process.env.HEDERA_OPERATOR_ID,r=o.operatorKey||process.env.HEDERA_OPERATOR_KEY,s=o.network||process.env.HEDERA_NETWORK||"testnet";let a;if("mainnet"===s?a="mainnet":("testnet"===s||console.warn(`Unsupported network specified: '${s}'. Defaulting to 'testnet'.`),a="testnet"),!i||!r)throw new Error("Operator ID and private key must be provided either through options or environment variables.");const c="true"===process.env.DISABLE_LOGGING,d=t.Logger.getInstance({level:o.logLevel||"info",silent:c}),g=n?.stateManager||new P({defaultEnvFilePath:E,defaultPrefix:"TODD"});d.info("State manager initialized");const p=new e.ServerSigner(i,r,a),m=new e.HederaAgentKit(p);await m.initialize(),d.info(`HederaAgentKit initialized for ${i} on ${a}`);const w=new N(m,g,{useEncryption:o.useEncryption,registryUrl:o.registryUrl,logLevel:o.logLevel});let y,v;if(n?.monitoringClient){const t=new e.ServerSigner(i,r,a);y=new e.HederaAgentKit(t),await y.initialize(),v=new N(y,g,{useEncryption:o.useEncryption,registryUrl:o.registryUrl,logLevel:"error"}),d.info("Monitoring client initialized")}const T={};return T.registerAgentTool=new u({hederaKit:m,hcs10Builder:w,logger:void 0}),n?.createAllTools&&(T.findRegistrationsTool=new b({hederaKit:m,hcs10Builder:w,logger:void 0}),T.retrieveProfileTool=new S({hederaKit:m,hcs10Builder:w,logger:void 0}),T.initiateConnectionTool=new h({hederaKit:m,hcs10Builder:w,logger:void 0}),T.listConnectionsTool=new f({hederaKit:m,hcs10Builder:w,logger:void 0}),T.sendMessageToConnectionTool=new l({hederaKit:m,hcs10Builder:w,logger:void 0}),T.checkMessagesTool=new I({hederaKit:m,hcs10Builder:w,logger:void 0}),T.connectionMonitorTool=new C({hederaKit:y||m,hcs10Builder:v||w,logger:void 0}),T.manageConnectionRequestsTool=new A({hederaKit:m,hcs10Builder:w,logger:void 0}),T.acceptConnectionRequestTool=new q({hederaKit:m,hcs10Builder:w,logger:void 0}),T.listUnapprovedConnectionRequestsTool=new M({hederaKit:m,hcs10Builder:w,logger:void 0}),d.info("All tools initialized")),{hederaKit:m,hcs10Builder:w,monitoringHederaKit:y,monitoringHcs10Builder:v,tools:T,stateManager:g}};
2
2
  //# sourceMappingURL=standards-agent-kit.cjs.map