@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,22 +1,37 @@
1
- import { HCS10Client as HCS10Client$1, Logger, AgentBuilder, AIAgentCapability, InboundTopicType } from "@hashgraphonline/standards-sdk";
2
- import { encryptMessage } from "./standards-agent-kit.es25.js";
3
- class HCS10Client {
4
- constructor(operatorId, operatorPrivateKey, network, options) {
1
+ import { BaseServiceBuilder } from "hedera-agent-kit";
2
+ import { Logger, HCS10Client as HCS10Client$1, AgentBuilder, AIAgentCapability, InboundTopicType, FeeConfigBuilder } from "@hashgraphonline/standards-sdk";
3
+ import fs from "fs";
4
+ import path from "path";
5
+ import axios from "axios";
6
+ const NOT_INITIALIZED_ERROR = "ConnectionsManager not initialized";
7
+ class HCS10Builder extends BaseServiceBuilder {
8
+ constructor(hederaKit, stateManager, options) {
9
+ super(hederaKit);
10
+ this.stateManager = stateManager;
11
+ this.useEncryption = options?.useEncryption || false;
12
+ this.guardedRegistryBaseUrl = options?.registryUrl || "";
13
+ const network = this.hederaKit.client.network;
14
+ this.network = network.toString().includes("mainnet") ? "mainnet" : "testnet";
15
+ const operatorId = this.hederaKit.signer.getAccountId().toString();
16
+ const operatorPrivateKey = this.hederaKit.signer?.getOperatorPrivateKey() ? this.hederaKit.signer.getOperatorPrivateKey().toStringRaw() : "";
17
+ this.sdkLogger = new Logger({
18
+ module: "HCS10Builder",
19
+ level: options?.logLevel || "info"
20
+ });
5
21
  this.standardClient = new HCS10Client$1({
6
- network,
22
+ network: this.network,
7
23
  operatorId,
8
24
  operatorPrivateKey,
9
- guardedRegistryBaseUrl: options?.registryUrl,
10
- logLevel: options?.logLevel
11
- });
12
- this.guardedRegistryBaseUrl = options?.registryUrl || "";
13
- this.useEncryption = options?.useEncryption || false;
14
- const shouldSilence = process.env.DISABLE_LOGGING === "true";
15
- this.logger = new Logger({
16
- level: options?.logLevel || "info",
17
- silent: shouldSilence
25
+ guardedRegistryBaseUrl: this.guardedRegistryBaseUrl,
26
+ logLevel: options?.logLevel || "info"
18
27
  });
28
+ if (this.stateManager) {
29
+ this.stateManager.initializeConnectionsManager(this.standardClient);
30
+ }
19
31
  }
32
+ /**
33
+ * Get the operator account ID
34
+ */
20
35
  getOperatorId() {
21
36
  const operator = this.standardClient.getClient().operatorAccountId;
22
37
  if (!operator) {
@@ -24,36 +39,75 @@ class HCS10Client {
24
39
  }
25
40
  return operator.toString();
26
41
  }
42
+ /**
43
+ * Get the network type
44
+ */
27
45
  getNetwork() {
28
- return this.standardClient.getNetwork();
46
+ return this.network;
29
47
  }
30
- async handleConnectionRequest(inboundTopicId, requestingAccountId, connectionRequestId, feeConfig) {
48
+ /**
49
+ * Get account and signer information
50
+ */
51
+ getAccountAndSigner() {
52
+ const result = this.standardClient.getAccountAndSigner();
53
+ return {
54
+ accountId: result.accountId,
55
+ signer: result.signer
56
+ };
57
+ }
58
+ /**
59
+ * Get the inbound topic ID for the current operator
60
+ */
61
+ async getInboundTopicId() {
31
62
  try {
32
- const result = await this.standardClient.handleConnectionRequest(
33
- inboundTopicId,
34
- requestingAccountId,
35
- connectionRequestId,
36
- feeConfig
63
+ const operatorId = this.getOperatorId();
64
+ this.logger.info(
65
+ `[HCS10Builder] Retrieving profile for operator ${operatorId} to find inbound topic...`
37
66
  );
38
- return result;
67
+ const profileResponse = await this.getAgentProfile(operatorId);
68
+ if (profileResponse.success && profileResponse.topicInfo?.inboundTopic) {
69
+ this.logger.info(
70
+ `[HCS10Builder] Found inbound topic for operator ${operatorId}: ${profileResponse.topicInfo.inboundTopic}`
71
+ );
72
+ return profileResponse.topicInfo.inboundTopic;
73
+ } else {
74
+ throw new Error(
75
+ `Could not retrieve inbound topic from profile for ${operatorId}. Profile success: ${profileResponse.success}, Error: ${profileResponse.error}`
76
+ );
77
+ }
39
78
  } catch (error) {
40
79
  this.logger.error(
41
- `Error handling connection request #${connectionRequestId} for topic ${inboundTopicId}:`,
80
+ `[HCS10Builder] Error fetching operator's inbound topic ID (${this.getOperatorId()}):`,
42
81
  error
43
82
  );
44
- throw new Error(
45
- `Failed to handle connection request: ${error instanceof Error ? error.message : String(error)}`
46
- );
83
+ const operatorId = this.getOperatorId();
84
+ let detailedMessage = `Failed to get inbound topic ID for operator ${operatorId}.`;
85
+ if (error instanceof Error && error.message.includes("does not have a valid HCS-11 memo")) {
86
+ detailedMessage += ` The account profile may not exist or is invalid. Please ensure this operator account (${operatorId}) is registered as an HCS-10 agent. You might need to register it first (e.g., using the 'register_agent' tool or SDK function).`;
87
+ } else if (error instanceof Error) {
88
+ detailedMessage += ` Reason: ${error.message}`;
89
+ } else {
90
+ detailedMessage += ` Unexpected error: ${String(error)}`;
91
+ }
92
+ throw new Error(detailedMessage);
47
93
  }
48
94
  }
49
95
  /**
50
- * Retrieves the profile for a given account ID using the standard SDK.
96
+ * Get agent profile
51
97
  */
52
98
  async getAgentProfile(accountId) {
53
- return this.standardClient.retrieveProfile(accountId);
99
+ try {
100
+ return await this.standardClient.retrieveProfile(accountId);
101
+ } catch (error) {
102
+ this.logger.error(
103
+ `[HCS10Builder] Error retrieving agent profile for account ${accountId}:`,
104
+ error
105
+ );
106
+ throw error;
107
+ }
54
108
  }
55
109
  /**
56
- * Exposes the standard SDK's submitConnectionRequest method.
110
+ * Submit connection request
57
111
  */
58
112
  async submitConnectionRequest(inboundTopicId, memo) {
59
113
  return this.standardClient.submitConnectionRequest(
@@ -62,105 +116,54 @@ class HCS10Client {
62
116
  );
63
117
  }
64
118
  /**
65
- * Exposes the standard SDK's waitForConnectionConfirmation method.
119
+ * Handle connection request
66
120
  */
67
- async waitForConnectionConfirmation(outboundTopicId, connectionRequestId, maxAttempts = 60, delayMs = 2e3) {
68
- return this.standardClient.waitForConnectionConfirmation(
69
- outboundTopicId,
70
- connectionRequestId,
71
- maxAttempts,
72
- delayMs
73
- );
74
- }
75
- /**
76
- * Creates and registers an agent using the standard SDK's HCS10Client.
77
- * This handles account creation, key generation, topic setup, and registration.
78
- *
79
- * When metadata includes fee configuration:
80
- * 1. The properties.feeConfig will be passed to the AgentBuilder
81
- * 2. The properties.inboundTopicType will be set to FEE_BASED
82
- * 3. The SDK's createAndRegisterAgent will apply the fees to the agent's inbound topic
83
- *
84
- * @param metadata - The agent's metadata, potentially including pfpBuffer, pfpFileName,
85
- * and fee configuration in properties.feeConfig
86
- * @returns The registration result from the standard SDK, containing accountId, keys, topics etc.
87
- */
88
- async createAndRegisterAgent(metadata) {
89
- const builder = new AgentBuilder().setName(metadata.name).setBio(metadata.description || "").setCapabilities(
90
- metadata.capabilities ? metadata.capabilities : [AIAgentCapability.TEXT_GENERATION]
91
- ).setType(metadata.type || "autonomous").setModel(metadata.model || "agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(InboundTopicType.PUBLIC);
92
- if (metadata?.feeConfig) {
93
- builder.setInboundTopicType(InboundTopicType.FEE_BASED);
94
- builder.setFeeConfig(metadata.feeConfig);
95
- }
96
- if (metadata.pfpBuffer && metadata.pfpFileName) {
97
- if (metadata.pfpBuffer.byteLength === 0) {
98
- this.logger.warn(
99
- "Provided PFP buffer is empty. Skipping profile picture."
100
- );
101
- } else {
102
- this.logger.info(
103
- `Setting profile picture: ${metadata.pfpFileName} (${metadata.pfpBuffer.byteLength} bytes)`
104
- );
105
- builder.setProfilePicture(metadata.pfpBuffer, metadata.pfpFileName);
106
- }
107
- } else {
108
- this.logger.warn(
109
- "Profile picture not provided in metadata. Agent creation might fail if required by the underlying SDK builder."
110
- );
111
- }
112
- if (metadata.social) {
113
- Object.entries(metadata.social).forEach(([platform, handle]) => {
114
- builder.addSocial(platform, handle);
115
- });
116
- }
117
- if (metadata.properties) {
118
- Object.entries(metadata.properties).forEach(([key, value]) => {
119
- builder.addProperty(key, value);
120
- });
121
- }
121
+ async handleConnectionRequest(inboundTopicId, requestingAccountId, connectionRequestId, feeConfig) {
122
122
  try {
123
- const hasFees = Boolean(metadata?.feeConfig);
124
- const result = await this.standardClient.createAndRegisterAgent(builder, {
125
- initialBalance: hasFees ? 50 : void 0
126
- });
127
- if (result?.metadata?.inboundTopicId && result?.metadata?.outboundTopicId) {
128
- this.agentChannels = {
129
- inboundTopicId: result.metadata.inboundTopicId,
130
- outboundTopicId: result.metadata.outboundTopicId
131
- };
123
+ const result = await this.standardClient.handleConnectionRequest(
124
+ inboundTopicId,
125
+ requestingAccountId,
126
+ connectionRequestId,
127
+ feeConfig
128
+ );
129
+ if (result && result.connectionTopicId && typeof result.connectionTopicId === "object" && "toString" in result.connectionTopicId) {
130
+ result.connectionTopicId = result.connectionTopicId.toString();
132
131
  }
133
132
  return result;
134
133
  } catch (error) {
135
- this.logger.error("Error during agent creation/registration:", error);
134
+ this.logger.error(
135
+ `Error handling connection request #${connectionRequestId} for topic ${inboundTopicId}:`,
136
+ error
137
+ );
136
138
  throw new Error(
137
- `Failed to create/register agent: ${error instanceof Error ? error.message : String(error)}`
139
+ `Failed to handle connection request: ${error instanceof Error ? error.message : String(error)}`
138
140
  );
139
141
  }
140
142
  }
141
143
  /**
142
- * Sends a structured HCS-10 message to the specified topic using the standard SDK client.
143
- * Handles potential inscription for large messages.
144
- *
145
- * @param topicId - The target topic ID (likely a connection topic).
146
- * @param operatorId - The operator ID string (e.g., "inboundTopic@accountId").
147
- * @param data - The actual message content/data.
148
- * @param memo - Optional memo for the message.
149
- * @param submitKey - Optional private key for topics requiring specific submit keys.
150
- * @returns A confirmation status string from the transaction receipt.
144
+ * Send message to a topic
151
145
  */
152
- async sendMessage(topicId, data, memo, submitKey) {
153
- if (this.useEncryption) {
154
- data = encryptMessage(data);
146
+ async sendMessage(topicId, data, memo) {
147
+ if (topicId && typeof topicId === "object" && "toString" in topicId) {
148
+ topicId = topicId?.toString();
149
+ }
150
+ if (!topicId || typeof topicId !== "string") {
151
+ throw new Error(
152
+ `Invalid topic ID provided to sendMessage: ${JSON.stringify(topicId)}`
153
+ );
155
154
  }
156
155
  try {
157
156
  const messageResponse = await this.standardClient.sendMessage(
158
157
  topicId,
159
158
  data,
160
159
  memo,
161
- submitKey
160
+ void 0
162
161
  );
163
- return messageResponse.topicSequenceNumber?.toNumber();
162
+ return {
163
+ sequenceNumber: messageResponse.topicSequenceNumber?.toNumber(),
164
+ receipt: messageResponse,
165
+ transactionId: "transactionId" in messageResponse ? messageResponse.transactionId?.toString() : void 0
166
+ };
164
167
  } catch (error) {
165
168
  this.logger.error(`Error sending message to topic ${topicId}:`, error);
166
169
  throw new Error(
@@ -169,12 +172,17 @@ class HCS10Client {
169
172
  }
170
173
  }
171
174
  /**
172
- * Retrieves messages from a topic using the standard SDK client.
173
- *
174
- * @param topicId - The topic ID to get messages from.
175
- * @returns Messages from the topic, mapped to the expected format.
175
+ * Get messages from a topic
176
176
  */
177
177
  async getMessages(topicId) {
178
+ if (topicId && typeof topicId === "object" && "toString" in topicId) {
179
+ topicId = topicId?.toString();
180
+ }
181
+ if (!topicId || typeof topicId !== "string") {
182
+ throw new Error(
183
+ `Invalid topic ID provided to getMessages: ${JSON.stringify(topicId)}`
184
+ );
185
+ }
178
186
  try {
179
187
  const result = await this.standardClient.getMessages(topicId);
180
188
  const mappedMessages = result.messages.map((sdkMessage) => {
@@ -182,8 +190,9 @@ class HCS10Client {
182
190
  return {
183
191
  ...sdkMessage,
184
192
  timestamp,
185
- data: sdkMessage.data,
186
- sequence_number: sdkMessage.sequence_number
193
+ data: sdkMessage.data || "",
194
+ sequence_number: sdkMessage.sequence_number,
195
+ p: "hcs-10"
187
196
  };
188
197
  });
189
198
  mappedMessages.sort(
@@ -195,13 +204,24 @@ class HCS10Client {
195
204
  return { messages: [] };
196
205
  }
197
206
  }
207
+ /**
208
+ * Get message stream from a topic
209
+ */
198
210
  async getMessageStream(topicId) {
211
+ if (topicId && typeof topicId === "object" && "toString" in topicId) {
212
+ topicId = topicId?.toString();
213
+ }
214
+ if (!topicId || typeof topicId !== "string") {
215
+ throw new Error(
216
+ `Invalid topic ID provided to getMessageStream: ${JSON.stringify(
217
+ topicId
218
+ )}`
219
+ );
220
+ }
199
221
  return this.standardClient.getMessageStream(topicId);
200
222
  }
201
223
  /**
202
- * Retrieves content from an inscribed message using the standard SDK client.
203
- * @param inscriptionIdOrData - The inscription ID (hcs://...) or potentially raw data string.
204
- * @returns The resolved message content.
224
+ * Get message content
205
225
  */
206
226
  async getMessageContent(inscriptionIdOrData) {
207
227
  try {
@@ -220,112 +240,1285 @@ class HCS10Client {
220
240
  }
221
241
  }
222
242
  /**
223
- * Retrieves the inbound topic ID associated with the current operator.
224
- * This typically involves fetching the operator's own HCS-10 profile.
225
- * @returns A promise that resolves to the operator's inbound topic ID.
226
- * @throws {Error} If the operator ID cannot be determined or the profile/topic cannot be retrieved.
243
+ * Get the standard client instance (for compatibility)
227
244
  */
228
- async getInboundTopicId() {
245
+ getStandardClient() {
246
+ return this.standardClient;
247
+ }
248
+ /**
249
+ * Load profile picture from URL or file path
250
+ */
251
+ async loadProfilePicture(profilePicture) {
229
252
  try {
230
- const operatorId = this.getOperatorId();
231
- this.logger.info(
232
- `[HCS10Client] Retrieving profile for operator ${operatorId} to find inbound topic...`
233
- );
234
- const profileResponse = await this.getAgentProfile(operatorId);
235
- if (profileResponse.success && profileResponse.topicInfo?.inboundTopic) {
253
+ if (!profilePicture) {
254
+ return null;
255
+ }
256
+ if (typeof profilePicture === "string") {
257
+ const isUrl = profilePicture.startsWith("http://") || profilePicture.startsWith("https://");
258
+ if (isUrl) {
259
+ this.logger.info(
260
+ `Loading profile picture from URL: ${profilePicture}`
261
+ );
262
+ const response = await axios.get(profilePicture, {
263
+ responseType: "arraybuffer"
264
+ });
265
+ const buffer = Buffer.from(response.data);
266
+ const urlPathname = new URL(profilePicture).pathname;
267
+ const filename = path.basename(urlPathname) || "profile.png";
268
+ return { buffer, filename };
269
+ } else {
270
+ if (!fs.existsSync(profilePicture)) {
271
+ this.logger.warn(
272
+ `Profile picture file not found: ${profilePicture}`
273
+ );
274
+ return null;
275
+ }
276
+ this.logger.info(
277
+ `Loading profile picture from file: ${profilePicture}`
278
+ );
279
+ const buffer = fs.readFileSync(profilePicture);
280
+ const filename = path.basename(profilePicture);
281
+ return { buffer, filename };
282
+ }
283
+ } else if (profilePicture.url) {
236
284
  this.logger.info(
237
- `[HCS10Client] Found inbound topic for operator ${operatorId}: ${profileResponse.topicInfo.inboundTopic}`
285
+ `Loading profile picture from URL: ${profilePicture.url}`
286
+ );
287
+ const response = await axios.get(profilePicture.url, {
288
+ responseType: "arraybuffer"
289
+ });
290
+ const buffer = Buffer.from(response.data);
291
+ const filename = profilePicture.filename || "profile.png";
292
+ return { buffer, filename };
293
+ } else if (profilePicture.path) {
294
+ if (!fs.existsSync(profilePicture.path)) {
295
+ this.logger.warn(
296
+ `Profile picture file not found: ${profilePicture.path}`
297
+ );
298
+ return null;
299
+ }
300
+ this.logger.info(
301
+ `Loading profile picture from file: ${profilePicture.path}`
302
+ );
303
+ const buffer = fs.readFileSync(profilePicture.path);
304
+ const filename = profilePicture.filename || path.basename(profilePicture.path);
305
+ return { buffer, filename };
306
+ }
307
+ return null;
308
+ } catch (error) {
309
+ this.logger.error("Failed to load profile picture:", error);
310
+ return null;
311
+ }
312
+ }
313
+ /**
314
+ * Create and register an agent
315
+ */
316
+ async createAndRegisterAgent(data) {
317
+ const builder = new AgentBuilder().setName(data.name).setBio(data.bio || "").setCapabilities(
318
+ data.capabilities || [AIAgentCapability.TEXT_GENERATION]
319
+ ).setType(data.type || "autonomous").setModel(data.model || "agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(InboundTopicType.PUBLIC);
320
+ if (data.alias) {
321
+ builder.setAlias(data.alias);
322
+ }
323
+ if (data.creator) {
324
+ builder.setCreator(data.creator);
325
+ }
326
+ if (data?.feeConfig) {
327
+ builder.setInboundTopicType(InboundTopicType.FEE_BASED);
328
+ builder.setFeeConfig(data.feeConfig);
329
+ }
330
+ if (data.existingProfilePictureTopicId) {
331
+ builder.setExistingProfilePicture(data.existingProfilePictureTopicId);
332
+ } else if (data.pfpBuffer && data.pfpFileName) {
333
+ if (data.pfpBuffer.byteLength === 0) {
334
+ this.logger.warn(
335
+ "Provided PFP buffer is empty. Skipping profile picture."
238
336
  );
239
- return profileResponse.topicInfo.inboundTopic;
240
337
  } else {
338
+ this.logger.info(
339
+ `Setting profile picture: ${data.pfpFileName} (${data.pfpBuffer.byteLength} bytes)`
340
+ );
341
+ builder.setProfilePicture(data.pfpBuffer, data.pfpFileName);
342
+ }
343
+ } else {
344
+ this.logger.warn(
345
+ "Profile picture not provided. Agent creation might fail if required by the underlying SDK builder."
346
+ );
347
+ }
348
+ if (data.socials) {
349
+ Object.entries(data.socials).forEach(([platform, handle]) => {
350
+ builder.addSocial(platform, handle);
351
+ });
352
+ }
353
+ if (data.properties) {
354
+ Object.entries(data.properties).forEach(([key, value]) => {
355
+ builder.addProperty(key, value);
356
+ });
357
+ }
358
+ try {
359
+ const hasFees = Boolean(data?.feeConfig);
360
+ const result = await this.standardClient.createAndRegisterAgent(builder, {
361
+ initialBalance: hasFees ? 50 : 10
362
+ });
363
+ return result;
364
+ } catch (error) {
365
+ this.logger.error("Error during agent creation/registration:", error);
366
+ throw new Error(
367
+ `Failed to create/register agent: ${error instanceof Error ? error.message : String(error)}`
368
+ );
369
+ }
370
+ }
371
+ /**
372
+ * Register a new HCS-10 agent
373
+ * Note: This performs multiple transactions and requires directExecution mode
374
+ */
375
+ async registerAgent(params) {
376
+ this.clearNotes();
377
+ if (this.hederaKit.operationalMode === "returnBytes") {
378
+ throw new Error(
379
+ "Agent registration requires multiple transactions and cannot be performed in returnBytes mode. Please use autonomous mode."
380
+ );
381
+ }
382
+ try {
383
+ let profilePictureData = null;
384
+ if (params.profilePicture) {
385
+ profilePictureData = await this.loadProfilePicture(
386
+ params.profilePicture
387
+ );
388
+ }
389
+ const registrationData = {
390
+ name: params.name,
391
+ ...params.bio !== void 0 && { bio: params.bio },
392
+ ...params.alias !== void 0 && { alias: params.alias },
393
+ ...params.type !== void 0 && { type: params.type },
394
+ ...params.model !== void 0 && { model: params.model },
395
+ ...params.capabilities !== void 0 && {
396
+ capabilities: params.capabilities
397
+ },
398
+ ...params.creator !== void 0 && { creator: params.creator },
399
+ ...params.socials !== void 0 && { socials: params.socials },
400
+ ...params.properties !== void 0 && {
401
+ properties: params.properties
402
+ },
403
+ ...params.existingProfilePictureTopicId !== void 0 && {
404
+ existingProfilePictureTopicId: params.existingProfilePictureTopicId
405
+ },
406
+ ...profilePictureData?.buffer !== void 0 && {
407
+ pfpBuffer: profilePictureData.buffer
408
+ },
409
+ ...profilePictureData?.filename !== void 0 && {
410
+ pfpFileName: profilePictureData.filename
411
+ }
412
+ };
413
+ if (params.hbarFee && params.hbarFee > 0) {
414
+ const feeConfigBuilder = new FeeConfigBuilder({
415
+ network: this.network,
416
+ logger: this.sdkLogger
417
+ });
418
+ const { accountId: collectorAccountId } = this.getAccountAndSigner();
419
+ if (!collectorAccountId) {
420
+ throw new Error("Could not determine account ID for fee collection.");
421
+ }
422
+ this.addNote(
423
+ `Setting the operator account (${collectorAccountId}) as the fee collector since no specific collector was provided.`
424
+ );
425
+ const effectiveExemptIds = params.exemptAccountIds?.filter(
426
+ (id) => id !== collectorAccountId && id.startsWith("0.0")
427
+ ) || [];
428
+ registrationData.feeConfig = feeConfigBuilder.addHbarFee(
429
+ params.hbarFee,
430
+ collectorAccountId,
431
+ effectiveExemptIds
432
+ );
433
+ }
434
+ const result = await this.createAndRegisterAgent(registrationData);
435
+ this.executeResult = {
436
+ success: true,
437
+ transactionId: result.transactionId,
438
+ receipt: void 0,
439
+ scheduleId: void 0,
440
+ rawResult: {
441
+ ...result,
442
+ name: params.name,
443
+ accountId: result?.metadata?.accountId || result.state?.agentMetadata?.accountId
444
+ }
445
+ };
446
+ } catch (error) {
447
+ this.logger.error("Failed to register agent:", error);
448
+ throw error;
449
+ }
450
+ return this;
451
+ }
452
+ /**
453
+ * Initiate a connection to another agent
454
+ */
455
+ async initiateConnection(params) {
456
+ this.clearNotes();
457
+ try {
458
+ const targetProfile = await this.getAgentProfile(params.targetAccountId);
459
+ if (!targetProfile.success || !targetProfile.topicInfo?.inboundTopic) {
241
460
  throw new Error(
242
- `Could not retrieve inbound topic from profile for ${operatorId}. Profile success: ${profileResponse.success}, Error: ${profileResponse.error}`
461
+ `Could not retrieve inbound topic for target account ${params.targetAccountId}`
243
462
  );
244
463
  }
464
+ const targetInboundTopicId = targetProfile.topicInfo.inboundTopic;
465
+ let memo;
466
+ if (params.memo !== void 0) {
467
+ memo = params.memo;
468
+ } else {
469
+ memo = params.disableMonitor ? "false" : "true";
470
+ this.addNote(
471
+ `No custom memo was provided. Using default memo '${memo}' based on monitoring preference.`
472
+ );
473
+ }
474
+ if (!params.disableMonitor) {
475
+ this.addNote(
476
+ `Monitoring will be enabled for this connection request as disableMonitor was not specified.`
477
+ );
478
+ }
479
+ const result = await this.submitConnectionRequest(
480
+ targetInboundTopicId,
481
+ memo
482
+ );
483
+ this.executeResult = {
484
+ success: true,
485
+ transactionId: "transactionId" in result ? result.transactionId?.toString() : void 0,
486
+ receipt: result,
487
+ scheduleId: void 0,
488
+ rawResult: {
489
+ targetAccountId: params.targetAccountId,
490
+ targetInboundTopicId,
491
+ connectionRequestSent: true,
492
+ monitoringEnabled: !params.disableMonitor,
493
+ ...result
494
+ }
495
+ };
245
496
  } catch (error) {
246
- this.logger.error(
247
- `[HCS10Client] Error fetching operator's inbound topic ID (${this.getOperatorId()}):`,
248
- error
497
+ this.logger.error("Failed to initiate connection:", error);
498
+ throw error;
499
+ }
500
+ return this;
501
+ }
502
+ /**
503
+ * Accept a connection request
504
+ * Note: This performs multiple transactions and requires directExecution mode
505
+ */
506
+ async acceptConnection(params) {
507
+ this.clearNotes();
508
+ if (this.hederaKit.operationalMode === "returnBytes") {
509
+ throw new Error(
510
+ "Accepting connections requires multiple transactions and cannot be performed in returnBytes mode. Please use autonomous mode."
249
511
  );
250
- const operatorId = this.getOperatorId();
251
- let detailedMessage = `Failed to get inbound topic ID for operator ${operatorId}.`;
252
- if (error instanceof Error && error.message.includes("does not have a valid HCS-11 memo")) {
253
- detailedMessage += ` The account profile may not exist or is invalid. Please ensure this operator account (${operatorId}) is registered as an HCS-10 agent. You might need to register it first (e.g., using the 'register_agent' tool or SDK function).`;
254
- } else if (error instanceof Error) {
255
- detailedMessage += ` Reason: ${error.message}`;
512
+ }
513
+ try {
514
+ const currentAgent = this.stateManager?.getCurrentAgent();
515
+ if (!currentAgent) {
516
+ throw new Error(
517
+ "Cannot accept connection request. No agent is currently active. Please register or select an agent first."
518
+ );
519
+ }
520
+ const connectionsManager = this.stateManager?.getConnectionsManager();
521
+ if (!connectionsManager) {
522
+ throw new Error(NOT_INITIALIZED_ERROR);
523
+ }
524
+ await connectionsManager.fetchConnectionData(currentAgent.accountId);
525
+ const allRequests = [
526
+ ...connectionsManager.getPendingRequests(),
527
+ ...connectionsManager.getConnectionsNeedingConfirmation()
528
+ ];
529
+ const request = allRequests.find(
530
+ (r) => r.uniqueRequestKey === params.requestKey || r.connectionRequestId?.toString() === params.requestKey || r.inboundRequestId?.toString() === params.requestKey
531
+ );
532
+ if (!request) {
533
+ throw new Error(
534
+ `Request with key ${params.requestKey} not found or no longer pending.`
535
+ );
536
+ }
537
+ if (!request.needsConfirmation || !request.inboundRequestId) {
538
+ throw new Error(
539
+ `Request with key ${params.requestKey} is not an inbound request that can be accepted.`
540
+ );
541
+ }
542
+ const targetAccountId = request.targetAccountId;
543
+ const inboundRequestId = request.inboundRequestId;
544
+ let feeConfig;
545
+ if (params.hbarFee && params.hbarFee > 0) {
546
+ const feeConfigBuilder = new FeeConfigBuilder({
547
+ network: this.network,
548
+ logger: this.sdkLogger
549
+ });
550
+ const { accountId: collectorAccountId } = this.getAccountAndSigner();
551
+ if (!collectorAccountId) {
552
+ throw new Error("Could not determine account ID for fee collection.");
553
+ }
554
+ this.addNote(
555
+ `Setting the operator account (${collectorAccountId}) as the fee collector since no specific collector was provided.`
556
+ );
557
+ const effectiveExemptIds = params.exemptAccountIds?.filter(
558
+ (id) => id !== collectorAccountId && id.startsWith("0.0")
559
+ ) || [];
560
+ feeConfig = feeConfigBuilder.addHbarFee(
561
+ params.hbarFee,
562
+ collectorAccountId,
563
+ effectiveExemptIds
564
+ );
565
+ }
566
+ const inboundTopicId = await this.getInboundTopicId();
567
+ const confirmationResult = await this.handleConnectionRequest(
568
+ inboundTopicId,
569
+ targetAccountId,
570
+ inboundRequestId,
571
+ feeConfig
572
+ );
573
+ let connectionTopicId = confirmationResult?.connectionTopicId;
574
+ if (connectionTopicId && typeof connectionTopicId === "object" && "toString" in connectionTopicId) {
575
+ connectionTopicId = connectionTopicId?.toString();
576
+ }
577
+ if (!connectionTopicId || typeof connectionTopicId !== "string") {
578
+ throw new Error(
579
+ `Failed to create connection topic. Got: ${JSON.stringify(
580
+ connectionTopicId
581
+ )}`
582
+ );
583
+ }
584
+ if (this.stateManager) {
585
+ const targetAgentName = request.targetAgentName || `Agent ${targetAccountId}`;
586
+ if (!request.targetAgentName) {
587
+ this.addNote(
588
+ `No agent name was provided in the connection request, using default name 'Agent ${targetAccountId}'.`
589
+ );
590
+ }
591
+ let targetInboundTopicId = request.targetInboundTopicId || "";
592
+ if (!targetInboundTopicId) {
593
+ try {
594
+ const targetProfile = await this.getAgentProfile(targetAccountId);
595
+ if (targetProfile.success && targetProfile.topicInfo?.inboundTopic) {
596
+ targetInboundTopicId = targetProfile.topicInfo.inboundTopic;
597
+ }
598
+ } catch (profileError) {
599
+ this.logger.warn(
600
+ `Could not fetch profile for ${targetAccountId}:`,
601
+ profileError
602
+ );
603
+ }
604
+ }
605
+ const newConnection = {
606
+ connectionId: `conn-${Date.now()}`,
607
+ targetAccountId,
608
+ targetAgentName,
609
+ targetInboundTopicId,
610
+ connectionTopicId,
611
+ status: "established",
612
+ created: /* @__PURE__ */ new Date()
613
+ };
614
+ this.stateManager.addActiveConnection(newConnection);
615
+ connectionsManager.markConnectionRequestProcessed(
616
+ request.targetInboundTopicId || "",
617
+ inboundRequestId
618
+ );
619
+ }
620
+ this.executeResult = {
621
+ success: true,
622
+ transactionId: void 0,
623
+ receipt: void 0,
624
+ scheduleId: void 0,
625
+ rawResult: {
626
+ targetAccountId,
627
+ connectionTopicId,
628
+ feeConfigured: !!params.hbarFee,
629
+ hbarFee: params.hbarFee || 0,
630
+ confirmationResult
631
+ }
632
+ };
633
+ } catch (error) {
634
+ this.logger.error("Failed to accept connection:", error);
635
+ throw error;
636
+ }
637
+ return this;
638
+ }
639
+ /**
640
+ * Send a message using HCS (for operations that need direct topic access)
641
+ */
642
+ async sendHCS10Message(params) {
643
+ this.clearNotes();
644
+ try {
645
+ const result = await this.sendMessage(params.topicId, params.message);
646
+ this.executeResult = {
647
+ success: true,
648
+ transactionId: result.transactionId,
649
+ receipt: result.receipt,
650
+ scheduleId: void 0,
651
+ rawResult: result
652
+ };
653
+ this.addNote(`Message sent to topic ${params.topicId}.`);
654
+ } catch (error) {
655
+ this.logger.error("Failed to send message:", error);
656
+ throw error;
657
+ }
658
+ return this;
659
+ }
660
+ /**
661
+ * Send a message to a connected account with optional response monitoring
662
+ */
663
+ async sendMessageToConnection(params) {
664
+ this.clearNotes();
665
+ if (!this.stateManager) {
666
+ throw new Error(
667
+ "StateManager is required to send messages to connections"
668
+ );
669
+ }
670
+ try {
671
+ const currentAgent = this.stateManager.getCurrentAgent();
672
+ if (!currentAgent) {
673
+ throw new Error(
674
+ "Cannot send message. No agent is currently active. Please register or select an agent first."
675
+ );
676
+ }
677
+ let connection;
678
+ if (params.targetIdentifier.includes("@")) {
679
+ const parts = params.targetIdentifier.split("@");
680
+ if (parts.length === 2) {
681
+ const accountId = parts[1];
682
+ connection = this.stateManager.getConnectionByIdentifier(accountId);
683
+ if (!connection) {
684
+ this.addNote(
685
+ `Could not find connection using request key '${params.targetIdentifier}', extracted account ID '${accountId}'.`
686
+ );
687
+ }
688
+ }
689
+ }
690
+ if (!connection) {
691
+ connection = this.stateManager.getConnectionByIdentifier(
692
+ params.targetIdentifier
693
+ );
694
+ }
695
+ if (!connection) {
696
+ const connections = this.stateManager.listConnections();
697
+ const availableIds = connections.map(
698
+ (c) => `${c.targetAccountId} (${c.connectionTopicId})`
699
+ );
700
+ throw new Error(
701
+ `Connection not found for identifier: ${params.targetIdentifier}. Available connections: ${availableIds.join(", ") || "none"}. Use 'list_connections' to see details.`
702
+ );
703
+ }
704
+ let connectionTopicId = connection.connectionTopicId;
705
+ if (connectionTopicId && typeof connectionTopicId === "object" && "toString" in connectionTopicId) {
706
+ connectionTopicId = connectionTopicId?.toString();
707
+ }
708
+ if (!connectionTopicId || typeof connectionTopicId !== "string") {
709
+ throw new Error(
710
+ `Invalid connection topic ID for ${connection.targetAccountId}: ${JSON.stringify(
711
+ connectionTopicId
712
+ )} (type: ${typeof connectionTopicId})`
713
+ );
714
+ }
715
+ const targetAgentName = connection.targetAgentName;
716
+ const operatorId = `${currentAgent.inboundTopicId}@${currentAgent.accountId}`;
717
+ const messageResult = await this.sendMessage(
718
+ connectionTopicId,
719
+ params.message,
720
+ `Agent message from ${currentAgent.name}`
721
+ );
722
+ if (!messageResult.sequenceNumber) {
723
+ throw new Error("Failed to send message");
724
+ }
725
+ let reply = null;
726
+ if (!params.disableMonitoring) {
727
+ reply = await this.monitorResponses(
728
+ connectionTopicId,
729
+ operatorId,
730
+ messageResult.sequenceNumber
731
+ );
256
732
  } else {
257
- detailedMessage += ` Unexpected error: ${String(error)}`;
733
+ this.addNote(
734
+ `Message sent successfully. Response monitoring was disabled.`
735
+ );
258
736
  }
259
- throw new Error(detailedMessage);
737
+ this.executeResult = {
738
+ success: true,
739
+ transactionId: messageResult.transactionId,
740
+ receipt: messageResult.receipt,
741
+ scheduleId: void 0,
742
+ rawResult: {
743
+ targetAgentName,
744
+ targetAccountId: connection.targetAccountId,
745
+ connectionTopicId,
746
+ sequenceNumber: messageResult.sequenceNumber,
747
+ reply,
748
+ monitoringEnabled: !params.disableMonitoring,
749
+ message: params.message,
750
+ messageResult
751
+ }
752
+ };
753
+ } catch (error) {
754
+ this.logger.error("Failed to send message to connection:", error);
755
+ throw error;
260
756
  }
757
+ return this;
261
758
  }
262
759
  /**
263
- * Retrieves the configured operator account ID and private key.
264
- * Required by tools needing to identify the current agent instance.
760
+ * Monitor responses on a topic after sending a message
265
761
  */
266
- getAccountAndSigner() {
267
- const result = this.standardClient.getAccountAndSigner();
268
- return {
269
- accountId: result.accountId,
270
- signer: result.signer
762
+ async monitorResponses(topicId, operatorId, sequenceNumber) {
763
+ const maxAttempts = 30;
764
+ let attempts = 0;
765
+ while (attempts < maxAttempts) {
766
+ try {
767
+ const messages = await this.getMessageStream(topicId);
768
+ for (const message of messages.messages) {
769
+ if (message.sequence_number < sequenceNumber || message.operator_id === operatorId) {
770
+ continue;
771
+ }
772
+ const content = await this.getMessageContent(message.data || "");
773
+ return content;
774
+ }
775
+ } catch (error) {
776
+ this.logger.error(`Error monitoring responses: ${error}`);
777
+ }
778
+ await new Promise((resolve) => setTimeout(resolve, 4e3));
779
+ attempts++;
780
+ }
781
+ return null;
782
+ }
783
+ /**
784
+ * Start passive monitoring for incoming connection requests
785
+ * This method monitors continuously in the background
786
+ */
787
+ async startPassiveConnectionMonitoring() {
788
+ this.clearNotes();
789
+ if (!this.stateManager) {
790
+ throw new Error("StateManager is required for passive monitoring");
791
+ }
792
+ const inboundTopicId = await this.getInboundTopicId();
793
+ this.logger.info(
794
+ `Starting passive connection monitoring on topic ${inboundTopicId}...`
795
+ );
796
+ this.executeResult = {
797
+ success: true,
798
+ transactionId: void 0,
799
+ receipt: void 0,
800
+ scheduleId: void 0,
801
+ rawResult: {
802
+ inboundTopicId,
803
+ message: `Started monitoring inbound topic ${inboundTopicId} for connection requests in the background.`
804
+ }
271
805
  };
806
+ return this;
272
807
  }
273
808
  /**
274
- * Retrieves the outbound topic ID for the current operator.
275
- * Fetches the operator's profile if necessary.
276
- * @returns The outbound topic ID string.
277
- * @throws If the outbound topic cannot be determined.
809
+ * Monitor for incoming connection requests
278
810
  */
279
- async getOutboundTopicId() {
280
- const operatorId = this.getOperatorId();
281
- const profile = await this.getAgentProfile(operatorId);
282
- if (profile.success && profile.topicInfo?.outboundTopic) {
283
- return profile.topicInfo.outboundTopic;
284
- } else {
811
+ async monitorConnections(params) {
812
+ this.clearNotes();
813
+ const {
814
+ acceptAll = false,
815
+ targetAccountId,
816
+ monitorDurationSeconds = 120,
817
+ hbarFees = [],
818
+ tokenFees = [],
819
+ exemptAccountIds = [],
820
+ defaultCollectorAccount
821
+ } = params;
822
+ if (!this.stateManager) {
823
+ throw new Error("StateManager is required for connection monitoring");
824
+ }
825
+ const currentAgent = this.stateManager.getCurrentAgent();
826
+ if (!currentAgent) {
285
827
  throw new Error(
286
- `Could not retrieve outbound topic from profile for ${operatorId}. Profile success: ${profile.success}, Error: ${profile.error}`
828
+ "Cannot monitor for connections. No agent is currently active."
287
829
  );
288
830
  }
831
+ const inboundTopicId = await this.getInboundTopicId();
832
+ const endTime = Date.now() + monitorDurationSeconds * 1e3;
833
+ const pollIntervalMs = 3e3;
834
+ let connectionRequestsFound = 0;
835
+ let acceptedConnections = 0;
836
+ const processedRequestIds = /* @__PURE__ */ new Set();
837
+ while (Date.now() < endTime) {
838
+ try {
839
+ const messagesResult = await this.getMessages(inboundTopicId);
840
+ const connectionRequests = messagesResult.messages.filter(
841
+ (msg) => msg.op === "connection_request" && typeof msg.sequence_number === "number"
842
+ );
843
+ for (const request of connectionRequests) {
844
+ const connectionRequestId = request.sequence_number;
845
+ if (!connectionRequestId || processedRequestIds.has(connectionRequestId)) {
846
+ continue;
847
+ }
848
+ const requestingAccountId = request.operator_id?.split("@")[1];
849
+ if (!requestingAccountId) {
850
+ continue;
851
+ }
852
+ connectionRequestsFound++;
853
+ if (targetAccountId && requestingAccountId !== targetAccountId) {
854
+ this.logger.info(
855
+ `Skipping request from ${requestingAccountId} (not target account)`
856
+ );
857
+ continue;
858
+ }
859
+ if (acceptAll || targetAccountId === requestingAccountId) {
860
+ this.logger.info(
861
+ `Accepting connection request from ${requestingAccountId}`
862
+ );
863
+ let feeConfig;
864
+ if (hbarFees.length > 0 || tokenFees.length > 0) {
865
+ const builder = new FeeConfigBuilder({
866
+ network: this.network,
867
+ logger: this.sdkLogger
868
+ });
869
+ for (const fee of hbarFees) {
870
+ const collectorAccount = fee.collectorAccount || defaultCollectorAccount || this.getOperatorId();
871
+ builder.addHbarFee(
872
+ fee.amount,
873
+ collectorAccount,
874
+ exemptAccountIds
875
+ );
876
+ }
877
+ for (const fee of tokenFees) {
878
+ const collectorAccount = fee.collectorAccount || defaultCollectorAccount || this.getOperatorId();
879
+ builder.addTokenFee(
880
+ fee.amount,
881
+ fee.tokenId,
882
+ collectorAccount,
883
+ void 0,
884
+ exemptAccountIds
885
+ );
886
+ }
887
+ feeConfig = builder;
888
+ }
889
+ await this.handleConnectionRequest(
890
+ inboundTopicId,
891
+ requestingAccountId,
892
+ connectionRequestId,
893
+ feeConfig
894
+ );
895
+ processedRequestIds.add(connectionRequestId);
896
+ acceptedConnections++;
897
+ }
898
+ }
899
+ } catch (error) {
900
+ this.logger.error("Error during connection monitoring:", error);
901
+ }
902
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
903
+ }
904
+ this.executeResult = {
905
+ success: true,
906
+ transactionId: void 0,
907
+ receipt: void 0,
908
+ scheduleId: void 0,
909
+ rawResult: {
910
+ connectionRequestsFound,
911
+ acceptedConnections,
912
+ monitorDurationSeconds,
913
+ processedRequestIds: Array.from(processedRequestIds)
914
+ }
915
+ };
916
+ this.addNote(
917
+ `Monitoring completed. Found ${connectionRequestsFound} requests, accepted ${acceptedConnections}.`
918
+ );
919
+ return this;
289
920
  }
290
- setClient(accountId, privateKey) {
291
- this.standardClient = new HCS10Client$1({
292
- network: this.getNetwork(),
293
- operatorId: accountId,
294
- operatorPrivateKey: privateKey,
295
- guardedRegistryBaseUrl: this.guardedRegistryBaseUrl
296
- });
297
- return this.standardClient;
921
+ /**
922
+ * Manage connection requests (list, view, or reject)
923
+ */
924
+ async manageConnectionRequests(params) {
925
+ this.clearNotes();
926
+ if (!this.stateManager) {
927
+ throw new Error(
928
+ "StateManager is required for managing connection requests"
929
+ );
930
+ }
931
+ const currentAgent = this.stateManager.getCurrentAgent();
932
+ if (!currentAgent) {
933
+ throw new Error(
934
+ "Cannot manage connection requests. No agent is currently active."
935
+ );
936
+ }
937
+ const connectionsManager = this.stateManager.getConnectionsManager();
938
+ if (!connectionsManager) {
939
+ throw new Error(NOT_INITIALIZED_ERROR);
940
+ }
941
+ try {
942
+ const { accountId } = this.getAccountAndSigner();
943
+ await connectionsManager.fetchConnectionData(accountId);
944
+ const pendingRequests = connectionsManager.getPendingRequests();
945
+ const needsConfirmation = connectionsManager.getConnectionsNeedingConfirmation();
946
+ const allRequests = [...pendingRequests, ...needsConfirmation];
947
+ switch (params.action) {
948
+ case "list":
949
+ this.executeResult = {
950
+ success: true,
951
+ transactionId: void 0,
952
+ receipt: void 0,
953
+ scheduleId: void 0,
954
+ rawResult: {
955
+ requests: allRequests.map((request, index) => ({
956
+ index: index + 1,
957
+ type: request.needsConfirmation ? "incoming" : "outgoing",
958
+ requestKey: request.uniqueRequestKey || `${request.connectionRequestId || request.inboundRequestId || "unknown"}`,
959
+ targetAccountId: request.targetAccountId,
960
+ targetAgentName: request.targetAgentName || `Agent ${request.targetAccountId}`,
961
+ created: request.created.toISOString(),
962
+ memo: request.memo,
963
+ bio: request.profileInfo?.bio
964
+ }))
965
+ }
966
+ };
967
+ break;
968
+ case "view": {
969
+ if (!params.requestKey) {
970
+ throw new Error("Request key is required for viewing a request");
971
+ }
972
+ const viewRequest = allRequests.find(
973
+ (r) => r.uniqueRequestKey === params.requestKey || r.connectionRequestId?.toString() === params.requestKey || r.inboundRequestId?.toString() === params.requestKey
974
+ );
975
+ if (!viewRequest) {
976
+ throw new Error(`Request with key ${params.requestKey} not found`);
977
+ }
978
+ this.executeResult = {
979
+ success: true,
980
+ transactionId: void 0,
981
+ receipt: void 0,
982
+ scheduleId: void 0,
983
+ rawResult: {
984
+ request: {
985
+ type: viewRequest.needsConfirmation ? "incoming" : "outgoing",
986
+ requestKey: viewRequest.uniqueRequestKey || `${viewRequest.connectionRequestId || viewRequest.inboundRequestId || "unknown"}`,
987
+ targetAccountId: viewRequest.targetAccountId,
988
+ targetAgentName: viewRequest.targetAgentName || `Agent ${viewRequest.targetAccountId}`,
989
+ created: viewRequest.created.toISOString(),
990
+ memo: viewRequest.memo,
991
+ profileInfo: viewRequest.profileInfo
992
+ }
993
+ }
994
+ };
995
+ break;
996
+ }
997
+ case "reject": {
998
+ if (!params.requestKey) {
999
+ throw new Error("Request key is required for rejecting a request");
1000
+ }
1001
+ const rejectRequest = allRequests.find(
1002
+ (r) => r.uniqueRequestKey === params.requestKey || r.connectionRequestId?.toString() === params.requestKey || r.inboundRequestId?.toString() === params.requestKey
1003
+ );
1004
+ if (!rejectRequest) {
1005
+ throw new Error(`Request with key ${params.requestKey} not found`);
1006
+ }
1007
+ if (rejectRequest.inboundRequestId) {
1008
+ connectionsManager.markConnectionRequestProcessed(
1009
+ rejectRequest.targetInboundTopicId || "",
1010
+ rejectRequest.inboundRequestId
1011
+ );
1012
+ } else if (rejectRequest.connectionRequestId) {
1013
+ connectionsManager.markConnectionRequestProcessed(
1014
+ rejectRequest.originTopicId || "",
1015
+ rejectRequest.connectionRequestId
1016
+ );
1017
+ }
1018
+ this.executeResult = {
1019
+ success: true,
1020
+ transactionId: void 0,
1021
+ receipt: void 0,
1022
+ scheduleId: void 0,
1023
+ rawResult: {
1024
+ rejectedRequest: {
1025
+ requestKey: params.requestKey,
1026
+ targetAccountId: rejectRequest.targetAccountId,
1027
+ targetAgentName: rejectRequest.targetAgentName || `Agent ${rejectRequest.targetAccountId}`
1028
+ }
1029
+ }
1030
+ };
1031
+ break;
1032
+ }
1033
+ }
1034
+ } catch (error) {
1035
+ this.logger.error("Failed to manage connection requests:", error);
1036
+ throw error;
1037
+ }
1038
+ return this;
298
1039
  }
299
1040
  /**
300
- * Validates that the operator account exists and has proper access for agent operations
1041
+ * List unapproved connection requests
301
1042
  */
302
- async validateOperator(options) {
1043
+ async listUnapprovedConnectionRequests() {
1044
+ this.clearNotes();
1045
+ if (!this.stateManager) {
1046
+ throw new Error(
1047
+ "StateManager is required for listing connection requests"
1048
+ );
1049
+ }
1050
+ const currentAgent = this.stateManager.getCurrentAgent();
1051
+ if (!currentAgent) {
1052
+ throw new Error(
1053
+ "Cannot list connection requests. No agent is currently active."
1054
+ );
1055
+ }
303
1056
  try {
304
- this.setClient(options.accountId, options.privateKey);
305
- const operatorId = this.getOperatorId();
306
- return {
307
- isValid: true,
308
- operator: { accountId: operatorId }
1057
+ const inboundTopicId = await this.getInboundTopicId();
1058
+ const messages = await this.getMessages(inboundTopicId);
1059
+ const unapprovedRequests = messages.messages.filter((msg) => msg.op === "connection_request").map((msg) => ({
1060
+ requestId: msg.sequence_number,
1061
+ fromAccountId: msg.operator_id?.split("@")[1] || "unknown",
1062
+ timestamp: msg.timestamp || new Date(msg?.created || "").getTime(),
1063
+ memo: msg.m || "",
1064
+ data: msg.data
1065
+ })).filter((req) => req.fromAccountId !== "unknown");
1066
+ this.executeResult = {
1067
+ success: true,
1068
+ transactionId: void 0,
1069
+ receipt: void 0,
1070
+ scheduleId: void 0,
1071
+ rawResult: {
1072
+ requests: unapprovedRequests,
1073
+ count: unapprovedRequests.length
1074
+ }
309
1075
  };
1076
+ if (unapprovedRequests.length === 0) {
1077
+ this.addNote("No unapproved connection requests found.");
1078
+ } else {
1079
+ this.addNote(
1080
+ `Found ${unapprovedRequests.length} unapproved connection request(s).`
1081
+ );
1082
+ }
310
1083
  } catch (error) {
311
- this.logger.error(`Validation error: ${error}`);
312
- return {
313
- isValid: false,
314
- error: error instanceof Error ? error.message : String(error)
1084
+ this.logger.error(
1085
+ "Failed to list unapproved connection requests:",
1086
+ error
1087
+ );
1088
+ throw error;
1089
+ }
1090
+ return this;
1091
+ }
1092
+ /**
1093
+ * List connections with enhanced details
1094
+ */
1095
+ async listConnections(params = {}) {
1096
+ this.clearNotes();
1097
+ if (!this.stateManager) {
1098
+ throw new Error("StateManager is required to list connections");
1099
+ }
1100
+ const includeDetails = params.includeDetails ?? true;
1101
+ const showPending = params.showPending ?? true;
1102
+ try {
1103
+ const connections = await this.getEnhancedConnections();
1104
+ if (connections.length === 0) {
1105
+ this.executeResult = {
1106
+ success: true,
1107
+ rawResult: {
1108
+ connections: [],
1109
+ message: "There are currently no active connections."
1110
+ }
1111
+ };
1112
+ return this;
1113
+ }
1114
+ const activeConnections = connections.filter(
1115
+ (c) => c.status === "established"
1116
+ );
1117
+ const pendingConnections = connections.filter(
1118
+ (c) => c.isPending
1119
+ );
1120
+ const needsConfirmation = connections.filter(
1121
+ (c) => c.needsConfirmation
1122
+ );
1123
+ let output = "";
1124
+ if (activeConnections.length > 0) {
1125
+ output += `🟢 Active Connections (${activeConnections.length}):
1126
+ `;
1127
+ activeConnections.forEach((conn, index) => {
1128
+ output += this.formatConnection(conn, index, includeDetails);
1129
+ });
1130
+ output += "\n";
1131
+ }
1132
+ if (showPending && needsConfirmation.length > 0) {
1133
+ output += `🟠 Connections Needing Confirmation (${needsConfirmation.length}):
1134
+ `;
1135
+ needsConfirmation.forEach((conn, index) => {
1136
+ output += this.formatConnection(conn, index, includeDetails);
1137
+ });
1138
+ output += "\n";
1139
+ }
1140
+ if (showPending && pendingConnections.length > 0) {
1141
+ output += `⚪ Pending Connection Requests (${pendingConnections.length}):
1142
+ `;
1143
+ pendingConnections.forEach((conn, index) => {
1144
+ output += this.formatConnection(conn, index, includeDetails);
1145
+ });
1146
+ }
1147
+ this.executeResult = {
1148
+ success: true,
1149
+ rawResult: {
1150
+ connections,
1151
+ formattedOutput: output.trim(),
1152
+ activeCount: activeConnections.length,
1153
+ pendingCount: pendingConnections.length,
1154
+ needsConfirmationCount: needsConfirmation.length
1155
+ }
1156
+ };
1157
+ } catch (error) {
1158
+ this.logger.error("Failed to list connections:", error);
1159
+ this.executeResult = {
1160
+ success: false,
1161
+ error: `Failed to list connections: ${error instanceof Error ? error.message : String(error)}`
1162
+ };
1163
+ }
1164
+ return this;
1165
+ }
1166
+ formatConnection(conn, index, includeDetails) {
1167
+ const connection = conn;
1168
+ let output = `${index + 1}. ${connection.profileInfo?.display_name || connection.targetAgentName || "Unknown Agent"} (${connection.targetAccountId})
1169
+ `;
1170
+ const displayTopicId = connection.isPending ? "(Pending Request)" : connection.connectionTopicId;
1171
+ output += ` Topic: ${displayTopicId}
1172
+ `;
1173
+ const statusText = connection.status || "unknown";
1174
+ output += ` Status: ${statusText}
1175
+ `;
1176
+ if (includeDetails) {
1177
+ if (connection.profileInfo?.bio) {
1178
+ output += ` Bio: ${connection.profileInfo.bio.substring(0, 100)}${connection.profileInfo.bio.length > 100 ? "..." : ""}
1179
+ `;
1180
+ }
1181
+ if (connection.created) {
1182
+ const createdLabel = connection.isPending ? "Request sent" : "Connection established";
1183
+ output += ` ${createdLabel}: ${connection.created.toLocaleString()}
1184
+ `;
1185
+ }
1186
+ if (connection.lastActivity) {
1187
+ output += ` Last activity: ${connection.lastActivity.toLocaleString()}
1188
+ `;
1189
+ }
1190
+ }
1191
+ return output;
1192
+ }
1193
+ async getEnhancedConnections() {
1194
+ try {
1195
+ const { accountId } = this.getAccountAndSigner();
1196
+ if (!accountId) {
1197
+ return this.stateManager.listConnections();
1198
+ }
1199
+ const connectionManager = this.stateManager.getConnectionsManager();
1200
+ if (!connectionManager) {
1201
+ this.logger.error(NOT_INITIALIZED_ERROR);
1202
+ return this.stateManager.listConnections();
1203
+ }
1204
+ const connections = await connectionManager.fetchConnectionData(
1205
+ accountId
1206
+ );
1207
+ for (const connection of connections) {
1208
+ this.stateManager.addActiveConnection(
1209
+ connection
1210
+ );
1211
+ }
1212
+ return connections;
1213
+ } catch (error) {
1214
+ this.logger.error("Failed to get enhanced connections:", error);
1215
+ return this.stateManager.listConnections();
1216
+ }
1217
+ }
1218
+ /**
1219
+ * Check messages on a connection
1220
+ */
1221
+ async checkMessages(params) {
1222
+ this.clearNotes();
1223
+ if (!this.stateManager) {
1224
+ throw new Error("StateManager is required to check messages");
1225
+ }
1226
+ const connection = this.stateManager.getConnectionByIdentifier(
1227
+ params.targetIdentifier
1228
+ );
1229
+ if (!connection) {
1230
+ this.executeResult = {
1231
+ success: false,
1232
+ error: `Could not find an active connection matching identifier "${params.targetIdentifier}". Use 'list_connections' to see active connections.`
1233
+ };
1234
+ return this;
1235
+ }
1236
+ const connectionTopicId = connection.connectionTopicId || "";
1237
+ if (!connectionTopicId || !connectionTopicId.match(/^\d+\.\d+\.\d+$/)) {
1238
+ this.logger.error(
1239
+ `Invalid connection topic ID format: ${connectionTopicId}`
1240
+ );
1241
+ this.executeResult = {
1242
+ success: false,
1243
+ error: `Invalid connection topic ID format: ${connectionTopicId}. Expected format: 0.0.XXXXX`
1244
+ };
1245
+ return this;
1246
+ }
1247
+ const targetAgentName = connection.targetAgentName;
1248
+ const lastProcessedTimestamp = this.stateManager.getLastTimestamp(connectionTopicId);
1249
+ this.logger.info(
1250
+ `Checking messages for connection with ${targetAgentName} (${connection.targetAccountId}) on topic ${connectionTopicId} (fetchLatest: ${params.fetchLatest}, lastCount: ${params.lastMessagesCount}, since: ${lastProcessedTimestamp})`
1251
+ );
1252
+ try {
1253
+ const result = await this.getMessages(connectionTopicId);
1254
+ const allMessages = result.messages;
1255
+ if (!allMessages || allMessages.length === 0) {
1256
+ this.executeResult = {
1257
+ success: true,
1258
+ rawResult: {
1259
+ messages: [],
1260
+ message: `No messages found on connection topic ${connectionTopicId}.`
1261
+ }
1262
+ };
1263
+ return this;
1264
+ }
1265
+ let messagesToProcess = [];
1266
+ let latestTimestampNanos = lastProcessedTimestamp;
1267
+ const isFetchingLatest = params.fetchLatest === true;
1268
+ if (isFetchingLatest) {
1269
+ this.logger.info("Fetching latest messages regardless of timestamp.");
1270
+ const count = params.lastMessagesCount ?? 1;
1271
+ messagesToProcess = allMessages.slice(-count);
1272
+ } else {
1273
+ this.logger.info(
1274
+ `Filtering for messages newer than ${lastProcessedTimestamp}`
1275
+ );
1276
+ messagesToProcess = allMessages.filter(
1277
+ (msg) => {
1278
+ const msgTimestampNanos = msg.timestamp * 1e6;
1279
+ return msgTimestampNanos > lastProcessedTimestamp;
1280
+ }
1281
+ );
1282
+ if (messagesToProcess.length > 0) {
1283
+ latestTimestampNanos = messagesToProcess.reduce(
1284
+ (maxTs, msg) => Math.max(maxTs, msg.timestamp * 1e6),
1285
+ lastProcessedTimestamp
1286
+ );
1287
+ }
1288
+ }
1289
+ if (messagesToProcess.length === 0) {
1290
+ const message = isFetchingLatest ? `Could not retrieve the latest message(s). No messages found on topic ${connectionTopicId}.` : `No new messages found for connection with ${targetAgentName} since last check.`;
1291
+ this.executeResult = {
1292
+ success: true,
1293
+ rawResult: {
1294
+ messages: [],
1295
+ message
1296
+ }
1297
+ };
1298
+ return this;
1299
+ }
1300
+ this.logger.info(`Processing ${messagesToProcess.length} message(s).`);
1301
+ let outputString = isFetchingLatest ? `Latest message(s) from ${targetAgentName}:
1302
+ ` : `New messages from ${targetAgentName}:
1303
+ `;
1304
+ const processedMessages = [];
1305
+ for (const msg of messagesToProcess) {
1306
+ let content = msg.data;
1307
+ try {
1308
+ if (typeof content === "string" && content.startsWith("hcs://")) {
1309
+ this.logger.debug(`Resolving inscribed message: ${content}`);
1310
+ content = await this.getMessageContent(content);
1311
+ this.logger.debug(`Resolved content length: ${content?.length}`);
1312
+ }
1313
+ let displayContent = content;
1314
+ try {
1315
+ const parsed = JSON.parse(content || "{}");
1316
+ if (parsed.p === "hcs-10" && parsed.op === "message" && parsed.data) {
1317
+ const senderOpId = parsed.operator_id || "unknown_sender";
1318
+ displayContent = `[${senderOpId}]: ${parsed.data}`;
1319
+ } else {
1320
+ displayContent = content;
1321
+ }
1322
+ } catch {
1323
+ displayContent = content;
1324
+ }
1325
+ const messageDate = new Date(msg.timestamp);
1326
+ outputString += `
1327
+ [${messageDate.toLocaleString()}] (Seq: ${msg.sequence_number})
1328
+ ${displayContent}
1329
+ `;
1330
+ processedMessages.push({
1331
+ timestamp: msg.timestamp,
1332
+ sequenceNumber: msg.sequence_number,
1333
+ content: displayContent,
1334
+ raw: msg
1335
+ });
1336
+ } catch (error) {
1337
+ const errorMsg = `Error processing message (Seq: ${msg.sequence_number}): ${error instanceof Error ? error.message : String(error)}`;
1338
+ this.logger.error(errorMsg);
1339
+ outputString += `
1340
+ [Error processing message Seq: ${msg.sequence_number}]
1341
+ `;
1342
+ }
1343
+ }
1344
+ if (!isFetchingLatest && latestTimestampNanos > lastProcessedTimestamp) {
1345
+ this.logger.debug(
1346
+ `Updating timestamp for topic ${connectionTopicId} to ${latestTimestampNanos}`
1347
+ );
1348
+ this.stateManager.updateTimestamp(
1349
+ connectionTopicId,
1350
+ latestTimestampNanos
1351
+ );
1352
+ }
1353
+ this.executeResult = {
1354
+ success: true,
1355
+ rawResult: {
1356
+ messages: processedMessages,
1357
+ formattedOutput: outputString.trim(),
1358
+ targetAgentName,
1359
+ connectionTopicId
1360
+ }
1361
+ };
1362
+ } catch (error) {
1363
+ this.logger.error(
1364
+ `Failed to check messages for topic ${connectionTopicId}: ${error}`
1365
+ );
1366
+ this.executeResult = {
1367
+ success: false,
1368
+ error: `Error checking messages for ${targetAgentName}: ${error instanceof Error ? error.message : String(error)}`
315
1369
  };
316
1370
  }
1371
+ return this;
317
1372
  }
318
- async initializeWithValidation(options) {
319
- const validationResult = await this.validateOperator(options);
320
- if (validationResult.isValid) {
321
- if (options.stateManager) {
322
- options.stateManager.initializeConnectionsManager(this.standardClient);
1373
+ /**
1374
+ * Find registrations using the configured registry
1375
+ */
1376
+ async findRegistrations(params) {
1377
+ this.clearNotes();
1378
+ try {
1379
+ const options = {
1380
+ network: this.network
1381
+ };
1382
+ if (params.accountId) {
1383
+ options.accountId = params.accountId;
1384
+ }
1385
+ if (params.tags && params.tags.length > 0) {
1386
+ options.tags = params.tags;
1387
+ }
1388
+ const result = await this.standardClient.findRegistrations(options);
1389
+ if (!result.success || result.error) {
1390
+ this.executeResult = {
1391
+ success: false,
1392
+ error: `Error finding registrations: ${result.error || "Unknown error"}`
1393
+ };
1394
+ return this;
323
1395
  }
1396
+ if (!result.registrations || result.registrations.length === 0) {
1397
+ this.executeResult = {
1398
+ success: true,
1399
+ rawResult: {
1400
+ registrations: [],
1401
+ message: "No registrations found matching the criteria."
1402
+ }
1403
+ };
1404
+ return this;
1405
+ }
1406
+ const formattedRegistrations = result.registrations.map((reg) => {
1407
+ const registration = reg;
1408
+ const agentName = registration.agent?.name || "Unknown Agent";
1409
+ const accountId = registration.accountId || "Unknown Account";
1410
+ const capabilities = registration.agent?.capabilities?.join(", ") || "None";
1411
+ return `Agent: ${agentName} (${accountId}), Capabilities: ${capabilities}`;
1412
+ }).join("\\n");
1413
+ this.executeResult = {
1414
+ success: true,
1415
+ rawResult: {
1416
+ registrations: result.registrations,
1417
+ formattedOutput: `Found ${result.registrations.length} registration(s):\\n${formattedRegistrations}`
1418
+ }
1419
+ };
1420
+ } catch (error) {
1421
+ this.logger.error("Error during FindRegistrations execution:", error);
1422
+ this.executeResult = {
1423
+ success: false,
1424
+ error: `Failed to search registrations: ${error instanceof Error ? error.message : String(error)}`
1425
+ };
324
1426
  }
325
- return validationResult;
1427
+ return this;
1428
+ }
1429
+ /**
1430
+ * Retrieve detailed profile information for an agent
1431
+ */
1432
+ async retrieveProfile(params) {
1433
+ this.clearNotes();
1434
+ try {
1435
+ const profileResponse = await this.standardClient.retrieveProfile(
1436
+ params.accountId,
1437
+ params.disableCache || false
1438
+ );
1439
+ if (!profileResponse.success) {
1440
+ this.executeResult = {
1441
+ success: false,
1442
+ error: `Failed to retrieve profile: ${profileResponse.error || "Unknown error"}`
1443
+ };
1444
+ return this;
1445
+ }
1446
+ const profile = profileResponse.profile;
1447
+ const topicInfo = profileResponse.topicInfo;
1448
+ let profileDetails = `Profile for ${params.accountId}:
1449
+ `;
1450
+ profileDetails += `Name: ${profile.name || "Unknown"}
1451
+ `;
1452
+ profileDetails += `Bio: ${profile.bio || "No bio provided"}
1453
+ `;
1454
+ profileDetails += `Type: ${profile.type || "Unknown"}
1455
+ `;
1456
+ profileDetails += `Model: ${profile.model || "Unknown"}
1457
+ `;
1458
+ if (profile.capabilities && profile.capabilities.length > 0) {
1459
+ profileDetails += `Capabilities: ${profile.capabilities.join(", ")}
1460
+ `;
1461
+ } else {
1462
+ profileDetails += `Capabilities: None listed
1463
+ `;
1464
+ }
1465
+ if (topicInfo) {
1466
+ profileDetails += `Inbound Topic: ${topicInfo.inboundTopic || "Unknown"}
1467
+ `;
1468
+ profileDetails += `Outbound Topic: ${topicInfo.outboundTopic || "Unknown"}
1469
+ `;
1470
+ profileDetails += `Profile Topic: ${topicInfo.profileTopicId || "Unknown"}
1471
+ `;
1472
+ }
1473
+ if (profile.social && Object.keys(profile.social).length > 0) {
1474
+ profileDetails += `Social: ${Object.entries(profile.social).map(([platform, handle]) => `${platform}: ${handle}`).join(", ")}
1475
+ `;
1476
+ }
1477
+ if (profile.properties && Object.keys(profile.properties).length > 0) {
1478
+ profileDetails += `Properties: ${JSON.stringify(profile.properties)}
1479
+ `;
1480
+ }
1481
+ this.executeResult = {
1482
+ success: true,
1483
+ rawResult: {
1484
+ profileDetails,
1485
+ rawProfile: profileResponse
1486
+ }
1487
+ };
1488
+ } catch (error) {
1489
+ this.logger.error(
1490
+ `Unexpected error retrieving profile for ${params.accountId}:`,
1491
+ error
1492
+ );
1493
+ this.executeResult = {
1494
+ success: false,
1495
+ error: `Unexpected error retrieving profile for ${params.accountId}: ${error instanceof Error ? error.message : String(error)}`
1496
+ };
1497
+ }
1498
+ return this;
1499
+ }
1500
+ /**
1501
+ * Override execute to return stored HCS10 operation results
1502
+ */
1503
+ async execute() {
1504
+ if (this.executeResult) {
1505
+ return {
1506
+ success: this.executeResult.success,
1507
+ transactionId: this.executeResult.transactionId,
1508
+ receipt: this.executeResult.receipt,
1509
+ scheduleId: this.executeResult.scheduleId,
1510
+ error: this.executeResult.error,
1511
+ rawResult: this.executeResult.rawResult,
1512
+ notes: this.notes
1513
+ };
1514
+ }
1515
+ return {
1516
+ success: false,
1517
+ error: "No operation result available. Call a builder method first."
1518
+ };
326
1519
  }
327
1520
  }
328
1521
  export {
329
- HCS10Client
1522
+ HCS10Builder
330
1523
  };
331
1524
  //# sourceMappingURL=standards-agent-kit.es2.js.map