@hashgraphonline/conversational-agent 0.1.205 → 0.1.207

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 (92) hide show
  1. package/dist/cjs/base-agent.d.ts +6 -0
  2. package/dist/cjs/context/ReferenceContextManager.d.ts +84 -0
  3. package/dist/cjs/context/ReferenceResponseProcessor.d.ts +76 -0
  4. package/dist/cjs/conversational-agent.d.ts +34 -0
  5. package/dist/cjs/index.cjs +1 -1
  6. package/dist/cjs/index.cjs.map +1 -1
  7. package/dist/cjs/langchain/ContentAwareAgentExecutor.d.ts +16 -0
  8. package/dist/cjs/langchain-agent.d.ts +1 -0
  9. package/dist/cjs/mcp/ContentProcessor.d.ts +37 -0
  10. package/dist/cjs/mcp/MCPClientManager.d.ts +19 -1
  11. package/dist/cjs/memory/ContentStorage.d.ts +205 -0
  12. package/dist/cjs/memory/MemoryWindow.d.ts +114 -0
  13. package/dist/cjs/memory/ReferenceIdGenerator.d.ts +45 -0
  14. package/dist/cjs/memory/SmartMemoryManager.d.ts +201 -0
  15. package/dist/cjs/memory/TokenCounter.d.ts +61 -0
  16. package/dist/cjs/memory/index.d.ts +7 -0
  17. package/dist/cjs/plugins/hbar-transfer/TransferHbarTool.d.ts +18 -0
  18. package/dist/cjs/services/ContentStoreManager.d.ts +54 -0
  19. package/dist/cjs/types/content-reference.d.ts +213 -0
  20. package/dist/cjs/types/index.d.ts +4 -0
  21. package/dist/esm/index12.js +15 -2
  22. package/dist/esm/index12.js.map +1 -1
  23. package/dist/esm/index14.js +119 -95
  24. package/dist/esm/index14.js.map +1 -1
  25. package/dist/esm/index15.js +65 -124
  26. package/dist/esm/index15.js.map +1 -1
  27. package/dist/esm/index16.js +161 -79
  28. package/dist/esm/index16.js.map +1 -1
  29. package/dist/esm/index17.js +161 -0
  30. package/dist/esm/index17.js.map +1 -0
  31. package/dist/esm/index18.js +236 -0
  32. package/dist/esm/index18.js.map +1 -0
  33. package/dist/esm/index19.js +95 -0
  34. package/dist/esm/index19.js.map +1 -0
  35. package/dist/esm/index2.js +3 -1
  36. package/dist/esm/index2.js.map +1 -1
  37. package/dist/esm/index20.js +663 -0
  38. package/dist/esm/index20.js.map +1 -0
  39. package/dist/esm/index21.js +233 -0
  40. package/dist/esm/index21.js.map +1 -0
  41. package/dist/esm/index22.js +182 -0
  42. package/dist/esm/index22.js.map +1 -0
  43. package/dist/esm/index23.js +126 -0
  44. package/dist/esm/index23.js.map +1 -0
  45. package/dist/esm/index24.js +68 -0
  46. package/dist/esm/index24.js.map +1 -0
  47. package/dist/esm/index25.js +38 -0
  48. package/dist/esm/index25.js.map +1 -0
  49. package/dist/esm/index6.js +143 -84
  50. package/dist/esm/index6.js.map +1 -1
  51. package/dist/esm/index7.js.map +1 -1
  52. package/dist/esm/index8.js +72 -7
  53. package/dist/esm/index8.js.map +1 -1
  54. package/dist/types/base-agent.d.ts +6 -0
  55. package/dist/types/context/ReferenceContextManager.d.ts +84 -0
  56. package/dist/types/context/ReferenceResponseProcessor.d.ts +76 -0
  57. package/dist/types/conversational-agent.d.ts +34 -0
  58. package/dist/types/langchain/ContentAwareAgentExecutor.d.ts +16 -0
  59. package/dist/types/langchain-agent.d.ts +1 -0
  60. package/dist/types/mcp/ContentProcessor.d.ts +37 -0
  61. package/dist/types/mcp/MCPClientManager.d.ts +19 -1
  62. package/dist/types/memory/ContentStorage.d.ts +205 -0
  63. package/dist/types/memory/MemoryWindow.d.ts +114 -0
  64. package/dist/types/memory/ReferenceIdGenerator.d.ts +45 -0
  65. package/dist/types/memory/SmartMemoryManager.d.ts +201 -0
  66. package/dist/types/memory/TokenCounter.d.ts +61 -0
  67. package/dist/types/memory/index.d.ts +7 -0
  68. package/dist/types/plugins/hbar-transfer/TransferHbarTool.d.ts +18 -0
  69. package/dist/types/services/ContentStoreManager.d.ts +54 -0
  70. package/dist/types/types/content-reference.d.ts +213 -0
  71. package/dist/types/types/index.d.ts +4 -0
  72. package/package.json +5 -3
  73. package/src/base-agent.ts +6 -0
  74. package/src/context/ReferenceContextManager.ts +345 -0
  75. package/src/context/ReferenceResponseProcessor.ts +296 -0
  76. package/src/conversational-agent.ts +166 -92
  77. package/src/langchain/ContentAwareAgentExecutor.ts +112 -0
  78. package/src/langchain-agent.ts +93 -5
  79. package/src/mcp/ContentProcessor.ts +317 -0
  80. package/src/mcp/MCPClientManager.ts +61 -1
  81. package/src/mcp/adapters/langchain.ts +41 -4
  82. package/src/memory/ContentStorage.ts +954 -0
  83. package/src/memory/MemoryWindow.ts +247 -0
  84. package/src/memory/ReferenceIdGenerator.ts +84 -0
  85. package/src/memory/SmartMemoryManager.ts +323 -0
  86. package/src/memory/TokenCounter.ts +152 -0
  87. package/src/memory/index.ts +8 -0
  88. package/src/plugins/hbar-transfer/TransferHbarTool.ts +19 -1
  89. package/src/plugins/hcs-10/HCS10Plugin.ts +5 -4
  90. package/src/services/ContentStoreManager.ts +199 -0
  91. package/src/types/content-reference.ts +281 -0
  92. package/src/types/index.ts +6 -0
@@ -67,6 +67,12 @@ export interface ChatResponse {
67
67
  tokenUsage?: TokenUsage;
68
68
  cost?: CostCalculation;
69
69
  metadata?: Record<string, unknown>;
70
+ tool_calls?: Array<{
71
+ id: string;
72
+ name: string;
73
+ args: Record<string, unknown>;
74
+ output?: string;
75
+ }>;
70
76
  [key: string]: unknown;
71
77
  }
