@hashgraphonline/standards-agent-kit 0.2.136 → 0.2.138

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 (211) hide show
  1. package/README.md +3 -4
  2. package/dist/cjs/builders/hcs10/hcs10-builder.d.ts +1 -0
  3. package/dist/cjs/builders/hcs2/hcs2-builder.d.ts +8 -7
  4. package/dist/cjs/builders/hcs6/hcs6-builder.d.ts +5 -4
  5. package/dist/cjs/builders/inscriber/inscriber-builder.d.ts +32 -1
  6. package/dist/cjs/index.d.ts +4 -0
  7. package/dist/cjs/signing/bytes-registry.d.ts +17 -0
  8. package/dist/cjs/signing/signer-provider.d.ts +45 -0
  9. package/dist/cjs/standards-agent-kit.cjs +1 -1
  10. package/dist/cjs/standards-agent-kit.cjs.map +1 -1
  11. package/dist/cjs/tools/hcs10/InitiateConnectionTool.d.ts +4 -4
  12. package/dist/cjs/tools/hcs2/CreateRegistryTool.d.ts +2 -2
  13. package/dist/cjs/tools/hcs2/DeleteEntryTool.d.ts +2 -2
  14. package/dist/cjs/tools/hcs2/UpdateEntryTool.d.ts +2 -2
  15. package/dist/cjs/tools/hcs6/RegisterDynamicHashinalTool.d.ts +10 -10
  16. package/dist/cjs/tools/hcs6/UpdateDynamicHashinalTool.d.ts +8 -8
  17. package/dist/cjs/tools/inscriber/InscribeFromBufferTool.d.ts +5 -4
  18. package/dist/cjs/tools/inscriber/InscribeFromFileTool.d.ts +2 -2
  19. package/dist/cjs/tools/inscriber/InscribeFromUrlTool.d.ts +4 -4
  20. package/dist/cjs/tools/inscriber/InscribeHashinalTool.d.ts +3 -3
  21. package/dist/cjs/types/inscription-response.d.ts +8 -0
  22. package/dist/cjs/types/tx-results.d.ts +15 -0
  23. package/dist/cjs/utils/CodedError.d.ts +4 -0
  24. package/dist/cjs/utils/inscription-utils.d.ts +21 -0
  25. package/dist/cjs/validation/hip412-schemas.d.ts +2 -2
  26. package/dist/es/builders/hcs10/hcs10-builder.d.ts +1 -0
  27. package/dist/es/builders/hcs2/hcs2-builder.d.ts +8 -7
  28. package/dist/es/builders/hcs6/hcs6-builder.d.ts +5 -4
  29. package/dist/es/builders/inscriber/inscriber-builder.d.ts +32 -1
  30. package/dist/es/index.d.ts +4 -0
  31. package/dist/es/signing/bytes-registry.d.ts +17 -0
  32. package/dist/es/signing/signer-provider.d.ts +45 -0
  33. package/dist/es/standards-agent-kit.es.js +46 -42
  34. package/dist/es/standards-agent-kit.es.js.map +1 -1
  35. package/dist/es/standards-agent-kit.es10.js +24 -83
  36. package/dist/es/standards-agent-kit.es10.js.map +1 -1
  37. package/dist/es/standards-agent-kit.es11.js +224 -20
  38. package/dist/es/standards-agent-kit.es11.js.map +1 -1
  39. package/dist/es/standards-agent-kit.es12.js +78 -27
  40. package/dist/es/standards-agent-kit.es12.js.map +1 -1
  41. package/dist/es/standards-agent-kit.es13.js +26 -36
  42. package/dist/es/standards-agent-kit.es13.js.map +1 -1
  43. package/dist/es/standards-agent-kit.es14.js +17 -39
  44. package/dist/es/standards-agent-kit.es14.js.map +1 -1
  45. package/dist/es/standards-agent-kit.es15.js +36 -58
  46. package/dist/es/standards-agent-kit.es15.js.map +1 -1
  47. package/dist/es/standards-agent-kit.es16.js +45 -18
  48. package/dist/es/standards-agent-kit.es16.js.map +1 -1
  49. package/dist/es/standards-agent-kit.es17.js +53 -16
  50. package/dist/es/standards-agent-kit.es17.js.map +1 -1
  51. package/dist/es/standards-agent-kit.es18.js +18 -28
  52. package/dist/es/standards-agent-kit.es18.js.map +1 -1
  53. package/dist/es/standards-agent-kit.es19.js +26 -12
  54. package/dist/es/standards-agent-kit.es19.js.map +1 -1
  55. package/dist/es/standards-agent-kit.es20.js +38 -136
  56. package/dist/es/standards-agent-kit.es20.js.map +1 -1
  57. package/dist/es/standards-agent-kit.es21.js +13 -24
  58. package/dist/es/standards-agent-kit.es21.js.map +1 -1
  59. package/dist/es/standards-agent-kit.es22.js +136 -39
  60. package/dist/es/standards-agent-kit.es22.js.map +1 -1
  61. package/dist/es/standards-agent-kit.es23.js +25 -41
  62. package/dist/es/standards-agent-kit.es23.js.map +1 -1
  63. package/dist/es/standards-agent-kit.es24.js +49 -31
  64. package/dist/es/standards-agent-kit.es24.js.map +1 -1
  65. package/dist/es/standards-agent-kit.es25.js +34 -18
  66. package/dist/es/standards-agent-kit.es25.js.map +1 -1
  67. package/dist/es/standards-agent-kit.es26.js +35 -19
  68. package/dist/es/standards-agent-kit.es26.js.map +1 -1
  69. package/dist/es/standards-agent-kit.es27.js +45 -32
  70. package/dist/es/standards-agent-kit.es27.js.map +1 -1
  71. package/dist/es/standards-agent-kit.es28.js +54 -25
  72. package/dist/es/standards-agent-kit.es28.js.map +1 -1
  73. package/dist/es/standards-agent-kit.es29.js +35 -23
  74. package/dist/es/standards-agent-kit.es29.js.map +1 -1
  75. package/dist/es/standards-agent-kit.es3.js +41 -1545
  76. package/dist/es/standards-agent-kit.es3.js.map +1 -1
  77. package/dist/es/standards-agent-kit.es30.js +23 -39
  78. package/dist/es/standards-agent-kit.es30.js.map +1 -1
  79. package/dist/es/standards-agent-kit.es31.js +30 -28
  80. package/dist/es/standards-agent-kit.es31.js.map +1 -1
  81. package/dist/es/standards-agent-kit.es32.js +45 -32
  82. package/dist/es/standards-agent-kit.es32.js.map +1 -1
  83. package/dist/es/standards-agent-kit.es33.js +50 -89
  84. package/dist/es/standards-agent-kit.es33.js.map +1 -1
  85. package/dist/es/standards-agent-kit.es34.js +35 -228
  86. package/dist/es/standards-agent-kit.es34.js.map +1 -1
  87. package/dist/es/standards-agent-kit.es35.js +87 -212
  88. package/dist/es/standards-agent-kit.es35.js.map +1 -1
  89. package/dist/es/standards-agent-kit.es36.js +188 -128
  90. package/dist/es/standards-agent-kit.es36.js.map +1 -1
  91. package/dist/es/standards-agent-kit.es37.js +167 -561
  92. package/dist/es/standards-agent-kit.es37.js.map +1 -1
  93. package/dist/es/standards-agent-kit.es38.js +236 -31
  94. package/dist/es/standards-agent-kit.es38.js.map +1 -1
  95. package/dist/es/standards-agent-kit.es39.js +483 -206
  96. package/dist/es/standards-agent-kit.es39.js.map +1 -1
  97. package/dist/es/standards-agent-kit.es4.js +359 -81
  98. package/dist/es/standards-agent-kit.es4.js.map +1 -1
  99. package/dist/es/standards-agent-kit.es40.js +39 -135
  100. package/dist/es/standards-agent-kit.es40.js.map +1 -1
  101. package/dist/es/standards-agent-kit.es41.js +244 -28
  102. package/dist/es/standards-agent-kit.es41.js.map +1 -1
  103. package/dist/es/standards-agent-kit.es42.js +132 -418
  104. package/dist/es/standards-agent-kit.es42.js.map +1 -1
  105. package/dist/es/standards-agent-kit.es43.js +28 -184
  106. package/dist/es/standards-agent-kit.es43.js.map +1 -1
  107. package/dist/es/standards-agent-kit.es44.js +423 -3
  108. package/dist/es/standards-agent-kit.es44.js.map +1 -1
  109. package/dist/es/standards-agent-kit.es45.js +185 -24
  110. package/dist/es/standards-agent-kit.es45.js.map +1 -1
  111. package/dist/es/standards-agent-kit.es46.js +3 -3
  112. package/dist/es/standards-agent-kit.es46.js.map +1 -1
  113. package/dist/es/standards-agent-kit.es47.js +21 -50
  114. package/dist/es/standards-agent-kit.es47.js.map +1 -1
  115. package/dist/es/standards-agent-kit.es48.js +8 -3
  116. package/dist/es/standards-agent-kit.es48.js.map +1 -1
  117. package/dist/es/standards-agent-kit.es49.js +3 -39
  118. package/dist/es/standards-agent-kit.es49.js.map +1 -1
  119. package/dist/es/standards-agent-kit.es5.js +1747 -73
  120. package/dist/es/standards-agent-kit.es5.js.map +1 -1
  121. package/dist/es/standards-agent-kit.es50.js +18 -16
  122. package/dist/es/standards-agent-kit.es50.js.map +1 -1
  123. package/dist/es/standards-agent-kit.es51.js +49 -49
  124. package/dist/es/standards-agent-kit.es51.js.map +1 -1
  125. package/dist/es/standards-agent-kit.es52.js +6 -0
  126. package/dist/es/standards-agent-kit.es52.js.map +1 -0
  127. package/dist/es/standards-agent-kit.es53.js +43 -0
  128. package/dist/es/standards-agent-kit.es53.js.map +1 -0
  129. package/dist/es/standards-agent-kit.es54.js +22 -0
  130. package/dist/es/standards-agent-kit.es54.js.map +1 -0
  131. package/dist/es/standards-agent-kit.es55.js +77 -0
  132. package/dist/es/standards-agent-kit.es55.js.map +1 -0
  133. package/dist/es/standards-agent-kit.es56.js +7 -0
  134. package/dist/es/standards-agent-kit.es56.js.map +1 -0
  135. package/dist/es/standards-agent-kit.es6.js +347 -32
  136. package/dist/es/standards-agent-kit.es6.js.map +1 -1
  137. package/dist/es/standards-agent-kit.es7.js +142 -293
  138. package/dist/es/standards-agent-kit.es7.js.map +1 -1
  139. package/dist/es/standards-agent-kit.es8.js +201 -21
  140. package/dist/es/standards-agent-kit.es8.js.map +1 -1
  141. package/dist/es/standards-agent-kit.es9.js +301 -213
  142. package/dist/es/standards-agent-kit.es9.js.map +1 -1
  143. package/dist/es/tools/hcs10/InitiateConnectionTool.d.ts +4 -4
  144. package/dist/es/tools/hcs2/CreateRegistryTool.d.ts +2 -2
  145. package/dist/es/tools/hcs2/DeleteEntryTool.d.ts +2 -2
  146. package/dist/es/tools/hcs2/UpdateEntryTool.d.ts +2 -2
  147. package/dist/es/tools/hcs6/RegisterDynamicHashinalTool.d.ts +10 -10
  148. package/dist/es/tools/hcs6/UpdateDynamicHashinalTool.d.ts +8 -8
  149. package/dist/es/tools/inscriber/InscribeFromBufferTool.d.ts +5 -4
  150. package/dist/es/tools/inscriber/InscribeFromFileTool.d.ts +2 -2
  151. package/dist/es/tools/inscriber/InscribeFromUrlTool.d.ts +4 -4
  152. package/dist/es/tools/inscriber/InscribeHashinalTool.d.ts +3 -3
  153. package/dist/es/types/inscription-response.d.ts +8 -0
  154. package/dist/es/types/tx-results.d.ts +15 -0
  155. package/dist/es/utils/CodedError.d.ts +4 -0
  156. package/dist/es/utils/inscription-utils.d.ts +21 -0
  157. package/dist/es/validation/hip412-schemas.d.ts +2 -2
  158. package/dist/umd/builders/hcs10/hcs10-builder.d.ts +1 -0
  159. package/dist/umd/builders/hcs2/hcs2-builder.d.ts +8 -7
  160. package/dist/umd/builders/hcs6/hcs6-builder.d.ts +5 -4
  161. package/dist/umd/builders/inscriber/inscriber-builder.d.ts +32 -1
  162. package/dist/umd/index.d.ts +4 -0
  163. package/dist/umd/signing/bytes-registry.d.ts +17 -0
  164. package/dist/umd/signing/signer-provider.d.ts +45 -0
  165. package/dist/umd/standards-agent-kit.umd.js +1 -1
  166. package/dist/umd/standards-agent-kit.umd.js.map +1 -1
  167. package/dist/umd/tools/hcs10/InitiateConnectionTool.d.ts +4 -4
  168. package/dist/umd/tools/hcs2/CreateRegistryTool.d.ts +2 -2
  169. package/dist/umd/tools/hcs2/DeleteEntryTool.d.ts +2 -2
  170. package/dist/umd/tools/hcs2/UpdateEntryTool.d.ts +2 -2
  171. package/dist/umd/tools/hcs6/RegisterDynamicHashinalTool.d.ts +10 -10
  172. package/dist/umd/tools/hcs6/UpdateDynamicHashinalTool.d.ts +8 -8
  173. package/dist/umd/tools/inscriber/InscribeFromBufferTool.d.ts +5 -4
  174. package/dist/umd/tools/inscriber/InscribeFromFileTool.d.ts +2 -2
  175. package/dist/umd/tools/inscriber/InscribeFromUrlTool.d.ts +4 -4
  176. package/dist/umd/tools/inscriber/InscribeHashinalTool.d.ts +3 -3
  177. package/dist/umd/types/inscription-response.d.ts +8 -0
  178. package/dist/umd/types/tx-results.d.ts +15 -0
  179. package/dist/umd/utils/CodedError.d.ts +4 -0
  180. package/dist/umd/utils/inscription-utils.d.ts +21 -0
  181. package/dist/umd/validation/hip412-schemas.d.ts +2 -2
  182. package/package.json +10 -5
  183. package/src/builders/hcs10/hcs10-builder.ts +239 -6
  184. package/src/builders/hcs2/hcs2-builder.ts +302 -9
  185. package/src/builders/hcs6/hcs6-builder.ts +79 -4
  186. package/src/builders/inscriber/inscriber-builder.ts +235 -2
  187. package/src/hcs10/HCS10Client.ts +1 -1
  188. package/src/index.ts +5 -1
  189. package/src/lib/zod-render/schema-extension.ts +0 -1
  190. package/src/signing/bytes-registry.ts +501 -0
  191. package/src/signing/signer-provider.ts +120 -0
  192. package/src/tools/hcs2/CreateRegistryTool.ts +30 -5
  193. package/src/tools/hcs2/DeleteEntryTool.ts +16 -2
  194. package/src/tools/hcs2/MigrateRegistryTool.ts +16 -2
  195. package/src/tools/hcs2/QueryRegistryTool.ts +11 -2
  196. package/src/tools/hcs2/RegisterEntryTool.ts +17 -3
  197. package/src/tools/hcs2/UpdateEntryTool.ts +16 -2
  198. package/src/tools/hcs6/CreateDynamicRegistryTool.ts +17 -3
  199. package/src/tools/hcs6/RegisterDynamicHashinalTool.ts +17 -3
  200. package/src/tools/hcs6/UpdateDynamicHashinalTool.ts +17 -3
  201. package/src/tools/inscriber/InscribeFromBufferTool.ts +126 -21
  202. package/src/tools/inscriber/InscribeFromFileTool.ts +10 -13
  203. package/src/tools/inscriber/InscribeFromUrlTool.ts +15 -11
  204. package/src/tools/inscriber/InscribeHashinalTool.ts +40 -168
  205. package/src/tools/inscriber/RetrieveInscriptionTool.ts +15 -16
  206. package/src/types/inscription-response.ts +27 -0
  207. package/src/types/tx-results.ts +18 -0
  208. package/src/utils/CodedError.ts +8 -0
  209. package/src/utils/Encryption.ts +0 -2
  210. package/src/utils/ensure-agent-has-hbar.ts +4 -5
  211. package/src/utils/inscription-utils.ts +53 -0
