@hashgraphonline/standards-agent-kit 0.2.119 → 0.2.121

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