@hashgraphonline/conversational-agent 0.1.211 → 0.1.214

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.
@@ -1,5 +1,5 @@
1
- import { ReferenceIdGenerator } from "./index24.js";
2
- import { DEFAULT_CONTENT_REFERENCE_CONFIG, ContentReferenceError } from "./index25.js";
1
+ import { ReferenceIdGenerator } from "./index25.js";
2
+ import { DEFAULT_CONTENT_REFERENCE_CONFIG, ContentReferenceError } from "./index26.js";
3
3
  const _ContentStorage = class _ContentStorage {
4
4
  constructor(maxStorage = _ContentStorage.DEFAULT_MAX_STORAGE, referenceConfig) {
5
5
  this.messages = [];
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import { AccountBuilder } from "./index26.js";
2
+ import { AccountBuilder } from "./index24.js";
3
3
  import { BaseHederaTransactionTool } from "hedera-agent-kit";
4
4
  const HbarTransferInputSchema = z.object({
5
5
  accountId: z.string().describe('Account ID for the transfer (e.g., "0.0.xxxx").'),
@@ -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("hex");
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 !== 64) {
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-f0-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-f0-9]{64})$/);
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('hex');\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 !== 64) {\n return false;\n }\n \n return /^[a-f0-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-f0-9]{64})$/);\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,KAAK;AAAA,EAC1B;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,cAAc,KAAK,EAAE;AAAA,EAC9B;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,0BAA0B;AAC7D,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
+ {"version":3,"file":"index24.js","sources":["../../src/plugins/hbar/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":"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"}
@@ -1,30 +1,68 @@
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 }
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("hex");
15
13
  }
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";
14
+ /**
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
19
+ */
20
+ static isValidReferenceId(id) {
21
+ if (!id || typeof id !== "string") {
22
+ return false;
23
+ }
24
+ if (id.length !== 64) {
25
+ return false;
26
+ }
27
+ return /^[a-f0-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;
38
+ }
39
+ const refFormatMatch = input.match(/^ref:\/\/([a-f0-9]{64})$/);
40
+ if (refFormatMatch) {
41
+ return refFormatMatch[1];
42
+ }
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);
24
63
  }
25
64
  }
26
65
  export {
27
- ContentReferenceError,
28
- DEFAULT_CONTENT_REFERENCE_CONFIG
66
+ ReferenceIdGenerator
29
67
  };
30
68
  //# sourceMappingURL=index25.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index25.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
+ {"version":3,"file":"index25.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('hex');\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 !== 64) {\n return false;\n }\n \n return /^[a-f0-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-f0-9]{64})$/);\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,KAAK;AAAA,EAC1B;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,cAAc,KAAK,EAAE;AAAA,EAC9B;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,0BAA0B;AAC7D,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=index26.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index26.js","sources":["../../src/plugins/hbar/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":"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"}
1
+ {"version":3,"file":"index26.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,5 +1,5 @@
1
1
  import { ServerSigner, getAllHederaCorePlugins } from "hedera-agent-kit";
2
- import { Logger, HederaMirrorNode } from "@hashgraphonline/standards-sdk";
2
+ import { Logger } from "@hashgraphonline/standards-sdk";
3
3
  import { createAgent } from "./index9.js";
4
4
  import { LangChainProvider } from "./index10.js";
5
5
  import { ChatOpenAI } from "@langchain/openai";
@@ -10,7 +10,6 @@ import { HCS2Plugin } from "./index3.js";
10
10
  import { InscribePlugin } from "./index4.js";
11
11
  import { HbarPlugin } from "./index5.js";
12
12
  import { OpenConvaiState } from "@hashgraphonline/standards-agent-kit";
13
- import { PrivateKey } from "@hashgraph/sdk";
14
13
  import { getSystemMessage } from "./index20.js";
15
14
  import { ContentStoreManager } from "./index17.js";
16
15
  import "./index12.js";
@@ -64,14 +63,9 @@ class ConversationalAgent {
64
63
  } = this.options;
65
64
  this.validateOptions(accountId, privateKey);
66
65
  try {
67
- const privateKeyInstance = await this.detectPrivateKeyType(
68
- accountId,
69
- privateKey,
70
- network
71
- );
72
66
  const serverSigner = new ServerSigner(
73
67
  accountId,
74
- privateKeyInstance,
68
+ privateKey,
75
69
  network
76
70
  );
77
71
  let llm;
@@ -207,6 +201,15 @@ class ConversationalAgent {
207
201
  if (!accountId || !privateKey) {
208
202
  throw new Error("Account ID and private key are required");
209
203
  }
204
+ if (typeof accountId !== "string") {
205
+ throw new Error(`Account ID must be a string, received ${typeof accountId}`);
206
+ }
207
+ if (typeof privateKey !== "string") {
208
+ throw new Error(`Private key must be a string, received ${typeof privateKey}: ${JSON.stringify(privateKey)}`);
209
+ }
210
+ if (privateKey.length < 10) {
211
+ throw new Error("Private key appears to be invalid (too short)");
212
+ }
210
213
  }
211
214
  /**
212
215
  * Prepares the list of plugins to use based on configuration.
@@ -392,23 +395,6 @@ class ConversationalAgent {
392
395
  mcpServers
393
396
  });
394
397
  }
395
- /**
396
- * Detect the private key type by querying the account info from mirror node
397
- * @param {string} accountId - The Hedera account ID
398
- * @param {string} privateKey - The private key string
399
- * @param {NetworkType} network - The Hedera Hashgraph
400
- * @returns {Promise<PrivateKey>} The appropriate PrivateKey instance
401
- */
402
- async detectPrivateKeyType(accountId, privateKey, network) {
403
- const mirrorNode = new HederaMirrorNode(network);
404
- const accountInfo = await mirrorNode.requestAccount(accountId);
405
- const keyType = accountInfo?.key?._type || "";
406
- if (keyType?.toLowerCase()?.includes("ecdsa")) {
407
- return PrivateKey.fromStringECDSA(privateKey);
408
- } else {
409
- return PrivateKey.fromStringED25519(privateKey);
410
- }
411
- }
412
398
  /**
413
399
  * Resolve entity references using LLM-based resolver
414
400
  * @param content - Message content to resolve