@@ -1,113 +1,1787 @@
1
1
  import { BaseServiceBuilder } from "hedera-agent-kit";
2
- import { HCS6Client } from "@hashgraphonline/standards-sdk";
3
- class HCS6Builder extends BaseServiceBuilder {
4
- constructor(hederaKit) {
2
+ import { SignerProviderRegistry } from "./standards-agent-kit.es3.js";
3
+ import { Logger, HCS10Client as HCS10Client$1, AgentBuilder, AIAgentCapability, InboundTopicType, FeeConfigBuilder } from "@hashgraphonline/standards-sdk";
4
+ import fs from "fs";
5
+ import path__default from "path";
6
+ import axios from "axios";
7
+ const NOT_INITIALIZED_ERROR = "ConnectionsManager not initialized";
8
+ class HCS10Builder extends BaseServiceBuilder {
9
+ constructor(hederaKit, stateManager, options) {
5
10
  super(hederaKit);
11
+ this.stateManager = stateManager;
12
+ const network = this.hederaKit.client.network;
13
+ this.network = network.toString().includes("mainnet") ? "mainnet" : "testnet";
14
+ const operatorId = this.hederaKit.signer.getAccountId().toString();
15
+ const operatorPrivateKey = this.hederaKit.signer?.getOperatorPrivateKey() ? this.hederaKit.signer.getOperatorPrivateKey().toStringRaw() : "";
16
+ this.sdkLogger = (() => {
17
+ try {
18
+ if (typeof Logger === "function") {
19
+ return new Logger({
20
+ module: "HCS10Builder",
21
+ level: options?.logLevel || "info"
22
+ });
23
+ }
24
+ } catch {
25
+ }
26
+ return {
27
+ debug: () => {
28
+ },
29
+ info: () => {
30
+ },
31
+ warn: () => {
32
+ },
33
+ error: () => {
34
+ },
35
+ trace: () => {
36
+ },
37
+ setLogLevel: () => {
38
+ },
39
+ getLevel: () => "info",
40
+ setSilent: () => {
41
+ },
42
+ setModule: () => {
43
+ }
44
+ };
45
+ })();
46
+ this.standardClient = new HCS10Client$1({
47
+ network: this.network,
48
+ operatorId,
49
+ operatorPrivateKey,
50
+ logLevel: options?.logLevel || "info"
51
+ });
52
+ if (this.stateManager) {
53
+ this.stateManager.initializeConnectionsManager(this.standardClient);
54
+ }
55
+ }
56
+ /**
57
+ * Get the operator account ID
58
+ */
59
+ getOperatorId() {
60
+ const operator = this.standardClient.getClient().operatorAccountId;
61
+ if (!operator) {
62
+ throw new Error("Operator Account ID not configured in standard client.");
63
+ }
64
+ return operator.toString();
65
+ }
66
+ /**
67
+ * Get the network type
68
+ */
69
+ getNetwork() {
70
+ return this.network;
71
+ }
72
+ /**
73
+ * Get state manager instance
74
+ */
75
+ getStateManager() {
76
+ return this.stateManager;
77
+ }
78
+ /**
79
+ * Get account and signer information
80
+ */
81
+ getAccountAndSigner() {
82
+ const result = this.standardClient.getAccountAndSigner();
83
+ return {
84
+ accountId: result.accountId,
85
+ signer: result.signer
86
+ };
87
+ }
88
+ /**
89
+ * Get the inbound topic ID for the current operator
90
+ */
91
+ async getInboundTopicId() {
92
+ try {
93
+ const operatorId = this.getOperatorId();
94
+ this.logger.info(
95
+ `[HCS10Builder] Retrieving profile for operator ${operatorId} to find inbound topic...`
96
+ );
97
+ const profileResponse = await this.getAgentProfile(operatorId);
98
+ if (profileResponse.success && profileResponse.topicInfo?.inboundTopic) {
99
+ this.logger.info(
100
+ `[HCS10Builder] Found inbound topic for operator ${operatorId}: ${profileResponse.topicInfo.inboundTopic}`
101
+ );
102
+ return profileResponse.topicInfo.inboundTopic;
103
+ } else {
104
+ throw new Error(
105
+ `Could not retrieve inbound topic from profile for ${operatorId}. Profile success: ${profileResponse.success}, Error: ${profileResponse.error}`
106
+ );
107
+ }
108
+ } catch (error) {
109
+ this.logger.error(
110
+ `[HCS10Builder] Error fetching operator's inbound topic ID (${this.getOperatorId()}):`,
111
+ error
112
+ );
113
+ const operatorId = this.getOperatorId();
114
+ let detailedMessage = `Failed to get inbound topic ID for operator ${operatorId}.`;
115
+ if (error instanceof Error && error.message.includes("does not have a valid HCS-11 memo")) {
116
+ 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).`;
117
+ } else if (error instanceof Error) {
118
+ detailedMessage += ` Reason: ${error.message}`;
119
+ } else {
120
+ detailedMessage += ` Unexpected error: ${String(error)}`;
121
+ }
122
+ throw new Error(detailedMessage);
123
+ }
124
+ }
125
+ /**
126
+ * Get agent profile
127
+ */
128
+ async getAgentProfile(accountId) {
129
+ try {
130
+ return await this.standardClient.retrieveProfile(accountId);
131
+ } catch (error) {
132
+ this.logger.error(
133
+ `[HCS10Builder] Error retrieving agent profile for account ${accountId}:`,
134
+ error
135
+ );
136
+ throw error;
137
+ }
138
+ }
139
+ /**
140
+ * Submit connection request
141
+ */
142
+ async submitConnectionRequest(inboundTopicId, memo) {
143
+ const start = SignerProviderRegistry.startHCSDelegate;
144
+ const exec = SignerProviderRegistry.walletExecutor;
145
+ const preferWallet = SignerProviderRegistry.preferWalletOnly;
146
+ const network = this.network;
147
+ try {
148
+ const { ByteBuildRegistry } = await import("./standards-agent-kit.es4.js");
149
+ if (exec && ByteBuildRegistry.has("submitConnectionRequest")) {
150
+ const built = await ByteBuildRegistry.build("submitConnectionRequest", this.hederaKit, { inboundTopicId, memo });
151
+ if (built && built.transactionBytes) {
152
+ const { transactionId } = await exec(built.transactionBytes, network);
153
+ return { transactionId };
154
+ }
155
+ }
156
+ } catch {
157
+ }
158
+ if (start && exec) {
159
+ try {
160
+ const request = { inboundTopicId, memo };
161
+ const { transactionBytes } = await start("submitConnectionRequest", request, network);
162
+ const { transactionId } = await exec(transactionBytes, network);
163
+ return { transactionId };
164
+ } catch (err) {
165
+ if (preferWallet) {
166
+ const e = new Error(`wallet_submit_failed: ${err instanceof Error ? err.message : String(err)}`);
167
+ e.code = "wallet_submit_failed";
168
+ throw e;
169
+ }
170
+ }
171
+ } else if (preferWallet) {
172
+ const e = new Error("wallet_unavailable: connect a wallet or configure StartHCSDelegate and WalletExecutor");
173
+ e.code = "wallet_unavailable";
174
+ throw e;
175
+ }
176
+ return this.standardClient.submitConnectionRequest(
177
+ inboundTopicId,
178
+ memo
179
+ );
180
+ }
181
+ /**
182
+ * Handle connection request
183
+ */
184
+ async handleConnectionRequest(inboundTopicId, requestingAccountId, connectionRequestId, feeConfig) {
185
+ try {
186
+ const start = SignerProviderRegistry.startHCSDelegate;
187
+ const exec = SignerProviderRegistry.walletExecutor;
188
+ const preferWallet = SignerProviderRegistry.preferWalletOnly;
189
+ const network = this.network;
190
+ if (start && exec) {
191
+ try {
192
+ const request = {
193
+ inboundTopicId,
194
+ requestingAccountId,
195
+ connectionRequestId,
196
+ feeConfig: feeConfig ? "configured" : void 0
197
+ };
198
+ const { transactionBytes } = await start("handleConnectionRequest", request, network);
199
+ const { transactionId } = await exec(transactionBytes, network);
200
+ const minimal = {
201
+ success: true,
202
+ transactionId
203
+ };
204
+ return minimal;
205
+ } catch (err) {
206
+ if (preferWallet) {
207
+ const e = new Error(`wallet_submit_failed: ${err instanceof Error ? err.message : String(err)}`);
208
+ e.code = "wallet_submit_failed";
209
+ throw e;
210
+ }
211
+ }
212
+ } else if (preferWallet) {
213
+ const e = new Error("wallet_unavailable: connect a wallet or configure StartHCSDelegate and WalletExecutor");
214
+ e.code = "wallet_unavailable";
215
+ throw e;
216
+ }
217
+ const result = await this.standardClient.handleConnectionRequest(
218
+ inboundTopicId,
219
+ requestingAccountId,
220
+ connectionRequestId,
221
+ feeConfig
222
+ );
223
+ if (result && result.connectionTopicId && typeof result.connectionTopicId === "object" && "toString" in result.connectionTopicId) {
224
+ result.connectionTopicId = result.connectionTopicId.toString();
225
+ }
226
+ return result;
227
+ } catch (error) {
228
+ this.logger.error(
229
+ `Error handling connection request #${connectionRequestId} for topic ${inboundTopicId}:`,
230
+ error
231
+ );
232
+ throw new Error(
233
+ `Failed to handle connection request: ${error instanceof Error ? error.message : String(error)}`
234
+ );
235
+ }
236
+ }
237
+ /**
238
+ * Send message to a topic
239
+ */
240
+ async sendMessage(topicId, data, memo) {
241
+ if (topicId && typeof topicId === "object" && "toString" in topicId) {
242
+ topicId = topicId?.toString();
243
+ }
244
+ if (!topicId || typeof topicId !== "string") {
245
+ throw new Error(
246
+ `Invalid topic ID provided to sendMessage: ${JSON.stringify(topicId)}`
247
+ );
248
+ }
249
+ try {
250
+ let prevMaxSeq = 0;
251
+ try {
252
+ const prev = await this.getMessages(topicId);
253
+ prevMaxSeq = prev.messages.reduce((max, m) => Math.max(max, m.sequence_number || 0), 0);
254
+ } catch {
255
+ }
256
+ const start = SignerProviderRegistry.startHCSDelegate;
257
+ const exec = SignerProviderRegistry.walletExecutor;
258
+ const preferWallet = SignerProviderRegistry.preferWalletOnly;
259
+ const network = this.network;
260
+ try {
261
+ const { ByteBuildRegistry } = await import("./standards-agent-kit.es4.js");
262
+ if (exec && ByteBuildRegistry.has("sendMessage")) {
263
+ const built = await ByteBuildRegistry.build("sendMessage", this.hederaKit, { topicId, data, memo });
264
+ if (built && built.transactionBytes) {
265
+ const { transactionId } = await exec(built.transactionBytes, network);
266
+ const sequenceNumber = await this.pollForNewSequence(topicId, prevMaxSeq);
267
+ return {
268
+ sequenceNumber,
269
+ receipt: { transactionId },
270
+ transactionId
271
+ };
272
+ }
273
+ }
274
+ } catch {
275
+ }
276
+ if (start && exec) {
277
+ try {
278
+ const request = { topicId, data, memo };
279
+ const { transactionBytes } = await start("sendMessage", request, network);
280
+ const { transactionId } = await exec(transactionBytes, network);
281
+ const sequenceNumber = await this.pollForNewSequence(topicId, prevMaxSeq);
282
+ return {
283
+ sequenceNumber,
284
+ receipt: { transactionId },
285
+ transactionId
286
+ };
287
+ } catch (err) {
288
+ if (preferWallet) {
289
+ const e = new Error(`wallet_submit_failed: ${err instanceof Error ? err.message : String(err)}`);
290
+ e.code = "wallet_submit_failed";
291
+ throw e;
292
+ }
293
+ }
294
+ } else if (preferWallet) {
295
+ const e = new Error("wallet_unavailable: connect a wallet or configure StartHCSDelegate and WalletExecutor");
296
+ e.code = "wallet_unavailable";
297
+ throw e;
298
+ }
299
+ const messageResponse = await this.standardClient.sendMessage(
300
+ topicId,
301
+ data,
302
+ memo,
303
+ void 0
304
+ );
305
+ return {
306
+ sequenceNumber: messageResponse.topicSequenceNumber?.toNumber(),
307
+ receipt: messageResponse,
308
+ transactionId: "transactionId" in messageResponse ? messageResponse.transactionId?.toString() : void 0
309
+ };
310
+ } catch (error) {
311
+ this.logger.error(`Error sending message to topic ${topicId}:`, error);
312
+ throw new Error(
313
+ `Failed to send message: ${error instanceof Error ? error.message : String(error)}`
314
+ );
315
+ }
316
+ }
317
+ /**
318
+ * Get messages from a topic
319
+ */
320
+ async getMessages(topicId) {
321
+ if (topicId && typeof topicId === "object" && "toString" in topicId) {
322
+ topicId = topicId?.toString();
323
+ }
324
+ if (!topicId || typeof topicId !== "string") {
325
+ throw new Error(
326
+ `Invalid topic ID provided to getMessages: ${JSON.stringify(topicId)}`
327
+ );
328
+ }
329
+ try {
330
+ const result = await this.standardClient.getMessages(topicId);
331
+ const mappedMessages = result.messages.map(
332
+ (sdkMessage) => {
333
+ const timestamp = sdkMessage?.created?.getTime() || 0;
334
+ return {
335
+ ...sdkMessage,
336
+ timestamp,
337
+ data: sdkMessage.data || "",
338
+ sequence_number: sdkMessage.sequence_number,
339
+ p: "hcs-10"
340
+ };
341
+ }
342
+ );
343
+ mappedMessages.sort(
344
+ (a, b) => a.timestamp - b.timestamp
345
+ );
346
+ return { messages: mappedMessages };
347
+ } catch (error) {
348
+ this.logger.error(`Error getting messages from topic ${topicId}:`, error);
349
+ return { messages: [] };
350
+ }
351
+ }
352
+ /**
353
+ * Get message stream from a topic
354
+ */
355
+ async getMessageStream(topicId) {
356
+ if (topicId && typeof topicId === "object" && "toString" in topicId) {
357
+ topicId = topicId?.toString();
358
+ }
359
+ if (!topicId || typeof topicId !== "string") {
360
+ throw new Error(
361
+ `Invalid topic ID provided to getMessageStream: ${JSON.stringify(
362
+ topicId
363
+ )}`
364
+ );
365
+ }
366
+ return this.standardClient.getMessageStream(topicId);
367
+ }
368
+ /**
369
+ * Get message content
370
+ */
371
+ async getMessageContent(inscriptionIdOrData) {
372
+ try {
373
+ const content = await this.standardClient.getMessageContent(
374
+ inscriptionIdOrData
375
+ );
376
+ return content;
377
+ } catch (error) {
378
+ this.logger.error(
379
+ `Error retrieving message content for: ${inscriptionIdOrData}`,
380
+ error
381
+ );
382
+ throw new Error(
383
+ `Failed to retrieve message content: ${error instanceof Error ? error.message : String(error)}`
384
+ );
385
+ }
386
+ }
387
+ /**
388
+ * Get the standard client instance (for compatibility)
389
+ */
390
+ getStandardClient() {
391
+ return this.standardClient;
392
+ }
393
+ /**
394
+ * Load profile picture from URL or file path
395
+ */
396
+ async loadProfilePicture(profilePicture) {
397
+ try {
398
+ if (!profilePicture) {
399
+ return null;
400
+ }
401
+ if (typeof profilePicture === "string") {
402
+ const isUrl = profilePicture.startsWith("http://") || profilePicture.startsWith("https://");
403
+ if (isUrl) {
404
+ this.logger.info(
405
+ `Loading profile picture from URL: ${profilePicture}`
406
+ );
407
+ const response = await axios.get(profilePicture, {
408
+ responseType: "arraybuffer"
409
+ });
410
+ const buffer = Buffer.from(response.data);
411
+ const urlPathname = new URL(profilePicture).pathname;
412
+ const filename = path__default.basename(urlPathname) || "profile.png";
413
+ return { buffer, filename };
414
+ } else {
415
+ if (!fs.existsSync(profilePicture)) {
416
+ this.logger.warn(
417
+ `Profile picture file not found: ${profilePicture}`
418
+ );
419
+ return null;
420
+ }
421
+ this.logger.info(
422
+ `Loading profile picture from file: ${profilePicture}`
423
+ );
424
+ const buffer = fs.readFileSync(profilePicture);
425
+ const filename = path__default.basename(profilePicture);
426
+ return { buffer, filename };
427
+ }
428
+ } else if (profilePicture.url) {
429
+ this.logger.info(
430
+ `Loading profile picture from URL: ${profilePicture.url}`
431
+ );
432
+ const response = await axios.get(profilePicture.url, {
433
+ responseType: "arraybuffer"
434
+ });
435
+ const buffer = Buffer.from(response.data);
436
+ const filename = profilePicture.filename || "profile.png";
437
+ return { buffer, filename };
438
+ } else if (profilePicture.path) {
439
+ if (!fs.existsSync(profilePicture.path)) {
440
+ this.logger.warn(
441
+ `Profile picture file not found: ${profilePicture.path}`
442
+ );
443
+ return null;
444
+ }
445
+ this.logger.info(
446
+ `Loading profile picture from file: ${profilePicture.path}`
447
+ );
448
+ const buffer = fs.readFileSync(profilePicture.path);
449
+ const filename = profilePicture.filename || path__default.basename(profilePicture.path);
450
+ return { buffer, filename };
451
+ }
452
+ return null;
453
+ } catch (error) {
454
+ this.logger.error("Failed to load profile picture:", error);
455
+ return null;
456
+ }
457
+ }
458
+ async pollForNewSequence(topicId, prevMax) {
459
+ const maxAttempts = 10;
460
+ const delayMs = 1e3;
461
+ for (let i = 0; i < maxAttempts; i++) {
462
+ try {
463
+ const res = await this.getMessages(topicId);
464
+ const maxSeq = res.messages.reduce((m, msg) => Math.max(m, msg.sequence_number || 0), prevMax);
465
+ if (maxSeq > prevMax) return maxSeq;
466
+ } catch {
467
+ }
468
+ await new Promise((r) => setTimeout(r, delayMs));
469
+ }
470
+ return void 0;
471
+ }
472
+ /**
473
+ * Create and register an agent
474
+ */
475
+ async createAndRegisterAgent(data) {
476
+ const builder = new AgentBuilder().setName(data.name).setBio(data.bio || "").setCapabilities(
477
+ data.capabilities || [AIAgentCapability.TEXT_GENERATION]
478
+ ).setType(data.type || "autonomous").setModel(data.model || "agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(InboundTopicType.PUBLIC);
479
+ if (data.alias) {
480
+ builder.setAlias(data.alias);
481
+ }
482
+ if (data.creator) {
483
+ builder.setCreator(data.creator);
484
+ }
485
+ if (data?.feeConfig) {
486
+ builder.setInboundTopicType(InboundTopicType.FEE_BASED);
487
+ builder.setFeeConfig(data.feeConfig);
488
+ }
489
+ if (data.existingProfilePictureTopicId) {
490
+ builder.setExistingProfilePicture(data.existingProfilePictureTopicId);
491
+ } else if (data.pfpBuffer && data.pfpFileName) {
492
+ if (data.pfpBuffer.byteLength === 0) {
493
+ this.logger.warn(
494
+ "Provided PFP buffer is empty. Skipping profile picture."
495
+ );
496
+ } else {
497
+ this.logger.info(
498
+ `Setting profile picture: ${data.pfpFileName} (${data.pfpBuffer.byteLength} bytes)`
499
+ );
500
+ builder.setProfilePicture(data.pfpBuffer, data.pfpFileName);
501
+ }
502
+ } else {
503
+ this.logger.warn(
504
+ "Profile picture not provided. Agent creation might fail if required by the underlying SDK builder."
505
+ );
506
+ }
507
+ if (data.socials) {
508
+ Object.entries(data.socials).forEach(([platform, handle]) => {
509
+ builder.addSocial(platform, handle);
510
+ });
511
+ }
512
+ if (data.properties) {
513
+ Object.entries(data.properties).forEach(([key, value]) => {
514
+ builder.addProperty(key, value);
515
+ });
516
+ }
517
+ try {
518
+ const hasFees = Boolean(data?.feeConfig);
519
+ const result = await this.standardClient.createAndRegisterAgent(builder, {
520
+ initialBalance: hasFees ? 50 : 10
521
+ });
522
+ return result;
523
+ } catch (error) {
524
+ this.logger.error("Error during agent creation/registration:", error);
525
+ throw new Error(
526
+ `Failed to create/register agent: ${error instanceof Error ? error.message : String(error)}`
527
+ );
528
+ }
529
+ }
530
+ /**
531
+ * Register a new HCS-10 agent
532
+ * Note: This performs multiple transactions and requires directExecution mode
533
+ */
534
+ async registerAgent(params) {
535
+ this.clearNotes();
536
+ if (this.hederaKit.operationalMode === "returnBytes") {
537
+ throw new Error(
538
+ "Agent registration requires multiple transactions and cannot be performed in returnBytes mode. Please use autonomous mode."
539
+ );
540
+ }
541
+ try {
542
+ let profilePictureData = null;
543
+ if (params.profilePicture) {
544
+ profilePictureData = await this.loadProfilePicture(
545
+ params.profilePicture
546
+ );
547
+ }
548
+ const registrationData = {
549
+ name: params.name,
550
+ ...params.bio !== void 0 && { bio: params.bio },
551
+ ...params.alias !== void 0 && { alias: params.alias },
552
+ ...params.type !== void 0 && { type: params.type },
553
+ ...params.model !== void 0 && { model: params.model },
554
+ ...params.capabilities !== void 0 && {
555
+ capabilities: params.capabilities
556
+ },
557
+ ...params.creator !== void 0 && { creator: params.creator },
558
+ ...params.socials !== void 0 && { socials: params.socials },
559
+ ...params.properties !== void 0 && {
560
+ properties: params.properties
561
+ },
562
+ ...params.existingProfilePictureTopicId !== void 0 && {
563
+ existingProfilePictureTopicId: params.existingProfilePictureTopicId
564
+ },
565
+ ...profilePictureData?.buffer !== void 0 && {
566
+ pfpBuffer: profilePictureData.buffer
567
+ },
568
+ ...profilePictureData?.filename !== void 0 && {
569
+ pfpFileName: profilePictureData.filename
570
+ }
571
+ };
572
+ if (params.hbarFee && params.hbarFee > 0) {
573
+ const feeConfigBuilder = new FeeConfigBuilder({
574
+ network: this.network,
575
+ logger: this.sdkLogger
576
+ });
577
+ const { accountId: collectorAccountId } = this.getAccountAndSigner();
578
+ if (!collectorAccountId) {
579
+ throw new Error("Could not determine account ID for fee collection.");
580
+ }
581
+ this.addNote(
582
+ `Setting the operator account (${collectorAccountId}) as the fee collector since no specific collector was provided.`
583
+ );
584
+ const effectiveExemptIds = params.exemptAccountIds?.filter(
585
+ (id) => id !== collectorAccountId && id.startsWith("0.0")
586
+ ) || [];
587
+ registrationData.feeConfig = feeConfigBuilder.addHbarFee(
588
+ params.hbarFee,
589
+ collectorAccountId,
590
+ effectiveExemptIds
591
+ );
592
+ }
593
+ const preferWallet = SignerProviderRegistry.preferWalletOnly;
594
+ const browserClient = SignerProviderRegistry.getBrowserHCSClient(this.network);
595
+ if (browserClient) {
596
+ try {
597
+ const aBuilder = new AgentBuilder().setNetwork(this.network).setName(registrationData.name).setAlias(registrationData.alias || `${registrationData.name}-${Date.now()}`).setBio(registrationData.bio || "").setType(registrationData.type || "autonomous").setModel(registrationData.model || "agent-model-2024");
598
+ if (registrationData.capabilities?.length) {
599
+ aBuilder.setCapabilities(registrationData.capabilities);
600
+ }
601
+ if (registrationData.creator) aBuilder.setCreator(registrationData.creator);
602
+ if (registrationData.existingProfilePictureTopicId) {
603
+ aBuilder.setExistingProfilePicture(registrationData.existingProfilePictureTopicId);
604
+ }
605
+ if (registrationData.socials) {
606
+ Object.entries(registrationData.socials).forEach(([platform, handle]) => {
607
+ if (handle && typeof handle === "string") {
608
+ aBuilder.addSocial(platform, handle);
609
+ }
610
+ });
611
+ }
612
+ if (registrationData.properties) {
613
+ Object.entries(registrationData.properties).forEach(([key, value]) => {
614
+ if (value != null) aBuilder.addProperty(key, value);
615
+ });
616
+ }
617
+ const resp = await browserClient.create(aBuilder, {
618
+ progressCallback: (_) => {
619
+ },
620
+ updateAccountMemo: true
621
+ });
622
+ this.executeResult = {
623
+ success: true,
624
+ transactionId: void 0,
625
+ receipt: void 0,
626
+ scheduleId: void 0,
627
+ rawResult: { result: resp, name: registrationData.name }
628
+ };
629
+ return this;
630
+ } catch (walletErr) {
631
+ if (preferWallet) {
632
+ throw new Error(`wallet_registration_failed: ${walletErr instanceof Error ? walletErr.message : String(walletErr)}`);
633
+ }
634
+ }
635
+ } else if (preferWallet) {
636
+ throw new Error("wallet_unavailable: BrowserHCSClient factory not provided");
637
+ }
638
+ const result = await this.createAndRegisterAgent(registrationData);
639
+ this.executeResult = {
640
+ success: true,
641
+ transactionId: result.transactionId,
642
+ receipt: void 0,
643
+ scheduleId: void 0,
644
+ rawResult: {
645
+ ...result,
646
+ name: params.name,
647
+ accountId: result?.metadata?.accountId || result.state?.agentMetadata?.accountId
648
+ }
649
+ };
650
+ } catch (error) {
651
+ this.logger.error("Failed to register agent:", error);
652
+ throw error;
653
+ }
654
+ return this;
6
655
  }
7
656
  /**
8
- * Get or create HCS-6 client
657
+ * Initiate a connection to another agent
9
658
  */
10
- async getHCS6Client() {
11
- if (!this.hcs6Client) {
12
- const operatorId = this.hederaKit.signer.getAccountId().toString();
13
- const operatorPrivateKey = this.hederaKit.signer?.getOperatorPrivateKey() ? this.hederaKit.signer.getOperatorPrivateKey().toString() : "";
14
- const network = this.hederaKit.client.network;
15
- const networkType = network.toString().includes("mainnet") ? "mainnet" : "testnet";
16
- const config = {
17
- network: networkType,
18
- operatorId,
19
- operatorKey: operatorPrivateKey
659
+ async initiateConnection(params) {
660
+ this.clearNotes();
661
+ try {
662
+ const targetProfile = await this.getAgentProfile(params.targetAccountId);
663
+ if (!targetProfile.success || !targetProfile.topicInfo?.inboundTopic) {
664
+ throw new Error(
665
+ `Could not retrieve inbound topic for target account ${params.targetAccountId}`
666
+ );
667
+ }
668
+ const targetInboundTopicId = targetProfile.topicInfo.inboundTopic;
669
+ let memo;
670
+ if (params.memo !== void 0) {
671
+ memo = params.memo;
672
+ } else {
673
+ memo = params.disableMonitor ? "false" : "true";
674
+ this.addNote(
675
+ `No custom memo was provided. Using default memo '${memo}' based on monitoring preference.`
676
+ );
677
+ }
678
+ if (!params.disableMonitor) {
679
+ this.addNote(
680
+ `Monitoring will be enabled for this connection request as disableMonitor was not specified.`
681
+ );
682
+ }
683
+ const result = await this.submitConnectionRequest(
684
+ targetInboundTopicId,
685
+ memo
686
+ );
687
+ this.executeResult = {
688
+ success: true,
689
+ transactionId: "transactionId" in result ? result.transactionId?.toString() : void 0,
690
+ receipt: result,
691
+ scheduleId: void 0,
692
+ rawResult: {
693
+ targetAccountId: params.targetAccountId,
694
+ targetInboundTopicId,
695
+ connectionRequestSent: true,
696
+ monitoringEnabled: !params.disableMonitor,
697
+ ...result
698
+ }
20
699
  };
21
- this.hcs6Client = new HCS6Client(config);
700
+ } catch (error) {
701
+ this.logger.error("Failed to initiate connection:", error);
702
+ throw error;
22
703
  }
23
- return this.hcs6Client;
704
+ return this;
24
705
  }
25
706
  /**
26
- * Create a new HCS-6 dynamic registry
27
- * Note: This executes the transaction directly via HCS6Client
707
+ * Accept a connection request
708
+ * Note: This performs multiple transactions and requires directExecution mode
28
709
  */
29
- async createRegistry(options = {}) {
30
- const client = await this.getHCS6Client();
31
- const sanitized = { ...options };
32
- if ("adminKey" in sanitized) {
33
- delete sanitized.adminKey;
710
+ async acceptConnection(params) {
711
+ this.clearNotes();
712
+ if (this.hederaKit.operationalMode === "returnBytes") {
713
+ throw new Error(
714
+ "Accepting connections requires multiple transactions and cannot be performed in returnBytes mode. Please use autonomous mode."
715
+ );
716
+ }
717
+ try {
718
+ const currentAgent = this.stateManager?.getCurrentAgent();
719
+ if (!currentAgent) {
720
+ throw new Error(
721
+ "Cannot accept connection request. No agent is currently active. Please register or select an agent first."
722
+ );
723
+ }
724
+ const connectionsManager = this.stateManager?.getConnectionsManager();
725
+ if (!connectionsManager) {
726
+ throw new Error(NOT_INITIALIZED_ERROR);
727
+ }
728
+ await connectionsManager.fetchConnectionData(currentAgent.accountId);
729
+ const allRequests = [
730
+ ...connectionsManager.getPendingRequests(),
731
+ ...connectionsManager.getConnectionsNeedingConfirmation()
732
+ ];
733
+ const request = allRequests.find(
734
+ (r) => r.uniqueRequestKey === params.requestKey || r.connectionRequestId?.toString() === params.requestKey || r.inboundRequestId?.toString() === params.requestKey
735
+ );
736
+ if (!request) {
737
+ throw new Error(
738
+ `Request with key ${params.requestKey} not found or no longer pending.`
739
+ );
740
+ }
741
+ if (!request.needsConfirmation || !request.inboundRequestId) {
742
+ throw new Error(
743
+ `Request with key ${params.requestKey} is not an inbound request that can be accepted.`
744
+ );
745
+ }
746
+ const targetAccountId = request.targetAccountId;
747
+ const inboundRequestId = request.inboundRequestId;
748
+ let feeConfig;
749
+ if (params.hbarFee && params.hbarFee > 0) {
750
+ const feeConfigBuilder = new FeeConfigBuilder({
751
+ network: this.network,
752
+ logger: this.sdkLogger
753
+ });
754
+ const { accountId: collectorAccountId } = this.getAccountAndSigner();
755
+ if (!collectorAccountId) {
756
+ throw new Error("Could not determine account ID for fee collection.");
757
+ }
758
+ this.addNote(
759
+ `Setting the operator account (${collectorAccountId}) as the fee collector since no specific collector was provided.`
760
+ );
761
+ const effectiveExemptIds = params.exemptAccountIds?.filter(
762
+ (id) => id !== collectorAccountId && id.startsWith("0.0")
763
+ ) || [];
764
+ feeConfig = feeConfigBuilder.addHbarFee(
765
+ params.hbarFee,
766
+ collectorAccountId,
767
+ effectiveExemptIds
768
+ );
769
+ }
770
+ const inboundTopicId = await this.getInboundTopicId();
771
+ const confirmationResult = await this.handleConnectionRequest(
772
+ inboundTopicId,
773
+ targetAccountId,
774
+ inboundRequestId,
775
+ feeConfig
776
+ );
777
+ let connectionTopicId = confirmationResult?.connectionTopicId;
778
+ if (connectionTopicId && typeof connectionTopicId === "object" && "toString" in connectionTopicId) {
779
+ connectionTopicId = connectionTopicId?.toString();
780
+ }
781
+ if (!connectionTopicId || typeof connectionTopicId !== "string") {
782
+ try {
783
+ const refreshed = await this.stateManager?.getConnectionsManager()?.fetchConnectionData(currentAgent.accountId);
784
+ const established = (refreshed || []).find(
785
+ (c) => c.targetAccountId === targetAccountId && c.status === "established"
786
+ );
787
+ if (established?.connectionTopicId) {
788
+ connectionTopicId = established.connectionTopicId;
789
+ }
790
+ } catch (e) {
791
+ this.logger.debug("Could not refresh connections after acceptance to derive topic id:", e);
792
+ }
793
+ }
794
+ if (!connectionTopicId || typeof connectionTopicId !== "string") {
795
+ throw new Error(
796
+ `Failed to create connection topic. Got: ${JSON.stringify(
797
+ connectionTopicId
798
+ )}`
799
+ );
800
+ }
801
+ if (this.stateManager) {
802
+ const targetAgentName = request.targetAgentName || `Agent ${targetAccountId}`;
803
+ if (!request.targetAgentName) {
804
+ this.addNote(
805
+ `No agent name was provided in the connection request, using default name 'Agent ${targetAccountId}'.`
806
+ );
807
+ }
808
+ let targetInboundTopicId = request.targetInboundTopicId || "";
809
+ if (!targetInboundTopicId) {
810
+ try {
811
+ const targetProfile = await this.getAgentProfile(targetAccountId);
812
+ if (targetProfile.success && targetProfile.topicInfo?.inboundTopic) {
813
+ targetInboundTopicId = targetProfile.topicInfo.inboundTopic;
814
+ }
815
+ } catch (profileError) {
816
+ this.logger.warn(
817
+ `Could not fetch profile for ${targetAccountId}:`,
818
+ profileError
819
+ );
820
+ }
821
+ }
822
+ const newConnection = {
823
+ connectionId: `conn-${Date.now()}`,
824
+ targetAccountId,
825
+ targetAgentName,
826
+ targetInboundTopicId,
827
+ connectionTopicId,
828
+ status: "established",
829
+ created: /* @__PURE__ */ new Date()
830
+ };
831
+ this.stateManager.addActiveConnection(newConnection);
832
+ connectionsManager.markConnectionRequestProcessed(
833
+ request.targetInboundTopicId || "",
834
+ inboundRequestId
835
+ );
836
+ }
837
+ this.executeResult = {
838
+ success: true,
839
+ transactionId: void 0,
840
+ receipt: void 0,
841
+ scheduleId: void 0,
842
+ rawResult: {
843
+ targetAccountId,
844
+ connectionTopicId,
845
+ feeConfigured: !!params.hbarFee,
846
+ hbarFee: params.hbarFee || 0,
847
+ confirmationResult
848
+ }
849
+ };
850
+ } catch (error) {
851
+ this.logger.error("Failed to accept connection:", error);
852
+ throw error;
34
853
  }
35
- return await client.createRegistry(sanitized);
854
+ return this;
36
855
  }
37
856
  /**
38
- * Register a new dynamic hashinal entry in an HCS-6 registry
857
+ * Send a message using HCS (for operations that need direct topic access)
39
858
  */
40
- async registerEntry(registryTopicId, options) {
41
- const client = await this.getHCS6Client();
42
- return await client.registerEntry(registryTopicId, options);
859
+ async sendHCS10Message(params) {
860
+ this.clearNotes();
861
+ try {
862
+ const result = await this.sendMessage(params.topicId, params.message);
863
+ this.executeResult = {
864
+ success: true,
865
+ transactionId: result.transactionId,
866
+ receipt: result.receipt,
867
+ scheduleId: void 0,
868
+ rawResult: result
869
+ };
870
+ this.addNote(`Message sent to topic ${params.topicId}.`);
871
+ } catch (error) {
872
+ this.logger.error("Failed to send message:", error);
873
+ throw error;
874
+ }
875
+ return this;
876
+ }
877
+ /**
878
+ * Send a message to a connected account with optional response monitoring
879
+ */
880
+ async sendMessageToConnection(params) {
881
+ this.clearNotes();
882
+ if (!this.stateManager) {
883
+ throw new Error(
884
+ "StateManager is required to send messages to connections"
885
+ );
886
+ }
887
+ try {
888
+ const currentAgent = this.stateManager.getCurrentAgent();
889
+ if (!currentAgent) {
890
+ throw new Error(
891
+ "Cannot send message. No agent is currently active. Please register or select an agent first."
892
+ );
893
+ }
894
+ let connection;
895
+ const identifier = params.targetIdentifier;
896
+ if (identifier.includes("@")) {
897
+ const parts = identifier.split("@");
898
+ if (parts.length === 2) {
899
+ const accountId = parts[1];
900
+ connection = this.stateManager.getConnectionByIdentifier(accountId);
901
+ if (!connection) {
902
+ this.addNote(
903
+ `Could not find connection using request key '${identifier}', extracted account ID '${accountId}'.`
904
+ );
905
+ }
906
+ }
907
+ }
908
+ if (!connection) {
909
+ connection = this.stateManager.getConnectionByIdentifier(identifier);
910
+ }
911
+ if (!connection && !identifier.startsWith("0.0.") && /^\d+$/.test(identifier)) {
912
+ const accountIdWithPrefix = `0.0.${identifier}`;
913
+ connection = this.stateManager.getConnectionByIdentifier(accountIdWithPrefix);
914
+ if (connection) {
915
+ this.addNote(
916
+ `Found connection using account ID with prefix: ${accountIdWithPrefix}`
917
+ );
918
+ }
919
+ }
920
+ if (!connection && /^[1-9]\d*$/.test(identifier)) {
921
+ const connections = this.stateManager.listConnections();
922
+ const index = parseInt(identifier) - 1;
923
+ if (index >= 0 && index < connections.length) {
924
+ connection = connections[index];
925
+ if (connection) {
926
+ this.addNote(
927
+ `Found connection by index ${identifier}: ${connection.targetAccountId}`
928
+ );
929
+ }
930
+ }
931
+ }
932
+ if (!connection) {
933
+ const connections = this.stateManager.listConnections();
934
+ const availableIds = connections.map(
935
+ (c, i) => `${i + 1}. ${c.targetAccountId} (Topic: ${c.connectionTopicId})`
936
+ );
937
+ let errorMsg = `Connection not found for identifier: "${identifier}"
938
+ `;
939
+ errorMsg += `Available connections:
940
+ ${availableIds.join("\n") || "No active connections"}`;
941
+ errorMsg += `
942
+
943
+ You can use:
944
+ `;
945
+ errorMsg += `- Connection number (e.g., "1", "2")
946
+ `;
947
+ errorMsg += `- Account ID (e.g., "0.0.6412936")
948
+ `;
949
+ errorMsg += `- Connection topic ID
950
+ `;
951
+ errorMsg += `Use 'list_connections' to see all active connections.`;
952
+ throw new Error(errorMsg);
953
+ }
954
+ let connectionTopicId = connection.connectionTopicId;
955
+ if (connectionTopicId && typeof connectionTopicId === "object" && "toString" in connectionTopicId) {
956
+ connectionTopicId = connectionTopicId?.toString();
957
+ }
958
+ if (!connectionTopicId || typeof connectionTopicId !== "string") {
959
+ throw new Error(
960
+ `Invalid connection topic ID for ${connection.targetAccountId}: ${JSON.stringify(
961
+ connectionTopicId
962
+ )} (type: ${typeof connectionTopicId})`
963
+ );
964
+ }
965
+ const targetAgentName = connection.targetAgentName;
966
+ const operatorId = `${currentAgent.inboundTopicId}@${currentAgent.accountId}`;
967
+ let baseSeq = 0;
968
+ try {
969
+ const prev = await this.getMessages(connectionTopicId);
970
+ baseSeq = prev.messages.reduce((max, m) => Math.max(max, m.sequence_number || 0), 0);
971
+ } catch {
972
+ }
973
+ const messageResult = await this.sendMessage(
974
+ connectionTopicId,
975
+ params.message,
976
+ `Agent message from ${currentAgent.name}`
977
+ );
978
+ const effectiveSeq = messageResult.sequenceNumber ?? baseSeq;
979
+ if (effectiveSeq === 0) {
980
+ throw new Error("Failed to send message");
981
+ }
982
+ let reply = null;
983
+ if (!params.disableMonitoring) {
984
+ reply = await this.monitorResponses(
985
+ connectionTopicId,
986
+ operatorId,
987
+ effectiveSeq
988
+ );
989
+ } else {
990
+ this.addNote(
991
+ `Message sent successfully. Response monitoring was disabled.`
992
+ );
993
+ }
994
+ this.executeResult = {
995
+ success: true,
996
+ transactionId: messageResult.transactionId,
997
+ receipt: messageResult.receipt,
998
+ scheduleId: void 0,
999
+ rawResult: {
1000
+ targetAgentName,
1001
+ targetAccountId: connection.targetAccountId,
1002
+ connectionTopicId,
1003
+ sequenceNumber: messageResult.sequenceNumber,
1004
+ reply,
1005
+ monitoringEnabled: !params.disableMonitoring,
1006
+ message: params.message,
1007
+ messageResult
1008
+ }
1009
+ };
1010
+ } catch (error) {
1011
+ this.logger.error("Failed to send message to connection:", error);
1012
+ throw error;
1013
+ }
1014
+ return this;
43
1015
  }
44
1016
  /**
45
- * Query entries from an HCS-6 registry
1017
+ * Monitor responses on a topic after sending a message
46
1018
  */
47
- async getRegistry(topicId, options = {}) {
48
- const client = await this.getHCS6Client();
49
- return await client.getRegistry(topicId, options);
1019
+ async monitorResponses(topicId, operatorId, sequenceNumber) {
1020
+ const maxAttempts = 30;
1021
+ let attempts = 0;
1022
+ while (attempts < maxAttempts) {
1023
+ try {
1024
+ const messages = await this.getMessageStream(topicId);
1025
+ for (const message of messages.messages) {
1026
+ if (message.sequence_number < sequenceNumber || message.operator_id === operatorId) {
1027
+ continue;
1028
+ }
1029
+ const content = await this.getMessageContent(message.data || "");
1030
+ return content;
1031
+ }
1032
+ } catch (error) {
1033
+ this.logger.error(`Error monitoring responses: ${error}`);
1034
+ }
1035
+ await new Promise((resolve) => setTimeout(resolve, 4e3));
1036
+ attempts++;
1037
+ }
1038
+ return null;
50
1039
  }
51
1040
  /**
52
- * Create a complete dynamic hashinal with inscription and registry
1041
+ * Start passive monitoring for incoming connection requests
1042
+ * This method monitors continuously in the background
53
1043
  */
54
- async createHashinal(options) {
55
- const client = await this.getHCS6Client();
56
- const metadata = {
57
- name: options.metadata?.name || "Dynamic Hashinal",
58
- creator: options.metadata?.creator || this.hederaKit.signer.getAccountId().toString(),
59
- description: options.metadata?.description || "Dynamic hashinal metadata",
60
- type: options.metadata?.type || "json",
61
- ...options.metadata
1044
+ async startPassiveConnectionMonitoring() {
1045
+ this.clearNotes();
1046
+ if (!this.stateManager) {
1047
+ throw new Error("StateManager is required for passive monitoring");
1048
+ }
1049
+ const inboundTopicId = await this.getInboundTopicId();
1050
+ this.logger.info(
1051
+ `Starting passive connection monitoring on topic ${inboundTopicId}...`
1052
+ );
1053
+ this.executeResult = {
1054
+ success: true,
1055
+ transactionId: void 0,
1056
+ receipt: void 0,
1057
+ scheduleId: void 0,
1058
+ rawResult: {
1059
+ inboundTopicId,
1060
+ message: `Started monitoring inbound topic ${inboundTopicId} for connection requests in the background.`
1061
+ }
62
1062
  };
63
- return await client.createHashinal({
64
- ...options,
65
- metadata
66
- });
1063
+ return this;
67
1064
  }
68
1065
  /**
69
- * Register a dynamic hashinal with combined inscription and registry creation
70
- * This is the main method for creating and updating dynamic hashinals
1066
+ * Monitor for incoming connection requests
71
1067
  */
72
- async register(options) {
73
- const client = await this.getHCS6Client();
74
- const metadata = {
75
- name: options.metadata?.name || "Dynamic Hashinal",
76
- creator: options.metadata?.creator || this.hederaKit.signer.getAccountId().toString(),
77
- description: options.metadata?.description || "Dynamic hashinal registration",
78
- type: options.metadata?.type || "json",
79
- ...options.metadata
1068
+ async monitorConnections(params) {
1069
+ this.clearNotes();
1070
+ const {
1071
+ acceptAll = false,
1072
+ targetAccountId,
1073
+ monitorDurationSeconds = 120,
1074
+ hbarFees = [],
1075
+ tokenFees = [],
1076
+ exemptAccountIds = [],
1077
+ defaultCollectorAccount
1078
+ } = params;
1079
+ if (!this.stateManager) {
1080
+ throw new Error("StateManager is required for connection monitoring");
1081
+ }
1082
+ const currentAgent = this.stateManager.getCurrentAgent();
1083
+ if (!currentAgent) {
1084
+ throw new Error(
1085
+ "Cannot monitor for connections. No agent is currently active."
1086
+ );
1087
+ }
1088
+ const inboundTopicId = await this.getInboundTopicId();
1089
+ const endTime = Date.now() + monitorDurationSeconds * 1e3;
1090
+ const pollIntervalMs = 3e3;
1091
+ let connectionRequestsFound = 0;
1092
+ let acceptedConnections = 0;
1093
+ const processedRequestIds = /* @__PURE__ */ new Set();
1094
+ while (Date.now() < endTime) {
1095
+ try {
1096
+ const messagesResult = await this.getMessages(inboundTopicId);
1097
+ const connectionRequests = messagesResult.messages.filter(
1098
+ (msg) => msg.op === "connection_request" && typeof msg.sequence_number === "number"
1099
+ );
1100
+ for (const request of connectionRequests) {
1101
+ const connectionRequestId = request.sequence_number;
1102
+ if (!connectionRequestId || processedRequestIds.has(connectionRequestId)) {
1103
+ continue;
1104
+ }
1105
+ const requestingAccountId = request.operator_id?.split("@")[1];
1106
+ if (!requestingAccountId) {
1107
+ continue;
1108
+ }
1109
+ connectionRequestsFound++;
1110
+ if (targetAccountId && requestingAccountId !== targetAccountId) {
1111
+ this.logger.info(
1112
+ `Skipping request from ${requestingAccountId} (not target account)`
1113
+ );
1114
+ continue;
1115
+ }
1116
+ if (acceptAll || targetAccountId === requestingAccountId) {
1117
+ this.logger.info(
1118
+ `Accepting connection request from ${requestingAccountId}`
1119
+ );
1120
+ let feeConfig;
1121
+ if (hbarFees.length > 0 || tokenFees.length > 0) {
1122
+ const builder = new FeeConfigBuilder({
1123
+ network: this.network,
1124
+ logger: this.sdkLogger
1125
+ });
1126
+ for (const fee of hbarFees) {
1127
+ const collectorAccount = fee.collectorAccount || defaultCollectorAccount || this.getOperatorId();
1128
+ builder.addHbarFee(
1129
+ fee.amount,
1130
+ collectorAccount,
1131
+ exemptAccountIds
1132
+ );
1133
+ }
1134
+ for (const fee of tokenFees) {
1135
+ const collectorAccount = fee.collectorAccount || defaultCollectorAccount || this.getOperatorId();
1136
+ builder.addTokenFee(
1137
+ fee.amount,
1138
+ fee.tokenId,
1139
+ collectorAccount,
1140
+ void 0,
1141
+ exemptAccountIds
1142
+ );
1143
+ }
1144
+ feeConfig = builder;
1145
+ }
1146
+ await this.handleConnectionRequest(
1147
+ inboundTopicId,
1148
+ requestingAccountId,
1149
+ connectionRequestId,
1150
+ feeConfig
1151
+ );
1152
+ processedRequestIds.add(connectionRequestId);
1153
+ acceptedConnections++;
1154
+ }
1155
+ }
1156
+ } catch (error) {
1157
+ this.logger.error("Error during connection monitoring:", error);
1158
+ }
1159
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
1160
+ }
1161
+ this.executeResult = {
1162
+ success: true,
1163
+ transactionId: void 0,
1164
+ receipt: void 0,
1165
+ scheduleId: void 0,
1166
+ rawResult: {
1167
+ connectionRequestsFound,
1168
+ acceptedConnections,
1169
+ monitorDurationSeconds,
1170
+ processedRequestIds: Array.from(processedRequestIds)
1171
+ }
80
1172
  };
81
- return await client.register({
82
- ...options,
83
- metadata
84
- });
1173
+ this.addNote(
1174
+ `Monitoring completed. Found ${connectionRequestsFound} requests, accepted ${acceptedConnections}.`
1175
+ );
1176
+ return this;
1177
+ }
1178
+ /**
1179
+ * Manage connection requests (list, view, or reject)
1180
+ */
1181
+ async manageConnectionRequests(params) {
1182
+ this.clearNotes();
1183
+ if (!this.stateManager) {
1184
+ throw new Error(
1185
+ "StateManager is required for managing connection requests"
1186
+ );
1187
+ }
1188
+ const currentAgent = this.stateManager.getCurrentAgent();
1189
+ if (!currentAgent) {
1190
+ throw new Error(
1191
+ "Cannot manage connection requests. No agent is currently active."
1192
+ );
1193
+ }
1194
+ const connectionsManager = this.stateManager.getConnectionsManager();
1195
+ if (!connectionsManager) {
1196
+ throw new Error(NOT_INITIALIZED_ERROR);
1197
+ }
1198
+ try {
1199
+ const { accountId } = this.getAccountAndSigner();
1200
+ await connectionsManager.fetchConnectionData(accountId);
1201
+ const pendingRequests = connectionsManager.getPendingRequests();
1202
+ const needsConfirmation = connectionsManager.getConnectionsNeedingConfirmation();
1203
+ const allRequests = [...pendingRequests, ...needsConfirmation];
1204
+ switch (params.action) {
1205
+ case "list":
1206
+ this.executeResult = {
1207
+ success: true,
1208
+ transactionId: void 0,
1209
+ receipt: void 0,
1210
+ scheduleId: void 0,
1211
+ rawResult: {
1212
+ requests: allRequests.map((request, index) => ({
1213
+ index: index + 1,
1214
+ type: request.needsConfirmation ? "incoming" : "outgoing",
1215
+ requestKey: request.uniqueRequestKey || `${request.connectionRequestId || request.inboundRequestId || "unknown"}`,
1216
+ targetAccountId: request.targetAccountId,
1217
+ targetAgentName: request.targetAgentName || `Agent ${request.targetAccountId}`,
1218
+ created: request.created.toISOString(),
1219
+ memo: request.memo,
1220
+ bio: request.profileInfo?.bio
1221
+ }))
1222
+ }
1223
+ };
1224
+ break;
1225
+ case "view": {
1226
+ if (!params.requestKey) {
1227
+ throw new Error("Request key is required for viewing a request");
1228
+ }
1229
+ const viewRequest = allRequests.find(
1230
+ (r) => r.uniqueRequestKey === params.requestKey || r.connectionRequestId?.toString() === params.requestKey || r.inboundRequestId?.toString() === params.requestKey
1231
+ );
1232
+ if (!viewRequest) {
1233
+ throw new Error(`Request with key ${params.requestKey} not found`);
1234
+ }
1235
+ this.executeResult = {
1236
+ success: true,
1237
+ transactionId: void 0,
1238
+ receipt: void 0,
1239
+ scheduleId: void 0,
1240
+ rawResult: {
1241
+ request: {
1242
+ type: viewRequest.needsConfirmation ? "incoming" : "outgoing",
1243
+ requestKey: viewRequest.uniqueRequestKey || `${viewRequest.connectionRequestId || viewRequest.inboundRequestId || "unknown"}`,
1244
+ targetAccountId: viewRequest.targetAccountId,
1245
+ targetAgentName: viewRequest.targetAgentName || `Agent ${viewRequest.targetAccountId}`,
1246
+ created: viewRequest.created.toISOString(),
1247
+ memo: viewRequest.memo,
1248
+ profileInfo: viewRequest.profileInfo
1249
+ }
1250
+ }
1251
+ };
1252
+ break;
1253
+ }
1254
+ case "reject": {
1255
+ if (!params.requestKey) {
1256
+ throw new Error("Request key is required for rejecting a request");
1257
+ }
1258
+ const rejectRequest = allRequests.find(
1259
+ (r) => r.uniqueRequestKey === params.requestKey || r.connectionRequestId?.toString() === params.requestKey || r.inboundRequestId?.toString() === params.requestKey
1260
+ );
1261
+ if (!rejectRequest) {
1262
+ throw new Error(`Request with key ${params.requestKey} not found`);
1263
+ }
1264
+ if (rejectRequest.inboundRequestId) {
1265
+ connectionsManager.markConnectionRequestProcessed(
1266
+ rejectRequest.targetInboundTopicId || "",
1267
+ rejectRequest.inboundRequestId
1268
+ );
1269
+ } else if (rejectRequest.connectionRequestId) {
1270
+ connectionsManager.markConnectionRequestProcessed(
1271
+ rejectRequest.originTopicId || "",
1272
+ rejectRequest.connectionRequestId
1273
+ );
1274
+ }
1275
+ this.executeResult = {
1276
+ success: true,
1277
+ transactionId: void 0,
1278
+ receipt: void 0,
1279
+ scheduleId: void 0,
1280
+ rawResult: {
1281
+ rejectedRequest: {
1282
+ requestKey: params.requestKey,
1283
+ targetAccountId: rejectRequest.targetAccountId,
1284
+ targetAgentName: rejectRequest.targetAgentName || `Agent ${rejectRequest.targetAccountId}`
1285
+ }
1286
+ }
1287
+ };
1288
+ break;
1289
+ }
1290
+ }
1291
+ } catch (error) {
1292
+ this.logger.error("Failed to manage connection requests:", error);
1293
+ throw error;
1294
+ }
1295
+ return this;
1296
+ }
1297
+ /**
1298
+ * List unapproved connection requests
1299
+ */
1300
+ async listUnapprovedConnectionRequests() {
1301
+ this.clearNotes();
1302
+ if (!this.stateManager) {
1303
+ throw new Error(
1304
+ "StateManager is required for listing connection requests"
1305
+ );
1306
+ }
1307
+ const currentAgent = this.stateManager.getCurrentAgent();
1308
+ if (!currentAgent) {
1309
+ throw new Error(
1310
+ "Cannot list connection requests. No agent is currently active."
1311
+ );
1312
+ }
1313
+ try {
1314
+ const inboundTopicId = await this.getInboundTopicId();
1315
+ const messages = await this.getMessages(inboundTopicId);
1316
+ const unapprovedRequests = messages.messages.filter(
1317
+ (msg) => msg.op === "connection_request"
1318
+ ).map((msg) => ({
1319
+ requestId: msg.sequence_number,
1320
+ fromAccountId: msg.operator_id?.split("@")[1] || "unknown",
1321
+ timestamp: msg.timestamp || new Date(msg?.created || "").getTime(),
1322
+ memo: msg.m || "",
1323
+ data: msg.data
1324
+ })).filter(
1325
+ (req) => req.fromAccountId !== "unknown"
1326
+ );
1327
+ this.executeResult = {
1328
+ success: true,
1329
+ transactionId: void 0,
1330
+ receipt: void 0,
1331
+ scheduleId: void 0,
1332
+ rawResult: {
1333
+ requests: unapprovedRequests,
1334
+ count: unapprovedRequests.length
1335
+ }
1336
+ };
1337
+ if (unapprovedRequests.length === 0) {
1338
+ this.addNote("No unapproved connection requests found.");
1339
+ } else {
1340
+ this.addNote(
1341
+ `Found ${unapprovedRequests.length} unapproved connection request(s).`
1342
+ );
1343
+ }
1344
+ } catch (error) {
1345
+ this.logger.error(
1346
+ "Failed to list unapproved connection requests:",
1347
+ error
1348
+ );
1349
+ throw error;
1350
+ }
1351
+ return this;
1352
+ }
1353
+ /**
1354
+ * List connections with enhanced details
1355
+ */
1356
+ async listConnections(params = {}) {
1357
+ this.clearNotes();
1358
+ if (!this.stateManager) {
1359
+ throw new Error("StateManager is required to list connections");
1360
+ }
1361
+ const includeDetails = params.includeDetails ?? true;
1362
+ const showPending = params.showPending ?? true;
1363
+ try {
1364
+ const connections = await this.getEnhancedConnections();
1365
+ if (connections.length === 0) {
1366
+ this.executeResult = {
1367
+ success: true,
1368
+ rawResult: {
1369
+ connections: [],
1370
+ message: "There are currently no active connections."
1371
+ }
1372
+ };
1373
+ return this;
1374
+ }
1375
+ const activeConnections = connections.filter(
1376
+ (c) => c.status === "established"
1377
+ );
1378
+ const pendingConnections = connections.filter(
1379
+ (c) => c.isPending
1380
+ );
1381
+ const needsConfirmation = connections.filter(
1382
+ (c) => c.needsConfirmation
1383
+ );
1384
+ let output = "";
1385
+ if (activeConnections.length > 0) {
1386
+ output += `🟢 Active Connections (${activeConnections.length}):
1387
+ `;
1388
+ activeConnections.forEach((conn, index) => {
1389
+ output += this.formatConnection(conn, index, includeDetails);
1390
+ });
1391
+ output += "\n";
1392
+ }
1393
+ if (showPending && needsConfirmation.length > 0) {
1394
+ output += `🟠 Connections Needing Confirmation (${needsConfirmation.length}):
1395
+ `;
1396
+ needsConfirmation.forEach((conn, index) => {
1397
+ output += this.formatConnection(conn, index, includeDetails);
1398
+ });
1399
+ output += "\n";
1400
+ }
1401
+ if (showPending && pendingConnections.length > 0) {
1402
+ output += `⚪ Pending Connection Requests (${pendingConnections.length}):
1403
+ `;
1404
+ pendingConnections.forEach((conn, index) => {
1405
+ output += this.formatConnection(conn, index, includeDetails);
1406
+ });
1407
+ }
1408
+ this.executeResult = {
1409
+ success: true,
1410
+ rawResult: {
1411
+ connections,
1412
+ formattedOutput: output.trim(),
1413
+ activeCount: activeConnections.length,
1414
+ pendingCount: pendingConnections.length,
1415
+ needsConfirmationCount: needsConfirmation.length
1416
+ }
1417
+ };
1418
+ } catch (error) {
1419
+ this.logger.error("Failed to list connections:", error);
1420
+ this.executeResult = {
1421
+ success: false,
1422
+ error: `Failed to list connections: ${error instanceof Error ? error.message : String(error)}`
1423
+ };
1424
+ }
1425
+ return this;
1426
+ }
1427
+ formatConnection(conn, index, includeDetails) {
1428
+ const connection = conn;
1429
+ let output = `${index + 1}. ${connection.profileInfo?.display_name || connection.targetAgentName || "Unknown Agent"} (${connection.targetAccountId})
1430
+ `;
1431
+ const displayTopicId = connection.isPending ? "(Pending Request)" : connection.connectionTopicId;
1432
+ output += ` Topic: ${displayTopicId}
1433
+ `;
1434
+ const statusText = connection.status || "unknown";
1435
+ output += ` Status: ${statusText}
1436
+ `;
1437
+ if (includeDetails) {
1438
+ if (connection.profileInfo?.bio) {
1439
+ output += ` Bio: ${connection.profileInfo.bio.substring(0, 100)}${connection.profileInfo.bio.length > 100 ? "..." : ""}
1440
+ `;
1441
+ }
1442
+ if (connection.created) {
1443
+ const createdLabel = connection.isPending ? "Request sent" : "Connection established";
1444
+ output += ` ${createdLabel}: ${connection.created.toLocaleString()}
1445
+ `;
1446
+ }
1447
+ if (connection.lastActivity) {
1448
+ output += ` Last activity: ${connection.lastActivity.toLocaleString()}
1449
+ `;
1450
+ }
1451
+ }
1452
+ return output;
1453
+ }
1454
+ async getEnhancedConnections() {
1455
+ try {
1456
+ const { accountId } = this.getAccountAndSigner();
1457
+ if (!accountId) {
1458
+ return this.stateManager.listConnections();
1459
+ }
1460
+ const connectionManager = this.stateManager.getConnectionsManager();
1461
+ if (!connectionManager) {
1462
+ this.logger.error(NOT_INITIALIZED_ERROR);
1463
+ return this.stateManager.listConnections();
1464
+ }
1465
+ const connections = await connectionManager.fetchConnectionData(
1466
+ accountId
1467
+ );
1468
+ for (const connection of connections) {
1469
+ this.stateManager.addActiveConnection(
1470
+ connection
1471
+ );
1472
+ }
1473
+ return connections;
1474
+ } catch (error) {
1475
+ this.logger.error("Failed to get enhanced connections:", error);
1476
+ return this.stateManager.listConnections();
1477
+ }
1478
+ }
1479
+ /**
1480
+ * Check messages on a connection
1481
+ */
1482
+ async checkMessages(params) {
1483
+ this.clearNotes();
1484
+ if (!this.stateManager) {
1485
+ throw new Error("StateManager is required to check messages");
1486
+ }
1487
+ const connection = this.stateManager.getConnectionByIdentifier(
1488
+ params.targetIdentifier
1489
+ );
1490
+ if (!connection) {
1491
+ this.executeResult = {
1492
+ success: false,
1493
+ error: `Could not find an active connection matching identifier "${params.targetIdentifier}". Use 'list_connections' to see active connections.`
1494
+ };
1495
+ return this;
1496
+ }
1497
+ const connectionTopicId = connection.connectionTopicId || "";
1498
+ if (!connectionTopicId || !connectionTopicId.match(/^\d+\.\d+\.\d+$/)) {
1499
+ this.logger.error(
1500
+ `Invalid connection topic ID format: ${connectionTopicId}`
1501
+ );
1502
+ this.executeResult = {
1503
+ success: false,
1504
+ error: `Invalid connection topic ID format: ${connectionTopicId}. Expected format: 0.0.XXXXX`
1505
+ };
1506
+ return this;
1507
+ }
1508
+ const targetAgentName = connection.targetAgentName;
1509
+ const lastProcessedTimestamp = this.stateManager.getLastTimestamp(connectionTopicId);
1510
+ this.logger.info(
1511
+ `Checking messages for connection with ${targetAgentName} (${connection.targetAccountId}) on topic ${connectionTopicId} (fetchLatest: ${params.fetchLatest}, lastCount: ${params.lastMessagesCount}, since: ${lastProcessedTimestamp})`
1512
+ );
1513
+ try {
1514
+ const result = await this.getMessages(connectionTopicId);
1515
+ const allMessages = result.messages;
1516
+ if (!allMessages || allMessages.length === 0) {
1517
+ this.executeResult = {
1518
+ success: true,
1519
+ rawResult: {
1520
+ messages: [],
1521
+ message: `No messages found on connection topic ${connectionTopicId}.`
1522
+ }
1523
+ };
1524
+ return this;
1525
+ }
1526
+ let messagesToProcess = [];
1527
+ let latestTimestampNanos = lastProcessedTimestamp;
1528
+ const isFetchingLatest = params.fetchLatest === true;
1529
+ if (isFetchingLatest) {
1530
+ this.logger.info("Fetching latest messages regardless of timestamp.");
1531
+ const count = params.lastMessagesCount ?? 1;
1532
+ messagesToProcess = allMessages.slice(-count);
1533
+ } else {
1534
+ this.logger.info(
1535
+ `Filtering for messages newer than ${lastProcessedTimestamp}`
1536
+ );
1537
+ messagesToProcess = allMessages.filter(
1538
+ (msg) => {
1539
+ const msgTimestampNanos = msg.timestamp * 1e6;
1540
+ return msgTimestampNanos > lastProcessedTimestamp;
1541
+ }
1542
+ );
1543
+ if (messagesToProcess.length > 0) {
1544
+ latestTimestampNanos = messagesToProcess.reduce(
1545
+ (maxTs, msg) => Math.max(maxTs, msg.timestamp * 1e6),
1546
+ lastProcessedTimestamp
1547
+ );
1548
+ }
1549
+ }
1550
+ if (messagesToProcess.length === 0) {
1551
+ 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.`;
1552
+ this.executeResult = {
1553
+ success: true,
1554
+ rawResult: {
1555
+ messages: [],
1556
+ message
1557
+ }
1558
+ };
1559
+ return this;
1560
+ }
1561
+ this.logger.info(`Processing ${messagesToProcess.length} message(s).`);
1562
+ let outputString = isFetchingLatest ? `Latest message(s) from ${targetAgentName}:
1563
+ ` : `New messages from ${targetAgentName}:
1564
+ `;
1565
+ const processedMessages = [];
1566
+ for (const msg of messagesToProcess) {
1567
+ let content = msg.data;
1568
+ try {
1569
+ if (typeof content === "string" && content.startsWith("hcs://")) {
1570
+ this.logger.debug(`Resolving inscribed message: ${content}`);
1571
+ content = await this.getMessageContent(content);
1572
+ this.logger.debug(`Resolved content length: ${content?.length}`);
1573
+ }
1574
+ let displayContent = content;
1575
+ try {
1576
+ const parsed = JSON.parse(content || "{}");
1577
+ if (parsed.p === "hcs-10" && parsed.op === "message" && parsed.data) {
1578
+ const senderOpId = parsed.operator_id || "unknown_sender";
1579
+ displayContent = `[${senderOpId}]: ${parsed.data}`;
1580
+ } else {
1581
+ displayContent = content;
1582
+ }
1583
+ } catch {
1584
+ displayContent = content;
1585
+ }
1586
+ const messageDate = new Date(msg.timestamp);
1587
+ outputString += `
1588
+ [${messageDate.toLocaleString()}] (Seq: ${msg.sequence_number})
1589
+ ${displayContent}
1590
+ `;
1591
+ processedMessages.push({
1592
+ timestamp: msg.timestamp,
1593
+ sequenceNumber: msg.sequence_number,
1594
+ content: displayContent,
1595
+ raw: msg
1596
+ });
1597
+ } catch (error) {
1598
+ const errorMsg = `Error processing message (Seq: ${msg.sequence_number}): ${error instanceof Error ? error.message : String(error)}`;
1599
+ this.logger.error(errorMsg);
1600
+ outputString += `
1601
+ [Error processing message Seq: ${msg.sequence_number}]
1602
+ `;
1603
+ }
1604
+ }
1605
+ if (!isFetchingLatest && latestTimestampNanos > lastProcessedTimestamp) {
1606
+ this.logger.debug(
1607
+ `Updating timestamp for topic ${connectionTopicId} to ${latestTimestampNanos}`
1608
+ );
1609
+ this.stateManager.updateTimestamp(
1610
+ connectionTopicId,
1611
+ latestTimestampNanos
1612
+ );
1613
+ }
1614
+ this.executeResult = {
1615
+ success: true,
1616
+ rawResult: {
1617
+ messages: processedMessages,
1618
+ formattedOutput: outputString.trim(),
1619
+ targetAgentName,
1620
+ connectionTopicId
1621
+ }
1622
+ };
1623
+ } catch (error) {
1624
+ this.logger.error(
1625
+ `Failed to check messages for topic ${connectionTopicId}: ${error}`
1626
+ );
1627
+ this.executeResult = {
1628
+ success: false,
1629
+ error: `Error checking messages for ${targetAgentName}: ${error instanceof Error ? error.message : String(error)}`
1630
+ };
1631
+ }
1632
+ return this;
85
1633
  }
86
1634
  /**
87
- * Submit a raw message to an HCS-6 topic
1635
+ * Find registrations using the configured registry
88
1636
  */
89
- async submitMessage(topicId, payload) {
90
- const client = await this.getHCS6Client();
91
- return await client.submitMessage(topicId, payload);
1637
+ async findRegistrations(params) {
1638
+ this.clearNotes();
1639
+ try {
1640
+ const options = {
1641
+ network: this.network
1642
+ };
1643
+ if (params.accountId) {
1644
+ options.accountId = params.accountId;
1645
+ }
1646
+ if (params.tags && params.tags.length > 0) {
1647
+ options.tags = params.tags;
1648
+ }
1649
+ const result = await this.standardClient.findRegistrations(options);
1650
+ if (!result.success || result.error) {
1651
+ this.executeResult = {
1652
+ success: false,
1653
+ error: `Error finding registrations: ${result.error || "Unknown error"}`
1654
+ };
1655
+ return this;
1656
+ }
1657
+ if (!result.registrations || result.registrations.length === 0) {
1658
+ this.executeResult = {
1659
+ success: true,
1660
+ rawResult: {
1661
+ registrations: [],
1662
+ message: "No registrations found matching the criteria."
1663
+ }
1664
+ };
1665
+ return this;
1666
+ }
1667
+ const formattedRegistrations = result.registrations.map((reg) => {
1668
+ const registration = reg;
1669
+ const agentName = registration.agent?.name || "Unknown Agent";
1670
+ const accountId = registration.accountId || "Unknown Account";
1671
+ const capabilities = registration.agent?.capabilities?.join(", ") || "None";
1672
+ return `Agent: ${agentName} (${accountId}), Capabilities: ${capabilities}`;
1673
+ }).join("\\n");
1674
+ this.executeResult = {
1675
+ success: true,
1676
+ rawResult: {
1677
+ registrations: result.registrations,
1678
+ formattedOutput: `Found ${result.registrations.length} registration(s):\\n${formattedRegistrations}`
1679
+ }
1680
+ };
1681
+ } catch (error) {
1682
+ this.logger.error("Error during FindRegistrations execution:", error);
1683
+ this.executeResult = {
1684
+ success: false,
1685
+ error: `Failed to search registrations: ${error instanceof Error ? error.message : String(error)}`
1686
+ };
1687
+ }
1688
+ return this;
92
1689
  }
93
1690
  /**
94
- * Get topic info from mirror node
1691
+ * Retrieve detailed profile information for an agent
95
1692
  */
96
- async getTopicInfo(topicId) {
97
- const client = await this.getHCS6Client();
98
- return await client.getTopicInfo(topicId);
1693
+ async retrieveProfile(params) {
1694
+ this.clearNotes();
1695
+ try {
1696
+ const profileResponse = await this.standardClient.retrieveProfile(
1697
+ params.accountId,
1698
+ params.disableCache || false
1699
+ );
1700
+ if (!profileResponse.success) {
1701
+ this.executeResult = {
1702
+ success: false,
1703
+ error: `Failed to retrieve profile: ${profileResponse.error || "Unknown error"}`
1704
+ };
1705
+ return this;
1706
+ }
1707
+ const profile = profileResponse.profile;
1708
+ const topicInfo = profileResponse.topicInfo;
1709
+ let profileDetails = `Profile for ${params.accountId}:
1710
+ `;
1711
+ profileDetails += `Name: ${profile.name || "Unknown"}
1712
+ `;
1713
+ profileDetails += `Bio: ${profile.bio || "No bio provided"}
1714
+ `;
1715
+ profileDetails += `Type: ${profile.type || "Unknown"}
1716
+ `;
1717
+ profileDetails += `Model: ${profile.model || "Unknown"}
1718
+ `;
1719
+ if (profile.capabilities && profile.capabilities.length > 0) {
1720
+ profileDetails += `Capabilities: ${profile.capabilities.join(", ")}
1721
+ `;
1722
+ } else {
1723
+ profileDetails += `Capabilities: None listed
1724
+ `;
1725
+ }
1726
+ if (topicInfo) {
1727
+ profileDetails += `Inbound Topic: ${topicInfo.inboundTopic || "Unknown"}
1728
+ `;
1729
+ profileDetails += `Outbound Topic: ${topicInfo.outboundTopic || "Unknown"}
1730
+ `;
1731
+ profileDetails += `Profile Topic: ${topicInfo.profileTopicId || "Unknown"}
1732
+ `;
1733
+ }
1734
+ if (profile.social && Object.keys(profile.social).length > 0) {
1735
+ profileDetails += `Social: ${Object.entries(profile.social).map(
1736
+ ([platform, handle]) => `${platform}: ${handle}`
1737
+ ).join(", ")}
1738
+ `;
1739
+ }
1740
+ if (profile.properties && Object.keys(profile.properties).length > 0) {
1741
+ profileDetails += `Properties: ${JSON.stringify(profile.properties)}
1742
+ `;
1743
+ }
1744
+ this.executeResult = {
1745
+ success: true,
1746
+ rawResult: {
1747
+ profileDetails,
1748
+ rawProfile: profileResponse
1749
+ }
1750
+ };
1751
+ } catch (error) {
1752
+ this.logger.error(
1753
+ `Unexpected error retrieving profile for ${params.accountId}:`,
1754
+ error
1755
+ );
1756
+ this.executeResult = {
1757
+ success: false,
1758
+ error: `Unexpected error retrieving profile for ${params.accountId}: ${error instanceof Error ? error.message : String(error)}`
1759
+ };
1760
+ }
1761
+ return this;
99
1762
  }
100
1763
  /**
101
- * Close the HCS-6 client
1764
+ * Override execute to return stored HCS10 operation results
102
1765
  */
103
- async close() {
104
- if (this.hcs6Client) {
105
- this.hcs6Client.close();
106
- this.hcs6Client = void 0;
1766
+ async execute() {
1767
+ if (this.executeResult) {
1768
+ return {
1769
+ success: this.executeResult.success,
1770
+ transactionId: this.executeResult.transactionId,
1771
+ receipt: this.executeResult.receipt,
1772
+ scheduleId: this.executeResult.scheduleId,
1773
+ error: this.executeResult.error,
1774
+ rawResult: this.executeResult.rawResult,
1775
+ notes: this.notes
1776
+ };
107
1777
  }
1778
+ return {
1779
+ success: false,
1780
+ error: "No operation result available. Call a builder method first."
1781
+ };
108
1782
  }
109
1783
  }
110
1784
  export {
111
- HCS6Builder
1785
+ HCS10Builder
112
1786
  };
113
1787
  //# sourceMappingURL=standards-agent-kit.es5.js.map