72
78
  export interface UsageStats extends TokenUsage {
@@ -0,0 +1,84 @@
1
+ import { ContentReference, ReferenceId } from '../types/content-reference';
2
+ import { ContentStorage } from '../memory/ContentStorage';
3
+ import { Logger } from '@hashgraphonline/standards-sdk';
4
+
5
+ export interface ReferenceContext {
6
+ reference: ContentReference;
7
+ displayedAt: Date;
8
+ lastAccessedAt: Date;
9
+ contextId: string;
10
+ conversationTurn: number;
11
+ }
12
+ export interface ReferenceDisplayOptions {
13
+ maxPreviewLength?: number;
14
+ showMetadata?: boolean;
15
+ showSize?: boolean;
16
+ includeActions?: boolean;
17
+ format?: 'inline' | 'card' | 'compact';
18
+ }
19
+ export interface DisplayResult {
20
+ displayText: string;
21
+ hasValidReference: boolean;
22
+ contextId?: string;
23
+ suggestedActions?: string[];
24
+ }
25
+ /**
26
+ * Manages content references within agent conversation context
27
+ * Tracks reference usage, provides display formatting, and handles reference validation
28
+ */
29
+ export declare class ReferenceContextManager {
30
+ private activeReferences;
31
+ private contentStorage;
32
+ private logger;
33
+ private conversationTurn;
34
+ constructor(contentStorage: ContentStorage, logger: Logger);
35
+ /**
36
+ * Add a reference to the current conversation context
37
+ */
38
+ addReference(reference: ContentReference): string;
39
+ /**
40
+ * Generate display text for a content reference
41
+ */
42
+ displayReference(reference: ContentReference, options?: ReferenceDisplayOptions): Promise<DisplayResult>;
43
+ /**
44
+ * Get the most recent reference for "inscribe it" commands
45
+ */
46
+ getMostRecentReference(): ContentReference | null;
47
+ /**
48
+ * Get reference by context ID
49
+ */
50
+ getReferenceByContextId(contextId: string): ContentReference | null;
51
+ /**
52
+ * Validate all active references and remove invalid ones
53
+ */
54
+ validateReferences(): Promise<{
55
+ valid: number;
56
+ invalid: number;
57
+ removed: ReferenceId[];
58
+ }>;
59
+ /**
60
+ * Clear old references based on age and usage
61
+ */
62
+ cleanupOldReferences(maxAgeMs?: number): number;
63
+ /**
64
+ * Get current context statistics
65
+ */
66
+ getContextStats(): {
67
+ activeReferences: number;
68
+ conversationTurn: number;
69
+ oldestReference: number | null;
70
+ mostRecentReference: number | null;
71
+ };
72
+ /**
73
+ * Clear all references from context
74
+ */
75
+ clear(): void;
76
+ private formatCardReference;
77
+ private formatInlineReference;
78
+ private formatCompactReference;
79
+ private formatInvalidReference;
80
+ private formatErrorReference;
81
+ private truncateText;
82
+ private getOldestReferenceAge;
83
+ private getMostRecentReferenceAge;
84
+ }
@@ -0,0 +1,76 @@
1
+ import { ContentReference, ReferenceId } from '../types/content-reference';
2
+ import { ReferenceContextManager, ReferenceDisplayOptions } from './ReferenceContextManager';
3
+ import { Logger } from '@hashgraphonline/standards-sdk';
4
+
5
+ export interface ResponseProcessingOptions {
6
+ autoDisplayReferences?: boolean;
7
+ displayOptions?: ReferenceDisplayOptions;
8
+ includeReferenceInstructions?: boolean;
9
+ contextualizeReferences?: boolean;
10
+ }
11
+ export interface ProcessedResponse {
12
+ content: string;
13
+ hasReferences: boolean;
14
+ referenceCount: number;
15
+ contextIds: string[];
16
+ suggestedActions: string[];
17
+ }
18
+ export interface ReferenceDetectionResult {
19
+ hasReferences: boolean;
20
+ references: Array<{
21
+ reference: ContentReference;
22
+ position: number;
23
+ originalText: string;
24
+ }>;
25
+ plainReferences: Array<{
26
+ referenceId: ReferenceId;
27
+ position: number;
28
+ originalText: string;
29
+ }>;
30
+ }
31
+ /**
32
+ * Processes agent responses to detect and display content references
33
+ * Handles both structured references and plain reference IDs
34
+ */
35
+ export declare class ReferenceResponseProcessor {
36
+ private contextManager;
37
+ private logger;
38
+ constructor(contextManager: ReferenceContextManager, logger: Logger);
39
+ /**
40
+ * Process an agent response to handle content references
41
+ */
42
+ processResponse(responseContent: string, options?: ResponseProcessingOptions): Promise<ProcessedResponse>;
43
+ /**
44
+ * Detect references in response content
45
+ */
46
+ private detectReferences;
47
+ /**
48
+ * Create a preview from content buffer
49
+ */
50
+ private createPreviewFromContent;
51
+ /**
52
+ * Validate reference ID format
53
+ */
54
+ private isValidReferenceId;
55
+ /**
56
+ * Get reference context statistics
57
+ */
58
+ getContextStats(): {
59
+ activeReferences: number;
60
+ conversationTurn: number;
61
+ oldestReference: number | null;
62
+ mostRecentReference: number | null;
63
+ };
64
+ /**
65
+ * Validate all references in context
66
+ */
67
+ validateAllReferences(): Promise<{
68
+ valid: number;
69
+ invalid: number;
70
+ removed: ReferenceId[];
71
+ }>;
72
+ /**
73
+ * Clean up old references
74
+ */
75
+ cleanupOldReferences(maxAgeMs?: number): number;
76
+ }
@@ -50,6 +50,7 @@ export declare class ConversationalAgent {
50
50
  stateManager: IStateManager;
51
51
  private options;
52
52
  private logger;
53
+ private contentStoreManager?;
53
54
  constructor(options: ConversationalAgentOptions);
54
55
  /**
55
56
  * Initialize the conversational agent with Hedera network connection and AI configuration
@@ -90,6 +91,35 @@ export declare class ConversationalAgent {
90
91
  type: 'human' | 'ai';
91
92
  content: string;
92
93
  }[]): Promise<ChatResponse>;
94
+ /**
95
+ * Validates initialization options and throws if required fields are missing.
96
+ *
97
+ * @param accountId - The Hedera account ID
98
+ * @param privateKey - The private key for the account
99
+ * @throws {Error} If required fields are missing
100
+ */
101
+ private validateOptions;
102
+ /**
103
+ * Prepares the list of plugins to use based on configuration.
104
+ *
105
+ * @returns Array of plugins to initialize with the agent
106
+ */
107
+ private preparePlugins;
108
+ /**
109
+ * Creates the agent configuration object.
110
+ *
111
+ * @param serverSigner - The server signer instance
112
+ * @param llm - The language model instance
113
+ * @param allPlugins - Array of plugins to use
114
+ * @returns Configuration object for creating the agent
115
+ */
116
+ private createAgentConfig;
117
+ /**
118
+ * Configures the HCS-10 plugin with the state manager.
119
+ *
120
+ * @param allPlugins - Array of all plugins
121
+ */
122
+ private configureHCS10Plugin;
93
123
  /**
94
124
  * Create a ConversationalAgent with specific plugins enabled
95
125
  */
@@ -146,4 +176,8 @@ export declare class ConversationalAgent {
146
176
  * @returns {Promise<PrivateKey>} The appropriate PrivateKey instance
147
177
  */
148
178
  private detectPrivateKeyType;
179
+ /**
180
+ * Clean up resources
181
+ */
182
+ cleanup(): Promise<void>;
149
183
  }
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("hedera-agent-kit"),t=require("@hashgraphonline/standards-agent-kit"),n=require("@hashgraphonline/standards-sdk"),r=require("zod"),o=require("@hashgraph/sdk"),i=require("bignumber.js"),s=require("langchain/agents"),a=require("@langchain/core/prompts"),c=require("@langchain/openai"),l=require("@modelcontextprotocol/sdk/client/index.js"),g=require("@modelcontextprotocol/sdk/client/stdio.js"),h=require("@langchain/core/tools"),u=require("@langchain/core/messages");class d extends e.BasePlugin{constructor(){super(...arguments),this.id="hcs-10",this.name="HCS-10 Plugin",this.description="HCS-10 agent tools for decentralized agent registration, connections, and messaging on Hedera",this.version="1.0.0",this.author="Hashgraph Online",this.namespace="hcs10",this.tools=[]}async initialize(e){await super.initialize(e);const r=e.config.hederaKit;if(r)try{this.stateManager=e.stateManager||e.config.stateManager||this.appConfig?.stateManager||new t.OpenConvaiState;const i=r.signer.getAccountId().toString();let s="",a="";try{const e=r.signer.getOperatorPrivateKey().toString(),t=new n.HCS10Client({network:r.network,operatorId:i,operatorPrivateKey:e,logLevel:"error"}),o=await t.retrieveProfile(i);o.success&&o.topicInfo&&(s=o.topicInfo.inboundTopic,a=o.topicInfo.outboundTopic)}catch(o){this.context.logger.warn("Could not retrieve profile topics:",o)}if(this.stateManager.setCurrentAgent({name:`Agent ${i}`,accountId:i,inboundTopicId:s,outboundTopicId:a,privateKey:r.signer.getOperatorPrivateKey().toString()}),this.context.logger.info(`Set current agent: ${i} with topics ${s}/${a}`),this.stateManager&&!this.stateManager.getConnectionsManager()){const e=r.signer.getOperatorPrivateKey().toString(),t=new n.HCS10Client({network:r.network,operatorId:i,operatorPrivateKey:e,logLevel:"error"});this.stateManager.initializeConnectionsManager(t),this.context.logger.info("ConnectionsManager initialized in HCS10Plugin")}this.initializeTools(),this.context.logger.info("HCS-10 Plugin initialized successfully")}catch(i){this.context.logger.error("Failed to initialize HCS-10 plugin:",i)}else this.context.logger.warn("HederaKit not found in context. HCS-10 tools will not be available.")}initializeTools(){if(!this.stateManager)throw new Error("StateManager must be initialized before creating tools");const e=this.context.config.hederaKit;if(!e)throw new Error("HederaKit not found in context config");const n=new t.HCS10Builder(e,this.stateManager);this.tools=[new t.RegisterAgentTool({hederaKit:e,hcs10Builder:n,logger:this.context.logger}),new t.FindRegistrationsTool({hederaKit:e,hcs10Builder:n,logger:this.context.logger}),new t.RetrieveProfileTool({hederaKit:e,hcs10Builder:n,logger:this.context.logger}),new t.InitiateConnectionTool({hederaKit:e,hcs10Builder:n,logger:this.context.logger}),new t.ListConnectionsTool({hederaKit:e,hcs10Builder:n,logger:this.context.logger}),new t.SendMessageToConnectionTool({hederaKit:e,hcs10Builder:n,logger:this.context.logger}),new t.CheckMessagesTool({hederaKit:e,hcs10Builder:n,logger:this.context.logger}),new t.ConnectionMonitorTool({hederaKit:e,hcs10Builder:n,logger:this.context.logger}),new t.ManageConnectionRequestsTool({hederaKit:e,hcs10Builder:n,logger:this.context.logger}),new t.AcceptConnectionRequestTool({hederaKit:e,hcs10Builder:n,logger:this.context.logger}),new t.ListUnapprovedConnectionRequestsTool({hederaKit:e,hcs10Builder:n,logger:this.context.logger})]}getTools(){return this.tools}getStateManager(){return this.stateManager}async cleanup(){this.tools=[],delete this.stateManager,this.context?.logger&&this.context.logger.info("HCS-10 Plugin cleaned up")}}class p extends e.BasePlugin{constructor(){super(...arguments),this.id="hcs-2",this.name="HCS-2 Plugin",this.description="HCS-2 registry management tools for decentralized registries on Hedera",this.version="1.0.0",this.author="Hashgraph Online",this.namespace="hcs2",this.tools=[]}async initialize(e){await super.initialize(e);if(e.config.hederaKit)try{this.initializeTools(),this.context.logger.info("HCS-2 Plugin initialized successfully")}catch(t){this.context.logger.error("Failed to initialize HCS-2 plugin:",t)}else this.context.logger.warn("HederaKit not found in context. HCS-2 tools will not be available.")}initializeTools(){const e=this.context.config.hederaKit;if(!e)throw new Error("HederaKit not found in context config");const n=new t.HCS2Builder(e);this.tools=[new t.CreateRegistryTool({hederaKit:e,hcs2Builder:n,logger:this.context.logger}),new t.RegisterEntryTool({hederaKit:e,hcs2Builder:n,logger:this.context.logger}),new t.UpdateEntryTool({hederaKit:e,hcs2Builder:n,logger:this.context.logger}),new t.DeleteEntryTool({hederaKit:e,hcs2Builder:n,logger:this.context.logger}),new t.MigrateRegistryTool({hederaKit:e,hcs2Builder:n,logger:this.context.logger}),new t.QueryRegistryTool({hederaKit:e,hcs2Builder:n,logger:this.context.logger})]}getTools(){return this.tools}async cleanup(){this.tools=[],this.context?.logger&&this.context.logger.info("HCS-2 Plugin cleaned up")}}class m extends e.BasePlugin{constructor(){super(...arguments),this.id="inscribe",this.name="Inscribe Plugin",this.description="Content inscription tools for storing data on Hedera Consensus Service",this.version="1.0.0",this.author="Hashgraph Online",this.namespace="inscribe",this.tools=[]}async initialize(e){await super.initialize(e);if(e.config.hederaKit)try{this.initializeTools(),this.context.logger.info("Inscribe Plugin initialized successfully")}catch(t){this.context.logger.error("Failed to initialize Inscribe plugin:",t)}else this.context.logger.warn("HederaKit not found in context. Inscription tools will not be available.")}initializeTools(){const e=this.context.config.hederaKit;if(!e)throw new Error("HederaKit not found in context config");const n=new t.InscriberBuilder(e);this.tools=[new t.InscribeFromUrlTool({hederaKit:e,inscriberBuilder:n,logger:this.context.logger}),new t.InscribeFromFileTool({hederaKit:e,inscriberBuilder:n,logger:this.context.logger}),new t.InscribeFromBufferTool({hederaKit:e,inscriberBuilder:n,logger:this.context.logger}),new t.InscribeHashinalTool({hederaKit:e,inscriberBuilder:n,logger:this.context.logger}),new t.RetrieveInscriptionTool({hederaKit:e,inscriberBuilder:n,logger:this.context.logger})]}getTools(){return this.tools}async cleanup(){this.tools=[],this.context?.logger&&this.context.logger.info("Inscribe Plugin cleaned up")}}class f extends e.BaseServiceBuilder{constructor(e){super(e)}transferHbar(e,t=!0){this.clearNotes();const n=new o.TransferTransaction;if(!e.transfers||0===e.transfers.length)throw new Error("HbarTransferParams must include at least one transfer.");let r=new i(0),s=!1;if(t&&this.kit.userAccountId&&"provideBytes"===this.kit.operationalMode&&1===e.transfers.length){const t=e.transfers[0],r="string"==typeof t.amount||"number"==typeof t.amount?t.amount:t.amount.toString(),a=new i(r);if(a.isPositive()){const e="string"==typeof t.accountId?o.AccountId.fromString(t.accountId):t.accountId,r=a.toFixed(8,i.ROUND_DOWN),c=o.Hbar.fromString(r);this.logger.info(`[AccountBuilder.transferHbar] Configuring user-initiated scheduled transfer: ${c.toString()} from ${this.kit.userAccountId} to ${e.toString()}`),this.addNote(`Configured HBAR transfer from your account (${this.kit.userAccountId}) to ${e.toString()} for ${c.toString()}.`),n.addHbarTransfer(e,c),n.addHbarTransfer(o.AccountId.fromString(this.kit.userAccountId),c.negated()),s=!0}}if(!s){const t=[];for(const n of e.transfers){const e="string"==typeof n.accountId?o.AccountId.fromString(n.accountId):n.accountId,s="string"==typeof n.amount||"number"==typeof n.amount?n.amount:n.amount.toString(),a=new i(s),c=a.toFixed(8,i.ROUND_DOWN);this.logger.info(`Processing transfer: ${s} HBAR (rounded to ${c}) for account ${e.toString()}`);const l=o.Hbar.fromString(c);t.push({accountId:e,amount:a,hbar:l});const g=l.toTinybars();r=r.plus(g.toString())}if(!r.isZero()&&(this.logger.warn(`Transfer sum not zero: ${r.toString()} tinybars off. Adjusting last transfer.`),t.length>0)){const e=t[t.length-1],n=r.dividedBy(-1e8),s=e.amount.plus(n).toFixed(8,i.ROUND_DOWN);e.hbar=o.Hbar.fromString(s),this.logger.info(`Adjusted last transfer for ${e.accountId.toString()} to ${s} HBAR`)}for(const e of t)n.addHbarTransfer(e.accountId,e.hbar)}return void 0!==e.memo&&(null===e.memo?this.logger.warn("Received null for memo in transferHbar."):n.setTransactionMemo(e.memo)),this.setCurrentTransaction(n),this}}const y=r.z.object({accountId:r.z.string().describe('Account ID for the transfer (e.g., "0.0.xxxx").'),amount:r.z.union([r.z.number(),r.z.string()]).describe("HBAR amount. Positive for credit, negative for debit. Builder handles Hbar unit & sum validation.")}),w=r.z.object({transfers:r.z.array(y).min(1).describe('Array of ALL transfers for this transaction. For multi-party transfers (e.g., "A sends 5 to C and B sends 3 to C"), include all transfers here: [{accountId: "A", amount: -5}, {accountId: "B", amount: -3}, {accountId: "C", amount: 8}]. Amounts must sum to zero.'),memo:r.z.string().optional().describe("Optional. Memo for the transaction.")});class b extends e.BaseHederaTransactionTool{constructor(){super(...arguments),this.name="hedera-account-transfer-hbar-v2",this.description='PRIMARY TOOL FOR HBAR TRANSFERS: Transfers HBAR between accounts. Supports multiple transfers in a single transaction - when multiple accounts need to send/receive HBAR (e.g., "A sends 5 HBAR to C and B sends 3 HBAR to C"), include ALL transfers in one transfers array. The sum of all transfers must equal zero. Use this for scheduled transactions and multi-signature scenarios.',this.specificInputSchema=w,this.namespace="account"}getServiceBuilder(){return new f(this.hederaKit)}async callBuilderMethod(e,t){await e.transferHbar(t)}}class x extends e.BasePlugin{constructor(){super(...arguments),this.id="hbar-transfer",this.name="HBAR Transfer Plugin",this.description="HBAR transfer tool with proper decimal handling for multi-signature transactions",this.version="1.0.0",this.author="Hashgraph Online",this.namespace="account",this.tools=[]}async initialize(e){await super.initialize(e);if(e.config.hederaKit)try{this.initializeTools(),this.context.logger.info("HBAR Transfer Plugin initialized successfully")}catch(t){this.context.logger.error("Failed to initialize HBAR Transfer plugin:",t)}else this.context.logger.warn("HederaKit not found in context. HBAR transfer tools will not be available.")}initializeTools(){const e=this.context.config.hederaKit;if(!e)throw new Error("HederaKit not found in context config");this.tools=[new b({hederaKit:e,logger:this.context.logger})]}getTools(){return this.tools}async shutdown(){this.tools=[]}}class v{constructor(e){this.config=e,this.tools=[],this.initialized=!1,this.logger=new n.Logger({module:"BaseAgent",silent:e.debug?.silent||!1})}getCore(){return this.agentKit}filterTools(e){let t=[...e];const n=this.config.filtering;return n?(n.namespaceWhitelist?.length&&(t=t.filter(e=>{const t=e.namespace;return!t||n.namespaceWhitelist.includes(t)})),n.toolBlacklist?.length&&(t=t.filter(e=>!n.toolBlacklist.includes(e.name))),n.toolPredicate&&(t=t.filter(n.toolPredicate)),this.logger.debug(`Filtered tools: ${e.length} → ${t.length}`),t):t}buildSystemPrompt(){const e=[],t=this.config.signer.getAccountId().toString(),n=this.config.execution?.userAccountId;this.config.messaging?.systemPreamble&&e.push(this.config.messaging.systemPreamble),e.push(`You are a helpful Hedera assistant. Your primary operator account is ${t}. You have tools to interact with the Hedera network. When using any tool, provide all necessary parameters as defined by that tool's schema and description.`),n&&e.push(`The user you are assisting has a personal Hedera account ID: ${n}. IMPORTANT: When the user says things like "I want to send HBAR" or "transfer my tokens", you MUST use ${n} as the sender/from account. For example, if user says "I want to send 2 HBAR to 0.0.800", you must set up a transfer where ${n} sends the HBAR, not your operator account.`);return"autonomous"===(this.config.execution?.operationalMode||"returnBytes")?e.push(`\nOPERATIONAL MODE: 'autonomous'. Your goal is to execute transactions directly using your tools. Your account ${t} will be the payer for these transactions. Even if the user's account (${n||"a specified account"}) is the actor in the transaction body (e.g., sender of HBAR), you (the agent with operator ${t}) are still executing and paying. For HBAR transfers, ensure the amounts in the 'transfers' array sum to zero (as per tool schema), balancing with your operator account if necessary.`):this.config.execution?.scheduleUserTransactionsInBytesMode&&n?e.push(`\nOPERATIONAL MODE: 'returnBytes' with scheduled transactions for user actions. When a user asks for a transaction to be prepared (e.g., creating a token, topic, transferring assets for them to sign, etc), you MUST default to creating a Scheduled Transaction using the appropriate tool with the metaOption 'schedule: true'. The user (with account ID ${n}) will be the one to ultimately pay for and (if needed) sign the inner transaction. Your operator account (${t}) will pay for creating the schedule entity itself. You MUST return the ScheduleId and details of the scheduled operation in a structured JSON format with these fields: success, op, schedule_id, description, payer_account_id_scheduled_tx, and scheduled_transaction_details.`):e.push(`\nOPERATIONAL MODE: 'returnBytes'. Your goal is to provide transaction bytes directly. When a user asks for a transaction to be prepared (e.g., for them to sign, or for scheduling without the default scheduling flow), you MUST call the appropriate tool. If you want raw bytes for the user to sign for their own account ${n||"if specified"}, ensure the tool constructs the transaction body accordingly and use metaOption 'returnBytes: true' if available, or ensure the builder is configured for the user.`),!1!==this.config.messaging?.conciseMode&&e.push("\nAlways be concise. If the tool provides a JSON string as its primary output (especially in returnBytes mode), make your accompanying text brief. If the tool does not provide JSON output or an error occurs, your narrative becomes primary; if notes were generated by the tool in such cases, append them to your textual response."),this.config.messaging?.systemPostamble&&e.push(this.config.messaging.systemPostamble),e.join("\n")}isReady(){return this.initialized}}class C{constructor(e){this.clients=new Map,this.tools=new Map,this.logger=e}async connectServer(e){try{if(this.isServerConnected(e.name))return{serverName:e.name,connected:!1,error:`Server ${e.name} is already connected`,tools:[]};if(e.transport&&"stdio"!==e.transport)throw new Error(`Transport ${e.transport} not yet supported`);const t=new g.StdioClientTransport({command:e.command,args:e.args,...e.env&&{env:e.env}}),n=new l.Client({name:`conversational-agent-${e.name}`,version:"1.0.0"},{capabilities:{}});await n.connect(t),this.clients.set(e.name,n);const r=(await n.listTools()).tools.map(t=>({...t,serverName:e.name}));return this.tools.set(e.name,r),this.logger.info(`Connected to MCP server ${e.name} with ${r.length} tools`),{serverName:e.name,connected:!0,tools:r}}catch(t){return this.logger.error(`Failed to connect to MCP server ${e.name}:`,t),{serverName:e.name,connected:!1,error:t instanceof Error?t.message:"Unknown error",tools:[]}}}async executeTool(e,t,n){const r=this.clients.get(e);if(!r)throw new Error(`MCP server ${e} not connected`);this.logger.debug(`Executing MCP tool ${t} on server ${e}`,n);try{return await r.callTool({name:t,arguments:n})}catch(o){throw this.logger.error(`Error executing MCP tool ${t}:`,o),o}}async disconnectAll(){for(const[t,n]of this.clients)try{await n.close(),this.logger.info(`Disconnected from MCP server ${t}`)}catch(e){this.logger.error(`Error disconnecting MCP server ${t}:`,e)}this.clients.clear(),this.tools.clear()}getAllTools(){const e=[];for(const t of this.tools.values())e.push(...t);return e}getServerTools(e){return this.tools.get(e)||[]}isServerConnected(e){return this.clients.has(e)}getConnectedServers(){return Array.from(this.clients.keys())}}function T(e,t,n){const r=S(e.inputSchema),o=`${e.serverName}_${e.name}`.replace(/[^a-zA-Z0-9_]/g,"_");let i=e.description||`MCP tool ${e.name} from ${e.serverName}`;return n?.toolDescriptions?.[e.name]&&(i=`${i}\n\n${n.toolDescriptions[e.name]}`),n?.additionalContext&&(i=`${i}\n\nContext: ${n.additionalContext}`),new h.DynamicStructuredTool({name:o,description:i,schema:r,func:async n=>{try{const r=await t.executeTool(e.serverName,e.name,n);if("string"==typeof r)return r;if(r&&"object"==typeof r&&"content"in r){const e=r.content;if(Array.isArray(e)){return e.filter(e=>"object"==typeof e&&null!==e&&"type"in e&&"text"===e.type&&"text"in e).map(e=>e.text).join("\n")}return JSON.stringify(e)}return JSON.stringify(r)}catch(r){const t=r instanceof Error?r.message:"Unknown error";return`Error executing MCP tool ${e.name}: ${t}`}}})}function S(e){if(!e||"object"!=typeof e)return r.z.object({});const t=e;if(t.type&&"object"!==t.type)return A(t);if(!t.properties||"object"!=typeof t.properties)return r.z.object({});const n={};for(const[r,o]of Object.entries(t.properties)){let e=A(o);Array.isArray(t.required)&&t.required.includes(r)||(e=e.optional()),n[r]=e}return r.z.object(n)}function A(e){if(!e||"object"!=typeof e||!("type"in e))return r.z.unknown();const t=e;let n;switch(t.type){case"string":n=r.z.string(),t.enum&&Array.isArray(t.enum)&&(n=r.z.enum(t.enum));break;case"number":n=r.z.number(),"minimum"in t&&"number"==typeof t.minimum&&(n=n.min(t.minimum)),"maximum"in t&&"number"==typeof t.maximum&&(n=n.max(t.maximum));break;case"integer":n=r.z.number().int(),"minimum"in t&&"number"==typeof t.minimum&&(n=n.min(t.minimum)),"maximum"in t&&"number"==typeof t.maximum&&(n=n.max(t.maximum));break;case"boolean":n=r.z.boolean();break;case"array":n=t.items?r.z.array(A(t.items)):r.z.array(r.z.unknown());break;case"object":n="properties"in t?S(t):r.z.object({}).passthrough();break;default:n=r.z.unknown()}return"description"in t&&"string"==typeof t.description&&(n=n.describe(t.description)),n}class P extends v{constructor(){super(...arguments),this.systemMessage=""}async boot(){if(this.initialized)this.logger.warn("Agent already initialized");else try{this.agentKit=await this.createAgentKit(),await this.agentKit.initialize();const t=this.config.ai?.modelName||process.env.OPENAI_MODEL_NAME||"gpt-4o-mini";this.tokenTracker=new e.TokenUsageCallbackHandler(t);const n=this.agentKit.getAggregatedLangChainTools();this.tools=this.filterTools(n),this.config.mcp?.servers&&this.config.mcp.servers.length>0&&await this.initializeMCP(),this.systemMessage=this.buildSystemPrompt(),await this.createExecutor(),this.initialized=!0,this.logger.info("LangChain Hedera agent initialized")}catch(t){throw this.logger.error("Failed to initialize agent:",t),t}}async chat(t,n){if(!this.initialized||!this.executor)throw new Error("Agent not initialized. Call boot() first.");try{const o=await this.executor.invoke({input:t,chat_history:n?.messages||[]});let i={output:o.output||"",message:o.output||"",notes:[]};const s=o?.intermediateSteps?.[0]?.observation;if(s&&"string"==typeof s&&this.isJSON(s))try{const e=JSON.parse(s);i={...i,...e}}catch(r){this.logger.error("Error parsing intermediate steps:",r)}if(i.output&&""!==i.output.trim()||(i.output="Agent action complete."),this.tokenTracker){const t=this.tokenTracker.getLatestTokenUsage();t&&(i.tokenUsage=t,i.cost=e.calculateTokenCostSync(t))}return i}catch(r){return this.handleError(r)}}async shutdown(){this.mcpManager&&await this.mcpManager.disconnectAll(),this.executor=void 0,this.agentKit=void 0,this.tools=[],this.initialized=!1,this.logger.info("Agent cleaned up")}switchMode(e){this.config.execution?this.config.execution.operationalMode=e:this.config.execution={operationalMode:e},this.agentKit&&(this.agentKit.operationalMode=e),this.systemMessage=this.buildSystemPrompt(),this.logger.info(`Operational mode switched to: ${e}`)}getUsageStats(){if(!this.tokenTracker)return{promptTokens:0,completionTokens:0,totalTokens:0,cost:{totalCost:0}};const t=this.tokenTracker.getTotalTokenUsage(),n=e.calculateTokenCostSync(t);return{...t,cost:n}}getUsageLog(){return this.tokenTracker?this.tokenTracker.getTokenUsageHistory().map(t=>({...t,cost:e.calculateTokenCostSync(t)})):[]}clearUsageStats(){this.tokenTracker&&(this.tokenTracker.reset(),this.logger.info("Usage statistics cleared"))}async createAgentKit(){const t=[...e.getAllHederaCorePlugins(),...this.config.extensions?.plugins||[]],n=this.config.execution?.operationalMode||"returnBytes",r=this.config.ai?.modelName||"gpt-4o";return new e.HederaAgentKit(this.config.signer,{plugins:t},n,this.config.execution?.userAccountId,this.config.execution?.scheduleUserTransactionsInBytesMode??!0,void 0,r,this.config.extensions?.mirrorConfig,this.config.debug?.silent??!1)}async createExecutor(){let e;if(this.config.ai?.provider&&this.config.ai.provider.getModel)e=this.config.ai.provider.getModel();else if(this.config.ai?.llm)e=this.config.ai.llm;else{const t=this.config.ai?.apiKey||process.env.OPENAI_API_KEY;if(!t)throw new Error("OpenAI API key required");e=new c.ChatOpenAI({apiKey:t,modelName:this.config.ai?.modelName||"gpt-4o-mini",temperature:this.config.ai?.temperature??.1,callbacks:this.tokenTracker?[this.tokenTracker]:[]})}const t=a.ChatPromptTemplate.fromMessages([["system",this.systemMessage],new a.MessagesPlaceholder("chat_history"),["human","{input}"],new a.MessagesPlaceholder("agent_scratchpad")]),n=this.tools,r=await s.createOpenAIToolsAgent({llm:e,tools:n,prompt:t});this.executor=new s.AgentExecutor({agent:r,tools:n,verbose:this.config.debug?.verbose??!1,returnIntermediateSteps:!0})}handleError(t){const n=t instanceof Error?t.message:"Unknown error";let r,o;this.logger.error("Chat error:",t),this.tokenTracker&&(r=this.tokenTracker.getLatestTokenUsage(),r&&(o=e.calculateTokenCostSync(r)));const i={output:"Sorry, I encountered an error processing your request.",message:"Error processing request.",error:n,notes:[]};return r&&(i.tokenUsage=r),o&&(i.cost=o),i}async initializeMCP(){this.mcpManager=new C(this.logger);for(const e of this.config.mcp.servers){if(!1===e.autoConnect){this.logger.info(`Skipping MCP server ${e.name} (autoConnect=false)`);continue}const t=await this.mcpManager.connectServer(e);if(t.connected){this.logger.info(`Connected to MCP server ${t.serverName} with ${t.tools.length} tools`);for(const n of t.tools){const t=T(n,this.mcpManager,e);this.tools.push(t)}}else this.logger.error(`Failed to connect to MCP server ${t.serverName}: ${t.error}`)}}isJSON(e){if("string"!=typeof e)return!1;const t=e.trim();if(!t)return!1;if(!(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")))return!1;try{return JSON.parse(t),!0}catch{return!1}}}function k(e){const t=e.framework||"langchain";switch(t){case"langchain":return new P(e);case"vercel":throw new Error("Vercel AI SDK support coming soon");case"baml":throw new Error("BAML support coming soon");default:throw new Error(`Unknown framework: ${t}`)}}class M{constructor(e){this.model=e}async generate(e,t){const n=await this.model.invoke(e,t);return"string"==typeof n?n:n.toString()}async*stream(e,t){const n=await this.model.stream(e,t);for await(const r of n)yield"string"==typeof r?r:r.toString()}getModel(){return this.model}}const H=e=>`You are a helpful assistant managing Hashgraph Online HCS-10 connections, messages, HCS-2 registries, and content inscription.\n\nYou have access to tools for:\n- HCS-10: registering agents, finding registered agents, initiating connections, listing active connections, sending messages over connections, and checking for new messages\n- HCS-2: creating registries, registering entries, updating entries, deleting entries, migrating registries, and querying registry contents\n- Inscription: inscribing content from URLs, files, or buffers, creating Hashinal NFTs, and retrieving inscriptions\n\n*** IMPORTANT CONTEXT ***\nYou are currently operating as agent: ${e} on the Hashgraph Online network\nWhen users ask about "my profile", "my account", "my connections", etc., use this account ID: ${e}\n\nRemember the connection numbers when listing connections, as users might refer to them.`,I="gpt-4o",z="testnet",B="autonomous";class K{constructor(e){this.options=e,this.stateManager=e.stateManager||new t.OpenConvaiState,this.hcs10Plugin=new d,this.hcs2Plugin=new p,this.inscribePlugin=new m,this.hbarTransferPlugin=new x,this.logger=new n.Logger({module:"ConversationalAgent",silent:e.disableLogging||!1})}async initialize(){const{accountId:t,privateKey:n,network:r=z,openAIApiKey:o,openAIModelName:i=I,verbose:s=!1,operationalMode:a=B,userAccountId:l,customSystemMessagePreamble:g,customSystemMessagePostamble:h,additionalPlugins:u=[],mirrorNodeConfig:d,disableLogging:p,scheduleUserTransactionsInBytesMode:m}=this.options;if(!t||!n)throw new Error("Account ID and private key are required");try{const f=await this.detectPrivateKeyType(t,n,r),y=new e.ServerSigner(t,f,r),w=[this.hcs10Plugin,this.hcs2Plugin,this.inscribePlugin,this.hbarTransferPlugin],b=e.getAllHederaCorePlugins();let x;if(this.options.enabledPlugins){const e=new Set(this.options.enabledPlugins);x=[...[...w,...b].filter(t=>e.has(t.id)),...u]}else x=[...w,...b,...u];const v=new c.ChatOpenAI({apiKey:o,modelName:i,temperature:.1});this.agent=k({framework:"langchain",signer:y,execution:{mode:"autonomous"===a?"direct":"bytes",operationalMode:a,...l&&{userAccountId:l},...void 0!==m&&{scheduleUserTransactions:m}},ai:{provider:new M(v),temperature:.1},filtering:{toolPredicate:e=>"hedera-account-transfer-hbar"!==e.name&&!(this.options.toolFilter&&!this.options.toolFilter(e))},messaging:{systemPreamble:g||H(t),...h&&{systemPostamble:h},conciseMode:!0},extensions:{plugins:x,...d&&{mirrorConfig:d}},...this.options.mcpServers&&{mcp:{servers:this.options.mcpServers,autoConnect:!0}},debug:{verbose:s,silent:p??!1}});const C=x.find(e=>"hcs-10"===e.id);C&&(C.appConfig={stateManager:this.stateManager}),await this.agent.boot()}catch(f){throw this.logger.error("Failed to initialize ConversationalAgent:",f),f}}getPlugin(){return this.hcs10Plugin}getStateManager(){return this.stateManager}getAgent(){if(!this.agent)throw new Error("Agent not initialized. Call initialize() first.");return this.agent}getConversationalAgent(){return this.getAgent()}async processMessage(e,t=[]){if(!this.agent)throw new Error("Agent not initialized. Call initialize() first.");const n={messages:t.map(e=>"human"===e.type?new u.HumanMessage(e.content):new u.AIMessage(e.content))};return this.agent.chat(e,n)}static withPlugins(e,t){return new K({...e,enabledPlugins:t})}static withHTS(e){return this.withPlugins(e,["hts-token"])}static withHCS2(e){return this.withPlugins(e,["hcs-2"])}static withHCS10(e){return this.withPlugins(e,["hcs-10"])}static withInscribe(e){return this.withPlugins(e,["inscribe"])}static withAccount(e){return this.withPlugins(e,["account"])}static withFileService(e){return this.withPlugins(e,["file-service"])}static withConsensusService(e){return this.withPlugins(e,["consensus-service"])}static withSmartContract(e){return this.withPlugins(e,["smart-contract"])}static withAllStandards(e){return this.withPlugins(e,["hcs-10","hcs-2","inscribe"])}static minimal(e){return this.withPlugins(e,[])}static withMCP(e,t){return new K({...e,mcpServers:t})}async detectPrivateKeyType(e,t,r){const i=new n.HederaMirrorNode(r),s=await i.requestAccount(e),a=s?.key?._type||"";return a?.toLowerCase()?.includes("ecdsa")?o.PrivateKey.fromStringECDSA(t):o.PrivateKey.fromStringED25519(t)}}exports.BaseAgent=v,exports.ConversationalAgent=K,exports.HCS10Plugin=d,exports.HCS2Plugin=p,exports.HbarTransferPlugin=x,exports.InscribePlugin=m,exports.LangChainAgent=P,exports.LangChainProvider=M,exports.MCPServers={filesystem:e=>({name:"filesystem",command:"npx",args:["-y","@modelcontextprotocol/server-filesystem",e],transport:"stdio",autoConnect:!0,additionalContext:"This server provides access to files and directories in the current working directory.",toolDescriptions:{list_directory:'Use this tool when users ask about files in the "current directory" or "working directory".',read_file:"Use this tool when users ask to see or check files in the current directory."}}),github:e=>({name:"github",command:"npx",args:["-y","@modelcontextprotocol/server-github"],...e&&{env:{GITHUB_TOKEN:e}},transport:"stdio",autoConnect:!0}),slack:e=>({name:"slack",command:"npx",args:["-y","@modelcontextprotocol/server-slack"],env:{SLACK_TOKEN:e},transport:"stdio",autoConnect:!0}),googleDrive:e=>({name:"google-drive",command:"npx",args:["-y","@modelcontextprotocol/server-google-drive"],env:{GOOGLE_CREDENTIALS:e},transport:"stdio",autoConnect:!0}),postgres:e=>({name:"postgres",command:"npx",args:["-y","@modelcontextprotocol/server-postgres",e],transport:"stdio",autoConnect:!0}),sqlite:e=>({name:"sqlite",command:"npx",args:["-y","@modelcontextprotocol/server-sqlite",e],transport:"stdio",autoConnect:!0}),custom:e=>e},exports.OpenConvAIPlugin=d,exports.createAgent=k,exports.createMCPConfig=function(e,t=!0){return{mcpServers:e.map(e=>({...e,autoConnect:e.autoConnect??t}))}},exports.validateServerConfig=function(e){const t=[];return e.name||t.push("Server name is required"),e.command||t.push("Server command is required"),e.args&&Array.isArray(e.args)||t.push("Server args must be an array"),e.transport&&!["stdio","http","websocket"].includes(e.transport)&&t.push("Invalid transport type. Must be stdio, http, or websocket"),t},Object.keys(e).forEach(t=>{"default"===t||Object.prototype.hasOwnProperty.call(exports,t)||Object.defineProperty(exports,t,{enumerable:!0,get:()=>e[t]})});
1
+ "use strict";Object.create,Object.defineProperty,Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("hedera-agent-kit"),t=require("@hashgraphonline/standards-agent-kit"),s=require("@hashgraphonline/standards-sdk"),n=require("zod"),r=require("@hashgraph/sdk"),o=require("bignumber.js"),i=require("langchain/agents"),a=require("@langchain/core/prompts"),c=require("@langchain/openai"),g=require("@modelcontextprotocol/sdk/client/index.js"),l=require("@modelcontextprotocol/sdk/client/stdio.js"),h=require("@langchain/core/tools"),u=require("tiktoken"),m=require("crypto"),d=require("@langchain/core/messages");class p extends e.BasePlugin{constructor(){super(...arguments),this.id="hcs-10",this.name="HCS-10 Plugin",this.description="HCS-10 agent tools for decentralized agent registration, connections, and messaging on Hedera",this.version="1.0.0",this.author="Hashgraph Online",this.namespace="hcs10",this.tools=[]}async initialize(e){await super.initialize(e);const n=e.config.hederaKit;if(n)try{this.stateManager=e.stateManager||e.config.stateManager||this.appConfig?.stateManager||new t.OpenConvaiState;const o=n.signer.getAccountId().toString();let i="",a="";try{const e=n.signer.getOperatorPrivateKey().toString(),t=new s.HCS10Client({network:n.network,operatorId:o,operatorPrivateKey:e,logLevel:"error"}),r=await t.retrieveProfile(o);r.success&&r.topicInfo&&(i=r.topicInfo.inboundTopic,a=r.topicInfo.outboundTopic)}catch(r){this.context.logger.warn("Could not retrieve profile topics:",r)}if(this.stateManager.setCurrentAgent({name:`Agent ${o}`,accountId:o,inboundTopicId:i,outboundTopicId:a,privateKey:n.signer.getOperatorPrivateKey().toString()}),this.context.logger.info(`Set current agent: ${o} with topics ${i}/${a}`),this.stateManager&&!this.stateManager.getConnectionsManager()){const e=n.signer.getOperatorPrivateKey().toString(),t=new s.HCS10Client({network:n.network,operatorId:o,operatorPrivateKey:e,logLevel:"error"});this.stateManager.initializeConnectionsManager(t),this.context.logger.info("ConnectionsManager initialized in HCS10Plugin")}this.initializeTools(),this.context.logger.info("HCS-10 Plugin initialized successfully")}catch(o){this.context.logger.error("Failed to initialize HCS-10 plugin:",o)}else this.context.logger.warn("HederaKit not found in context. HCS-10 tools will not be available.")}initializeTools(){if(!this.stateManager)throw new Error("StateManager must be initialized before creating tools");const e=this.context.config.hederaKit;if(!e)throw new Error("HederaKit not found in context config");const s=new t.HCS10Builder(e,this.stateManager);this.tools=[new t.RegisterAgentTool({hederaKit:e,hcs10Builder:s,logger:this.context.logger}),new t.FindRegistrationsTool({hederaKit:e,hcs10Builder:s,logger:this.context.logger}),new t.RetrieveProfileTool({hederaKit:e,hcs10Builder:s,logger:this.context.logger}),new t.InitiateConnectionTool({hederaKit:e,hcs10Builder:s,logger:this.context.logger}),new t.ListConnectionsTool({hederaKit:e,hcs10Builder:s,logger:this.context.logger}),new t.SendMessageToConnectionTool({hederaKit:e,hcs10Builder:s,logger:this.context.logger}),new t.CheckMessagesTool({hederaKit:e,hcs10Builder:s,logger:this.context.logger}),new t.ConnectionMonitorTool({hederaKit:e,hcs10Builder:s,logger:this.context.logger}),new t.ManageConnectionRequestsTool({hederaKit:e,hcs10Builder:s,logger:this.context.logger}),new t.AcceptConnectionRequestTool({hederaKit:e,hcs10Builder:s,logger:this.context.logger}),new t.ListUnapprovedConnectionRequestsTool({hederaKit:e,hcs10Builder:s,logger:this.context.logger})]}getTools(){return this.tools}getStateManager(){return this.stateManager}async cleanup(){this.tools=[],delete this.stateManager,this.context?.logger&&this.context.logger.info("HCS-10 Plugin cleaned up")}}class f extends e.BasePlugin{constructor(){super(...arguments),this.id="hcs-2",this.name="HCS-2 Plugin",this.description="HCS-2 registry management tools for decentralized registries on Hedera",this.version="1.0.0",this.author="Hashgraph Online",this.namespace="hcs2",this.tools=[]}async initialize(e){await super.initialize(e);if(e.config.hederaKit)try{this.initializeTools(),this.context.logger.info("HCS-2 Plugin initialized successfully")}catch(t){this.context.logger.error("Failed to initialize HCS-2 plugin:",t)}else this.context.logger.warn("HederaKit not found in context. HCS-2 tools will not be available.")}initializeTools(){const e=this.context.config.hederaKit;if(!e)throw new Error("HederaKit not found in context config");const s=new t.HCS2Builder(e);this.tools=[new t.CreateRegistryTool({hederaKit:e,hcs2Builder:s,logger:this.context.logger}),new t.RegisterEntryTool({hederaKit:e,hcs2Builder:s,logger:this.context.logger}),new t.UpdateEntryTool({hederaKit:e,hcs2Builder:s,logger:this.context.logger}),new t.DeleteEntryTool({hederaKit:e,hcs2Builder:s,logger:this.context.logger}),new t.MigrateRegistryTool({hederaKit:e,hcs2Builder:s,logger:this.context.logger}),new t.QueryRegistryTool({hederaKit:e,hcs2Builder:s,logger:this.context.logger})]}getTools(){return this.tools}async cleanup(){this.tools=[],this.context?.logger&&this.context.logger.info("HCS-2 Plugin cleaned up")}}class y extends e.BasePlugin{constructor(){super(...arguments),this.id="inscribe",this.name="Inscribe Plugin",this.description="Content inscription tools for storing data on Hedera Consensus Service",this.version="1.0.0",this.author="Hashgraph Online",this.namespace="inscribe",this.tools=[]}async initialize(e){await super.initialize(e);if(e.config.hederaKit)try{this.initializeTools(),this.context.logger.info("Inscribe Plugin initialized successfully")}catch(t){this.context.logger.error("Failed to initialize Inscribe plugin:",t)}else this.context.logger.warn("HederaKit not found in context. Inscription tools will not be available.")}initializeTools(){const e=this.context.config.hederaKit;if(!e)throw new Error("HederaKit not found in context config");const s=new t.InscriberBuilder(e);this.tools=[new t.InscribeFromUrlTool({hederaKit:e,inscriberBuilder:s,logger:this.context.logger}),new t.InscribeFromFileTool({hederaKit:e,inscriberBuilder:s,logger:this.context.logger}),new t.InscribeFromBufferTool({hederaKit:e,inscriberBuilder:s,logger:this.context.logger}),new t.InscribeHashinalTool({hederaKit:e,inscriberBuilder:s,logger:this.context.logger}),new t.RetrieveInscriptionTool({hederaKit:e,inscriberBuilder:s,logger:this.context.logger})]}getTools(){return this.tools}async cleanup(){this.tools=[],this.context?.logger&&this.context.logger.info("Inscribe Plugin cleaned up")}}class w extends e.BaseServiceBuilder{constructor(e){super(e)}transferHbar(e,t=!0){this.clearNotes();const s=new r.TransferTransaction;if(!e.transfers||0===e.transfers.length)throw new Error("HbarTransferParams must include at least one transfer.");let n=new o(0),i=!1;if(t&&this.kit.userAccountId&&"provideBytes"===this.kit.operationalMode&&1===e.transfers.length){const t=e.transfers[0],n="string"==typeof t.amount||"number"==typeof t.amount?t.amount:t.amount.toString(),a=new o(n);if(a.isPositive()){const e="string"==typeof t.accountId?r.AccountId.fromString(t.accountId):t.accountId,n=a.toFixed(8,o.ROUND_DOWN),c=r.Hbar.fromString(n);this.logger.info(`[AccountBuilder.transferHbar] Configuring user-initiated scheduled transfer: ${c.toString()} from ${this.kit.userAccountId} to ${e.toString()}`),this.addNote(`Configured HBAR transfer from your account (${this.kit.userAccountId}) to ${e.toString()} for ${c.toString()}.`),s.addHbarTransfer(e,c),s.addHbarTransfer(r.AccountId.fromString(this.kit.userAccountId),c.negated()),i=!0}}if(!i){const t=[];for(const s of e.transfers){const e="string"==typeof s.accountId?r.AccountId.fromString(s.accountId):s.accountId,i="string"==typeof s.amount||"number"==typeof s.amount?s.amount:s.amount.toString(),a=new o(i),c=a.toFixed(8,o.ROUND_DOWN);this.logger.info(`Processing transfer: ${i} HBAR (rounded to ${c}) for account ${e.toString()}`);const g=r.Hbar.fromString(c);t.push({accountId:e,amount:a,hbar:g});const l=g.toTinybars();n=n.plus(l.toString())}if(!n.isZero()&&(this.logger.warn(`Transfer sum not zero: ${n.toString()} tinybars off. Adjusting last transfer.`),t.length>0)){const e=t[t.length-1],s=n.dividedBy(-1e8),i=e.amount.plus(s).toFixed(8,o.ROUND_DOWN);e.hbar=r.Hbar.fromString(i),this.logger.info(`Adjusted last transfer for ${e.accountId.toString()} to ${i} HBAR`)}for(const e of t)s.addHbarTransfer(e.accountId,e.hbar)}return void 0!==e.memo&&(null===e.memo?this.logger.warn("Received null for memo in transferHbar."):s.setTransactionMemo(e.memo)),this.setCurrentTransaction(s),this}}const S=n.z.object({accountId:n.z.string().describe('Account ID for the transfer (e.g., "0.0.xxxx").'),amount:n.z.union([n.z.number(),n.z.string()]).describe("HBAR amount in decimal format (e.g., 1 for 1 HBAR, 0.5 for 0.5 HBAR). Positive for credit, negative for debit. DO NOT multiply by 10^8 for tinybars - just use the HBAR amount directly.")}),T=n.z.object({transfers:n.z.array(S).min(1).describe('Array of ALL transfers for this transaction. For multi-party transfers (e.g., "A sends 5 to C and B sends 3 to C"), include all transfers here: [{accountId: "A", amount: -5}, {accountId: "B", amount: -3}, {accountId: "C", amount: 8}]. Amounts must sum to zero.'),memo:n.z.string().optional().describe("Optional. Memo for the transaction.")});class C extends e.BaseHederaTransactionTool{constructor(){super(...arguments),this.name="hedera-account-transfer-hbar-v2",this.description='PRIMARY TOOL FOR HBAR TRANSFERS: Transfers HBAR between accounts. Supports multiple transfers in a single transaction - when multiple accounts need to send/receive HBAR (e.g., "A sends 5 HBAR to C and B sends 3 HBAR to C"), include ALL transfers in one transfers array. The sum of all transfers must equal zero. Use this for scheduled transactions and multi-signature scenarios.',this.specificInputSchema=T,this.namespace="account"}getServiceBuilder(){return new w(this.hederaKit)}async callBuilderMethod(e,t){await e.transferHbar(t)}}class x extends e.BasePlugin{constructor(){super(...arguments),this.id="hbar-transfer",this.name="HBAR Transfer Plugin",this.description="HBAR transfer tool with proper decimal handling for multi-signature transactions",this.version="1.0.0",this.author="Hashgraph Online",this.namespace="account",this.tools=[]}async initialize(e){await super.initialize(e);if(e.config.hederaKit)try{this.initializeTools(),this.context.logger.info("HBAR Transfer Plugin initialized successfully")}catch(t){this.context.logger.error("Failed to initialize HBAR Transfer plugin:",t)}else this.context.logger.warn("HederaKit not found in context. HBAR transfer tools will not be available.")}initializeTools(){const e=this.context.config.hederaKit;if(!e)throw new Error("HederaKit not found in context config");this.tools=[new C({hederaKit:e,logger:this.context.logger})]}getTools(){return this.tools}async shutdown(){this.tools=[]}}class M extends i.AgentExecutor{constructor(e){super(e),this.MCP_REFERENCE_THRESHOLD=10240,this.logger=new s.Logger({module:"ContentAwareAgentExecutor"})}async _call(e){try{const t=this._takeNextStep.bind(this);this._takeNextStep=async(e,n,r,o,i)=>{const a=await t(e,n,r,o,i);if(Array.isArray(a)){return await Promise.all(a.map(async e=>{const{action:t,observation:n}=e;if("string"==typeof n){const e=globalThis.Buffer.from(n,"utf8");if(e.length>this.MCP_REFERENCE_THRESHOLD||s.shouldUseReference(e)){this.logger.info(`[ContentAwareAgentExecutor] Large tool output detected: ${e.length} bytes from ${t.tool}`);const n=s.ContentStoreService.getInstance();if(n)try{const s=`content-ref:${await n.storeContent(e,{contentType:"text",source:"tool",toolName:t.tool,originalSize:e.length})}`;return this.logger.info(`[ContentAwareAgentExecutor] Stored large output as reference: ${s}`),{action:t,observation:s}}catch(r){this.logger.warn("[ContentAwareAgentExecutor] Failed to store content as reference:",r)}else this.logger.warn("[ContentAwareAgentExecutor] ContentStoreService not available")}}return e}))}return a};const n=await super._call(e);return this._takeNextStep=t,n}catch(t){throw this.logger.error("[ContentAwareAgentExecutor] Error in _call:",t),t}}}class v{constructor(e){this.config=e,this.tools=[],this.initialized=!1,this.logger=new s.Logger({module:"BaseAgent",silent:e.debug?.silent||!1})}getCore(){return this.agentKit}filterTools(e){let t=[...e];const s=this.config.filtering;return s?(s.namespaceWhitelist?.length&&(t=t.filter(e=>{const t=e.namespace;return!t||s.namespaceWhitelist.includes(t)})),s.toolBlacklist?.length&&(t=t.filter(e=>!s.toolBlacklist.includes(e.name))),s.toolPredicate&&(t=t.filter(s.toolPredicate)),this.logger.debug(`Filtered tools: ${e.length} → ${t.length}`),t):t}buildSystemPrompt(){const e=[],t=this.config.signer.getAccountId().toString(),s=this.config.execution?.userAccountId;this.config.messaging?.systemPreamble&&e.push(this.config.messaging.systemPreamble),e.push(`You are a helpful Hedera assistant. Your primary operator account is ${t}. You have tools to interact with the Hedera network. When using any tool, provide all necessary parameters as defined by that tool's schema and description.`),s&&e.push(`The user you are assisting has a personal Hedera account ID: ${s}. IMPORTANT: When the user says things like "I want to send HBAR" or "transfer my tokens", you MUST use ${s} as the sender/from account. For example, if user says "I want to send 2 HBAR to 0.0.800", you must set up a transfer where ${s} sends the HBAR, not your operator account.`);return"autonomous"===(this.config.execution?.operationalMode||"returnBytes")?e.push(`\nOPERATIONAL MODE: 'autonomous'. Your goal is to execute transactions directly using your tools. Your account ${t} will be the payer for these transactions. Even if the user's account (${s||"a specified account"}) is the actor in the transaction body (e.g., sender of HBAR), you (the agent with operator ${t}) are still executing and paying. For HBAR transfers, ensure the amounts in the 'transfers' array sum to zero (as per tool schema), balancing with your operator account if necessary.`):this.config.execution?.scheduleUserTransactionsInBytesMode&&s?e.push(`\nOPERATIONAL MODE: 'returnBytes' with scheduled transactions for user actions. When a user asks for a transaction to be prepared (e.g., creating a token, topic, transferring assets for them to sign, etc), you MUST default to creating a Scheduled Transaction using the appropriate tool with the metaOption 'schedule: true'. The user (with account ID ${s}) will be the one to ultimately pay for and (if needed) sign the inner transaction. Your operator account (${t}) will pay for creating the schedule entity itself. You MUST return the ScheduleId and details of the scheduled operation in a structured JSON format with these fields: success, op, schedule_id, description, payer_account_id_scheduled_tx, and scheduled_transaction_details.`):e.push(`\nOPERATIONAL MODE: 'returnBytes'. Your goal is to provide transaction bytes directly. When a user asks for a transaction to be prepared (e.g., for them to sign, or for scheduling without the default scheduling flow), you MUST call the appropriate tool. If you want raw bytes for the user to sign for their own account ${s||"if specified"}, ensure the tool constructs the transaction body accordingly and use metaOption 'returnBytes: true' if available, or ensure the builder is configured for the user.`),!1!==this.config.messaging?.conciseMode&&e.push("\nAlways be concise. If the tool provides a JSON string as its primary output (especially in returnBytes mode), make your accompanying text brief. If the tool does not provide JSON output or an error occurs, your narrative becomes primary; if notes were generated by the tool in such cases, append them to your textual response."),this.config.messaging?.systemPostamble&&e.push(this.config.messaging.systemPostamble),e.join("\n")}isReady(){return this.initialized}}class A{constructor(e,t){this.contentStorage=e,this.logger=t}analyzeResponse(e){const t=[];let s=0;this.extractContentFromResponse(e,t),s=t.reduce((e,t)=>e+t.sizeBytes,0);const n=t.reduce((e,t)=>Math.max(e,t.sizeBytes),0);return{shouldProcess:t.some(e=>this.contentStorage.shouldUseReference("string"==typeof e.content?e.content:JSON.stringify(e.content))),contents:t,totalSize:s,largestContentSize:n}}async processResponse(e,t,s){try{const n=this.analyzeResponse(e);if(!n.shouldProcess)return{content:e,wasProcessed:!1};return await this.createReferencedResponse(e,n,t,s)}catch(n){return this.logger.error("Error processing MCP response:",n),{content:e,wasProcessed:!1,errors:[n instanceof Error?n.message:"Unknown processing error"]}}}extractContentFromResponse(e,t){if(null!=e)if(Array.isArray(e))e.forEach(e=>this.extractContentFromResponse(e,t));else{if("object"==typeof e){const s=e;if("text"===s.type&&"string"==typeof s.text)return void t.push({content:s.text,type:"text",sizeBytes:globalThis.Buffer.byteLength(s.text,"utf8"),mimeType:"text/plain"});if("image"===s.type&&"string"==typeof s.data)return void t.push({content:s.data,type:"image",sizeBytes:Math.ceil(.75*s.data.length),mimeType:s.mimeType||"image/jpeg"});if("resource"===s.type&&s.resource){const e=JSON.stringify(s.resource);return void t.push({content:e,type:"resource",sizeBytes:globalThis.Buffer.byteLength(e,"utf8"),mimeType:"application/json"})}return void Object.values(s).forEach(e=>this.extractContentFromResponse(e,t))}"string"==typeof e&&e.length>1e3&&t.push({content:e,type:"text",sizeBytes:globalThis.Buffer.byteLength(e,"utf8"),mimeType:this.detectMimeType(e)})}}async createReferencedResponse(e,t,s,n){const r=this.deepClone(e),o=[];let i=!1,a=0;for(const l of t.contents)if(this.contentStorage.shouldUseReference("string"==typeof l.content?l.content:JSON.stringify(l.content)))try{const e=globalThis.Buffer.from("string"==typeof l.content?l.content:JSON.stringify(l.content),"utf8"),t={contentType:this.mapMimeTypeToContentType(l.mimeType),source:"mcp_tool",mcpToolName:`${s}::${n}`,tags:["mcp_response",s,n]};void 0!==l.mimeType&&(t.mimeType=l.mimeType);const o=await this.contentStorage.storeContentIfLarge(e,t);o&&(this.replaceContentInResponse(r,l.content,this.createLightweightReference(o)),i=!0,a+=e.length)}catch(g){o.push(`Failed to create reference: ${g instanceof Error?g.message:"Unknown error"}`)}const c={content:r,wasProcessed:!0,referenceCreated:i,originalSize:a};return o.length>0&&(c.errors=o),c}createLightweightReference(e){return{type:"content_reference",referenceId:e.referenceId,preview:e.preview,size:e.metadata.sizeBytes,contentType:e.metadata.contentType,format:"ref://{id}",_isReference:!0}}replaceContentInResponse(e,t,s){if(null!=e)if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]===t?e[n]=s:this.replaceContentInResponse(e[n],t,s);else if("object"==typeof e){const n=e;for(const e in n)n[e]===t?n[e]=s:this.replaceContentInResponse(n[e],t,s)}}detectMimeType(e){return e.trim().startsWith("{")||e.trim().startsWith("[")?"application/json":e.includes("<html>")||e.includes("<!DOCTYPE")?"text/html":e.includes("# ")||e.includes("## ")?"text/markdown":"text/plain"}mapMimeTypeToContentType(e){return e?e.startsWith("text/plain")?"text":"application/json"===e?"json":"text/html"===e?"html":"text/markdown"===e?"markdown":e.startsWith("text/")?"text":"binary":"text"}deepClone(e){if(null===e||"object"!=typeof e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e))return e.map(e=>this.deepClone(e));const t={};for(const s in e)e.hasOwnProperty(s)&&(t[s]=this.deepClone(e[s]));return t}}class k{constructor(e,t){this.clients=new Map,this.tools=new Map,this.logger=e,t&&(this.contentProcessor=new A(t,e))}async connectServer(e){try{if(this.isServerConnected(e.name))return{serverName:e.name,connected:!1,error:`Server ${e.name} is already connected`,tools:[]};if(e.transport&&"stdio"!==e.transport)throw new Error(`Transport ${e.transport} not yet supported`);const t=new l.StdioClientTransport({command:e.command,args:e.args,...e.env&&{env:e.env}}),s=new g.Client({name:`conversational-agent-${e.name}`,version:"1.0.0"},{capabilities:{}});await s.connect(t),this.clients.set(e.name,s);const n=(await s.listTools()).tools.map(t=>({...t,serverName:e.name}));return this.tools.set(e.name,n),this.logger.info(`Connected to MCP server ${e.name} with ${n.length} tools`),{serverName:e.name,connected:!0,tools:n}}catch(t){return this.logger.error(`Failed to connect to MCP server ${e.name}:`,t),{serverName:e.name,connected:!1,error:t instanceof Error?t.message:"Unknown error",tools:[]}}}async executeTool(e,t,s){const n=this.clients.get(e);if(!n)throw new Error(`MCP server ${e} not connected`);this.logger.debug(`Executing MCP tool ${t} on server ${e}`,s);try{const r=await n.callTool({name:t,arguments:s});if(this.contentProcessor){const s=await this.contentProcessor.processResponse(r,e,t);return s.wasProcessed&&(this.logger.debug(`Processed MCP response from ${e}::${t}`,{referenceCreated:s.referenceCreated,originalSize:s.originalSize,errors:s.errors}),s.errors&&s.errors.length>0&&this.logger.warn(`Content processing warnings for ${e}::${t}:`,s.errors)),s.content}return r}catch(r){throw this.logger.error(`Error executing MCP tool ${t}:`,r),r}}async disconnectAll(){for(const[t,s]of this.clients)try{await s.close(),this.logger.info(`Disconnected from MCP server ${t}`)}catch(e){this.logger.error(`Error disconnecting MCP server ${t}:`,e)}this.clients.clear(),this.tools.clear()}getAllTools(){const e=[];for(const t of this.tools.values())e.push(...t);return e}getServerTools(e){return this.tools.get(e)||[]}isServerConnected(e){return this.clients.has(e)}getConnectedServers(){return Array.from(this.clients.keys())}enableContentProcessing(e){this.contentProcessor=new A(e,this.logger),this.logger.info("Content processing enabled for MCP responses")}disableContentProcessing(){delete this.contentProcessor,this.logger.info("Content processing disabled for MCP responses")}isContentProcessingEnabled(){return void 0!==this.contentProcessor}analyzeResponseContent(e){if(!this.contentProcessor)throw new Error("Content processing is not enabled");return this.contentProcessor.analyzeResponse(e)}}function b(e,t,n){const r=P(e.inputSchema),o=`${e.serverName}_${e.name}`.replace(/[^a-zA-Z0-9_]/g,"_");let i=e.description||`MCP tool ${e.name} from ${e.serverName}`;return n?.toolDescriptions?.[e.name]&&(i=`${i}\n\n${n.toolDescriptions[e.name]}`),n?.additionalContext&&(i=`${i}\n\nContext: ${n.additionalContext}`),new h.DynamicStructuredTool({name:o,description:i,schema:r,func:async n=>{try{const o=await t.executeTool(e.serverName,e.name,n);let i="";if("string"==typeof o)i=o;else if(o&&"object"==typeof o&&"content"in o){const e=o.content;if(Array.isArray(e)){i=e.filter(e=>"object"==typeof e&&null!==e&&"type"in e&&"text"===e.type&&"text"in e).map(e=>e.text).join("\n")}else i=JSON.stringify(e)}else i=JSON.stringify(o);const a=globalThis.Buffer.from(i,"utf8");console.log(`[MCP Adapter] Response size: ${a.length} bytes, tool: ${e.serverName}_${e.name}`);const c=10240;if(a.length>c||s.shouldUseReference(a)){console.log(`[MCP Adapter] Content exceeds threshold (${a.length} > ${c}), storing as reference`);const t=s.ContentStoreService.getInstance();if(t)try{const s=await t.storeContent(a,{contentType:"text",source:"mcp",mcpToolName:`${e.serverName}_${e.name}`,originalSize:a.length});return console.log(`[MCP Adapter] Stored content as reference: content-ref:${s}`),`content-ref:${s}`}catch(r){console.warn("Failed to store large MCP content as reference:",r)}else console.warn("[MCP Adapter] ContentStoreService not available")}return i}catch(o){const t=o instanceof Error?o.message:"Unknown error";return`Error executing MCP tool ${e.name}: ${t}`}}})}function P(e){if(!e||"object"!=typeof e)return n.z.object({});const t=e;if(t.type&&"object"!==t.type)return R(t);if(!t.properties||"object"!=typeof t.properties)return n.z.object({});const s={};for(const[n,r]of Object.entries(t.properties)){let e=R(r);Array.isArray(t.required)&&t.required.includes(n)||(e=e.optional()),s[n]=e}return n.z.object(s)}function R(e){if(!e||"object"!=typeof e||!("type"in e))return n.z.unknown();const t=e;let s;switch(t.type){case"string":s=n.z.string(),t.enum&&Array.isArray(t.enum)&&(s=n.z.enum(t.enum));break;case"number":s=n.z.number(),"minimum"in t&&"number"==typeof t.minimum&&(s=s.min(t.minimum)),"maximum"in t&&"number"==typeof t.maximum&&(s=s.max(t.maximum));break;case"integer":s=n.z.number().int(),"minimum"in t&&"number"==typeof t.minimum&&(s=s.min(t.minimum)),"maximum"in t&&"number"==typeof t.maximum&&(s=s.max(t.maximum));break;case"boolean":s=n.z.boolean();break;case"array":s=t.items?n.z.array(R(t.items)):n.z.array(n.z.unknown());break;case"object":s="properties"in t?P(t):n.z.object({}).passthrough();break;default:s=n.z.unknown()}return"description"in t&&"string"==typeof t.description&&(s=s.describe(t.description)),s}const E=class e{constructor(e="gpt-4o"){this.modelName=e;try{this.encoding=u.encoding_for_model(e)}catch(t){console.warn(`Model ${e} not found, falling back to gpt-4o encoding`),this.encoding=u.encoding_for_model("gpt-4o"),this.modelName="gpt-4o"}}countTokens(e){if(!e||""===e.trim())return 0;try{return this.encoding.encode(e).length}catch(t){return console.warn("Error counting tokens, falling back to word-based estimation:",t),Math.ceil(1.3*e.split(/\s+/).length)}}countMessageTokens(t){return this.countTokens(t.content)+this.countTokens(this.getMessageRole(t))+e.MESSAGE_OVERHEAD+e.ROLE_OVERHEAD}countMessagesTokens(e){return e&&0!==e.length?e.reduce((e,t)=>e+this.countMessageTokens(t),0):0}estimateSystemPromptTokens(t){if(!t||""===t.trim())return 0;return this.countTokens(t)+this.countTokens("system")+e.MESSAGE_OVERHEAD+e.ROLE_OVERHEAD}estimateContextSize(e,t){return this.estimateSystemPromptTokens(e)+this.countMessagesTokens(t)+10}getMessageRole(e){switch(e._getType()){case"human":default:return"user";case"ai":return"assistant";case"system":return"system";case"function":return"function";case"tool":return"tool"}}getModelName(){return this.modelName}dispose(){try{this.encoding.free()}catch(e){console.warn("Error disposing encoding:",e)}}};E.MESSAGE_OVERHEAD=3,E.ROLE_OVERHEAD=1;let I=E;const z=class e{constructor(t=e.DEFAULT_MAX_TOKENS,s=e.DEFAULT_RESERVE_TOKENS,n){if(this.messages=[],this.systemPrompt="",this.systemPromptTokens=0,s>=t)throw new Error("Reserve tokens must be less than max tokens");this.maxTokens=t,this.reserveTokens=s,this.tokenCounter=n||new I}addMessage(e){this.tokenCounter.countMessageTokens(e),this.messages.push(e);let t=[];return this.getCurrentTokenCount()>this.maxTokens-this.reserveTokens&&(this.messages.pop(),t=this.pruneToFit(),this.messages.push(e)),{added:!0,prunedMessages:t,currentTokenCount:this.getCurrentTokenCount(),remainingCapacity:this.getRemainingTokenCapacity()}}pruneToFit(){const t=[],s=this.maxTokens-this.reserveTokens;for(;this.getCurrentTokenCount()>s&&this.messages.length>0;){const s=Math.min(e.PRUNING_BATCH_SIZE,this.messages.length);for(let e=0;e<s;e++){const e=this.messages.shift();e&&t.push(e)}if(t.length>1e3){console.warn("MemoryWindow: Excessive pruning detected, stopping to prevent infinite loop");break}}return t}getCurrentTokenCount(){const e=this.tokenCounter.countMessagesTokens(this.messages);return this.systemPromptTokens+e}getRemainingTokenCapacity(){return Math.max(0,this.maxTokens-this.getCurrentTokenCount())}canAddMessage(e){const t=this.tokenCounter.countMessageTokens(e),s=this.getCurrentTokenCount()+t>this.maxTokens-this.reserveTokens;return!(t>this.maxTokens)&&(!s||this.messages.length>0)}getMessages(){return[...this.messages]}clear(){this.messages=[]}setSystemPrompt(e){this.systemPrompt=e,this.systemPromptTokens=this.tokenCounter.estimateSystemPromptTokens(e)}getSystemPrompt(){return this.systemPrompt}getConfig(){return{maxTokens:this.maxTokens,reserveTokens:this.reserveTokens,currentTokens:this.getCurrentTokenCount(),messageCount:this.messages.length,systemPromptTokens:this.systemPromptTokens}}updateLimits(e,t){if(void 0!==t&&t>=e)throw new Error("Reserve tokens must be less than max tokens");this.maxTokens=e,void 0!==t&&(this.reserveTokens=t),this.getCurrentTokenCount()>this.maxTokens-this.reserveTokens&&this.pruneToFit()}getStats(){const e=this.getCurrentTokenCount(),t=this.maxTokens,s=e/t*100;return{totalMessages:this.messages.length,currentTokens:e,maxTokens:t,reserveTokens:this.reserveTokens,systemPromptTokens:this.systemPromptTokens,usagePercentage:Math.round(100*s)/100,remainingCapacity:this.getRemainingTokenCapacity(),canAcceptMore:this.getRemainingTokenCapacity()>this.reserveTokens}}dispose(){this.clear(),this.tokenCounter.dispose()}};z.DEFAULT_MAX_TOKENS=8e3,z.DEFAULT_RESERVE_TOKENS=1e3,z.PRUNING_BATCH_SIZE=2;let B=z;class H{static generateId(e){const t=m.createHash("sha256");return t.update(e),t.digest("base64url")}static isValidReferenceId(e){return!(!e||"string"!=typeof e)&&(43===e.length&&/^[A-Za-z0-9_-]+$/.test(e))}static extractReferenceId(e){if(!e||"string"!=typeof e)return null;const t=e.match(/^ref:\/\/([A-Za-z0-9_-]{43})$/);return t?t[1]:this.isValidReferenceId(e)?e:null}static formatReference(e){return`ref://${e}`}static generateTestId(e){const t=globalThis.Buffer.from(`test-${e}-${Date.now()}`);return this.generateId(t)}}const O={sizeThresholdBytes:10240,maxAgeMs:36e5,maxReferences:100,maxTotalStorageBytes:104857600,enableAutoCleanup:!0,cleanupIntervalMs:3e5,enablePersistence:!1,storageBackend:"memory",cleanupPolicies:{recent:{maxAgeMs:18e5,priority:1},userContent:{maxAgeMs:72e5,priority:2},agentGenerated:{maxAgeMs:36e5,priority:3},default:{maxAgeMs:36e5,priority:4}}};class $ extends Error{constructor(e,t,s,n){super(e),this.type=t,this.referenceId=s,this.suggestedActions=n,this.name="ContentReferenceError"}}const N=class e{constructor(t=e.DEFAULT_MAX_STORAGE,s){this.messages=[],this.idCounter=0,this.contentStore=new Map,this.maxStorage=t,this.referenceConfig={...O,...s},this.referenceStats={activeReferences:0,totalStorageBytes:0,recentlyCleanedUp:0,totalResolutions:0,failedResolutions:0,averageContentSize:0,storageUtilization:0,performanceMetrics:{averageCreationTimeMs:0,averageResolutionTimeMs:0,averageCleanupTimeMs:0,creationTimes:[],resolutionTimes:[],cleanupTimes:[]}},this.referenceConfig.enableAutoCleanup&&this.startReferenceCleanupTimer()}storeMessages(e){if(0===e.length)return{stored:0,dropped:0};const t=new Date;let s=0;const n=e.map(e=>({message:e,storedAt:t,id:this.generateId()}));for(this.messages.push(...n);this.messages.length>this.maxStorage;)this.messages.shift(),s++;return{stored:n.length,dropped:s}}getRecentMessages(e){if(e<=0||0===this.messages.length)return[];const t=Math.max(0,this.messages.length-e);return this.messages.slice(t).map(e=>e.message)}searchMessages(e,t={}){if(!e||0===this.messages.length)return[];const{caseSensitive:s=!1,limit:n,useRegex:r=!1}=t;let o=[];if(r)try{const t=new RegExp(e,s?"g":"gi");o=this.messages.filter(e=>t.test(e.message.content)).map(e=>e.message)}catch(i){return console.warn("Invalid regex pattern:",e,i),[]}else{const t=s?e:e.toLowerCase();o=this.messages.filter(e=>{const n=e.message.content;return(s?n:n.toLowerCase()).includes(t)}).map(e=>e.message)}return n?o.slice(0,n):o}getMessagesFromTimeRange(e,t){return e>t||0===this.messages.length?[]:this.messages.filter(s=>s.storedAt>=e&&s.storedAt<=t).map(e=>e.message)}getStorageStats(){const e=this.messages.length,t=e>0?Math.round(e/this.maxStorage*100):0;let s,n;return e>0&&(s=this.messages[0].storedAt,n=this.messages[e-1].storedAt),{totalMessages:e,maxStorageLimit:this.maxStorage,usagePercentage:t,oldestMessageTime:s,newestMessageTime:n}}clear(){this.messages=[],this.idCounter=0}getTotalStoredMessages(){return this.messages.length}updateStorageLimit(e){if(e<=0)throw new Error("Storage limit must be greater than 0");for(this.maxStorage=e;this.messages.length>this.maxStorage;)this.messages.shift()}getMessagesByType(e,t){const s=this.messages.filter(t=>t.message._getType()===e).map(e=>e.message);return t?s.slice(0,t):s}getConfig(){return{maxStorage:this.maxStorage,currentUsage:this.messages.length,utilizationPercentage:this.messages.length/this.maxStorage*100}}generateId(){return`msg_${++this.idCounter}_${Date.now()}`}getRecentMessagesByTime(e){if(e<=0||0===this.messages.length)return[];const t=new Date(Date.now()-60*e*1e3);return this.messages.filter(e=>e.storedAt>=t).map(e=>e.message)}exportMessages(){return this.messages.map(e=>({content:e.message.content,type:e.message._getType(),storedAt:e.storedAt.toISOString(),id:e.id}))}shouldUseReference(e){return(globalThis.Buffer.isBuffer(e)?e.length:globalThis.Buffer.byteLength(e,"utf8"))>this.referenceConfig.sizeThresholdBytes}async storeContentIfLarge(e,t){const s=globalThis.Buffer.isBuffer(e)?e:globalThis.Buffer.from(e,"utf8");if(!this.shouldUseReference(s))return null;const n={contentType:t.contentType||this.detectContentType(s,t.mimeType),sizeBytes:s.length,source:t.source,tags:[]};return void 0!==t.mimeType&&(n.mimeType=t.mimeType),void 0!==t.mcpToolName&&(n.mcpToolName=t.mcpToolName),void 0!==t.fileName&&(n.fileName=t.fileName),void 0!==t.tags&&(n.tags=t.tags),void 0!==t.customMetadata&&(n.customMetadata=t.customMetadata),await this.storeContent(s,n)}async storeContent(e,t){const s=Date.now();try{const n=new Date,r=H.generateId(e),o={...t,createdAt:n,lastAccessedAt:n,accessCount:0},i={content:e,metadata:o,state:"active"},a=this.calculateExpirationTime(t.source);void 0!==a&&(i.expiresAt=a),this.contentStore.set(r,i),this.updateStatsAfterStore(e.length),await this.enforceReferenceStorageLimits();const c=this.createContentPreview(e,o.contentType),g={contentType:o.contentType,sizeBytes:o.sizeBytes,source:o.source};void 0!==o.fileName&&(g.fileName=o.fileName),void 0!==o.mimeType&&(g.mimeType=o.mimeType);const l={referenceId:r,state:"active",preview:c,metadata:g,createdAt:n,format:"ref://{id}"},h=Date.now()-s;return this.recordPerformanceMetric("creation",h),console.log(`[ContentStorage] Stored content with reference ID: ${r} (${e.length} bytes)`),l}catch(n){const e=Date.now()-s;throw this.recordPerformanceMetric("creation",e),console.error("[ContentStorage] Failed to store content:",n),new $(`Failed to store content: ${n instanceof Error?n.message:"Unknown error"}`,"system_error",void 0,["Try again","Check storage limits","Contact administrator"])}}async resolveReference(e){const t=Date.now();try{if(!H.isValidReferenceId(e))return this.referenceStats.failedResolutions++,{success:!1,error:"Invalid reference ID format",errorType:"not_found",suggestedActions:["Check the reference ID format","Ensure the reference ID is complete"]};const s=this.contentStore.get(e);if(!s)return this.referenceStats.failedResolutions++,{success:!1,error:"Reference not found",errorType:"not_found",suggestedActions:["Verify the reference ID","Check if the content has expired","Request fresh content"]};if(s.expiresAt&&s.expiresAt<new Date)return s.state="expired",this.referenceStats.failedResolutions++,{success:!1,error:"Reference has expired",errorType:"expired",suggestedActions:["Request fresh content","Use alternative content source"]};if("active"!==s.state)return this.referenceStats.failedResolutions++,{success:!1,error:`Reference is ${s.state}`,errorType:"expired"===s.state?"expired":"corrupted",suggestedActions:["Request fresh content","Check reference validity"]};s.metadata.lastAccessedAt=new Date,s.metadata.accessCount++,this.referenceStats.totalResolutions++;const n=Date.now()-t;return this.recordPerformanceMetric("resolution",n),console.log(`[ContentStorage] Resolved reference ${e} (${s.content.length} bytes, access count: ${s.metadata.accessCount})`),{success:!0,content:s.content,metadata:s.metadata}}catch(s){const n=Date.now()-t;return this.recordPerformanceMetric("resolution",n),this.referenceStats.failedResolutions++,console.error(`[ContentStorage] Error resolving reference ${e}:`,s),{success:!1,error:`System error resolving reference: ${s instanceof Error?s.message:"Unknown error"}`,errorType:"system_error",suggestedActions:["Try again","Contact administrator"]}}}async hasReference(e){if(!H.isValidReferenceId(e))return!1;const t=this.contentStore.get(e);return!!t&&(t.expiresAt&&t.expiresAt<new Date?(t.state="expired",!1):"active"===t.state)}async cleanupReference(e){const t=this.contentStore.get(e);return!!t&&(this.referenceStats.totalStorageBytes-=t.content.length,this.referenceStats.activeReferences--,this.referenceStats.recentlyCleanedUp++,this.contentStore.delete(e),console.log(`[ContentStorage] Cleaned up reference ${e} (${t.content.length} bytes)`),!0)}async getStats(){return this.updateReferenceStorageStats(),{...this.referenceStats,performanceMetrics:{averageCreationTimeMs:this.calculateAverage(this.referenceStats.performanceMetrics.creationTimes),averageResolutionTimeMs:this.calculateAverage(this.referenceStats.performanceMetrics.resolutionTimes),averageCleanupTimeMs:this.calculateAverage(this.referenceStats.performanceMetrics.cleanupTimes)}}}async updateConfig(e){this.referenceConfig={...this.referenceConfig,...e},this.cleanupTimer&&(clearInterval(this.cleanupTimer),delete this.cleanupTimer),this.referenceConfig.enableAutoCleanup&&this.startReferenceCleanupTimer(),console.log("[ContentStorage] Reference configuration updated")}async performCleanup(){const e=Date.now(),t=[];let s=0;try{console.log("[ContentStorage] Starting reference cleanup process...");const r=new Date,o=[];for(const[e,t]of this.contentStore.entries()){let s=!1;t.expiresAt&&t.expiresAt<r&&(s=!0,t.state="expired");const n=r.getTime()-t.metadata.createdAt.getTime();n>this.getCleanupPolicy(t.metadata.source).maxAgeMs&&(s=!0),"cleanup_pending"===t.state&&(s=!0),s&&o.push(e)}o.sort((e,t)=>{const s=this.contentStore.get(e),n=this.contentStore.get(t),r=this.getCleanupPolicy(s.metadata.source).priority;return this.getCleanupPolicy(n.metadata.source).priority-r});for(const e of o)try{await this.cleanupReference(e)&&s++}catch(n){t.push(`Failed to cleanup ${e}: ${n instanceof Error?n.message:"Unknown error"}`)}if(this.contentStore.size>this.referenceConfig.maxReferences){const e=Array.from(this.contentStore.entries()).sort(([,e],[,t])=>e.metadata.lastAccessedAt.getTime()-t.metadata.lastAccessedAt.getTime()),r=this.contentStore.size-this.referenceConfig.maxReferences;for(let o=0;o<r&&o<e.length;o++){const[r]=e[o];try{await this.cleanupReference(r)&&s++}catch(n){t.push(`Failed to cleanup excess reference ${r}: ${n instanceof Error?n.message:"Unknown error"}`)}}}const i=Date.now()-e;return this.recordPerformanceMetric("cleanup",i),console.log(`[ContentStorage] Reference cleanup completed: ${s} references cleaned up, ${t.length} errors`),{cleanedUp:s,errors:t}}catch(n){const r=Date.now()-e;this.recordPerformanceMetric("cleanup",r);const o=`Cleanup process failed: ${n instanceof Error?n.message:"Unknown error"}`;return console.error("[ContentStorage]",o),t.push(o),{cleanedUp:s,errors:t}}}getReferenceConfig(){return{...this.referenceConfig}}async enforceReferenceStorageLimits(){this.contentStore.size>=this.referenceConfig.maxReferences&&await this.performCleanup(),this.referenceStats.totalStorageBytes>=this.referenceConfig.maxTotalStorageBytes&&await this.performCleanup()}calculateExpirationTime(e){const t=this.getCleanupPolicy(e);return new Date(Date.now()+t.maxAgeMs)}getCleanupPolicy(e){switch(e){case"mcp_tool":return this.referenceConfig.cleanupPolicies.recent;case"user_upload":return this.referenceConfig.cleanupPolicies.userContent;case"agent_generated":return this.referenceConfig.cleanupPolicies.agentGenerated;default:return this.referenceConfig.cleanupPolicies.default}}detectContentType(e,t){if(t)return"text/html"===t?"html":"text/markdown"===t?"markdown":"application/json"===t?"json":t.startsWith("text/")?"text":"binary";const s=e.toString("utf8",0,Math.min(e.length,1e3));return s.startsWith("{")||s.startsWith("[")?"json":s.includes("<html>")||s.includes("<!DOCTYPE")?"html":s.includes("#")&&s.includes("\n")?"markdown":"text"}createContentPreview(e,t){let s=e.toString("utf8",0,Math.min(e.length,400));if("html"===t)s=s.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim();else if("json"===t)try{const e=JSON.parse(s);s=JSON.stringify(e,null,0)}catch{}return s=s.trim(),s.length>200&&(s=s.substring(0,200)+"..."),s||"[Binary content]"}updateStatsAfterStore(e){this.referenceStats.activeReferences++,this.referenceStats.totalStorageBytes+=e,this.updateReferenceStorageStats()}updateReferenceStorageStats(){let e;this.referenceStats.activeReferences>0&&(this.referenceStats.averageContentSize=this.referenceStats.totalStorageBytes/this.referenceStats.activeReferences),this.referenceStats.storageUtilization=this.referenceStats.totalStorageBytes/this.referenceConfig.maxTotalStorageBytes*100;let t=0;for(const[s,n]of this.contentStore.entries())n.metadata.accessCount>t&&(t=n.metadata.accessCount,e=s);void 0!==e?this.referenceStats.mostAccessedReferenceId=e:delete this.referenceStats.mostAccessedReferenceId}recordPerformanceMetric(e,t){const s=this.referenceStats.performanceMetrics;switch(e){case"creation":s.creationTimes.push(t),s.creationTimes.length>100&&s.creationTimes.shift();break;case"resolution":s.resolutionTimes.push(t),s.resolutionTimes.length>100&&s.resolutionTimes.shift();break;case"cleanup":s.cleanupTimes.push(t),s.cleanupTimes.length>100&&s.cleanupTimes.shift()}}calculateAverage(e){return 0===e.length?0:e.reduce((e,t)=>e+t,0)/e.length}startReferenceCleanupTimer(){this.cleanupTimer=setInterval(async()=>{try{await this.performCleanup()}catch(e){console.error("[ContentStorage] Error in scheduled reference cleanup:",e)}},this.referenceConfig.cleanupIntervalMs)}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),delete this.cleanupTimer),this.contentStore.clear(),this.clear()}};N.DEFAULT_MAX_STORAGE=1e3;let _=N;const D=class e{constructor(t={}){this.config={...e.DEFAULT_CONFIG,...t},this.tokenCounter=new I(this.config.modelName),this.contentStorage=new _(this.config.storageLimit),this.memoryWindow=new B(this.config.maxTokens,this.config.reserveTokens,this.tokenCounter)}addMessage(e){const t=this.memoryWindow.addMessage(e);t.prunedMessages.length>0&&this.contentStorage.storeMessages(t.prunedMessages)}getMessages(){return this.memoryWindow.getMessages()}clear(e=!1){this.memoryWindow.clear(),e&&this.contentStorage.clear()}setSystemPrompt(e){this.memoryWindow.setSystemPrompt(e)}getSystemPrompt(){return this.memoryWindow.getSystemPrompt()}searchHistory(e,t={}){return this.contentStorage.searchMessages(e,t)}getRecentHistory(e){return this.contentStorage.getRecentMessages(e)}canAddMessage(e){return this.memoryWindow.canAddMessage(e)}getMemoryStats(){const e=this.memoryWindow.getStats();return{totalActiveMessages:e.totalMessages,currentTokenCount:e.currentTokens,maxTokens:e.maxTokens,remainingCapacity:e.remainingCapacity,systemPromptTokens:e.systemPromptTokens,usagePercentage:e.usagePercentage}}getStorageStats(){return this.contentStorage.getStorageStats()}getOverallStats(){const e=this.getMemoryStats(),t=this.getStorageStats();return{activeMemory:e,storage:t,totalMessagesManaged:e.totalActiveMessages+t.totalMessages,activeMemoryUtilization:e.usagePercentage,storageUtilization:t.usagePercentage}}updateConfig(e){this.config={...this.config,...e},void 0===e.maxTokens&&void 0===e.reserveTokens||this.memoryWindow.updateLimits(this.config.maxTokens,this.config.reserveTokens),void 0!==e.storageLimit&&this.contentStorage.updateStorageLimit(this.config.storageLimit)}getConfig(){return{...this.config}}getHistoryFromTimeRange(e,t){return this.contentStorage.getMessagesFromTimeRange(e,t)}getHistoryByType(e,t){return this.contentStorage.getMessagesByType(e,t)}getRecentHistoryByTime(e){return this.contentStorage.getRecentMessagesByTime(e)}exportState(){return{config:this.config,activeMessages:this.memoryWindow.getMessages().map(e=>({content:e.content,type:e._getType()})),systemPrompt:this.memoryWindow.getSystemPrompt(),memoryStats:this.getMemoryStats(),storageStats:this.getStorageStats(),storedMessages:this.contentStorage.exportMessages()}}getContextSummary(e=!1){const t=this.getMessages(),s={activeMessageCount:t.length,systemPrompt:this.getSystemPrompt(),recentMessages:t.slice(-5),memoryUtilization:this.getMemoryStats().usagePercentage,hasStoredHistory:this.getStorageStats().totalMessages>0};return e?{...s,recentStoredMessages:this.getRecentHistory(10),storageStats:this.getStorageStats()}:s}performMaintenance(){}dispose(){this.memoryWindow.dispose(),this.contentStorage.dispose(),this.tokenCounter.dispose()}};D.DEFAULT_CONFIG={maxTokens:8e3,reserveTokens:1e3,modelName:"gpt-4o",storageLimit:1e3};let K=D;class L extends v{constructor(){super(...arguments),this.systemMessage=""}async boot(){if(this.initialized)this.logger.warn("Agent already initialized");else try{this.agentKit=await this.createAgentKit(),await this.agentKit.initialize();const t=this.config.ai?.modelName||process.env.OPENAI_MODEL_NAME||"gpt-4o-mini";this.tokenTracker=new e.TokenUsageCallbackHandler(t);const s=this.agentKit.getAggregatedLangChainTools();this.tools=this.filterTools(s),this.config.mcp?.servers&&this.config.mcp.servers.length>0&&await this.initializeMCP(),this.smartMemory=new K({modelName:t,maxTokens:9e4,reserveTokens:1e4,storageLimit:1e3}),this.logger.info("SmartMemoryManager initialized:",{modelName:t,toolsCount:this.tools.length,maxTokens:9e4,reserveTokens:1e4}),this.systemMessage=this.buildSystemPrompt(),this.smartMemory.setSystemPrompt(this.systemMessage),await this.createExecutor(),this.initialized=!0,this.logger.info("LangChain Hedera agent initialized")}catch(t){throw this.logger.error("Failed to initialize agent:",t),t}}async chat(t,s){if(!this.initialized||!this.executor||!this.smartMemory)throw new Error("Agent not initialized. Call boot() first.");try{if(this.logger.info("LangChainAgent.chat called with:",{message:t,contextLength:s?.messages?.length||0}),s?.messages&&s.messages.length>0){this.smartMemory.clear();for(const e of s.messages)this.smartMemory.addMessage(e)}const{HumanMessage:r}=await import("@langchain/core/messages");this.smartMemory.addMessage(new r(t));const o=this.smartMemory.getMemoryStats();this.logger.info("Memory stats before execution:",{totalMessages:o.totalActiveMessages,currentTokens:o.currentTokenCount,maxTokens:o.maxTokens,usagePercentage:o.usagePercentage,toolsCount:this.tools.length});const i=await this.executor.invoke({input:t,chat_history:this.smartMemory.getMessages()});this.logger.info("LangChainAgent executor result:",i);let a={output:i.output||"",message:i.output||"",notes:[],intermediateSteps:i.intermediateSteps};if(i.intermediateSteps&&Array.isArray(i.intermediateSteps)){const e=i.intermediateSteps.map((e,t)=>({id:`call_${t}`,name:e.action?.tool||"unknown",args:e.action?.toolInput||{},output:"string"==typeof e.observation?e.observation:JSON.stringify(e.observation)}));e.length>0&&(a.tool_calls=e)}const c=i?.intermediateSteps?.[0]?.observation;if(c&&"string"==typeof c&&this.isJSON(c))try{const e=JSON.parse(c);a={...a,...e}}catch(n){this.logger.error("Error parsing intermediate steps:",n)}if(a.output&&""!==a.output.trim()||(a.output="Agent action complete."),a.output){const{AIMessage:e}=await import("@langchain/core/messages");this.smartMemory.addMessage(new e(a.output))}if(this.tokenTracker){const t=this.tokenTracker.getLatestTokenUsage();t&&(a.tokenUsage=t,a.cost=e.calculateTokenCostSync(t))}const g=this.smartMemory.getMemoryStats();return a.metadata={...a.metadata,memoryStats:{activeMessages:g.totalActiveMessages,tokenUsage:g.currentTokenCount,maxTokens:g.maxTokens,usagePercentage:g.usagePercentage}},this.logger.info("LangChainAgent.chat returning response:",a),a}catch(n){return this.logger.error("LangChainAgent.chat error:",n),this.handleError(n)}}async shutdown(){this.mcpManager&&await this.mcpManager.disconnectAll(),this.smartMemory&&(this.smartMemory.dispose(),this.smartMemory=void 0),this.executor=void 0,this.agentKit=void 0,this.tools=[],this.initialized=!1,this.logger.info("Agent cleaned up")}switchMode(e){this.config.execution?this.config.execution.operationalMode=e:this.config.execution={operationalMode:e},this.agentKit&&(this.agentKit.operationalMode=e),this.systemMessage=this.buildSystemPrompt(),this.logger.info(`Operational mode switched to: ${e}`)}getUsageStats(){if(!this.tokenTracker)return{promptTokens:0,completionTokens:0,totalTokens:0,cost:{totalCost:0}};const t=this.tokenTracker.getTotalTokenUsage(),s=e.calculateTokenCostSync(t);return{...t,cost:s}}getUsageLog(){return this.tokenTracker?this.tokenTracker.getTokenUsageHistory().map(t=>({...t,cost:e.calculateTokenCostSync(t)})):[]}clearUsageStats(){this.tokenTracker&&(this.tokenTracker.reset(),this.logger.info("Usage statistics cleared"))}async createAgentKit(){const t=[...e.getAllHederaCorePlugins(),...this.config.extensions?.plugins||[]],s=this.config.execution?.operationalMode||"returnBytes",n=this.config.ai?.modelName||"gpt-4o";return new e.HederaAgentKit(this.config.signer,{plugins:t},s,this.config.execution?.userAccountId,this.config.execution?.scheduleUserTransactionsInBytesMode??!0,void 0,n,this.config.extensions?.mirrorConfig,this.config.debug?.silent??!1)}async createExecutor(){let e;if(this.config.ai?.provider&&this.config.ai.provider.getModel)e=this.config.ai.provider.getModel();else if(this.config.ai?.llm)e=this.config.ai.llm;else{const t=this.config.ai?.apiKey||process.env.OPENAI_API_KEY;if(!t)throw new Error("OpenAI API key required");e=new c.ChatOpenAI({apiKey:t,modelName:this.config.ai?.modelName||"gpt-4o-mini",temperature:this.config.ai?.temperature??.1,callbacks:this.tokenTracker?[this.tokenTracker]:[]})}const t=a.ChatPromptTemplate.fromMessages([["system",this.systemMessage],new a.MessagesPlaceholder("chat_history"),["human","{input}"],new a.MessagesPlaceholder("agent_scratchpad")]),s=this.tools,n=await i.createOpenAIToolsAgent({llm:e,tools:s,prompt:t});this.executor=new M({agent:n,tools:s,verbose:this.config.debug?.verbose??!1,returnIntermediateSteps:!0})}handleError(t){const s=t instanceof Error?t.message:"Unknown error";let n,r;this.logger.error("Chat error:",t),this.tokenTracker&&(n=this.tokenTracker.getLatestTokenUsage(),n&&(r=e.calculateTokenCostSync(n)));const o={output:"Sorry, I encountered an error processing your request.",message:"Error processing request.",error:s,notes:[]};return n&&(o.tokenUsage=n),r&&(o.cost=r),o}async initializeMCP(){this.mcpManager=new k(this.logger);for(const e of this.config.mcp.servers){if(!1===e.autoConnect){this.logger.info(`Skipping MCP server ${e.name} (autoConnect=false)`);continue}const t=await this.mcpManager.connectServer(e);if(t.connected){this.logger.info(`Connected to MCP server ${t.serverName} with ${t.tools.length} tools`);for(const s of t.tools){const t=b(s,this.mcpManager,e);this.tools.push(t)}}else this.logger.error(`Failed to connect to MCP server ${t.serverName}: ${t.error}`)}}isJSON(e){if("string"!=typeof e)return!1;const t=e.trim();if(!t)return!1;if(!(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")))return!1;try{return JSON.parse(t),!0}catch{return!1}}}function U(e){const t=e.framework||"langchain";switch(t){case"langchain":return new L(e);case"vercel":throw new Error("Vercel AI SDK support coming soon");case"baml":throw new Error("BAML support coming soon");default:throw new Error(`Unknown framework: ${t}`)}}class F{constructor(e){this.model=e}async generate(e,t){const s=await this.model.invoke(e,t);return"string"==typeof s?s:s.toString()}async*stream(e,t){const s=await this.model.stream(e,t);for await(const n of s)yield"string"==typeof n?n:n.toString()}getModel(){return this.model}}const j=e=>`You are a helpful assistant managing Hashgraph Online HCS-10 connections, messages, HCS-2 registries, and content inscription.\n\nYou have access to tools for:\n- HCS-10: registering agents, finding registered agents, initiating connections, listing active connections, sending messages over connections, and checking for new messages\n- HCS-2: creating registries, registering entries, updating entries, deleting entries, migrating registries, and querying registry contents\n- Inscription: inscribing content from URLs, files, or buffers, creating Hashinal NFTs, and retrieving inscriptions\n\n*** IMPORTANT CONTEXT ***\nYou are currently operating as agent: ${e} on the Hashgraph Online network\nWhen users ask about "my profile", "my account", "my connections", etc., use this account ID: ${e}\n\nRemember the connection numbers when listing connections, as users might refer to them.`;class q{constructor(e){this.storage=e}async storeContent(e,t){return(await this.storage.storeContent(e,t)).referenceId}async resolveReference(e){const t=await this.storage.resolveReference(e);if(t.success&&t.content){const e={content:t.content};return t.metadata&&(e.metadata={...void 0!==t.metadata.mimeType&&{mimeType:t.metadata.mimeType},...void 0!==t.metadata.fileName&&{fileName:t.metadata.fileName},originalSize:t.metadata.sizeBytes}),e}throw new Error(t.error||"Reference not found")}async hasReference(e){return await this.storage.hasReference(e)}async cleanupReference(e){await this.storage.cleanupReference(e)}async getStats(){return await this.storage.getStats()}async updateConfig(e){return await this.storage.updateConfig(e)}async performCleanup(){await this.storage.performCleanup()}async dispose(){return Promise.resolve(this.storage.dispose())}}class W{constructor(e){this.adapter=e}async resolveReference(e){return await this.adapter.resolveReference(e)}shouldUseReference(e){return s.shouldUseReference(e)}extractReferenceId(e){return s.extractReferenceId(e)}}class J{constructor(e=1e3,t,s){this.isRegistered=!1,this.logger=s||{info:console.log,debug:console.log,warn:console.warn,error:console.error},this.contentStorage=new _(e,t),this.adapter=new q(this.contentStorage),this.resolver=new W(this.adapter)}async initialize(){if(this.isRegistered)this.logger.warn("ContentStoreManager is already initialized");else try{await s.ContentStoreService.setInstance(this.adapter),s.ContentResolverRegistry.register(this.resolver),this.isRegistered=!0,this.logger.info("ContentStoreManager initialized and registered for cross-package access")}catch(e){throw this.logger.error("Failed to initialize ContentStoreManager:",e),e}}getContentStorage(){return this.contentStorage}async getStats(){return await this.contentStorage.getStats()}async updateConfig(e){return await this.contentStorage.updateConfig(e)}async performCleanup(){return await this.contentStorage.performCleanup()}shouldUseReference(e){return this.contentStorage.shouldUseReference(e)}async storeContentIfLarge(e,t){return await this.contentStorage.storeContentIfLarge(e,t)}async dispose(){this.isRegistered&&(this.contentStorage.dispose(),s.ContentStoreService.dispose(),s.ContentResolverRegistry.unregister(),this.isRegistered=!1,this.logger.info("ContentStoreManager disposed and unregistered"))}isInitialized(){return this.isRegistered}}const Y="gpt-4o",G="testnet",V="autonomous";class Z{constructor(e){this.options=e,this.stateManager=e.stateManager||new t.OpenConvaiState,this.hcs10Plugin=new p,this.hcs2Plugin=new f,this.inscribePlugin=new y,this.hbarTransferPlugin=new x,this.logger=new s.Logger({module:"ConversationalAgent",silent:e.disableLogging||!1})}async initialize(){const{accountId:t,privateKey:s,network:n=G,openAIApiKey:r,openAIModelName:o=Y}=this.options;this.validateOptions(t,s);try{const i=await this.detectPrivateKeyType(t,s,n),a=new e.ServerSigner(t,i,n),g=this.preparePlugins(),l=new c.ChatOpenAI({apiKey:r,modelName:o,temperature:.1}),h=this.createAgentConfig(a,l,g);this.agent=U(h),this.configureHCS10Plugin(g),this.options.mcpServers&&this.options.mcpServers.length>0&&(this.contentStoreManager=new J,await this.contentStoreManager.initialize(),this.logger.info("ContentStoreManager initialized for MCP content reference support")),await this.agent.boot()}catch(i){throw this.logger.error("Failed to initialize ConversationalAgent:",i),i}}getPlugin(){return this.hcs10Plugin}getStateManager(){return this.stateManager}getAgent(){if(!this.agent)throw new Error("Agent not initialized. Call initialize() first.");return this.agent}getConversationalAgent(){return this.getAgent()}async processMessage(e,t=[]){if(!this.agent)throw new Error("Agent not initialized. Call initialize() first.");const s={messages:t.map(e=>"human"===e.type?new d.HumanMessage(e.content):new d.AIMessage(e.content))};return this.agent.chat(e,s)}validateOptions(e,t){if(!e||!t)throw new Error("Account ID and private key are required")}preparePlugins(){const{additionalPlugins:t=[],enabledPlugins:s}=this.options,n=[this.hcs10Plugin,this.hcs2Plugin,this.inscribePlugin,this.hbarTransferPlugin],r=e.getAllHederaCorePlugins();if(s){const e=new Set(s);return[...[...n,...r].filter(t=>e.has(t.id)),...t]}return[...n,...r,...t]}createAgentConfig(e,t,s){const{operationalMode:n=V,userAccountId:r,scheduleUserTransactionsInBytesMode:o,customSystemMessagePreamble:i,customSystemMessagePostamble:a,verbose:c=!1,mirrorNodeConfig:g,disableLogging:l,accountId:h=""}=this.options;return{framework:"langchain",signer:e,execution:{mode:"autonomous"===n?"direct":"bytes",operationalMode:n,...r&&{userAccountId:r},...void 0!==o&&{scheduleUserTransactions:o}},ai:{provider:new F(t),temperature:.1},filtering:{toolPredicate:e=>"hedera-account-transfer-hbar"!==e.name&&!(this.options.toolFilter&&!this.options.toolFilter(e))},messaging:{systemPreamble:i||j(h),...a&&{systemPostamble:a},conciseMode:!0},extensions:{plugins:s,...g&&{mirrorConfig:g}},...this.options.mcpServers&&{mcp:{servers:this.options.mcpServers,autoConnect:!0}},debug:{verbose:c,silent:l??!1}}}configureHCS10Plugin(e){const t=e.find(e=>"hcs-10"===e.id);t&&(t.appConfig={stateManager:this.stateManager})}static withPlugins(e,t){return new Z({...e,enabledPlugins:t})}static withHTS(e){return this.withPlugins(e,["hts-token"])}static withHCS2(e){return this.withPlugins(e,["hcs-2"])}static withHCS10(e){return this.withPlugins(e,["hcs-10"])}static withInscribe(e){return this.withPlugins(e,["inscribe"])}static withAccount(e){return this.withPlugins(e,["account"])}static withFileService(e){return this.withPlugins(e,["file-service"])}static withConsensusService(e){return this.withPlugins(e,["consensus-service"])}static withSmartContract(e){return this.withPlugins(e,["smart-contract"])}static withAllStandards(e){return this.withPlugins(e,["hcs-10","hcs-2","inscribe"])}static minimal(e){return this.withPlugins(e,[])}static withMCP(e,t){return new Z({...e,mcpServers:t})}async detectPrivateKeyType(e,t,n){const o=new s.HederaMirrorNode(n),i=await o.requestAccount(e),a=i?.key?._type||"";return a?.toLowerCase()?.includes("ecdsa")?r.PrivateKey.fromStringECDSA(t):r.PrivateKey.fromStringED25519(t)}async cleanup(){this.contentStoreManager&&(await this.contentStoreManager.dispose(),this.logger.info("ContentStoreManager cleaned up")),this.agent}}exports.BaseAgent=v,exports.ConversationalAgent=Z,exports.HCS10Plugin=p,exports.HCS2Plugin=f,exports.HbarTransferPlugin=x,exports.InscribePlugin=y,exports.LangChainAgent=L,exports.LangChainProvider=F,exports.MCPServers={filesystem:e=>({name:"filesystem",command:"npx",args:["-y","@modelcontextprotocol/server-filesystem",e],transport:"stdio",autoConnect:!0,additionalContext:"This server provides access to files and directories in the current working directory.",toolDescriptions:{list_directory:'Use this tool when users ask about files in the "current directory" or "working directory".',read_file:"Use this tool when users ask to see or check files in the current directory."}}),github:e=>({name:"github",command:"npx",args:["-y","@modelcontextprotocol/server-github"],...e&&{env:{GITHUB_TOKEN:e}},transport:"stdio",autoConnect:!0}),slack:e=>({name:"slack",command:"npx",args:["-y","@modelcontextprotocol/server-slack"],env:{SLACK_TOKEN:e},transport:"stdio",autoConnect:!0}),googleDrive:e=>({name:"google-drive",command:"npx",args:["-y","@modelcontextprotocol/server-google-drive"],env:{GOOGLE_CREDENTIALS:e},transport:"stdio",autoConnect:!0}),postgres:e=>({name:"postgres",command:"npx",args:["-y","@modelcontextprotocol/server-postgres",e],transport:"stdio",autoConnect:!0}),sqlite:e=>({name:"sqlite",command:"npx",args:["-y","@modelcontextprotocol/server-sqlite",e],transport:"stdio",autoConnect:!0}),custom:e=>e},exports.OpenConvAIPlugin=p,exports.createAgent=U,exports.createMCPConfig=function(e,t=!0){return{mcpServers:e.map(e=>({...e,autoConnect:e.autoConnect??t}))}},exports.validateServerConfig=function(e){const t=[];return e.name||t.push("Server name is required"),e.command||t.push("Server command is required"),e.args&&Array.isArray(e.args)||t.push("Server args must be an array"),e.transport&&!["stdio","http","websocket"].includes(e.transport)&&t.push("Invalid transport type. Must be stdio, http, or websocket"),t},Object.keys(e).forEach(t=>{"default"===t||Object.prototype.hasOwnProperty.call(exports,t)||Object.defineProperty(exports,t,{enumerable:!0,get:()=>e[t]})});
2
2
  //# sourceMappingURL=index.cjs.map