@hashgraphonline/conversational-agent 0.1.208 → 0.1.209

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 (68) hide show
  1. package/dist/cjs/conversational-agent.d.ts +67 -8
  2. package/dist/cjs/index.cjs +1 -1
  3. package/dist/cjs/index.cjs.map +1 -1
  4. package/dist/cjs/index.d.ts +1 -0
  5. package/dist/cjs/langchain-agent.d.ts +8 -0
  6. package/dist/cjs/memory/SmartMemoryManager.d.ts +58 -21
  7. package/dist/cjs/memory/index.d.ts +1 -1
  8. package/dist/esm/index.js +8 -0
  9. package/dist/esm/index.js.map +1 -1
  10. package/dist/esm/index12.js +124 -46
  11. package/dist/esm/index12.js.map +1 -1
  12. package/dist/esm/index13.js +178 -13
  13. package/dist/esm/index13.js.map +1 -1
  14. package/dist/esm/index14.js +604 -100
  15. package/dist/esm/index14.js.map +1 -1
  16. package/dist/esm/index15.js +464 -9
  17. package/dist/esm/index15.js.map +1 -1
  18. package/dist/esm/index16.js +44 -172
  19. package/dist/esm/index16.js.map +1 -1
  20. package/dist/esm/index17.js +11 -156
  21. package/dist/esm/index17.js.map +1 -1
  22. package/dist/esm/index18.js +106 -191
  23. package/dist/esm/index18.js.map +1 -1
  24. package/dist/esm/index19.js +9 -660
  25. package/dist/esm/index19.js.map +1 -1
  26. package/dist/esm/index2.js +22 -13
  27. package/dist/esm/index2.js.map +1 -1
  28. package/dist/esm/index20.js +150 -206
  29. package/dist/esm/index20.js.map +1 -1
  30. package/dist/esm/index21.js +140 -166
  31. package/dist/esm/index21.js.map +1 -1
  32. package/dist/esm/index22.js +47 -105
  33. package/dist/esm/index22.js.map +1 -1
  34. package/dist/esm/index23.js +24 -89
  35. package/dist/esm/index23.js.map +1 -1
  36. package/dist/esm/index24.js +83 -56
  37. package/dist/esm/index24.js.map +1 -1
  38. package/dist/esm/index25.js +236 -32
  39. package/dist/esm/index25.js.map +1 -1
  40. package/dist/esm/index5.js +1 -1
  41. package/dist/esm/index6.js +295 -17
  42. package/dist/esm/index6.js.map +1 -1
  43. package/dist/esm/index8.js +82 -8
  44. package/dist/esm/index8.js.map +1 -1
  45. package/dist/types/conversational-agent.d.ts +67 -8
  46. package/dist/types/index.d.ts +1 -0
  47. package/dist/types/langchain-agent.d.ts +8 -0
  48. package/dist/types/memory/SmartMemoryManager.d.ts +58 -21
  49. package/dist/types/memory/index.d.ts +1 -1
  50. package/package.json +3 -3
  51. package/src/context/ReferenceContextManager.ts +9 -4
  52. package/src/context/ReferenceResponseProcessor.ts +3 -4
  53. package/src/conversational-agent.ts +379 -31
  54. package/src/index.ts +2 -0
  55. package/src/langchain/ContentAwareAgentExecutor.ts +0 -1
  56. package/src/langchain-agent.ts +94 -11
  57. package/src/mcp/ContentProcessor.ts +13 -3
  58. package/src/mcp/adapters/langchain.ts +1 -9
  59. package/src/memory/ContentStorage.ts +3 -51
  60. package/src/memory/MemoryWindow.ts +4 -16
  61. package/src/memory/ReferenceIdGenerator.ts +0 -4
  62. package/src/memory/SmartMemoryManager.ts +400 -33
  63. package/src/memory/TokenCounter.ts +12 -16
  64. package/src/memory/index.ts +1 -1
  65. package/src/plugins/hcs-10/HCS10Plugin.ts +44 -14
  66. package/src/services/ContentStoreManager.ts +0 -3
  67. package/src/types/content-reference.ts +8 -8
  68. package/src/types/index.ts +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index22.js","sources":["../../src/memory/TokenCounter.ts"],"sourcesContent":["import { encoding_for_model } from 'tiktoken';\nimport type { TiktokenModel } from 'tiktoken';\nimport type { BaseMessage } from '@langchain/core/messages';\n\n/**\n * Token counter utility for OpenAI models using tiktoken encoding\n * Provides accurate token counting for text content and chat messages\n */\nexport class TokenCounter {\n private encoding: ReturnType<typeof encoding_for_model>;\n private modelName: TiktokenModel;\n\n // Token overhead per message for chat completion format\n private static readonly MESSAGE_OVERHEAD = 3; // <|start|>role<|end|>content<|end|>\n private static readonly ROLE_OVERHEAD = 1; // Additional token for role specification\n\n constructor(modelName: TiktokenModel = 'gpt-4o') {\n this.modelName = modelName;\n try {\n this.encoding = encoding_for_model(modelName);\n } catch (error) {\n // Fallback to gpt-4o if specific model encoding is not available\n console.warn(`Model ${modelName} not found, falling back to gpt-4o encoding`);\n this.encoding = encoding_for_model('gpt-4o');\n this.modelName = 'gpt-4o';\n }\n }\n\n /**\n * Count tokens in raw text content\n * @param text - The text to count tokens for\n * @returns Number of tokens\n */\n countTokens(text: string): number {\n if (!text || text.trim() === '') {\n return 0;\n }\n\n try {\n const tokens = this.encoding.encode(text);\n return tokens.length;\n } catch (error) {\n console.warn('Error counting tokens, falling back to word-based estimation:', error);\n // Fallback: rough estimation based on words (typically 1.3 tokens per word)\n return Math.ceil(text.split(/\\s+/).length * 1.3);\n }\n }\n\n /**\n * Count tokens for a single chat message including role overhead\n * @param message - The message to count tokens for\n * @returns Number of tokens including message formatting overhead\n */\n countMessageTokens(message: BaseMessage): number {\n const contentTokens = this.countTokens(message.content as string);\n const roleTokens = this.countTokens(this.getMessageRole(message));\n \n // Add overhead for message structure and role\n return contentTokens + roleTokens + TokenCounter.MESSAGE_OVERHEAD + TokenCounter.ROLE_OVERHEAD;\n }\n\n /**\n * Count tokens for multiple messages\n * @param messages - Array of messages to count\n * @returns Total token count for all messages\n */\n countMessagesTokens(messages: BaseMessage[]): number {\n if (!messages || messages.length === 0) {\n return 0;\n }\n\n return messages.reduce((total, message) => {\n return total + this.countMessageTokens(message);\n }, 0);\n }\n\n /**\n * Estimate tokens for system prompt\n * System prompts have slightly different overhead in chat completions\n * @param systemPrompt - The system prompt text\n * @returns Estimated token count\n */\n estimateSystemPromptTokens(systemPrompt: string): number {\n if (!systemPrompt || systemPrompt.trim() === '') {\n return 0;\n }\n\n const contentTokens = this.countTokens(systemPrompt);\n const roleTokens = this.countTokens('system');\n \n // System messages have similar overhead to regular messages\n return contentTokens + roleTokens + TokenCounter.MESSAGE_OVERHEAD + TokenCounter.ROLE_OVERHEAD;\n }\n\n /**\n * Get total context size estimate including system prompt and messages\n * @param systemPrompt - System prompt text\n * @param messages - Conversation messages\n * @returns Total estimated token count\n */\n estimateContextSize(systemPrompt: string, messages: BaseMessage[]): number {\n const systemTokens = this.estimateSystemPromptTokens(systemPrompt);\n const messageTokens = this.countMessagesTokens(messages);\n \n // Add a small buffer for chat completion overhead\n const completionOverhead = 10;\n \n return systemTokens + messageTokens + completionOverhead;\n }\n\n /**\n * Get the role string for a message\n * @param message - The message to get the role for\n * @returns Role string ('user', 'assistant', 'system', etc.)\n */\n private getMessageRole(message: BaseMessage): string {\n const messageType = message._getType();\n switch (messageType) {\n case 'human':\n return 'user';\n case 'ai':\n return 'assistant';\n case 'system':\n return 'system';\n case 'function':\n return 'function';\n case 'tool':\n return 'tool';\n default:\n return 'user'; // Default fallback\n }\n }\n\n /**\n * Get the model name being used for token counting\n * @returns The tiktoken model name\n */\n getModelName(): string {\n return this.modelName;\n }\n\n /**\n * Clean up encoding resources\n */\n dispose(): void {\n try {\n this.encoding.free();\n } catch (error) {\n console.warn('Error disposing encoding:', error);\n }\n }\n}"],"names":[],"mappings":";AAQO,MAAM,gBAAN,MAAM,cAAa;AAAA;AAAA,EAQxB,YAAY,YAA2B,UAAU;AAC/C,SAAK,YAAY;AACjB,QAAI;AACF,WAAK,WAAW,mBAAmB,SAAS;AAAA,IAC9C,SAAS,OAAO;AAEd,cAAQ,KAAK,SAAS,SAAS,6CAA6C;AAC5E,WAAK,WAAW,mBAAmB,QAAQ;AAC3C,WAAK,YAAY;AAAA,IACnB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,YAAY,MAAsB;AAChC,QAAI,CAAC,QAAQ,KAAK,KAAA,MAAW,IAAI;AAC/B,aAAO;AAAA,IACT;AAEA,QAAI;AACF,YAAM,SAAS,KAAK,SAAS,OAAO,IAAI;AACxC,aAAO,OAAO;AAAA,IAChB,SAAS,OAAO;AACd,cAAQ,KAAK,iEAAiE,KAAK;AAEnF,aAAO,KAAK,K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AA,MACT,KAAK;AACH,eAAO;AAAA,MACT;AACE,eAAO;AAAA,IAAA;AAAA,EAEb;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,eAAuB;AACrB,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA,EAKA,UAAgB;AACd,QAAI;AACF,WAAK,SAAS,KAAA;AAAA,IAChB,SAAS,OAAO;AACd,cAAQ,KAAK,6BAA6B,KAAK;AAAA,IACjD;AAAA,EACF;AACF;AA1IE,cAAwB,mBAAmB;AAC3C,cAAwB,gBAAgB;AANnC,IAAM,eAAN;"}
1
+ {"version":3,"file":"index22.js","sources":["../../src/memory/ReferenceIdGenerator.ts"],"sourcesContent":["import { createHash } from 'crypto';\nimport { ReferenceId } from '../types/content-reference';\n\n/**\n * Content-based reference ID generator using SHA-256 (HCS-1 style)\n * \n * Generates deterministic reference IDs based on content hashing.\n * Same content always produces the same reference ID.\n */\nexport class ReferenceIdGenerator {\n /**\n * Generate a content-based reference ID using SHA-256 hashing\n * \n * @param content The content to generate a reference ID for\n * @returns Deterministic reference ID based on content hash\n */\n static generateId(content: Buffer): ReferenceId {\n const hash = createHash('sha256');\n hash.update(content);\n return hash.digest('base64url');\n }\n \n /**\n * Validate that a string is a properly formatted reference ID\n * \n * @param id The ID to validate\n * @returns true if the ID is valid format\n */\n static isValidReferenceId(id: string): id is ReferenceId {\n if (!id || typeof id !== 'string') {\n return false;\n }\n \n if (id.length !== 43) {\n return false;\n }\n \n return /^[A-Za-z0-9_-]+$/.test(id);\n }\n \n /**\n * Extract reference ID from ref:// format\n * \n * @param input Input string that may contain a reference ID\n * @returns Extracted reference ID or null if not found\n */\n static extractReferenceId(input: string): ReferenceId | null {\n if (!input || typeof input !== 'string') {\n return null;\n }\n \n const refFormatMatch = input.match(/^ref:\\/\\/([A-Za-z0-9_-]{43})$/);\n if (refFormatMatch) {\n return refFormatMatch[1] as ReferenceId;\n }\n \n return this.isValidReferenceId(input) ? input : null;\n }\n \n /**\n * Format a reference ID in the standard ref:// format\n * \n * @param referenceId The reference ID to format\n * @returns Formatted reference string\n */\n static formatReference(referenceId: ReferenceId): string {\n return `ref://${referenceId}`;\n }\n \n /**\n * Generate a test reference ID (for testing purposes only)\n * \n * @param testSeed A test seed to generate a fake but valid ID format\n * @returns A valid format reference ID for testing\n */\n static generateTestId(testSeed: string): ReferenceId {\n const content = Buffer.from(`test-${testSeed}-${Date.now()}`);\n return this.generateId(content);\n }\n}"],"names":[],"mappings":";AASO,MAAM,qBAAqB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOhC,OAAO,WAAW,SAA8B;AAC9C,UAAM,OAAO,WAAW,QAAQ;AAChC,SAAK,OAAO,OAAO;AACnB,WAAO,KAAK,OAAO,WAAW;AAAA,EAChC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAO,mBAAmB,IAA+B;AACvD,QAAI,CAAC,MAAM,OAAO,OAAO,UAAU;AACjC,aAAO;AAAA,IACT;AAEA,QAAI,GAAG,WAAW,IAAI;AACpB,aAAO;AAAA,IACT;AAEA,WAAO,mBAAmB,KAAK,EAAE;AAAA,EACnC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAO,mBAAmB,OAAmC;AAC3D,QAAI,CAAC,SAAS,OAAO,UAAU,UAAU;AACvC,aAAO;AAAA,IACT;AAEA,UAAM,iBAAiB,MAAM,MAAM,+BAA+B;AAClE,QAAI,gBAAgB;AAClB,aAAO,eAAe,CAAC;AAAA,IACzB;AAEA,WAAO,KAAK,mBAAmB,KAAK,IAAI,QAAQ;AAAA,EAClD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAO,gBAAgB,aAAkC;AACvD,WAAO,SAAS,WAAW;AAAA,EAC7B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAO,eAAe,UAA+B;AACnD,UAAM,UAAU,OAAO,KAAK,QAAQ,QAAQ,IAAI,KAAK,IAAA,CAAK,EAAE;AAC5D,WAAO,KAAK,WAAW,OAAO;AAAA,EAChC;AACF;"}
@@ -1,95 +1,30 @@
1
- import { TransferTransaction, AccountId, Hbar } from "@hashgraph/sdk";
2
- import BigNumber from "bignumber.js";
3
- import { BaseServiceBuilder } from "hedera-agent-kit";
4
- class AccountBuilder extends BaseServiceBuilder {
5
- constructor(hederaKit) {
6
- super(hederaKit);
1
+ const DEFAULT_CONTENT_REFERENCE_CONFIG = {
2
+ sizeThresholdBytes: 10 * 1024,
3
+ maxAgeMs: 60 * 60 * 1e3,
4
+ maxReferences: 100,
5
+ maxTotalStorageBytes: 100 * 1024 * 1024,
6
+ enableAutoCleanup: true,
7
+ cleanupIntervalMs: 5 * 60 * 1e3,
8
+ enablePersistence: false,
9
+ storageBackend: "memory",
10
+ cleanupPolicies: {
11
+ recent: { maxAgeMs: 30 * 60 * 1e3, priority: 1 },
12
+ userContent: { maxAgeMs: 2 * 60 * 60 * 1e3, priority: 2 },
13
+ agentGenerated: { maxAgeMs: 60 * 60 * 1e3, priority: 3 },
14
+ default: { maxAgeMs: 60 * 60 * 1e3, priority: 4 }
7
15
  }
8
- /**
9
- * Transfers HBAR between accounts with proper decimal handling
10
- */
11
- transferHbar(params, isUserInitiated = true) {
12
- this.clearNotes();
13
- const transaction = new TransferTransaction();
14
- if (!params.transfers || params.transfers.length === 0) {
15
- throw new Error("HbarTransferParams must include at least one transfer.");
16
- }
17
- let netZeroInTinybars = new BigNumber(0);
18
- let userTransferProcessedForScheduling = false;
19
- if (isUserInitiated && this.kit.userAccountId && this.kit.operationalMode === "provideBytes" && params.transfers.length === 1) {
20
- const receiverTransfer = params.transfers[0];
21
- const amountValue = typeof receiverTransfer.amount === "string" || typeof receiverTransfer.amount === "number" ? receiverTransfer.amount : receiverTransfer.amount.toString();
22
- const amountBigNum = new BigNumber(amountValue);
23
- if (amountBigNum.isPositive()) {
24
- const recipientAccountId = typeof receiverTransfer.accountId === "string" ? AccountId.fromString(receiverTransfer.accountId) : receiverTransfer.accountId;
25
- const roundedAmount = amountBigNum.toFixed(8, BigNumber.ROUND_DOWN);
26
- const sdkHbarAmount = Hbar.fromString(roundedAmount);
27
- this.logger.info(
28
- `[AccountBuilder.transferHbar] Configuring user-initiated scheduled transfer: ${sdkHbarAmount.toString()} from ${this.kit.userAccountId} to ${recipientAccountId.toString()}`
29
- );
30
- this.addNote(
31
- `Configured HBAR transfer from your account (${this.kit.userAccountId}) to ${recipientAccountId.toString()} for ${sdkHbarAmount.toString()}.`
32
- );
33
- transaction.addHbarTransfer(recipientAccountId, sdkHbarAmount);
34
- transaction.addHbarTransfer(
35
- AccountId.fromString(this.kit.userAccountId),
36
- sdkHbarAmount.negated()
37
- );
38
- userTransferProcessedForScheduling = true;
39
- }
40
- }
41
- if (!userTransferProcessedForScheduling) {
42
- const processedTransfers = [];
43
- for (const transferInput of params.transfers) {
44
- const accountId = typeof transferInput.accountId === "string" ? AccountId.fromString(transferInput.accountId) : transferInput.accountId;
45
- const amountValue = typeof transferInput.amount === "string" || typeof transferInput.amount === "number" ? transferInput.amount : transferInput.amount.toString();
46
- const amountBigNum = new BigNumber(amountValue);
47
- const roundedAmount = amountBigNum.toFixed(8, BigNumber.ROUND_DOWN);
48
- this.logger.info(
49
- `Processing transfer: ${amountValue} HBAR (rounded to ${roundedAmount}) for account ${accountId.toString()}`
50
- );
51
- const sdkHbarAmount = Hbar.fromString(roundedAmount);
52
- processedTransfers.push({
53
- accountId,
54
- amount: amountBigNum,
55
- hbar: sdkHbarAmount
56
- });
57
- const tinybarsContribution = sdkHbarAmount.toTinybars();
58
- netZeroInTinybars = netZeroInTinybars.plus(
59
- tinybarsContribution.toString()
60
- );
61
- }
62
- if (!netZeroInTinybars.isZero()) {
63
- this.logger.warn(
64
- `Transfer sum not zero: ${netZeroInTinybars.toString()} tinybars off. Adjusting last transfer.`
65
- );
66
- if (processedTransfers.length > 0) {
67
- const lastTransfer = processedTransfers[processedTransfers.length - 1];
68
- const adjustment = netZeroInTinybars.dividedBy(-1e8);
69
- const adjustedAmount = lastTransfer.amount.plus(adjustment);
70
- const adjustedRounded = adjustedAmount.toFixed(8, BigNumber.ROUND_DOWN);
71
- lastTransfer.hbar = Hbar.fromString(adjustedRounded);
72
- this.logger.info(
73
- `Adjusted last transfer for ${lastTransfer.accountId.toString()} to ${adjustedRounded} HBAR`
74
- );
75
- }
76
- }
77
- for (const transfer of processedTransfers) {
78
- transaction.addHbarTransfer(transfer.accountId, transfer.hbar);
79
- }
80
- }
81
- if (typeof params.memo !== "undefined") {
82
- if (params.memo === null) {
83
- this.logger.warn("Received null for memo in transferHbar.");
84
- } else {
85
- transaction.setTransactionMemo(params.memo);
86
- }
87
- }
88
- this.setCurrentTransaction(transaction);
89
- return this;
16
+ };
17
+ class ContentReferenceError extends Error {
18
+ constructor(message, type, referenceId, suggestedActions) {
19
+ super(message);
20
+ this.type = type;
21
+ this.referenceId = referenceId;
22
+ this.suggestedActions = suggestedActions;
23
+ this.name = "ContentReferenceError";
90
24
  }
91
25
  }
92
26
  export {
93
- AccountBuilder
27
+ ContentReferenceError,
28
+ DEFAULT_CONTENT_REFERENCE_CONFIG
94
29
  };
95
30
  //# sourceMappingURL=index23.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index23.js","sources":["../../src/plugins/hbar-transfer/AccountBuilder.ts"],"sourcesContent":["import {\n AccountId,\n Hbar,\n TransferTransaction,\n} from '@hashgraph/sdk';\nimport BigNumber from 'bignumber.js';\nimport { HederaAgentKit, BaseServiceBuilder } from 'hedera-agent-kit';\nimport { HbarTransferParams } from './types';\n\n/**\n * Custom AccountBuilder that properly handles HBAR decimal conversion\n */\nexport class AccountBuilder extends BaseServiceBuilder {\n constructor(hederaKit: HederaAgentKit) {\n super(hederaKit);\n }\n\n /**\n * Transfers HBAR between accounts with proper decimal handling\n */\n public transferHbar(\n params: HbarTransferParams,\n isUserInitiated: boolean = true\n ): this {\n this.clearNotes();\n const transaction = new TransferTransaction();\n \n if (!params.transfers || params.transfers.length === 0) {\n throw new Error('HbarTransferParams must include at least one transfer.');\n }\n\n let netZeroInTinybars = new BigNumber(0);\n let userTransferProcessedForScheduling = false;\n\n if (\n isUserInitiated &&\n this.kit.userAccountId &&\n (this.kit.operationalMode as string) === 'provideBytes' &&\n params.transfers.length === 1\n ) {\n const receiverTransfer = params.transfers[0];\n const amountValue =\n typeof receiverTransfer.amount === 'string' ||\n typeof receiverTransfer.amount === 'number'\n ? receiverTransfer.amount\n : receiverTransfer.amount.toString();\n\n const amountBigNum = new BigNumber(amountValue);\n\n if (amountBigNum.isPositive()) {\n const recipientAccountId =\n typeof receiverTransfer.accountId === 'string'\n ? AccountId.fromString(receiverTransfer.accountId)\n : receiverTransfer.accountId;\n\n const roundedAmount = amountBigNum.toFixed(8, BigNumber.ROUND_DOWN);\n const sdkHbarAmount = Hbar.fromString(roundedAmount);\n\n this.logger.info(\n `[AccountBuilder.transferHbar] Configuring user-initiated scheduled transfer: ${sdkHbarAmount.toString()} from ${\n this.kit.userAccountId\n } to ${recipientAccountId.toString()}`\n );\n \n this.addNote(\n `Configured HBAR transfer from your account (${\n this.kit.userAccountId\n }) to ${recipientAccountId.toString()} for ${sdkHbarAmount.toString()}.`\n );\n\n transaction.addHbarTransfer(recipientAccountId, sdkHbarAmount);\n transaction.addHbarTransfer(\n AccountId.fromString(this.kit.userAccountId),\n sdkHbarAmount.negated()\n );\n\n userTransferProcessedForScheduling = true;\n }\n }\n\n if (!userTransferProcessedForScheduling) {\n const processedTransfers: Array<{\n accountId: AccountId;\n amount: BigNumber;\n hbar: Hbar;\n }> = [];\n \n for (const transferInput of params.transfers) {\n const accountId =\n typeof transferInput.accountId === 'string'\n ? AccountId.fromString(transferInput.accountId)\n : transferInput.accountId;\n\n const amountValue =\n typeof transferInput.amount === 'string' ||\n typeof transferInput.amount === 'number'\n ? transferInput.amount\n : transferInput.amount.toString();\n\n const amountBigNum = new BigNumber(amountValue);\n const roundedAmount = amountBigNum.toFixed(8, BigNumber.ROUND_DOWN);\n \n this.logger.info(\n `Processing transfer: ${amountValue} HBAR (rounded to ${roundedAmount}) for account ${accountId.toString()}`\n );\n\n const sdkHbarAmount = Hbar.fromString(roundedAmount);\n processedTransfers.push({\n accountId,\n amount: amountBigNum,\n hbar: sdkHbarAmount\n });\n\n const tinybarsContribution = sdkHbarAmount.toTinybars();\n netZeroInTinybars = netZeroInTinybars.plus(\n tinybarsContribution.toString()\n );\n }\n\n if (!netZeroInTinybars.isZero()) {\n this.logger.warn(\n `Transfer sum not zero: ${netZeroInTinybars.toString()} tinybars off. Adjusting last transfer.`\n );\n \n if (processedTransfers.length > 0) {\n const lastTransfer = processedTransfers[processedTransfers.length - 1];\n const adjustment = netZeroInTinybars.dividedBy(-100000000);\n const adjustedAmount = lastTransfer.amount.plus(adjustment);\n const adjustedRounded = adjustedAmount.toFixed(8, BigNumber.ROUND_DOWN);\n lastTransfer.hbar = Hbar.fromString(adjustedRounded);\n \n this.logger.info(\n `Adjusted last transfer for ${lastTransfer.accountId.toString()} to ${adjustedRounded} HBAR`\n );\n }\n }\n \n for (const transfer of processedTransfers) {\n transaction.addHbarTransfer(transfer.accountId, transfer.hbar);\n }\n }\n\n if (typeof params.memo !== 'undefined') {\n if (params.memo === null) {\n this.logger.warn('Received null for memo in transferHbar.');\n } else {\n transaction.setTransactionMemo(params.memo);\n }\n }\n\n this.setCurrentTransaction(transaction);\n return this;\n }\n}"],"names":[],"mappings":";;;AAYO,MAAM,uBAAuB,mBAAmB;AAAA,EACrD,YAAY,WAA2B;AACrC,UAAM,SAAS;AAAA,EACjB;AAAA;AAAA;AAAA;AAAA,EAKO,aACL,QACA,kBAA2B,MACrB;AACN,SAAK,WAAA;AACL,UAAM,cAAc,IAAI,oBAAA;AAExB,QAAI,CAAC,OAAO,aAAa,OAAO,UAAU,WAAW,GAAG;AACtD,YAAM,IAAI,MAAM,wDAAwD;AAAA,IAC1E;AAEA,QAAI,oBAAoB,IAAI,UAAU,CAAC;AACvC,QAAI,qCA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AU;AAElE,aAAK,OAAO;AAAA,UACV,wBAAwB,WAAW,qBAAqB,aAAa,iBAAiB,UAAU,UAAU;AAAA,QAAA;AAG5G,cAAM,gBAAgB,KAAK,WAAW,aAAa;AACnD,2BAAmB,KAAK;AAAA,UACtB;AAAA,UACA,QAAQ;AAAA,UACR,MAAM;AAAA,QAAA,CACP;AAED,cAAM,uBAAuB,cAAc,WAAA;AAC3C,4BAAoB,kBAAkB;AAAA,UACpC,qBAAqB,SAAA;AAAA,QAAS;AAAA,MAElC;AAEA,UAAI,CAAC,kBAAkB,UAAU;AAC/B,aAAK,OAAO;AAAA,UACV,0BAA0B,kBAAkB,SAAA,CAAU;AAAA,QAAA;AAGxD,YAAI,mBAAmB,SAAS,GAAG;AACjC,gBAAM,eAAe,mBAAmB,mBAAmB,SAAS,CAAC;AACrE,gBAAM,aAAa,kBAAkB,UAAU,IAAU;AACzD,gBAAM,iBAAiB,aAAa,OAAO,KAAK,UAAU;AAC1D,gBAAM,kBAAkB,eAAe,QAAQ,GAAG,UAAU,UAAU;AACtE,uBAAa,OAAO,KAAK,WAAW,eAAe;AAEnD,eAAK,OAAO;AAAA,YACV,8BAA8B,aAAa,UAAU,SAAA,CAAU,OAAO,eAAe;AAAA,UAAA;AAAA,QAEzF;AAAA,MACF;AAEA,iBAAW,YAAY,oBAAoB;AACzC,oBAAY,gBAAgB,SAAS,WAAW,SAAS,IAAI;AAAA,MAC/D;AAAA,IACF;AAEA,QAAI,OAAO,OAAO,SAAS,aAAa;AACtC,UAAI,OAAO,SAAS,MAAM;AACxB,aAAK,OAAO,KAAK,yCAAyC;AAAA,MAC5D,OAAO;AACL,oBAAY,mBAAmB,OAAO,IAAI;AAAA,MAC5C;AAAA,IACF;AAEA,SAAK,sBAAsB,WAAW;AACtC,WAAO;AAAA,EACT;AACF;"}
1
+ {"version":3,"file":"index23.js","sources":["../../src/types/content-reference.ts"],"sourcesContent":["/**\n * Content Reference System Types\n * \n * Shared interfaces for the Reference-Based Content System that handles\n * large content storage with unique reference IDs to optimize context window usage.\n */\n\n/**\n * Unique identifier for stored content references\n * Format: Cryptographically secure 32-byte identifier with base64url encoding\n */\nexport type ReferenceId = string;\n\n/**\n * Lifecycle state of a content reference\n */\nexport type ReferenceLifecycleState = 'active' | 'expired' | 'cleanup_pending' | 'invalid';\n\n/**\n * Content types supported by the reference system\n */\nexport type ContentType = 'text' | 'json' | 'html' | 'markdown' | 'binary' | 'unknown';\n\n/**\n * Sources that created the content reference\n */\nexport type ContentSource = 'mcp_tool' | 'user_upload' | 'agent_generated' | 'system';\n\n/**\n * Metadata associated with stored content\n */\nexport interface ContentMetadata {\n /** Content type classification */\n contentType: ContentType;\n \n /** MIME type of the original content */\n mimeType?: string;\n \n /** Size in bytes of the stored content */\n sizeBytes: number;\n \n /** When the content was originally stored */\n createdAt: Date;\n \n /** Last time the content was accessed via reference resolution */\n lastAccessedAt: Date;\n \n /** Source that created this content reference */\n source: ContentSource;\n \n /** Name of the MCP tool that generated the content (if applicable) */\n mcpToolName?: string;\n \n /** Original filename or suggested name for the content */\n fileName?: string;\n \n /** Number of times this reference has been resolved */\n accessCount: number;\n \n /** Tags for categorization and cleanup policies */\n tags?: string[];\n \n /** Custom metadata from the source */\n customMetadata?: Record<string, unknown>;\n}\n\n/**\n * Core content reference object passed through agent context\n * Designed to be lightweight (<100 tokens) while providing enough \n * information for agent decision-making\n */\nexport interface ContentReference {\n /** Unique identifier for resolving the content */\n referenceId: ReferenceId;\n \n /** Current lifecycle state */\n state: ReferenceLifecycleState;\n \n /** Brief description or preview of the content (max 200 chars) */\n preview: string;\n \n /** Essential metadata for agent decision-making */\n metadata: Pick<ContentMetadata, 'contentType' | 'sizeBytes' | 'source' | 'fileName' | 'mimeType'>;\n \n /** When this reference was created */\n createdAt: Date;\n \n /** Special format indicator for reference IDs in content */\n readonly format: 'ref://{id}';\n}\n\n/**\n * Result of attempting to resolve a content reference\n */\nexport interface ReferenceResolutionResult {\n /** Whether the resolution was successful */\n success: boolean;\n \n /** The resolved content if successful */\n content?: Buffer;\n \n /** Complete metadata if successful */\n metadata?: ContentMetadata;\n \n /** Error message if resolution failed */\n error?: string;\n \n /** Specific error type for targeted error handling */\n errorType?: 'not_found' | 'expired' | 'corrupted' | 'access_denied' | 'system_error';\n \n /** Suggested actions for recovery */\n suggestedActions?: string[];\n}\n\n/**\n * Configuration for content reference storage and lifecycle\n */\nexport interface ContentReferenceConfig {\n /** Size threshold above which content should be stored as references (default: 10KB) */\n sizeThresholdBytes: number;\n \n /** Maximum age for unused references before cleanup (default: 1 hour) */\n maxAgeMs: number;\n \n /** Maximum number of references to store simultaneously */\n maxReferences: number;\n \n /** Maximum total storage size for all references */\n maxTotalStorageBytes: number;\n \n /** Whether to enable automatic cleanup */\n enableAutoCleanup: boolean;\n \n /** Interval for cleanup checks in milliseconds */\n cleanupIntervalMs: number;\n \n /** Whether to persist references across restarts */\n enablePersistence: boolean;\n \n /** Storage backend configuration */\n storageBackend: 'memory' | 'filesystem' | 'hybrid';\n \n /** Cleanup policies for different content types */\n cleanupPolicies: {\n /** Policy for content marked as \"recent\" from MCP tools */\n recent: { maxAgeMs: number; priority: number };\n \n /** Policy for user-uploaded content */\n userContent: { maxAgeMs: number; priority: number };\n \n /** Policy for agent-generated content */\n agentGenerated: { maxAgeMs: number; priority: number };\n \n /** Default policy for other content */\n default: { maxAgeMs: number; priority: number };\n };\n}\n\n/**\n * Default configuration values\n */\nexport const DEFAULT_CONTENT_REFERENCE_CONFIG: ContentReferenceConfig = {\n sizeThresholdBytes: 10 * 1024,\n maxAgeMs: 60 * 60 * 1000,\n maxReferences: 100,\n maxTotalStorageBytes: 100 * 1024 * 1024,\n enableAutoCleanup: true,\n cleanupIntervalMs: 5 * 60 * 1000,\n enablePersistence: false,\n storageBackend: 'memory',\n cleanupPolicies: {\n recent: { maxAgeMs: 30 * 60 * 1000, priority: 1 },\n userContent: { maxAgeMs: 2 * 60 * 60 * 1000, priority: 2 },\n agentGenerated: { maxAgeMs: 60 * 60 * 1000, priority: 3 },\n default: { maxAgeMs: 60 * 60 * 1000, priority: 4 }\n }\n};\n\n/**\n * Statistics about content reference usage and storage\n */\nexport interface ContentReferenceStats {\n /** Total number of active references */\n activeReferences: number;\n \n /** Total storage used by all references in bytes */\n totalStorageBytes: number;\n \n /** Number of references cleaned up in last cleanup cycle */\n recentlyCleanedUp: number;\n \n /** Number of successful reference resolutions since startup */\n totalResolutions: number;\n \n /** Number of failed resolution attempts */\n failedResolutions: number;\n \n /** Average content size in bytes */\n averageContentSize: number;\n \n /** Most frequently accessed reference ID */\n mostAccessedReferenceId?: ReferenceId;\n \n /** Storage utilization percentage */\n storageUtilization: number;\n \n /** Performance metrics */\n performanceMetrics: {\n /** Average time to create a reference in milliseconds */\n averageCreationTimeMs: number;\n \n /** Average time to resolve a reference in milliseconds */\n averageResolutionTimeMs: number;\n \n /** Average cleanup time in milliseconds */\n averageCleanupTimeMs: number;\n };\n}\n\n/**\n * Error types for content reference operations\n */\nexport class ContentReferenceError extends Error {\n constructor(\n message: string,\n public readonly type: ReferenceResolutionResult['errorType'],\n public readonly referenceId?: ReferenceId,\n public readonly suggestedActions?: string[]\n ) {\n super(message);\n this.name = 'ContentReferenceError';\n }\n}\n\n/**\n * Interface for content reference storage implementations\n */\nexport interface ContentReferenceStore {\n /**\n * Store content and return a reference\n */\n storeContent(\n content: Buffer,\n metadata: Omit<ContentMetadata, 'createdAt' | 'lastAccessedAt' | 'accessCount'>\n ): Promise<ContentReference>;\n \n /**\n * Resolve a reference to its content\n */\n resolveReference(referenceId: ReferenceId): Promise<ReferenceResolutionResult>;\n \n /**\n * Check if a reference exists and is valid\n */\n hasReference(referenceId: ReferenceId): Promise<boolean>;\n \n /**\n * Mark a reference for cleanup\n */\n cleanupReference(referenceId: ReferenceId): Promise<boolean>;\n \n /**\n * Get current storage statistics\n */\n getStats(): Promise<ContentReferenceStats>;\n \n /**\n * Update configuration\n */\n updateConfig(config: Partial<ContentReferenceConfig>): Promise<void>;\n \n /**\n * Perform cleanup based on current policies\n */\n performCleanup(): Promise<{ cleanedUp: number; errors: string[] }>;\n \n /**\n * Dispose of resources\n */\n dispose(): Promise<void>;\n}"],"names":[],"mappings":"AAiKO,MAAM,mCAA2D;AAAA,EACtE,oBAAoB,KAAK;AAAA,EACzB,UAAU,KAAK,KAAK;AAAA,EACpB,eAAe;AAAA,EACf,sBAAsB,MAAM,OAAO;AAAA,EACnC,mBAAmB;AAAA,EACnB,mBAAmB,IAAI,KAAK;AAAA,EAC5B,mBAAmB;AAAA,EACnB,gBAAgB;AAAA,EAChB,iBAAiB;AAAA,IACf,QAAQ,EAAE,UAAU,KAAK,KAAK,KAAM,UAAU,EAAA;AAAA,IAC9C,aAAa,EAAE,UAAU,IAAI,KAAK,KAAK,KAAM,UAAU,EAAA;AAAA,IACvD,gBAAgB,EAAE,UAAU,KAAK,KAAK,KAAM,UAAU,EAAA;AAAA,IACtD,SAAS,EAAE,UAAU,KAAK,KAAK,KAAM,UAAU,EAAA;AAAA,EAAE;AAErD;AA8CO,MAAM,8BAA8B,MAAM;AAAA,EAC/C,YACE,SACgB,MACA,aACA,kBAChB;AACA,UAAM,OAAO;AAJG,SAAA,OAAA;AACA,SAAA,cAAA;AACA,SAAA,mBAAA;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;"}
@@ -1,68 +1,95 @@
1
- import { createHash } from "crypto";
2
- class ReferenceIdGenerator {
3
- /**
4
- * Generate a content-based reference ID using SHA-256 hashing
5
- *
6
- * @param content The content to generate a reference ID for
7
- * @returns Deterministic reference ID based on content hash
8
- */
9
- static generateId(content) {
10
- const hash = createHash("sha256");
11
- hash.update(content);
12
- return hash.digest("base64url");
1
+ import { TransferTransaction, AccountId, Hbar } from "@hashgraph/sdk";
2
+ import BigNumber from "bignumber.js";
3
+ import { BaseServiceBuilder } from "hedera-agent-kit";
4
+ class AccountBuilder extends BaseServiceBuilder {
5
+ constructor(hederaKit) {
6
+ super(hederaKit);
13
7
  }
14
8
  /**
15
- * Validate that a string is a properly formatted reference ID
16
- *
17
- * @param id The ID to validate
18
- * @returns true if the ID is valid format
9
+ * Transfers HBAR between accounts with proper decimal handling
19
10
  */
20
- static isValidReferenceId(id) {
21
- if (!id || typeof id !== "string") {
22
- return false;
11
+ transferHbar(params, isUserInitiated = true) {
12
+ this.clearNotes();
13
+ const transaction = new TransferTransaction();
14
+ if (!params.transfers || params.transfers.length === 0) {
15
+ throw new Error("HbarTransferParams must include at least one transfer.");
23
16
  }
24
- if (id.length !== 43) {
25
- return false;
17
+ let netZeroInTinybars = new BigNumber(0);
18
+ let userTransferProcessedForScheduling = false;
19
+ if (isUserInitiated && this.kit.userAccountId && this.kit.operationalMode === "provideBytes" && params.transfers.length === 1) {
20
+ const receiverTransfer = params.transfers[0];
21
+ const amountValue = typeof receiverTransfer.amount === "string" || typeof receiverTransfer.amount === "number" ? receiverTransfer.amount : receiverTransfer.amount.toString();
22
+ const amountBigNum = new BigNumber(amountValue);
23
+ if (amountBigNum.isPositive()) {
24
+ const recipientAccountId = typeof receiverTransfer.accountId === "string" ? AccountId.fromString(receiverTransfer.accountId) : receiverTransfer.accountId;
25
+ const roundedAmount = amountBigNum.toFixed(8, BigNumber.ROUND_DOWN);
26
+ const sdkHbarAmount = Hbar.fromString(roundedAmount);
27
+ this.logger.info(
28
+ `[AccountBuilder.transferHbar] Configuring user-initiated scheduled transfer: ${sdkHbarAmount.toString()} from ${this.kit.userAccountId} to ${recipientAccountId.toString()}`
29
+ );
30
+ this.addNote(
31
+ `Configured HBAR transfer from your account (${this.kit.userAccountId}) to ${recipientAccountId.toString()} for ${sdkHbarAmount.toString()}.`
32
+ );
33
+ transaction.addHbarTransfer(recipientAccountId, sdkHbarAmount);
34
+ transaction.addHbarTransfer(
35
+ AccountId.fromString(this.kit.userAccountId),
36
+ sdkHbarAmount.negated()
37
+ );
38
+ userTransferProcessedForScheduling = true;
39
+ }
26
40
  }
27
- return /^[A-Za-z0-9_-]+$/.test(id);
28
- }
29
- /**
30
- * Extract reference ID from ref:// format
31
- *
32
- * @param input Input string that may contain a reference ID
33
- * @returns Extracted reference ID or null if not found
34
- */
35
- static extractReferenceId(input) {
36
- if (!input || typeof input !== "string") {
37
- return null;
41
+ if (!userTransferProcessedForScheduling) {
42
+ const processedTransfers = [];
43
+ for (const transferInput of params.transfers) {
44
+ const accountId = typeof transferInput.accountId === "string" ? AccountId.fromString(transferInput.accountId) : transferInput.accountId;
45
+ const amountValue = typeof transferInput.amount === "string" || typeof transferInput.amount === "number" ? transferInput.amount : transferInput.amount.toString();
46
+ const amountBigNum = new BigNumber(amountValue);
47
+ const roundedAmount = amountBigNum.toFixed(8, BigNumber.ROUND_DOWN);
48
+ this.logger.info(
49
+ `Processing transfer: ${amountValue} HBAR (rounded to ${roundedAmount}) for account ${accountId.toString()}`
50
+ );
51
+ const sdkHbarAmount = Hbar.fromString(roundedAmount);
52
+ processedTransfers.push({
53
+ accountId,
54
+ amount: amountBigNum,
55
+ hbar: sdkHbarAmount
56
+ });
57
+ const tinybarsContribution = sdkHbarAmount.toTinybars();
58
+ netZeroInTinybars = netZeroInTinybars.plus(
59
+ tinybarsContribution.toString()
60
+ );
61
+ }
62
+ if (!netZeroInTinybars.isZero()) {
63
+ this.logger.warn(
64
+ `Transfer sum not zero: ${netZeroInTinybars.toString()} tinybars off. Adjusting last transfer.`
65
+ );
66
+ if (processedTransfers.length > 0) {
67
+ const lastTransfer = processedTransfers[processedTransfers.length - 1];
68
+ const adjustment = netZeroInTinybars.dividedBy(-1e8);
69
+ const adjustedAmount = lastTransfer.amount.plus(adjustment);
70
+ const adjustedRounded = adjustedAmount.toFixed(8, BigNumber.ROUND_DOWN);
71
+ lastTransfer.hbar = Hbar.fromString(adjustedRounded);
72
+ this.logger.info(
73
+ `Adjusted last transfer for ${lastTransfer.accountId.toString()} to ${adjustedRounded} HBAR`
74
+ );
75
+ }
76
+ }
77
+ for (const transfer of processedTransfers) {
78
+ transaction.addHbarTransfer(transfer.accountId, transfer.hbar);
79
+ }
38
80
  }
39
- const refFormatMatch = input.match(/^ref:\/\/([A-Za-z0-9_-]{43})$/);
40
- if (refFormatMatch) {
41
- return refFormatMatch[1];
81
+ if (typeof params.memo !== "undefined") {
82
+ if (params.memo === null) {
83
+ this.logger.warn("Received null for memo in transferHbar.");
84
+ } else {
85
+ transaction.setTransactionMemo(params.memo);
86
+ }
42
87
  }
43
- return this.isValidReferenceId(input) ? input : null;
44
- }
45
- /**
46
- * Format a reference ID in the standard ref:// format
47
- *
48
- * @param referenceId The reference ID to format
49
- * @returns Formatted reference string
50
- */
51
- static formatReference(referenceId) {
52
- return `ref://${referenceId}`;
53
- }
54
- /**
55
- * Generate a test reference ID (for testing purposes only)
56
- *
57
- * @param testSeed A test seed to generate a fake but valid ID format
58
- * @returns A valid format reference ID for testing
59
- */
60
- static generateTestId(testSeed) {
61
- const content = Buffer.from(`test-${testSeed}-${Date.now()}`);
62
- return this.generateId(content);
88
+ this.setCurrentTransaction(transaction);
89
+ return this;
63
90
  }
64
91
  }
65
92
  export {
66
- ReferenceIdGenerator
93
+ AccountBuilder
67
94
  };
68
95
  //# sourceMappingURL=index24.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index24.js","sources":["../../src/memory/ReferenceIdGenerator.ts"],"sourcesContent":["import { createHash } from 'crypto';\nimport { ReferenceId } from '../types/content-reference';\n\n/**\n * Content-based reference ID generator using SHA-256 (HCS-1 style)\n * \n * Generates deterministic reference IDs based on content hashing.\n * Same content always produces the same reference ID.\n */\nexport class ReferenceIdGenerator {\n /**\n * Generate a content-based reference ID using SHA-256 hashing\n * \n * @param content The content to generate a reference ID for\n * @returns Deterministic reference ID based on content hash\n */\n static generateId(content: Buffer): ReferenceId {\n const hash = createHash('sha256');\n hash.update(content);\n return hash.digest('base64url');\n }\n \n /**\n * Validate that a string is a properly formatted reference ID\n * \n * @param id The ID to validate\n * @returns true if the ID is valid format\n */\n static isValidReferenceId(id: string): id is ReferenceId {\n if (!id || typeof id !== 'string') {\n return false;\n }\n \n // Check length (base64url encoding of SHA-256 hash = 43 chars)\n if (id.length !== 43) {\n return false;\n }\n \n // Check character set (base64url: A-Z, a-z, 0-9, -, _)\n return /^[A-Za-z0-9_-]+$/.test(id);\n }\n \n /**\n * Extract reference ID from ref:// format\n * \n * @param input Input string that may contain a reference ID\n * @returns Extracted reference ID or null if not found\n */\n static extractReferenceId(input: string): ReferenceId | null {\n if (!input || typeof input !== 'string') {\n return null;\n }\n \n // Check for ref:// format\n const refFormatMatch = input.match(/^ref:\\/\\/([A-Za-z0-9_-]{43})$/);\n if (refFormatMatch) {\n return refFormatMatch[1] as ReferenceId;\n }\n \n // Check if input is directly a valid reference ID\n return this.isValidReferenceId(input) ? input : null;\n }\n \n /**\n * Format a reference ID in the standard ref:// format\n * \n * @param referenceId The reference ID to format\n * @returns Formatted reference string\n */\n static formatReference(referenceId: ReferenceId): string {\n return `ref://${referenceId}`;\n }\n \n /**\n * Generate a test reference ID (for testing purposes only)\n * \n * @param testSeed A test seed to generate a fake but valid ID format\n * @returns A valid format reference ID for testing\n */\n static generateTestId(testSeed: string): ReferenceId {\n const content = Buffer.from(`test-${testSeed}-${Date.now()}`);\n return this.generateId(content);\n }\n}"],"names":[],"mappings":";AASO,MAAM,qBAAqB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOhC,OAAO,WAAW,SAA8B;AAC9C,UAAM,OAAO,WAAW,QAAQ;AAChC,SAAK,OAAO,OAAO;AACnB,WAAO,KAAK,OAAO,WAAW;AAAA,EAChC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAO,mBAAmB,IAA+B;AACvD,QAAI,CAAC,MAAM,OAAO,OAAO,UAAU;AACjC,aAAO;AAAA,IACT;AAGA,QAAI,GAAG,WAAW,IAAI;AACpB,aAAO;AAAA,IACT;AAGA,WAAO,mBAAmB,KAAK,EAAE;AAAA,EACnC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAO,mBAAmB,OAAmC;AAC3D,QAAI,CAAC,SAAS,OAAO,UAAU,UAAU;AACvC,aAAO;AAAA,IACT;AAGA,UAAM,iBAAiB,MAAM,MAAM,+BAA+B;AAClE,QAAI,gBAAgB;AAClB,aAAO,eAAe,CAAC;AAAA,IACzB;AAGA,WAAO,KAAK,mBAAmB,KAAK,IAAI,QAAQ;AAAA,EAClD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAO,gBAAgB,aAAkC;AACvD,WAAO,SAAS,WAAW;AAAA,EAC7B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAO,eAAe,UAA+B;AACnD,UAAM,UAAU,OAAO,KAAK,QAAQ,QAAQ,IAAI,KAAK,IAAA,CAAK,EAAE;AAC5D,WAAO,KAAK,WAAW,OAAO;AAAA,EAChC;AACF;"}
1
+ {"version":3,"file":"index24.js","sources":["../../src/plugins/hbar-transfer/AccountBuilder.ts"],"sourcesContent":["import {\n AccountId,\n Hbar,\n TransferTransaction,\n} from '@hashgraph/sdk';\nimport BigNumber from 'bignumber.js';\nimport { HederaAgentKit, BaseServiceBuilder } from 'hedera-agent-kit';\nimport { HbarTransferParams } from './types';\n\n/**\n * Custom AccountBuilder that properly handles HBAR decimal conversion\n */\nexport class AccountBuilder extends BaseServiceBuilder {\n constructor(hederaKit: HederaAgentKit) {\n super(hederaKit);\n }\n\n /**\n * Transfers HBAR between accounts with proper decimal handling\n */\n public transferHbar(\n params: HbarTransferParams,\n isUserInitiated: boolean = true\n ): this {\n this.clearNotes();\n const transaction = new TransferTransaction();\n \n if (!params.transfers || params.transfers.length === 0) {\n throw new Error('HbarTransferParams must include at least one transfer.');\n }\n\n let netZeroInTinybars = new BigNumber(0);\n let userTransferProcessedForScheduling = false;\n\n if (\n isUserInitiated &&\n this.kit.userAccountId &&\n (this.kit.operationalMode as string) === 'provideBytes' &&\n params.transfers.length === 1\n ) {\n const receiverTransfer = params.transfers[0];\n const amountValue =\n typeof receiverTransfer.amount === 'string' ||\n typeof receiverTransfer.amount === 'number'\n ? receiverTransfer.amount\n : receiverTransfer.amount.toString();\n\n const amountBigNum = new BigNumber(amountValue);\n\n if (amountBigNum.isPositive()) {\n const recipientAccountId =\n typeof receiverTransfer.accountId === 'string'\n ? AccountId.fromString(receiverTransfer.accountId)\n : receiverTransfer.accountId;\n\n const roundedAmount = amountBigNum.toFixed(8, BigNumber.ROUND_DOWN);\n const sdkHbarAmount = Hbar.fromString(roundedAmount);\n\n this.logger.info(\n `[AccountBuilder.transferHbar] Configuring user-initiated scheduled transfer: ${sdkHbarAmount.toString()} from ${\n this.kit.userAccountId\n } to ${recipientAccountId.toString()}`\n );\n \n this.addNote(\n `Configured HBAR transfer from your account (${\n this.kit.userAccountId\n }) to ${recipientAccountId.toString()} for ${sdkHbarAmount.toString()}.`\n );\n\n transaction.addHbarTransfer(recipientAccountId, sdkHbarAmount);\n transaction.addHbarTransfer(\n AccountId.fromString(this.kit.userAccountId),\n sdkHbarAmount.negated()\n );\n\n userTransferProcessedForScheduling = true;\n }\n }\n\n if (!userTransferProcessedForScheduling) {\n const processedTransfers: Array<{\n accountId: AccountId;\n amount: BigNumber;\n hbar: Hbar;\n }> = [];\n \n for (const transferInput of params.transfers) {\n const accountId =\n typeof transferInput.accountId === 'string'\n ? AccountId.fromString(transferInput.accountId)\n : transferInput.accountId;\n\n const amountValue =\n typeof transferInput.amount === 'string' ||\n typeof transferInput.amount === 'number'\n ? transferInput.amount\n : transferInput.amount.toString();\n\n const amountBigNum = new BigNumber(amountValue);\n const roundedAmount = amountBigNum.toFixed(8, BigNumber.ROUND_DOWN);\n \n this.logger.info(\n `Processing transfer: ${amountValue} HBAR (rounded to ${roundedAmount}) for account ${accountId.toString()}`\n );\n\n const sdkHbarAmount = Hbar.fromString(roundedAmount);\n processedTransfers.push({\n accountId,\n amount: amountBigNum,\n hbar: sdkHbarAmount\n });\n\n const tinybarsContribution = sdkHbarAmount.toTinybars();\n netZeroInTinybars = netZeroInTinybars.plus(\n tinybarsContribution.toString()\n );\n }\n\n if (!netZeroInTinybars.isZero()) {\n this.logger.warn(\n `Transfer sum not zero: ${netZeroInTinybars.toString()} tinybars off. Adjusting last transfer.`\n );\n \n if (processedTransfers.length > 0) {\n const lastTransfer = processedTransfers[processedTransfers.length - 1];\n const adjustment = netZeroInTinybars.dividedBy(-100000000);\n const adjustedAmount = lastTransfer.amount.plus(adjustment);\n const adjustedRounded = adjustedAmount.toFixed(8, BigNumber.ROUND_DOWN);\n lastTransfer.hbar = Hbar.fromString(adjustedRounded);\n \n this.logger.info(\n `Adjusted last transfer for ${lastTransfer.accountId.toString()} to ${adjustedRounded} HBAR`\n );\n }\n }\n \n for (const transfer of processedTransfers) {\n transaction.addHbarTransfer(transfer.accountId, transfer.hbar);\n }\n }\n\n if (typeof params.memo !== 'undefined') {\n if (params.memo === null) {\n this.logger.warn('Received null for memo in transferHbar.');\n } else {\n transaction.setTransactionMemo(params.memo);\n }\n }\n\n this.setCurrentTransaction(transaction);\n return this;\n }\n}"],"names":[],"mappings":";;;AAYO,MAAM,uBAAuB,mBAAmB;AAAA,EACrD,YAAY,WAA2B;AACrC,UAAM,SAAS;AAAA,EACjB;AAAA;AAAA;AAAA;AAAA,EAKO,aACL,QACA,kBAA2B,MACrB;AACN,SAAK,WAAA;AACL,UAAM,cAAc,IAAI,oBAAA;AAExB,QAAI,CAAC,OAAO,aAAa,OAAO,UAAU,WAAW,GAAG;AACtD,YAAM,IAAI,MAAM,wDAAwD;AAAA,IAC1E;AAEA,QAAI,oBAAoB,IAAI,UAAU,CAAC;AACvC,QAAI,qCAAqC;AAEzC,QACE,mBACA,KAAK,IAAI,iBACR,KAAK,IAAI,oBAA+B,kBACzC,OAAO,UAAU,WAAW,GAC5B;AACA,YAAM,mBAAmB,OAAO,UAAU,CAAC;AAC3C,YAAM,cACJ,OAAO,iBAAiB,WAAW,YACnC,OAAO,iBAAiB,WAAW,WAC/B,iBAAiB,SACjB,iBAAiB,OAAO,SAAA;AAE9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