@hashgraphonline/conversational-agent 0.1.208 → 0.1.210
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/conversational-agent-cli.js +30 -0
- package/cli/readme.md +181 -0
- package/dist/cjs/base-agent.d.ts +3 -1
- package/dist/cjs/conversational-agent.d.ts +64 -13
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.ts +6 -3
- package/dist/cjs/langchain-agent.d.ts +11 -0
- package/dist/cjs/memory/SmartMemoryManager.d.ts +65 -22
- package/dist/cjs/memory/TokenCounter.d.ts +1 -1
- package/dist/cjs/memory/index.d.ts +1 -1
- package/dist/cjs/plugins/hbar/AirdropToolWrapper.d.ts +43 -0
- package/dist/{types/plugins/hbar-transfer/HbarTransferPlugin.d.ts → cjs/plugins/hbar/HbarPlugin.d.ts} +2 -1
- package/dist/{types/plugins/hbar-transfer → cjs/plugins/hbar}/TransferHbarTool.d.ts +1 -1
- package/dist/cjs/plugins/hbar/index.d.ts +3 -0
- package/dist/cjs/plugins/index.d.ts +2 -1
- package/dist/cjs/services/EntityResolver.d.ts +26 -0
- package/dist/cjs/tools/EntityResolverTool.d.ts +104 -0
- package/dist/cjs/types/inscription.d.ts +37 -0
- package/dist/esm/index.js +16 -2
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/index12.js +121 -46
- package/dist/esm/index12.js.map +1 -1
- package/dist/esm/index13.js +177 -13
- package/dist/esm/index13.js.map +1 -1
- package/dist/esm/index14.js +599 -100
- package/dist/esm/index14.js.map +1 -1
- package/dist/esm/index15.js +426 -9
- package/dist/esm/index15.js.map +1 -1
- package/dist/esm/index16.js +119 -160
- package/dist/esm/index16.js.map +1 -1
- package/dist/esm/index17.js +140 -150
- package/dist/esm/index17.js.map +1 -1
- package/dist/esm/index18.js +44 -231
- package/dist/esm/index18.js.map +1 -1
- package/dist/esm/index19.js +86 -643
- package/dist/esm/index19.js.map +1 -1
- package/dist/esm/index2.js +22 -13
- package/dist/esm/index2.js.map +1 -1
- package/dist/esm/index20.js +20 -230
- package/dist/esm/index20.js.map +1 -1
- package/dist/esm/index21.js +9 -179
- package/dist/esm/index21.js.map +1 -1
- package/dist/esm/index22.js +140 -89
- package/dist/esm/index22.js.map +1 -1
- package/dist/esm/index23.js +141 -81
- package/dist/esm/index23.js.map +1 -1
- package/dist/esm/index24.js +4 -4
- package/dist/esm/index24.js.map +1 -1
- package/dist/esm/index25.js +0 -8
- package/dist/esm/index25.js.map +1 -1
- package/dist/esm/index26.js +95 -0
- package/dist/esm/index26.js.map +1 -0
- package/dist/esm/index27.js +242 -0
- package/dist/esm/index27.js.map +1 -0
- package/dist/esm/index5.js +32 -19
- package/dist/esm/index5.js.map +1 -1
- package/dist/esm/index6.js +276 -37
- package/dist/esm/index6.js.map +1 -1
- package/dist/esm/index7.js +2 -2
- package/dist/esm/index7.js.map +1 -1
- package/dist/esm/index8.js +124 -18
- package/dist/esm/index8.js.map +1 -1
- package/dist/types/base-agent.d.ts +3 -1
- package/dist/types/conversational-agent.d.ts +64 -13
- package/dist/types/index.d.ts +6 -3
- package/dist/types/langchain-agent.d.ts +11 -0
- package/dist/types/memory/SmartMemoryManager.d.ts +65 -22
- package/dist/types/memory/TokenCounter.d.ts +1 -1
- package/dist/types/memory/index.d.ts +1 -1
- package/dist/types/plugins/hbar/AirdropToolWrapper.d.ts +43 -0
- package/dist/{cjs/plugins/hbar-transfer/HbarTransferPlugin.d.ts → types/plugins/hbar/HbarPlugin.d.ts} +2 -1
- package/dist/{cjs/plugins/hbar-transfer → types/plugins/hbar}/TransferHbarTool.d.ts +1 -1
- package/dist/types/plugins/hbar/index.d.ts +3 -0
- package/dist/types/plugins/index.d.ts +2 -1
- package/dist/types/services/EntityResolver.d.ts +26 -0
- package/dist/types/tools/EntityResolverTool.d.ts +104 -0
- package/dist/types/types/inscription.d.ts +37 -0
- package/package.json +13 -4
- package/src/base-agent.ts +14 -9
- package/src/config/system-message.ts +11 -2
- package/src/context/ReferenceContextManager.ts +10 -5
- package/src/context/ReferenceResponseProcessor.ts +3 -4
- package/src/conversational-agent.ts +372 -57
- package/src/index.ts +19 -3
- package/src/langchain/ContentAwareAgentExecutor.ts +0 -1
- package/src/langchain-agent.ts +168 -33
- package/src/mcp/ContentProcessor.ts +11 -3
- package/src/mcp/adapters/langchain.ts +1 -10
- package/src/memory/ContentStorage.ts +2 -55
- package/src/memory/MemoryWindow.ts +4 -17
- package/src/memory/ReferenceIdGenerator.ts +4 -8
- package/src/memory/SmartMemoryManager.ts +375 -47
- package/src/memory/TokenCounter.ts +15 -22
- package/src/memory/index.ts +1 -1
- package/src/plugins/hbar/AirdropToolWrapper.ts +157 -0
- package/src/plugins/hbar/HbarPlugin.ts +86 -0
- package/src/plugins/{hbar-transfer → hbar}/TransferHbarTool.ts +3 -3
- package/src/plugins/hbar/index.ts +3 -0
- package/src/plugins/hcs-10/HCS10Plugin.ts +44 -14
- package/src/plugins/index.ts +2 -1
- package/src/services/ContentStoreManager.ts +0 -3
- package/src/services/EntityResolver.ts +135 -0
- package/src/tools/EntityResolverTool.ts +170 -0
- package/src/types/content-reference.ts +8 -8
- package/src/types/index.ts +0 -1
- package/src/types/inscription.ts +40 -0
- package/dist/cjs/plugins/hbar-transfer/index.d.ts +0 -1
- package/dist/types/plugins/hbar-transfer/index.d.ts +0 -1
- package/src/plugins/hbar-transfer/HbarTransferPlugin.ts +0 -66
- package/src/plugins/hbar-transfer/index.ts +0 -1
- /package/dist/cjs/plugins/{hbar-transfer → hbar}/AccountBuilder.d.ts +0 -0
- /package/dist/cjs/plugins/{hbar-transfer → hbar}/types.d.ts +0 -0
- /package/dist/types/plugins/{hbar-transfer → hbar}/AccountBuilder.d.ts +0 -0
- /package/dist/types/plugins/{hbar-transfer → hbar}/types.d.ts +0 -0
- /package/src/plugins/{hbar-transfer → hbar}/AccountBuilder.ts +0 -0
- /package/src/plugins/{hbar-transfer → hbar}/types.ts +0 -0
package/dist/esm/index19.js
CHANGED
|
@@ -1,663 +1,106 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
this.
|
|
8
|
-
this.
|
|
9
|
-
this.
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
};
|
|
27
|
-
if (this.referenceConfig.enableAutoCleanup) {
|
|
28
|
-
this.startReferenceCleanupTimer();
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
/**
|
|
32
|
-
* Store messages in the content storage
|
|
33
|
-
* Automatically drops oldest messages if storage limit is exceeded
|
|
34
|
-
* @param messages - Messages to store
|
|
35
|
-
* @returns Result indicating how many messages were stored and dropped
|
|
36
|
-
*/
|
|
37
|
-
storeMessages(messages) {
|
|
38
|
-
if (messages.length === 0) {
|
|
39
|
-
return { stored: 0, dropped: 0 };
|
|
40
|
-
}
|
|
41
|
-
const now = /* @__PURE__ */ new Date();
|
|
42
|
-
let dropped = 0;
|
|
43
|
-
const storedMessages = messages.map((message) => ({
|
|
44
|
-
message,
|
|
45
|
-
storedAt: now,
|
|
46
|
-
id: this.generateId()
|
|
47
|
-
}));
|
|
48
|
-
this.messages.push(...storedMessages);
|
|
49
|
-
while (this.messages.length > this.maxStorage) {
|
|
50
|
-
this.messages.shift();
|
|
51
|
-
dropped++;
|
|
52
|
-
}
|
|
53
|
-
return {
|
|
54
|
-
stored: storedMessages.length,
|
|
55
|
-
dropped
|
|
56
|
-
};
|
|
57
|
-
}
|
|
58
|
-
/**
|
|
59
|
-
* Get the most recent messages from storage
|
|
60
|
-
* @param count - Number of recent messages to retrieve
|
|
61
|
-
* @returns Array of recent messages in chronological order
|
|
62
|
-
*/
|
|
63
|
-
getRecentMessages(count) {
|
|
64
|
-
if (count <= 0 || this.messages.length === 0) {
|
|
65
|
-
return [];
|
|
66
|
-
}
|
|
67
|
-
const startIndex = Math.max(0, this.messages.length - count);
|
|
68
|
-
return this.messages.slice(startIndex).map((stored) => stored.message);
|
|
69
|
-
}
|
|
70
|
-
/**
|
|
71
|
-
* Search for messages containing specific text or patterns
|
|
72
|
-
* @param query - Search term or regex pattern
|
|
73
|
-
* @param options - Search configuration options
|
|
74
|
-
* @returns Array of matching messages
|
|
75
|
-
*/
|
|
76
|
-
searchMessages(query, options = {}) {
|
|
77
|
-
if (!query || this.messages.length === 0) {
|
|
78
|
-
return [];
|
|
79
|
-
}
|
|
80
|
-
const {
|
|
81
|
-
caseSensitive = false,
|
|
82
|
-
limit,
|
|
83
|
-
useRegex = false
|
|
84
|
-
} = options;
|
|
85
|
-
let matches = [];
|
|
86
|
-
if (useRegex) {
|
|
87
|
-
try {
|
|
88
|
-
const regex = new RegExp(query, caseSensitive ? "g" : "gi");
|
|
89
|
-
matches = this.messages.filter((stored) => regex.test(stored.message.content)).map((stored) => stored.message);
|
|
90
|
-
} catch (error) {
|
|
91
|
-
console.warn("Invalid regex pattern:", query, error);
|
|
92
|
-
return [];
|
|
93
|
-
}
|
|
94
|
-
} else {
|
|
95
|
-
const searchTerm = caseSensitive ? query : query.toLowerCase();
|
|
96
|
-
matches = this.messages.filter((stored) => {
|
|
97
|
-
const content = stored.message.content;
|
|
98
|
-
const searchContent = caseSensitive ? content : content.toLowerCase();
|
|
99
|
-
return searchContent.includes(searchTerm);
|
|
100
|
-
}).map((stored) => stored.message);
|
|
101
|
-
}
|
|
102
|
-
return limit ? matches.slice(0, limit) : matches;
|
|
103
|
-
}
|
|
104
|
-
/**
|
|
105
|
-
* Get messages from a specific time range
|
|
106
|
-
* @param startTime - Start of time range (inclusive)
|
|
107
|
-
* @param endTime - End of time range (inclusive)
|
|
108
|
-
* @returns Array of messages within the time range
|
|
109
|
-
*/
|
|
110
|
-
getMessagesFromTimeRange(startTime, endTime) {
|
|
111
|
-
if (startTime > endTime || this.messages.length === 0) {
|
|
112
|
-
return [];
|
|
113
|
-
}
|
|
114
|
-
return this.messages.filter(
|
|
115
|
-
(stored) => stored.storedAt >= startTime && stored.storedAt <= endTime
|
|
116
|
-
).map((stored) => stored.message);
|
|
117
|
-
}
|
|
118
|
-
/**
|
|
119
|
-
* Get storage statistics and usage information
|
|
120
|
-
* @returns Current storage statistics
|
|
121
|
-
*/
|
|
122
|
-
getStorageStats() {
|
|
123
|
-
const totalMessages = this.messages.length;
|
|
124
|
-
const usagePercentage = totalMessages > 0 ? Math.round(totalMessages / this.maxStorage * 100) : 0;
|
|
125
|
-
let oldestMessageTime;
|
|
126
|
-
let newestMessageTime;
|
|
127
|
-
if (totalMessages > 0) {
|
|
128
|
-
oldestMessageTime = this.messages[0].storedAt;
|
|
129
|
-
newestMessageTime = this.messages[totalMessages - 1].storedAt;
|
|
130
|
-
}
|
|
131
|
-
return {
|
|
132
|
-
totalMessages,
|
|
133
|
-
maxStorageLimit: this.maxStorage,
|
|
134
|
-
usagePercentage,
|
|
135
|
-
oldestMessageTime,
|
|
136
|
-
newestMessageTime
|
|
137
|
-
};
|
|
138
|
-
}
|
|
139
|
-
/**
|
|
140
|
-
* Clear all stored messages
|
|
141
|
-
*/
|
|
142
|
-
clear() {
|
|
143
|
-
this.messages = [];
|
|
144
|
-
this.idCounter = 0;
|
|
145
|
-
}
|
|
146
|
-
/**
|
|
147
|
-
* Get total number of stored messages
|
|
148
|
-
* @returns Number of messages currently in storage
|
|
149
|
-
*/
|
|
150
|
-
getTotalStoredMessages() {
|
|
151
|
-
return this.messages.length;
|
|
152
|
-
}
|
|
153
|
-
/**
|
|
154
|
-
* Update the maximum storage limit
|
|
155
|
-
* @param newLimit - New maximum storage limit
|
|
156
|
-
*/
|
|
157
|
-
updateStorageLimit(newLimit) {
|
|
158
|
-
if (newLimit <= 0) {
|
|
159
|
-
throw new Error("Storage limit must be greater than 0");
|
|
160
|
-
}
|
|
161
|
-
this.maxStorage = newLimit;
|
|
162
|
-
while (this.messages.length > this.maxStorage) {
|
|
163
|
-
this.messages.shift();
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
/**
|
|
167
|
-
* Get messages by message type
|
|
168
|
-
* @param messageType - Type of messages to retrieve ('human', 'ai', 'system', etc.)
|
|
169
|
-
* @param limit - Maximum number of messages to return
|
|
170
|
-
* @returns Array of messages of the specified type
|
|
171
|
-
*/
|
|
172
|
-
getMessagesByType(messageType, limit) {
|
|
173
|
-
const filtered = this.messages.filter((stored) => stored.message._getType() === messageType).map((stored) => stored.message);
|
|
174
|
-
return limit ? filtered.slice(0, limit) : filtered;
|
|
175
|
-
}
|
|
176
|
-
/**
|
|
177
|
-
* Get the current storage configuration
|
|
178
|
-
* @returns Storage configuration object
|
|
179
|
-
*/
|
|
180
|
-
getConfig() {
|
|
181
|
-
return {
|
|
182
|
-
maxStorage: this.maxStorage,
|
|
183
|
-
currentUsage: this.messages.length,
|
|
184
|
-
utilizationPercentage: this.messages.length / this.maxStorage * 100
|
|
185
|
-
};
|
|
186
|
-
}
|
|
187
|
-
/**
|
|
188
|
-
* Generate a unique ID for stored messages
|
|
189
|
-
* @returns Unique string identifier
|
|
190
|
-
*/
|
|
191
|
-
generateId() {
|
|
192
|
-
return `msg_${++this.idCounter}_${Date.now()}`;
|
|
193
|
-
}
|
|
194
|
-
/**
|
|
195
|
-
* Get messages stored within the last N minutes
|
|
196
|
-
* @param minutes - Number of minutes to look back
|
|
197
|
-
* @returns Array of messages from the last N minutes
|
|
198
|
-
*/
|
|
199
|
-
getRecentMessagesByTime(minutes) {
|
|
200
|
-
if (minutes <= 0 || this.messages.length === 0) {
|
|
201
|
-
return [];
|
|
202
|
-
}
|
|
203
|
-
const cutoffTime = new Date(Date.now() - minutes * 60 * 1e3);
|
|
204
|
-
return this.messages.filter((stored) => stored.storedAt >= cutoffTime).map((stored) => stored.message);
|
|
205
|
-
}
|
|
206
|
-
/**
|
|
207
|
-
* Export messages to a JSON-serializable format
|
|
208
|
-
* @returns Serializable representation of stored messages
|
|
209
|
-
*/
|
|
210
|
-
exportMessages() {
|
|
211
|
-
return this.messages.map((stored) => ({
|
|
212
|
-
content: stored.message.content,
|
|
213
|
-
type: stored.message._getType(),
|
|
214
|
-
storedAt: stored.storedAt.toISOString(),
|
|
215
|
-
id: stored.id
|
|
216
|
-
}));
|
|
217
|
-
}
|
|
218
|
-
// ========== Reference-Based Content Storage Methods ==========
|
|
219
|
-
/**
|
|
220
|
-
* Determine if content should be stored as a reference based on size
|
|
221
|
-
*/
|
|
222
|
-
shouldUseReference(content) {
|
|
223
|
-
const size = Buffer.isBuffer(content) ? content.length : Buffer.byteLength(content, "utf8");
|
|
224
|
-
return size > this.referenceConfig.sizeThresholdBytes;
|
|
225
|
-
}
|
|
226
|
-
/**
|
|
227
|
-
* Store content and return a reference if it exceeds the size threshold
|
|
228
|
-
* Otherwise returns null to indicate direct content should be used
|
|
229
|
-
*/
|
|
230
|
-
async storeContentIfLarge(content, metadata) {
|
|
231
|
-
const buffer = Buffer.isBuffer(content) ? content : Buffer.from(content, "utf8");
|
|
232
|
-
if (!this.shouldUseReference(buffer)) {
|
|
233
|
-
return null;
|
|
234
|
-
}
|
|
235
|
-
const storeMetadata = {
|
|
236
|
-
contentType: metadata.contentType || this.detectContentType(buffer, metadata.mimeType),
|
|
237
|
-
sizeBytes: buffer.length,
|
|
238
|
-
source: metadata.source,
|
|
239
|
-
tags: []
|
|
240
|
-
};
|
|
241
|
-
if (metadata.mimeType !== void 0) {
|
|
242
|
-
storeMetadata.mimeType = metadata.mimeType;
|
|
243
|
-
}
|
|
244
|
-
if (metadata.mcpToolName !== void 0) {
|
|
245
|
-
storeMetadata.mcpToolName = metadata.mcpToolName;
|
|
246
|
-
}
|
|
247
|
-
if (metadata.fileName !== void 0) {
|
|
248
|
-
storeMetadata.fileName = metadata.fileName;
|
|
249
|
-
}
|
|
250
|
-
if (metadata.tags !== void 0) {
|
|
251
|
-
storeMetadata.tags = metadata.tags;
|
|
252
|
-
}
|
|
253
|
-
if (metadata.customMetadata !== void 0) {
|
|
254
|
-
storeMetadata.customMetadata = metadata.customMetadata;
|
|
255
|
-
}
|
|
256
|
-
return await this.storeContent(buffer, storeMetadata);
|
|
257
|
-
}
|
|
258
|
-
/**
|
|
259
|
-
* Store content and return a reference (implements ContentReferenceStore)
|
|
260
|
-
*/
|
|
261
|
-
async storeContent(content, metadata) {
|
|
262
|
-
const startTime = Date.now();
|
|
1
|
+
import { StructuredTool } from "@langchain/core/tools";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { Logger } from "@hashgraphonline/standards-sdk";
|
|
4
|
+
class AirdropToolWrapper extends StructuredTool {
|
|
5
|
+
constructor(originalTool, agentKit) {
|
|
6
|
+
super();
|
|
7
|
+
this.name = "hedera-hts-airdrop-token";
|
|
8
|
+
this.description = "Airdrops fungible tokens to multiple recipients. Automatically converts human-readable amounts to smallest units based on token decimals.";
|
|
9
|
+
this.schema = z.object({
|
|
10
|
+
tokenId: z.string().describe('The ID of the fungible token to airdrop (e.g., "0.0.yyyy").'),
|
|
11
|
+
recipients: z.array(
|
|
12
|
+
z.object({
|
|
13
|
+
accountId: z.string().describe('Recipient account ID (e.g., "0.0.xxxx").'),
|
|
14
|
+
amount: z.union([z.number(), z.string()]).describe(
|
|
15
|
+
'Amount in human-readable format (e.g., "10" for 10 tokens).'
|
|
16
|
+
)
|
|
17
|
+
})
|
|
18
|
+
).min(1).describe("Array of recipient objects, each with accountId and amount."),
|
|
19
|
+
memo: z.string().optional().describe("Optional. Memo for the transaction.")
|
|
20
|
+
});
|
|
21
|
+
this.originalTool = originalTool;
|
|
22
|
+
this.agentKit = agentKit;
|
|
23
|
+
this.logger = new Logger({ module: "AirdropToolWrapper" });
|
|
24
|
+
}
|
|
25
|
+
async _call(input) {
|
|
263
26
|
try {
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
const fullMetadata = {
|
|
267
|
-
...metadata,
|
|
268
|
-
createdAt: now,
|
|
269
|
-
lastAccessedAt: now,
|
|
270
|
-
accessCount: 0
|
|
271
|
-
};
|
|
272
|
-
const storedContent = {
|
|
273
|
-
content,
|
|
274
|
-
metadata: fullMetadata,
|
|
275
|
-
state: "active"
|
|
276
|
-
};
|
|
277
|
-
const expirationTime = this.calculateExpirationTime(metadata.source);
|
|
278
|
-
if (expirationTime !== void 0) {
|
|
279
|
-
storedContent.expiresAt = expirationTime;
|
|
280
|
-
}
|
|
281
|
-
this.contentStore.set(referenceId, storedContent);
|
|
282
|
-
this.updateStatsAfterStore(content.length);
|
|
283
|
-
await this.enforceReferenceStorageLimits();
|
|
284
|
-
const preview = this.createContentPreview(content, fullMetadata.contentType);
|
|
285
|
-
const referenceMetadata = {
|
|
286
|
-
contentType: fullMetadata.contentType,
|
|
287
|
-
sizeBytes: fullMetadata.sizeBytes,
|
|
288
|
-
source: fullMetadata.source
|
|
289
|
-
};
|
|
290
|
-
if (fullMetadata.fileName !== void 0) {
|
|
291
|
-
referenceMetadata.fileName = fullMetadata.fileName;
|
|
292
|
-
}
|
|
293
|
-
if (fullMetadata.mimeType !== void 0) {
|
|
294
|
-
referenceMetadata.mimeType = fullMetadata.mimeType;
|
|
295
|
-
}
|
|
296
|
-
const reference = {
|
|
297
|
-
referenceId,
|
|
298
|
-
state: "active",
|
|
299
|
-
preview,
|
|
300
|
-
metadata: referenceMetadata,
|
|
301
|
-
createdAt: now,
|
|
302
|
-
format: "ref://{id}"
|
|
303
|
-
};
|
|
304
|
-
const duration = Date.now() - startTime;
|
|
305
|
-
this.recordPerformanceMetric("creation", duration);
|
|
306
|
-
console.log(`[ContentStorage] Stored content with reference ID: ${referenceId} (${content.length} bytes)`);
|
|
307
|
-
return reference;
|
|
308
|
-
} catch (error) {
|
|
309
|
-
const duration = Date.now() - startTime;
|
|
310
|
-
this.recordPerformanceMetric("creation", duration);
|
|
311
|
-
console.error("[ContentStorage] Failed to store content:", error);
|
|
312
|
-
throw new ContentReferenceError(
|
|
313
|
-
`Failed to store content: ${error instanceof Error ? error.message : "Unknown error"}`,
|
|
314
|
-
"system_error",
|
|
315
|
-
void 0,
|
|
316
|
-
["Try again", "Check storage limits", "Contact administrator"]
|
|
27
|
+
this.logger.info(
|
|
28
|
+
`Processing airdrop request for token ${input.tokenId} with ${input.recipients.length} recipients`
|
|
317
29
|
);
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
this.
|
|
30
|
+
const tokenInfo = await this.getTokenInfo(input.tokenId);
|
|
31
|
+
const decimals = tokenInfo.decimals || 0;
|
|
32
|
+
this.logger.info(`Token ${input.tokenId} has ${decimals} decimal places`);
|
|
33
|
+
const convertedRecipients = input.recipients.map((recipient) => {
|
|
34
|
+
const humanAmount = typeof recipient.amount === "string" ? parseFloat(recipient.amount) : recipient.amount;
|
|
35
|
+
const smallestUnitAmount = this.convertToSmallestUnits(
|
|
36
|
+
humanAmount,
|
|
37
|
+
decimals
|
|
38
|
+
);
|
|
39
|
+
this.logger.info(
|
|
40
|
+
`Converting amount for ${recipient.accountId}: ${humanAmount} tokens → ${smallestUnitAmount} smallest units`
|
|
41
|
+
);
|
|
328
42
|
return {
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
errorType: "not_found",
|
|
332
|
-
suggestedActions: ["Check the reference ID format", "Ensure the reference ID is complete"]
|
|
43
|
+
...recipient,
|
|
44
|
+
amount: smallestUnitAmount.toString()
|
|
333
45
|
};
|
|
334
|
-
}
|
|
335
|
-
const
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
return {
|
|
339
|
-
success: false,
|
|
340
|
-
error: "Reference not found",
|
|
341
|
-
errorType: "not_found",
|
|
342
|
-
suggestedActions: ["Verify the reference ID", "Check if the content has expired", "Request fresh content"]
|
|
343
|
-
};
|
|
344
|
-
}
|
|
345
|
-
if (storedContent.expiresAt && storedContent.expiresAt < /* @__PURE__ */ new Date()) {
|
|
346
|
-
storedContent.state = "expired";
|
|
347
|
-
this.referenceStats.failedResolutions++;
|
|
348
|
-
return {
|
|
349
|
-
success: false,
|
|
350
|
-
error: "Reference has expired",
|
|
351
|
-
errorType: "expired",
|
|
352
|
-
suggestedActions: ["Request fresh content", "Use alternative content source"]
|
|
353
|
-
};
|
|
354
|
-
}
|
|
355
|
-
if (storedContent.state !== "active") {
|
|
356
|
-
this.referenceStats.failedResolutions++;
|
|
357
|
-
return {
|
|
358
|
-
success: false,
|
|
359
|
-
error: `Reference is ${storedContent.state}`,
|
|
360
|
-
errorType: storedContent.state === "expired" ? "expired" : "corrupted",
|
|
361
|
-
suggestedActions: ["Request fresh content", "Check reference validity"]
|
|
362
|
-
};
|
|
363
|
-
}
|
|
364
|
-
storedContent.metadata.lastAccessedAt = /* @__PURE__ */ new Date();
|
|
365
|
-
storedContent.metadata.accessCount++;
|
|
366
|
-
this.referenceStats.totalResolutions++;
|
|
367
|
-
const duration = Date.now() - startTime;
|
|
368
|
-
this.recordPerformanceMetric("resolution", duration);
|
|
369
|
-
console.log(`[ContentStorage] Resolved reference ${referenceId} (${storedContent.content.length} bytes, access count: ${storedContent.metadata.accessCount})`);
|
|
370
|
-
return {
|
|
371
|
-
success: true,
|
|
372
|
-
content: storedContent.content,
|
|
373
|
-
metadata: storedContent.metadata
|
|
46
|
+
});
|
|
47
|
+
const convertedInput = {
|
|
48
|
+
...input,
|
|
49
|
+
recipients: convertedRecipients
|
|
374
50
|
};
|
|
51
|
+
this.logger.info(`Calling original airdrop tool with converted amounts`);
|
|
52
|
+
return await this.originalTool._call(convertedInput);
|
|
375
53
|
} catch (error) {
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
this.referenceStats.failedResolutions++;
|
|
379
|
-
console.error(`[ContentStorage] Error resolving reference ${referenceId}:`, error);
|
|
380
|
-
return {
|
|
381
|
-
success: false,
|
|
382
|
-
error: `System error resolving reference: ${error instanceof Error ? error.message : "Unknown error"}`,
|
|
383
|
-
errorType: "system_error",
|
|
384
|
-
suggestedActions: ["Try again", "Contact administrator"]
|
|
385
|
-
};
|
|
54
|
+
this.logger.error("Error in airdrop tool wrapper:", error);
|
|
55
|
+
throw error;
|
|
386
56
|
}
|
|
387
57
|
}
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
*/
|
|
391
|
-
async hasReference(referenceId) {
|
|
392
|
-
if (!ReferenceIdGenerator.isValidReferenceId(referenceId)) {
|
|
393
|
-
return false;
|
|
394
|
-
}
|
|
395
|
-
const storedContent = this.contentStore.get(referenceId);
|
|
396
|
-
if (!storedContent) {
|
|
397
|
-
return false;
|
|
398
|
-
}
|
|
399
|
-
if (storedContent.expiresAt && storedContent.expiresAt < /* @__PURE__ */ new Date()) {
|
|
400
|
-
storedContent.state = "expired";
|
|
401
|
-
return false;
|
|
402
|
-
}
|
|
403
|
-
return storedContent.state === "active";
|
|
404
|
-
}
|
|
405
|
-
/**
|
|
406
|
-
* Mark a reference for cleanup
|
|
407
|
-
*/
|
|
408
|
-
async cleanupReference(referenceId) {
|
|
409
|
-
const storedContent = this.contentStore.get(referenceId);
|
|
410
|
-
if (!storedContent) {
|
|
411
|
-
return false;
|
|
412
|
-
}
|
|
413
|
-
this.referenceStats.totalStorageBytes -= storedContent.content.length;
|
|
414
|
-
this.referenceStats.activeReferences--;
|
|
415
|
-
this.referenceStats.recentlyCleanedUp++;
|
|
416
|
-
this.contentStore.delete(referenceId);
|
|
417
|
-
console.log(`[ContentStorage] Cleaned up reference ${referenceId} (${storedContent.content.length} bytes)`);
|
|
418
|
-
return true;
|
|
58
|
+
convertToSmallestUnits(amount, decimals) {
|
|
59
|
+
return Math.floor(amount * Math.pow(10, decimals));
|
|
419
60
|
}
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
*/
|
|
423
|
-
async getStats() {
|
|
424
|
-
this.updateReferenceStorageStats();
|
|
425
|
-
return {
|
|
426
|
-
...this.referenceStats,
|
|
427
|
-
performanceMetrics: {
|
|
428
|
-
averageCreationTimeMs: this.calculateAverage(this.referenceStats.performanceMetrics.creationTimes),
|
|
429
|
-
averageResolutionTimeMs: this.calculateAverage(this.referenceStats.performanceMetrics.resolutionTimes),
|
|
430
|
-
averageCleanupTimeMs: this.calculateAverage(this.referenceStats.performanceMetrics.cleanupTimes)
|
|
431
|
-
}
|
|
432
|
-
};
|
|
433
|
-
}
|
|
434
|
-
/**
|
|
435
|
-
* Update reference configuration
|
|
436
|
-
*/
|
|
437
|
-
async updateConfig(config) {
|
|
438
|
-
this.referenceConfig = { ...this.referenceConfig, ...config };
|
|
439
|
-
if (this.cleanupTimer) {
|
|
440
|
-
clearInterval(this.cleanupTimer);
|
|
441
|
-
delete this.cleanupTimer;
|
|
442
|
-
}
|
|
443
|
-
if (this.referenceConfig.enableAutoCleanup) {
|
|
444
|
-
this.startReferenceCleanupTimer();
|
|
445
|
-
}
|
|
446
|
-
console.log("[ContentStorage] Reference configuration updated");
|
|
61
|
+
async getTokenInfo(tokenId) {
|
|
62
|
+
return await this.queryTokenInfo(tokenId);
|
|
447
63
|
}
|
|
448
|
-
|
|
449
|
-
* Perform cleanup based on current policies (implements ContentReferenceStore)
|
|
450
|
-
*/
|
|
451
|
-
async performCleanup() {
|
|
452
|
-
const startTime = Date.now();
|
|
453
|
-
const errors = [];
|
|
454
|
-
let cleanedUp = 0;
|
|
64
|
+
async queryTokenInfo(tokenId) {
|
|
455
65
|
try {
|
|
456
|
-
|
|
457
|
-
const
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
if (
|
|
468
|
-
|
|
66
|
+
this.logger.info("Querying token info using mirror node");
|
|
67
|
+
const mirrorNode = this.agentKit.mirrorNode;
|
|
68
|
+
if (!mirrorNode) {
|
|
69
|
+
this.logger.info(
|
|
70
|
+
"MirrorNode not found in agentKit, attempting to access via fetch"
|
|
71
|
+
);
|
|
72
|
+
const network = this.agentKit.network || "testnet";
|
|
73
|
+
const mirrorNodeUrl = network === "mainnet" ? "https://mainnet.mirrornode.hedera.com" : "https://testnet.mirrornode.hedera.com";
|
|
74
|
+
const response = await fetch(
|
|
75
|
+
`${mirrorNodeUrl}/api/v1/tokens/${tokenId}`
|
|
76
|
+
);
|
|
77
|
+
if (response.ok) {
|
|
78
|
+
const tokenData = await response.json();
|
|
79
|
+
const decimals = parseInt(String(tokenData.decimals || "0"));
|
|
80
|
+
this.logger.info(
|
|
81
|
+
`Token ${tokenId} found with ${decimals} decimals via API`
|
|
82
|
+
);
|
|
83
|
+
return { ...tokenData, decimals };
|
|
469
84
|
}
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
85
|
+
} else {
|
|
86
|
+
const tokenData = await mirrorNode.getTokenInfo(tokenId);
|
|
87
|
+
if (tokenData && typeof tokenData.decimals !== "undefined") {
|
|
88
|
+
const decimals = parseInt(tokenData.decimals.toString()) || 0;
|
|
89
|
+
this.logger.info(`Token ${tokenId} found with ${decimals} decimals`);
|
|
90
|
+
return { ...tokenData, decimals };
|
|
475
91
|
}
|
|
476
92
|
}
|
|
477
|
-
|
|
478
|
-
const aContent = this.contentStore.get(a);
|
|
479
|
-
const bContent = this.contentStore.get(b);
|
|
480
|
-
const aPriority = this.getCleanupPolicy(aContent.metadata.source).priority;
|
|
481
|
-
const bPriority = this.getCleanupPolicy(bContent.metadata.source).priority;
|
|
482
|
-
return bPriority - aPriority;
|
|
483
|
-
});
|
|
484
|
-
for (const referenceId of toCleanup) {
|
|
485
|
-
try {
|
|
486
|
-
const success = await this.cleanupReference(referenceId);
|
|
487
|
-
if (success) {
|
|
488
|
-
cleanedUp++;
|
|
489
|
-
}
|
|
490
|
-
} catch (error) {
|
|
491
|
-
errors.push(`Failed to cleanup ${referenceId}: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
492
|
-
}
|
|
493
|
-
}
|
|
494
|
-
if (this.contentStore.size > this.referenceConfig.maxReferences) {
|
|
495
|
-
const sortedByAge = Array.from(this.contentStore.entries()).sort(([, a], [, b]) => a.metadata.lastAccessedAt.getTime() - b.metadata.lastAccessedAt.getTime());
|
|
496
|
-
const excessCount = this.contentStore.size - this.referenceConfig.maxReferences;
|
|
497
|
-
for (let i = 0; i < excessCount && i < sortedByAge.length; i++) {
|
|
498
|
-
const [referenceId] = sortedByAge[i];
|
|
499
|
-
try {
|
|
500
|
-
const success = await this.cleanupReference(referenceId);
|
|
501
|
-
if (success) {
|
|
502
|
-
cleanedUp++;
|
|
503
|
-
}
|
|
504
|
-
} catch (error) {
|
|
505
|
-
errors.push(`Failed to cleanup excess reference ${referenceId}: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
506
|
-
}
|
|
507
|
-
}
|
|
508
|
-
}
|
|
509
|
-
const duration = Date.now() - startTime;
|
|
510
|
-
this.recordPerformanceMetric("cleanup", duration);
|
|
511
|
-
console.log(`[ContentStorage] Reference cleanup completed: ${cleanedUp} references cleaned up, ${errors.length} errors`);
|
|
512
|
-
return { cleanedUp, errors };
|
|
93
|
+
throw new Error(`Token data not found or missing decimals field`);
|
|
513
94
|
} catch (error) {
|
|
514
|
-
|
|
515
|
-
this.
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
return { cleanedUp, errors };
|
|
520
|
-
}
|
|
521
|
-
}
|
|
522
|
-
/**
|
|
523
|
-
* Get reference configuration for debugging
|
|
524
|
-
*/
|
|
525
|
-
getReferenceConfig() {
|
|
526
|
-
return { ...this.referenceConfig };
|
|
527
|
-
}
|
|
528
|
-
// ========== Private Reference Storage Helper Methods ==========
|
|
529
|
-
async enforceReferenceStorageLimits() {
|
|
530
|
-
if (this.contentStore.size >= this.referenceConfig.maxReferences) {
|
|
531
|
-
await this.performCleanup();
|
|
532
|
-
}
|
|
533
|
-
if (this.referenceStats.totalStorageBytes >= this.referenceConfig.maxTotalStorageBytes) {
|
|
534
|
-
await this.performCleanup();
|
|
535
|
-
}
|
|
536
|
-
}
|
|
537
|
-
calculateExpirationTime(source) {
|
|
538
|
-
const policy = this.getCleanupPolicy(source);
|
|
539
|
-
return new Date(Date.now() + policy.maxAgeMs);
|
|
540
|
-
}
|
|
541
|
-
getCleanupPolicy(source) {
|
|
542
|
-
switch (source) {
|
|
543
|
-
case "mcp_tool":
|
|
544
|
-
return this.referenceConfig.cleanupPolicies.recent;
|
|
545
|
-
case "user_upload":
|
|
546
|
-
return this.referenceConfig.cleanupPolicies.userContent;
|
|
547
|
-
case "agent_generated":
|
|
548
|
-
return this.referenceConfig.cleanupPolicies.agentGenerated;
|
|
549
|
-
default:
|
|
550
|
-
return this.referenceConfig.cleanupPolicies.default;
|
|
551
|
-
}
|
|
552
|
-
}
|
|
553
|
-
detectContentType(content, mimeType) {
|
|
554
|
-
if (mimeType) {
|
|
555
|
-
if (mimeType === "text/html") return "html";
|
|
556
|
-
if (mimeType === "text/markdown") return "markdown";
|
|
557
|
-
if (mimeType === "application/json") return "json";
|
|
558
|
-
if (mimeType.startsWith("text/")) return "text";
|
|
559
|
-
return "binary";
|
|
560
|
-
}
|
|
561
|
-
const contentStr = content.toString("utf8", 0, Math.min(content.length, 1e3));
|
|
562
|
-
if (contentStr.startsWith("{") || contentStr.startsWith("[")) return "json";
|
|
563
|
-
if (contentStr.includes("<html>") || contentStr.includes("<!DOCTYPE")) return "html";
|
|
564
|
-
if (contentStr.includes("#") && contentStr.includes("\n")) return "markdown";
|
|
565
|
-
return "text";
|
|
566
|
-
}
|
|
567
|
-
createContentPreview(content, contentType) {
|
|
568
|
-
const maxLength = 200;
|
|
569
|
-
let preview = content.toString("utf8", 0, Math.min(content.length, maxLength * 2));
|
|
570
|
-
if (contentType === "html") {
|
|
571
|
-
preview = preview.replace(/<[^>]*>/g, "").replace(/\s+/g, " ").trim();
|
|
572
|
-
} else if (contentType === "json") {
|
|
573
|
-
try {
|
|
574
|
-
const parsed = JSON.parse(preview);
|
|
575
|
-
preview = JSON.stringify(parsed, null, 0);
|
|
576
|
-
} catch {
|
|
577
|
-
}
|
|
578
|
-
}
|
|
579
|
-
preview = preview.trim();
|
|
580
|
-
if (preview.length > maxLength) {
|
|
581
|
-
preview = preview.substring(0, maxLength) + "...";
|
|
582
|
-
}
|
|
583
|
-
return preview || "[Binary content]";
|
|
584
|
-
}
|
|
585
|
-
updateStatsAfterStore(sizeBytes) {
|
|
586
|
-
this.referenceStats.activeReferences++;
|
|
587
|
-
this.referenceStats.totalStorageBytes += sizeBytes;
|
|
588
|
-
this.updateReferenceStorageStats();
|
|
589
|
-
}
|
|
590
|
-
updateReferenceStorageStats() {
|
|
591
|
-
if (this.referenceStats.activeReferences > 0) {
|
|
592
|
-
this.referenceStats.averageContentSize = this.referenceStats.totalStorageBytes / this.referenceStats.activeReferences;
|
|
593
|
-
}
|
|
594
|
-
this.referenceStats.storageUtilization = this.referenceStats.totalStorageBytes / this.referenceConfig.maxTotalStorageBytes * 100;
|
|
595
|
-
let mostAccessedId;
|
|
596
|
-
let maxAccess = 0;
|
|
597
|
-
for (const [referenceId, storedContent] of this.contentStore.entries()) {
|
|
598
|
-
if (storedContent.metadata.accessCount > maxAccess) {
|
|
599
|
-
maxAccess = storedContent.metadata.accessCount;
|
|
600
|
-
mostAccessedId = referenceId;
|
|
601
|
-
}
|
|
602
|
-
}
|
|
603
|
-
if (mostAccessedId !== void 0) {
|
|
604
|
-
this.referenceStats.mostAccessedReferenceId = mostAccessedId;
|
|
605
|
-
} else {
|
|
606
|
-
delete this.referenceStats.mostAccessedReferenceId;
|
|
607
|
-
}
|
|
608
|
-
}
|
|
609
|
-
recordPerformanceMetric(type, timeMs) {
|
|
610
|
-
const metrics = this.referenceStats.performanceMetrics;
|
|
611
|
-
const maxRecords = 100;
|
|
612
|
-
switch (type) {
|
|
613
|
-
case "creation":
|
|
614
|
-
metrics.creationTimes.push(timeMs);
|
|
615
|
-
if (metrics.creationTimes.length > maxRecords) {
|
|
616
|
-
metrics.creationTimes.shift();
|
|
617
|
-
}
|
|
618
|
-
break;
|
|
619
|
-
case "resolution":
|
|
620
|
-
metrics.resolutionTimes.push(timeMs);
|
|
621
|
-
if (metrics.resolutionTimes.length > maxRecords) {
|
|
622
|
-
metrics.resolutionTimes.shift();
|
|
623
|
-
}
|
|
624
|
-
break;
|
|
625
|
-
case "cleanup":
|
|
626
|
-
metrics.cleanupTimes.push(timeMs);
|
|
627
|
-
if (metrics.cleanupTimes.length > maxRecords) {
|
|
628
|
-
metrics.cleanupTimes.shift();
|
|
629
|
-
}
|
|
630
|
-
break;
|
|
631
|
-
}
|
|
632
|
-
}
|
|
633
|
-
calculateAverage(times) {
|
|
634
|
-
if (times.length === 0) return 0;
|
|
635
|
-
return times.reduce((sum, time) => sum + time, 0) / times.length;
|
|
636
|
-
}
|
|
637
|
-
startReferenceCleanupTimer() {
|
|
638
|
-
this.cleanupTimer = setInterval(async () => {
|
|
639
|
-
try {
|
|
640
|
-
await this.performCleanup();
|
|
641
|
-
} catch (error) {
|
|
642
|
-
console.error("[ContentStorage] Error in scheduled reference cleanup:", error);
|
|
643
|
-
}
|
|
644
|
-
}, this.referenceConfig.cleanupIntervalMs);
|
|
645
|
-
}
|
|
646
|
-
/**
|
|
647
|
-
* Clean up resources (enhanced to include reference cleanup)
|
|
648
|
-
*/
|
|
649
|
-
async dispose() {
|
|
650
|
-
if (this.cleanupTimer) {
|
|
651
|
-
clearInterval(this.cleanupTimer);
|
|
652
|
-
delete this.cleanupTimer;
|
|
95
|
+
this.logger.warn(`Failed to query token info for ${tokenId}:`, error);
|
|
96
|
+
this.logger.info(
|
|
97
|
+
"Falling back to assumed 0 decimal places (smallest units)"
|
|
98
|
+
);
|
|
99
|
+
return { decimals: 0 };
|
|
653
100
|
}
|
|
654
|
-
this.contentStore.clear();
|
|
655
|
-
this.clear();
|
|
656
101
|
}
|
|
657
|
-
}
|
|
658
|
-
_ContentStorage.DEFAULT_MAX_STORAGE = 1e3;
|
|
659
|
-
let ContentStorage = _ContentStorage;
|
|
102
|
+
}
|
|
660
103
|
export {
|
|
661
|
-
|
|
104
|
+
AirdropToolWrapper
|
|
662
105
|
};
|
|
663
106
|
//# sourceMappingURL=index19.js.map
|