@hashgraphonline/conversational-agent 0.1.208 → 0.1.210

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/bin/conversational-agent-cli.js +30 -0
  2. package/cli/readme.md +181 -0
  3. package/dist/cjs/base-agent.d.ts +3 -1
  4. package/dist/cjs/conversational-agent.d.ts +64 -13
  5. package/dist/cjs/index.cjs +1 -1
  6. package/dist/cjs/index.cjs.map +1 -1
  7. package/dist/cjs/index.d.ts +6 -3
  8. package/dist/cjs/langchain-agent.d.ts +11 -0
  9. package/dist/cjs/memory/SmartMemoryManager.d.ts +65 -22
  10. package/dist/cjs/memory/TokenCounter.d.ts +1 -1
  11. package/dist/cjs/memory/index.d.ts +1 -1
  12. package/dist/cjs/plugins/hbar/AirdropToolWrapper.d.ts +43 -0
  13. package/dist/{types/plugins/hbar-transfer/HbarTransferPlugin.d.ts → cjs/plugins/hbar/HbarPlugin.d.ts} +2 -1
  14. package/dist/{types/plugins/hbar-transfer → cjs/plugins/hbar}/TransferHbarTool.d.ts +1 -1
  15. package/dist/cjs/plugins/hbar/index.d.ts +3 -0
  16. package/dist/cjs/plugins/index.d.ts +2 -1
  17. package/dist/cjs/services/EntityResolver.d.ts +26 -0
  18. package/dist/cjs/tools/EntityResolverTool.d.ts +104 -0
  19. package/dist/cjs/types/inscription.d.ts +37 -0
  20. package/dist/esm/index.js +16 -2
  21. package/dist/esm/index.js.map +1 -1
  22. package/dist/esm/index12.js +121 -46
  23. package/dist/esm/index12.js.map +1 -1
  24. package/dist/esm/index13.js +177 -13
  25. package/dist/esm/index13.js.map +1 -1
  26. package/dist/esm/index14.js +599 -100
  27. package/dist/esm/index14.js.map +1 -1
  28. package/dist/esm/index15.js +426 -9
  29. package/dist/esm/index15.js.map +1 -1
  30. package/dist/esm/index16.js +119 -160
  31. package/dist/esm/index16.js.map +1 -1
  32. package/dist/esm/index17.js +140 -150
  33. package/dist/esm/index17.js.map +1 -1
  34. package/dist/esm/index18.js +44 -231
  35. package/dist/esm/index18.js.map +1 -1
  36. package/dist/esm/index19.js +86 -643
  37. package/dist/esm/index19.js.map +1 -1
  38. package/dist/esm/index2.js +22 -13
  39. package/dist/esm/index2.js.map +1 -1
  40. package/dist/esm/index20.js +20 -230
  41. package/dist/esm/index20.js.map +1 -1
  42. package/dist/esm/index21.js +9 -179
  43. package/dist/esm/index21.js.map +1 -1
  44. package/dist/esm/index22.js +140 -89
  45. package/dist/esm/index22.js.map +1 -1
  46. package/dist/esm/index23.js +141 -81
  47. package/dist/esm/index23.js.map +1 -1
  48. package/dist/esm/index24.js +4 -4
  49. package/dist/esm/index24.js.map +1 -1
  50. package/dist/esm/index25.js +0 -8
  51. package/dist/esm/index25.js.map +1 -1
  52. package/dist/esm/index26.js +95 -0
  53. package/dist/esm/index26.js.map +1 -0
  54. package/dist/esm/index27.js +242 -0
  55. package/dist/esm/index27.js.map +1 -0
  56. package/dist/esm/index5.js +32 -19
  57. package/dist/esm/index5.js.map +1 -1
  58. package/dist/esm/index6.js +276 -37
  59. package/dist/esm/index6.js.map +1 -1
  60. package/dist/esm/index7.js +2 -2
  61. package/dist/esm/index7.js.map +1 -1
  62. package/dist/esm/index8.js +124 -18
  63. package/dist/esm/index8.js.map +1 -1
  64. package/dist/types/base-agent.d.ts +3 -1
  65. package/dist/types/conversational-agent.d.ts +64 -13
  66. package/dist/types/index.d.ts +6 -3
  67. package/dist/types/langchain-agent.d.ts +11 -0
  68. package/dist/types/memory/SmartMemoryManager.d.ts +65 -22
  69. package/dist/types/memory/TokenCounter.d.ts +1 -1
  70. package/dist/types/memory/index.d.ts +1 -1
  71. package/dist/types/plugins/hbar/AirdropToolWrapper.d.ts +43 -0
  72. package/dist/{cjs/plugins/hbar-transfer/HbarTransferPlugin.d.ts → types/plugins/hbar/HbarPlugin.d.ts} +2 -1
  73. package/dist/{cjs/plugins/hbar-transfer → types/plugins/hbar}/TransferHbarTool.d.ts +1 -1
  74. package/dist/types/plugins/hbar/index.d.ts +3 -0
  75. package/dist/types/plugins/index.d.ts +2 -1
  76. package/dist/types/services/EntityResolver.d.ts +26 -0
  77. package/dist/types/tools/EntityResolverTool.d.ts +104 -0
  78. package/dist/types/types/inscription.d.ts +37 -0
  79. package/package.json +13 -4
  80. package/src/base-agent.ts +14 -9
  81. package/src/config/system-message.ts +11 -2
  82. package/src/context/ReferenceContextManager.ts +10 -5
  83. package/src/context/ReferenceResponseProcessor.ts +3 -4
  84. package/src/conversational-agent.ts +372 -57
  85. package/src/index.ts +19 -3
  86. package/src/langchain/ContentAwareAgentExecutor.ts +0 -1
  87. package/src/langchain-agent.ts +168 -33
  88. package/src/mcp/ContentProcessor.ts +11 -3
  89. package/src/mcp/adapters/langchain.ts +1 -10
  90. package/src/memory/ContentStorage.ts +2 -55
  91. package/src/memory/MemoryWindow.ts +4 -17
  92. package/src/memory/ReferenceIdGenerator.ts +4 -8
  93. package/src/memory/SmartMemoryManager.ts +375 -47
  94. package/src/memory/TokenCounter.ts +15 -22
  95. package/src/memory/index.ts +1 -1
  96. package/src/plugins/hbar/AirdropToolWrapper.ts +157 -0
  97. package/src/plugins/hbar/HbarPlugin.ts +86 -0
  98. package/src/plugins/{hbar-transfer → hbar}/TransferHbarTool.ts +3 -3
  99. package/src/plugins/hbar/index.ts +3 -0
  100. package/src/plugins/hcs-10/HCS10Plugin.ts +44 -14
  101. package/src/plugins/index.ts +2 -1
  102. package/src/services/ContentStoreManager.ts +0 -3
  103. package/src/services/EntityResolver.ts +135 -0
  104. package/src/tools/EntityResolverTool.ts +170 -0
  105. package/src/types/content-reference.ts +8 -8
  106. package/src/types/index.ts +0 -1
  107. package/src/types/inscription.ts +40 -0
  108. package/dist/cjs/plugins/hbar-transfer/index.d.ts +0 -1
  109. package/dist/types/plugins/hbar-transfer/index.d.ts +0 -1
  110. package/src/plugins/hbar-transfer/HbarTransferPlugin.ts +0 -66
  111. package/src/plugins/hbar-transfer/index.ts +0 -1
  112. /package/dist/cjs/plugins/{hbar-transfer → hbar}/AccountBuilder.d.ts +0 -0
  113. /package/dist/cjs/plugins/{hbar-transfer → hbar}/types.d.ts +0 -0
  114. /package/dist/types/plugins/{hbar-transfer → hbar}/AccountBuilder.d.ts +0 -0
  115. /package/dist/types/plugins/{hbar-transfer → hbar}/types.d.ts +0 -0
  116. /package/src/plugins/{hbar-transfer → hbar}/AccountBuilder.ts +0 -0
  117. /package/src/plugins/{hbar-transfer → hbar}/types.ts +0 -0
@@ -1,2 +1,2 @@
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 T 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 w=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.")}),S=n.z.object({transfers:n.z.array(w).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=S,this.namespace="account"}getServiceBuilder(){return new T(this.hederaKit)}async callBuilderMethod(e,t){await e.transferHbar(t)}}class M 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 x extends i.AgentExecutor{constructor(e){super(e),this.logger=new s.Logger({module:"ContentAwareAgentExecutor"})}}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 k{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 b{constructor(e,t){this.clients=new Map,this.tools=new Map,this.logger=e,t&&(this.contentProcessor=new k(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 k(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 A(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 I=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)}}};I.MESSAGE_OVERHEAD=3,I.ROLE_OVERHEAD=1;let E=I;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 E}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 K=class e{constructor(t={}){this.config={...e.DEFAULT_CONFIG,...t},this.tokenCounter=new E(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()}};K.DEFAULT_CONFIG={maxTokens:8e3,reserveTokens:1e3,modelName:"gpt-4o",storageLimit:1e3};let D=K;class U 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 D({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 x({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 b(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=A(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 L(e){const t=e.framework||"langchain";switch(t){case"langchain":return new U(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 M,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=L(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=M,exports.InscribePlugin=y,exports.LangChainAgent=U,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=L,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"),n=require("@hashgraphonline/standards-sdk"),s=require("zod"),r=require("@hashgraph/sdk"),o=require("bignumber.js"),i=require("@langchain/core/tools"),a=require("langchain/agents"),c=require("@langchain/core/prompts"),g=require("@langchain/openai"),l=require("@modelcontextprotocol/sdk/client/index.js"),h=require("@modelcontextprotocol/sdk/client/stdio.js"),u=require("tiktoken"),m=require("crypto"),d=require("@langchain/anthropic"),p=require("@langchain/core/messages");class f 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 s=e.config.hederaKit;if(s)try{this.stateManager=e.stateManager||e.config.stateManager||this.appConfig?.stateManager||new t.OpenConvaiState;const i=s.signer.getAccountId().toString();let a="",c="";try{const e=s.signer.getOperatorPrivateKey(),t="function"==typeof e?.toStringRaw?e.toStringRaw():"function"==typeof e?.toString?e.toString():String(e),r=new n.HCS10Client({network:s.network,operatorId:i,operatorPrivateKey:t,logLevel:"error"}),o=await r.retrieveProfile(i);o.success&&o.topicInfo&&(a=o.topicInfo.inboundTopic,c=o.topicInfo.outboundTopic)}catch(r){this.context.logger.warn("Could not retrieve profile topics:",r)}if(this.stateManager.setCurrentAgent({name:`Agent ${i}`,accountId:i,inboundTopicId:a,outboundTopicId:c,privateKey:(()=>{const e=s.signer.getOperatorPrivateKey();return"function"==typeof e?.toStringRaw?e.toStringRaw():"function"==typeof e?.toString?e.toString():String(e)})()}),this.context.logger.info(`Set current agent: ${i} with topics ${a}/${c}`),this.stateManager&&!this.stateManager.getConnectionsManager())try{const e=s.signer.getOperatorPrivateKey(),t="function"==typeof e?.toStringRaw?e.toStringRaw():"function"==typeof e?.toString?e.toString():String(e),r=new n.HCS10Client({network:s.network,operatorId:i,operatorPrivateKey:t,logLevel:"error"});this.stateManager.initializeConnectionsManager(r),this.context.logger.info("ConnectionsManager initialized in HCS10Plugin")}catch(o){this.context.logger.warn("Could not initialize ConnectionsManager:",o)}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 y 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 w 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 T extends e.BaseServiceBuilder{constructor(e){super(e)}transferHbar(e,t=!0){this.clearNotes();const n=new r.TransferTransaction;if(!e.transfers||0===e.transfers.length)throw new Error("HbarTransferParams must include at least one transfer.");let s=new o(0),i=!1;if(t&&this.kit.userAccountId&&"provideBytes"===this.kit.operationalMode&&1===e.transfers.length){const t=e.transfers[0],s="string"==typeof t.amount||"number"==typeof t.amount?t.amount:t.amount.toString(),a=new o(s);if(a.isPositive()){const e="string"==typeof t.accountId?r.AccountId.fromString(t.accountId):t.accountId,s=a.toFixed(8,o.ROUND_DOWN),c=r.Hbar.fromString(s);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(r.AccountId.fromString(this.kit.userAccountId),c.negated()),i=!0}}if(!i){const t=[];for(const n of e.transfers){const e="string"==typeof n.accountId?r.AccountId.fromString(n.accountId):n.accountId,i="string"==typeof n.amount||"number"==typeof n.amount?n.amount:n.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();s=s.plus(l.toString())}if(!s.isZero()&&(this.logger.warn(`Transfer sum not zero: ${s.toString()} tinybars off. Adjusting last transfer.`),t.length>0)){const e=t[t.length-1],n=s.dividedBy(-1e8),i=e.amount.plus(n).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)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 S=s.z.object({accountId:s.z.string().describe('Account ID for the transfer (e.g., "0.0.xxxx").'),amount:s.z.union([s.z.number(),s.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.")}),C=s.z.object({transfers:s.z.array(S).min(1).describe('Array of transfers. For simple transfers from your operator account, just include the recipient with positive amount: [{accountId: "0.0.800", amount: 1}]. For complex multi-party transfers, include all parties with negative amounts for senders and positive for receivers.'),memo:s.z.string().optional().describe("Optional. Memo for the transaction.")});class M extends e.BaseHederaTransactionTool{constructor(){super(...arguments),this.name="hedera-account-transfer-hbar-v2",this.description='PRIMARY TOOL FOR HBAR TRANSFERS: Transfers HBAR between accounts. For simple transfers from the operator account, just specify the recipient with a positive amount (e.g., [{accountId: "0.0.800", amount: 1}] to send 1 HBAR to 0.0.800). The sender will be automatically added. For multi-party transfers (e.g., "A sends 5 HBAR to C and B sends 3 HBAR to C"), include ALL transfers with their amounts (negative for senders, positive for receivers).',this.specificInputSchema=C,this.namespace="account"}getServiceBuilder(){return new T(this.hederaKit)}async callBuilderMethod(e,t){await e.transferHbar(t)}}class v extends i.StructuredTool{constructor(e,t){super(),this.name="hedera-hts-airdrop-token",this.description="Airdrops fungible tokens to multiple recipients. Automatically converts human-readable amounts to smallest units based on token decimals.",this.schema=s.z.object({tokenId:s.z.string().describe('The ID of the fungible token to airdrop (e.g., "0.0.yyyy").'),recipients:s.z.array(s.z.object({accountId:s.z.string().describe('Recipient account ID (e.g., "0.0.xxxx").'),amount:s.z.union([s.z.number(),s.z.string()]).describe('Amount in human-readable format (e.g., "10" for 10 tokens).')})).min(1).describe("Array of recipient objects, each with accountId and amount."),memo:s.z.string().optional().describe("Optional. Memo for the transaction.")}),this.originalTool=e,this.agentKit=t,this.logger=new n.Logger({module:"AirdropToolWrapper"})}async _call(e){try{this.logger.info(`Processing airdrop request for token ${e.tokenId} with ${e.recipients.length} recipients`);const t=(await this.getTokenInfo(e.tokenId)).decimals||0;this.logger.info(`Token ${e.tokenId} has ${t} decimal places`);const n=e.recipients.map(e=>{const n="string"==typeof e.amount?parseFloat(e.amount):e.amount,s=this.convertToSmallestUnits(n,t);return this.logger.info(`Converting amount for ${e.accountId}: ${n} tokens → ${s} smallest units`),{...e,amount:s.toString()}}),s={...e,recipients:n};return this.logger.info("Calling original airdrop tool with converted amounts"),await this.originalTool._call(s)}catch(t){throw this.logger.error("Error in airdrop tool wrapper:",t),t}}convertToSmallestUnits(e,t){return Math.floor(e*Math.pow(10,t))}async getTokenInfo(e){return await this.queryTokenInfo(e)}async queryTokenInfo(e){try{this.logger.info("Querying token info using mirror node");const t=this.agentKit.mirrorNode;if(t){const n=await t.getTokenInfo(e);if(n&&void 0!==n.decimals){const t=parseInt(n.decimals.toString())||0;return this.logger.info(`Token ${e} found with ${t} decimals`),{...n,decimals:t}}}else{this.logger.info("MirrorNode not found in agentKit, attempting to access via fetch");const t="mainnet"===(this.agentKit.network||"testnet")?"https://mainnet.mirrornode.hedera.com":"https://testnet.mirrornode.hedera.com",n=await fetch(`${t}/api/v1/tokens/${e}`);if(n.ok){const t=await n.json(),s=parseInt(String(t.decimals||"0"));return this.logger.info(`Token ${e} found with ${s} decimals via API`),{...t,decimals:s}}}throw new Error("Token data not found or missing decimals field")}catch(t){return this.logger.warn(`Failed to query token info for ${e}:`,t),this.logger.info("Falling back to assumed 0 decimal places (smallest units)"),{decimals:0}}}}class x extends e.BasePlugin{constructor(){super(...arguments),this.id="hbar",this.name="HBAR Plugin",this.description="HBAR operations: transfer tool with robust decimal handling and compatibility with airdrop improvements",this.version="1.0.0",this.author="Hashgraph Online",this.namespace="account",this.tools=[],this.originalAirdropTool=null}async initialize(e){await super.initialize(e);if(e.config.hederaKit)try{this.initializeTools(),this.context.logger.info("HBAR Plugin initialized successfully")}catch(t){this.context.logger.error("Failed to initialize HBAR plugin:",t)}else this.context.logger.warn("HederaKit not found in context. HBAR tools will not be available.")}initializeTools(){const t=this.context.config.hederaKit;if(!t)throw new Error("HederaKit not found in context config");const n=new M({hederaKit:t,logger:this.context.logger});this.tools=[n];try{this.context.logger.info("Creating wrapper for passed original airdrop tool");const n=new e.HederaAirdropTokenTool({hederaKit:t,logger:this.context.logger}),s=new v(n,t);this.tools.push(s),this.context.logger.info("Added wrapped airdrop tool to HBAR Plugin")}catch(s){this.context.logger.error("Error creating airdrop tool wrapper:",s)}this.context.logger.info(`HBAR Plugin tools initialized with ${this.tools.length} tools`)}getTools(){return this.tools}async shutdown(){this.tools=[]}}class k extends a.AgentExecutor{constructor(e){super(e),this.logger=new n.Logger({module:"ContentAwareAgentExecutor"})}}class A{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 Hashgraph. 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 when possible. 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. IMPORTANT: Only use metaOption 'returnBytes: true' for tools that explicitly support it (like HBAR transfers, token operations). Many tools (inscriptions, HCS-2, HCS-20, etc.) do NOT support returnBytes and will execute directly - this is expected behavior. For tools without returnBytes support, simply call them with their standard parameters. If you need raw bytes for the user to sign for their own account ${n||"if specified"}, ensure the tool constructs the transaction body accordingly when returnBytes IS supported.`),!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 b{constructor(e,t){this.contentStorage=e,this.logger=t}analyzeResponse(e){const t=[];let n=0;this.extractContentFromResponse(e,t),n=t.reduce((e,t)=>e+t.sizeBytes,0);const s=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:n,largestContentSize:s}}async processResponse(e,t,n){try{const s=this.analyzeResponse(e);if(!s.shouldProcess)return{content:e,wasProcessed:!1};return await this.createReferencedResponse(e,s,t,n)}catch(s){return this.logger.error("Error processing MCP response:",s),{content:e,wasProcessed:!1,errors:[s instanceof Error?s.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 n=e;if("text"===n.type&&"string"==typeof n.text)return void t.push({content:n.text,type:"text",sizeBytes:globalThis.Buffer.byteLength(n.text,"utf8"),mimeType:this.detectMimeType(n.text)});if("image"===n.type&&"string"==typeof n.data)return void t.push({content:n.data,type:"image",sizeBytes:Math.ceil(.75*n.data.length),mimeType:n.mimeType||"image/jpeg"});if("resource"===n.type&&n.resource){const e=JSON.stringify(n.resource);return void t.push({content:e,type:"resource",sizeBytes:globalThis.Buffer.byteLength(e,"utf8"),mimeType:"application/json"})}return void Object.values(n).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,n,s){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:`${n}::${s}`,tags:["mcp_response",n,s]};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,n){if(null!=e)if(Array.isArray(e))for(let s=0;s<e.length;s++)e[s]===t?e[s]=n:this.replaceContentInResponse(e[s],t,n);else if("object"==typeof e){const s=e;if("text"===s.type&&s.text===t){for(const e of Object.keys(s))delete s[e];for(const e of Object.keys(n))s[e]=n[e];return}for(const e in s)s[e]===t?s[e]=n:this.replaceContentInResponse(s[e],t,n)}}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 n in e)e.hasOwnProperty(n)&&(t[n]=this.deepClone(e[n]));return t}}class P{constructor(e,t){this.clients=new Map,this.tools=new Map,this.logger=e,t&&(this.contentProcessor=new b(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 h.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 s=(await n.listTools()).tools.map(t=>({...t,serverName:e.name}));return this.tools.set(e.name,s),this.logger.info(`Connected to MCP server ${e.name} with ${s.length} tools`),{serverName:e.name,connected:!0,tools:s}}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 s=this.clients.get(e);if(!s)throw new Error(`MCP server ${e} not connected`);this.logger.debug(`Executing MCP tool ${t} on server ${e}`,n);try{const r=await s.callTool({name:t,arguments:n});if(this.contentProcessor){const n=await this.contentProcessor.processResponse(r,e,t);return n.wasProcessed&&(this.logger.debug(`Processed MCP response from ${e}::${t}`,{referenceCreated:n.referenceCreated,originalSize:n.originalSize,errors:n.errors}),n.errors&&n.errors.length>0&&this.logger.warn(`Content processing warnings for ${e}::${t}:`,n.errors)),n.content}return r}catch(r){throw this.logger.error(`Error executing MCP tool ${t}:`,r),r}}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())}enableContentProcessing(e){this.contentProcessor=new b(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 I(e,t,s){const r=R(e.inputSchema),o=`${e.serverName}_${e.name}`.replace(/[^a-zA-Z0-9_]/g,"_");let a=e.description||`MCP tool ${e.name} from ${e.serverName}`;return s?.toolDescriptions?.[e.name]&&(a=`${a}\n\n${s.toolDescriptions[e.name]}`),s?.additionalContext&&(a=`${a}\n\nContext: ${s.additionalContext}`),new i.DynamicStructuredTool({name:o,description:a,schema:r,func:async s=>{try{const o=await t.executeTool(e.serverName,e.name,s);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"),c=10240;if(a.length>c||n.shouldUseReference(a)){const t=n.ContentStoreService.getInstance();if(t)try{return`content-ref:${await t.storeContent(a,{contentType:"text",source:"mcp",mcpToolName:`${e.serverName}_${e.name}`,originalSize:a.length})}`}catch(r){}}return i}catch(o){const t=o instanceof Error?o.message:"Unknown error";return`Error executing MCP tool ${e.name}: ${t}`}}})}function R(e){if(!e||"object"!=typeof e)return s.z.object({});const t=e;if(t.type&&"object"!==t.type)return E(t);if(!t.properties||"object"!=typeof t.properties)return s.z.object({});const n={};for(const[s,r]of Object.entries(t.properties)){let e=E(r);Array.isArray(t.required)&&t.required.includes(s)||(e=e.optional()),n[s]=e}return s.z.object(n)}function E(e){if(!e||"object"!=typeof e||!("type"in e))return s.z.unknown();const t=e;let n;switch(t.type){case"string":n=s.z.string(),t.enum&&Array.isArray(t.enum)&&(n=s.z.enum(t.enum));break;case"number":n=s.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=s.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=s.z.boolean();break;case"array":n=t.items?s.z.array(E(t.items)):s.z.array(s.z.unknown());break;case"object":n="properties"in t?R(t):s.z.object({}).passthrough();break;default:n=s.z.unknown()}return"description"in t&&"string"==typeof t.description&&(n=n.describe(t.description)),n}const z=class e{constructor(e="gpt-4o"){this.modelName=String(e);try{this.encoding=u.encoding_for_model(e)}catch{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 Math.ceil(1.3*e.split(/\s+/).length)}}countMessageTokens(t){return this.countTokens(String(t.content??""))+this.countTokens(this.getMessageRole(t))+e.MESSAGE_OVERHEAD+e.ROLE_OVERHEAD}countMessagesTokens(e){if(!e||0===e.length)return 0;let t=0;for(const n of e)t+=this.countMessageTokens(n);return t}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{}}};z.MESSAGE_OVERHEAD=3,z.ROLE_OVERHEAD=1;let B=z;const O=class e{constructor(t=e.DEFAULT_MAX_TOKENS,n=e.DEFAULT_RESERVE_TOKENS,s){if(this.messages=[],this.systemPrompt="",this.systemPromptTokens=0,n>=t)throw new Error("Reserve tokens must be less than max tokens");this.maxTokens=t,this.reserveTokens=n,this.tokenCounter=s||new B}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=[],n=this.maxTokens-this.reserveTokens;for(;this.getCurrentTokenCount()>n&&this.messages.length>0;){const n=Math.min(e.PRUNING_BATCH_SIZE,this.messages.length);for(let e=0;e<n;e++){const e=this.messages.shift();e&&t.push(e)}if(t.length>1e3)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),n=this.getCurrentTokenCount()+t>this.maxTokens-this.reserveTokens;return!(t>this.maxTokens)&&(!n||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,n=e/t*100;return{totalMessages:this.messages.length,currentTokens:e,maxTokens:t,reserveTokens:this.reserveTokens,systemPromptTokens:this.systemPromptTokens,usagePercentage:Math.round(100*n)/100,remainingCapacity:this.getRemainingTokenCapacity(),canAcceptMore:this.getRemainingTokenCapacity()>this.reserveTokens}}dispose(){this.clear(),this.tokenCounter.dispose()}};O.DEFAULT_MAX_TOKENS=8e3,O.DEFAULT_RESERVE_TOKENS=1e3,O.PRUNING_BATCH_SIZE=2;let N=O;class ${static generateId(e){const t=m.createHash("sha256");return t.update(e),t.digest("hex")}static isValidReferenceId(e){return!(!e||"string"!=typeof e)&&(64===e.length&&/^[a-f0-9]+$/.test(e))}static extractReferenceId(e){if(!e||"string"!=typeof e)return null;const t=e.match(/^ref:\/\/([a-f0-9]{64})$/);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 H={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,n,s){super(e),this.type=t,this.referenceId=n,this.suggestedActions=s,this.name="ContentReferenceError"}}const D=class e{constructor(t=e.DEFAULT_MAX_STORAGE,n){this.messages=[],this.idCounter=0,this.contentStore=new Map,this.maxStorage=t,this.referenceConfig={...H,...n},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 n=0;const s=e.map(e=>({message:e,storedAt:t,id:this.generateId()}));for(this.messages.push(...s);this.messages.length>this.maxStorage;)this.messages.shift(),n++;return{stored:s.length,dropped:n}}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:n=!1,limit:s,useRegex:r=!1}=t;let o=[];if(r)try{const t=new RegExp(e,n?"g":"gi");o=this.messages.filter(e=>t.test(e.message.content)).map(e=>e.message)}catch(i){return[]}else{const t=n?e:e.toLowerCase();o=this.messages.filter(e=>{const s=e.message.content;return(n?s:s.toLowerCase()).includes(t)}).map(e=>e.message)}return s?o.slice(0,s):o}getMessagesFromTimeRange(e,t){return e>t||0===this.messages.length?[]:this.messages.filter(n=>n.storedAt>=e&&n.storedAt<=t).map(e=>e.message)}getStorageStats(){const e=this.messages.length,t=e>0?Math.round(e/this.maxStorage*100):0;let n,s;return e>0&&(n=this.messages[0].storedAt,s=this.messages[e-1].storedAt),{totalMessages:e,maxStorageLimit:this.maxStorage,usagePercentage:t,oldestMessageTime:n,newestMessageTime:s}}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 n=this.messages.filter(t=>t.message._getType()===e).map(e=>e.message);return t?n.slice(0,t):n}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 n=globalThis.Buffer.isBuffer(e)?e:globalThis.Buffer.from(e,"utf8");if(!this.shouldUseReference(n))return null;const s={contentType:t.contentType||this.detectContentType(n,t.mimeType),sizeBytes:n.length,source:t.source,tags:[]};return void 0!==t.mimeType&&(s.mimeType=t.mimeType),void 0!==t.mcpToolName&&(s.mcpToolName=t.mcpToolName),void 0!==t.fileName&&(s.fileName=t.fileName),void 0!==t.tags&&(s.tags=t.tags),void 0!==t.customMetadata&&(s.customMetadata=t.customMetadata),await this.storeContent(n,s)}async storeContent(e,t){const n=Date.now();try{const s=new Date,r=$.generateId(e),o={...t,createdAt:s,lastAccessedAt:s,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:s,format:"ref://{id}"},h=Date.now()-n;return this.recordPerformanceMetric("creation",h),l}catch(s){const e=Date.now()-n;throw this.recordPerformanceMetric("creation",e),new _(`Failed to store content: ${s instanceof Error?s.message:"Unknown error"}`,"system_error",void 0,["Try again","Check storage limits","Contact administrator"])}}async resolveReference(e){const t=Date.now();try{if(!$.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 n=this.contentStore.get(e);if(!n)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(n.expiresAt&&n.expiresAt<new Date)return n.state="expired",this.referenceStats.failedResolutions++,{success:!1,error:"Reference has expired",errorType:"expired",suggestedActions:["Request fresh content","Use alternative content source"]};if("active"!==n.state)return this.referenceStats.failedResolutions++,{success:!1,error:`Reference is ${n.state}`,errorType:"expired"===n.state?"expired":"corrupted",suggestedActions:["Request fresh content","Check reference validity"]};n.metadata.lastAccessedAt=new Date,n.metadata.accessCount++,this.referenceStats.totalResolutions++;const s=Date.now()-t;return this.recordPerformanceMetric("resolution",s),{success:!0,content:n.content,metadata:n.metadata}}catch(n){const e=Date.now()-t;return this.recordPerformanceMetric("resolution",e),this.referenceStats.failedResolutions++,{success:!1,error:`System error resolving reference: ${n instanceof Error?n.message:"Unknown error"}`,errorType:"system_error",suggestedActions:["Try again","Contact administrator"]}}}async hasReference(e){if(!$.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),!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()}async performCleanup(){const e=Date.now(),t=[];let n=0;try{const r=new Date,o=[];for(const[e,t]of this.contentStore.entries()){let n=!1;t.expiresAt&&t.expiresAt<r&&(n=!0,t.state="expired");const s=r.getTime()-t.metadata.createdAt.getTime();s>this.getCleanupPolicy(t.metadata.source).maxAgeMs&&(n=!0),"cleanup_pending"===t.state&&(n=!0),n&&o.push(e)}o.sort((e,t)=>{const n=this.contentStore.get(e),s=this.contentStore.get(t),r=this.getCleanupPolicy(n.metadata.source).priority;return this.getCleanupPolicy(s.metadata.source).priority-r});for(const e of o)try{await this.cleanupReference(e)&&n++}catch(s){t.push(`Failed to cleanup ${e}: ${s instanceof Error?s.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)&&n++}catch(s){t.push(`Failed to cleanup excess reference ${r}: ${s instanceof Error?s.message:"Unknown error"}`)}}}const i=Date.now()-e;return this.recordPerformanceMetric("cleanup",i),{cleanedUp:n,errors:t}}catch(s){const r=Date.now()-e;this.recordPerformanceMetric("cleanup",r);const o=`Cleanup process failed: ${s instanceof Error?s.message:"Unknown error"}`;return t.push(o),{cleanedUp:n,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 n=e.toString("utf8",0,Math.min(e.length,1e3));return n.startsWith("{")||n.startsWith("[")?"json":n.includes("<html>")||n.includes("<!DOCTYPE")?"html":n.includes("#")&&n.includes("\n")?"markdown":"text"}createContentPreview(e,t){let n=e.toString("utf8",0,Math.min(e.length,400));if("html"===t)n=n.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim();else if("json"===t)try{const e=JSON.parse(n);n=JSON.stringify(e,null,0)}catch{}return n=n.trim(),n.length>200&&(n=n.substring(0,200)+"..."),n||"[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[n,s]of this.contentStore.entries())s.metadata.accessCount>t&&(t=s.metadata.accessCount,e=n);void 0!==e?this.referenceStats.mostAccessedReferenceId=e:delete this.referenceStats.mostAccessedReferenceId}recordPerformanceMetric(e,t){const n=this.referenceStats.performanceMetrics;switch(e){case"creation":n.creationTimes.push(t),n.creationTimes.length>100&&n.creationTimes.shift();break;case"resolution":n.resolutionTimes.push(t),n.resolutionTimes.length>100&&n.resolutionTimes.shift();break;case"cleanup":n.cleanupTimes.push(t),n.cleanupTimes.length>100&&n.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){}},this.referenceConfig.cleanupIntervalMs)}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),delete this.cleanupTimer),this.contentStore.clear(),this.clear()}};D.DEFAULT_MAX_STORAGE=1e3;let L=D;const K='"isEntityAssociation":true',U=class e{constructor(t={}){this.config={...e.DEFAULT_CONFIG,...t},this.tokenCounter=new B(this.config.modelName),this._contentStorage=new L(this.config.storageLimit),this.memoryWindow=new N(this.config.maxTokens,this.config.reserveTokens,this.tokenCounter)}get contentStorage(){return this._contentStorage}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(),n={activeMessageCount:t.length,systemPrompt:this.getSystemPrompt(),recentMessages:t.slice(-5),memoryUtilization:this.getMemoryStats().usagePercentage,hasStoredHistory:this.getStorageStats().totalMessages>0};return e?{...n,recentStoredMessages:this.getRecentHistory(10),storageStats:this.getStorageStats()}:n}performMaintenance(){}storeEntityAssociation(e,t,n,s){try{if(!e||"string"!=typeof e||0===e.trim().length)return;if(!t||"string"!=typeof t||0===t.trim().length)return;if(!n||"string"!=typeof n||0===n.trim().length)return;const r=e.trim(),o=t.trim().substring(0,100),i=n.trim().toLowerCase(),a={entityId:r,entityName:o,entityType:i,createdAt:new Date,isEntityAssociation:!0,...null!=s&&""!==s.trim()?{transactionId:s.trim()}:{}},c={_getType:()=>"system",content:JSON.stringify(a),id:`entity_${r}_${Date.now()}`,name:"entity_association",additional_kwargs:{entityId:r,entityName:o,entityType:i,isEntityAssociation:!0}};this._contentStorage.storeMessages([c])}catch(r){}}resolveEntityReference(e,t={}){try{if(!e||"string"!=typeof e)return[];const n=e.trim();if(0===n.length)return[];n.length;const{entityType:s,limit:r=10,fuzzyMatch:o=!0}=t,i=Math.max(1,Math.min(r||10,100)),a=/^0\.0\.\d+$/.test(n),c=this._contentStorage.searchMessages(n.substring(0,200),{caseSensitive:!1,limit:2*i}),g=[];for(const e of c)try{const t=e.content;if(t.includes(K)||t.includes("entityId")){const e=JSON.parse(t);if(e.entityId&&e.entityName&&e.entityType){if(s&&e.entityType!==s)continue;if(a&&e.entityId!==n)continue;g.push(e)}}}catch{continue}if(o&&0===g.length&&!a){const t=[e.toLowerCase(),"token","account",s||""].filter(Boolean);for(const n of t){if(n===e.toLowerCase())continue;const t=this._contentStorage.searchMessages(n,{caseSensitive:!1,limit:r});for(const e of t)try{const t=e.content;if(t.includes(K)){const e=JSON.parse(t);if(e.entityId&&e.entityName&&e.entityType){if(s&&e.entityType!==s)continue;g.push(e)}}}catch{continue}}}const l=g.filter((e,t,n)=>n.findIndex(t=>t.entityId===e.entityId)===t).sort((e,t)=>new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime());return l.slice(0,i)}catch(n){return[]}}getEntityAssociations(e){try{const n=e?e.trim().toLowerCase():void 0;if(e&&(!n||0===n.length))return[];const s=n||"entityId",r=this._contentStorage.searchMessages(s,{caseSensitive:!1,limit:100}),o=[];for(const e of r)try{const t=e.content;if(t.includes(K)){const e=JSON.parse(t);if(e.entityId&&e.entityName&&e.entityType){if(n&&e.entityType!==n)continue;e.createdAt&&"string"==typeof e.createdAt&&(e.createdAt=new Date(e.createdAt)),o.push(e)}}}catch(t){continue}return o.filter((e,t,n)=>n.findIndex(t=>t.entityId===e.entityId)===t).sort((e,t)=>{const n=e=>e instanceof Date?e.getTime():new Date(e).getTime(),s=n(e.createdAt);return n(t.createdAt)-s})}catch(n){return[]}}dispose(){this.memoryWindow.dispose(),this._contentStorage.dispose(),this.tokenCounter.dispose()}};U.DEFAULT_CONFIG={maxTokens:8e3,reserveTokens:1e3,modelName:"gpt-4o",storageLimit:1e3};let F=U;class j extends A{constructor(){super(...arguments),this.systemMessage="",this.mcpConnectionStatus=new Map}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&&(!1!==this.config.mcp.autoConnect?await this.initializeMCP():(this.logger.info("MCP servers configured but autoConnect=false, skipping synchronous connection"),this.mcpManager=new P(this.logger))),this.smartMemory=new F({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,n){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:n?.messages?.length||0}),n?.messages&&n.messages.length>0){this.smartMemory.clear();for(const e of n.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(s){this.logger.error("Error parsing intermediate steps:",s)}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(s){return this.logger.error("LangChainAgent.chat error:",s),this.handleError(s)}}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(),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"))}getMCPConnectionStatus(){return new Map(this.mcpConnectionStatus)}async createAgentKit(){const t=[...e.getAllHederaCorePlugins(),...this.config.extensions?.plugins||[]],n=this.config.execution?.operationalMode||"returnBytes",s=this.config.ai?.modelName||"gpt-4o";return new e.HederaAgentKit(this.config.signer,{plugins:t},n,this.config.execution?.userAccountId,this.config.execution?.scheduleUserTransactionsInBytesMode??!1,void 0,s,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");const n=this.config.ai?.modelName||"gpt-4o-mini",s=n.toLowerCase().includes("gpt-5")||n.toLowerCase().includes("gpt5");e=new g.ChatOpenAI({apiKey:t,modelName:n,callbacks:this.tokenTracker?[this.tokenTracker]:[],...s?{temperature:1}:{}})}const t=c.ChatPromptTemplate.fromMessages([["system",this.systemMessage],new c.MessagesPlaceholder("chat_history"),["human","{input}"],new c.MessagesPlaceholder("agent_scratchpad")]),n=this.tools,s=await a.createOpenAIToolsAgent({llm:e,tools:n,prompt:t});this.executor=new k({agent:s,tools:n,verbose:this.config.debug?.verbose??!1,returnIntermediateSteps:!0})}handleError(t){const n=t instanceof Error?t.message:"Unknown error";let s,r;this.logger.error("Chat error:",t),this.tokenTracker&&(s=this.tokenTracker.getLatestTokenUsage(),s&&(r=e.calculateTokenCostSync(s)));let o=n,i=n;n.includes("429")?n.includes("quota")?(o="API quota exceeded. Please check your OpenAI billing and usage limits.",i="I'm currently unable to respond because the API quota has been exceeded. Please check your OpenAI account billing and usage limits, then try again."):(o="Too many requests. Please wait a moment and try again.",i="I'm receiving too many requests right now. Please wait a moment and try again."):n.includes("401")||n.includes("unauthorized")?(o="API authentication failed. Please check your API key configuration.",i="There's an issue with the API authentication. Please check your OpenAI API key configuration in settings."):n.includes("timeout")?(o="Request timed out. Please try again.",i="The request took too long to process. Please try again."):n.includes("network")||n.includes("fetch")?(o="Network error. Please check your internet connection and try again.",i="There was a network error. Please check your internet connection and try again."):n.includes("400")&&(o=n,i=n);const a={output:i,message:o,error:n,notes:[]};return s&&(a.tokenUsage=s),r&&(a.cost=r),a}async initializeMCP(){this.mcpManager=new P(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=I(n,this.mcpManager,e);this.tools.push(t)}}else this.logger.error(`Failed to connect to MCP server ${t.serverName}: ${t.error}`)}}async connectMCPServers(){this.config.mcp?.servers&&0!==this.config.mcp.servers.length&&(this.mcpManager||(this.mcpManager=new P(this.logger)),this.logger.info(`Starting background MCP server connections for ${this.config.mcp.servers.length} servers...`),this.config.mcp.servers.forEach(e=>{this.connectServerInBackground(e)}),this.logger.info("MCP server connections initiated in background"))}connectServerInBackground(e){const t=e.name;setTimeout(async()=>{try{this.logger.info(`Background connecting to MCP server: ${t}`);const n=await this.mcpManager.connectServer(e);if(this.mcpConnectionStatus.set(t,n),n.connected){this.logger.info(`Successfully connected to MCP server ${n.serverName} with ${n.tools.length} tools`);for(const t of n.tools){const n=I(t,this.mcpManager,e);this.tools.push(n)}this.initialized&&this.executor&&(this.logger.info(`Recreating executor with ${this.tools.length} total tools`),await this.createExecutor())}else this.logger.error(`Failed to connect to MCP server ${n.serverName}: ${n.error}`)}catch(n){this.logger.error(`Background connection failed for MCP server ${t}:`,n),this.mcpConnectionStatus.set(t,{connected:!1,serverName:t,tools:[],error:n instanceof Error?n.message:"Connection failed"})}},1e3)}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 q(e){const t=e.framework||"langchain";switch(t){case"langchain":return new j(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 W{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 s of n)yield"string"==typeof s?s:s.toString()}getModel(){return this.model}}const J=e=>`You are a helpful assistant managing Hashgraph Online HCS-10 connections, messages, HCS-2 registries, content inscription, and Hedera Hashgraph operations.\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- Hedera Token Service (HTS): creating tokens, transferring tokens, airdropping tokens, and managing token operations\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\n*** CRITICAL ENTITY HANDLING RULES ***\n- When users refer to entities (tokens, topics, accounts) with pronouns like "it", "that", "the token/topic", etc., ALWAYS use the most recently created entity of that type\n- Entity IDs look like "0.0.XXXXXX" and are stored in memory after creation\n- NEVER use example or placeholder IDs like "0.0.123456" - always use actual created entity IDs\n- Account ID ${e} is NOT a token - tokens and accounts are different entities\n\nRemember the connection numbers when listing connections, as users might refer to them.`;class Y{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 G{constructor(e){this.adapter=e}async resolveReference(e){return await this.adapter.resolveReference(e)}shouldUseReference(e){return n.shouldUseReference(e)}extractReferenceId(e){return n.extractReferenceId(e)}}class V{constructor(e=1e3,t,n){this.isRegistered=!1,this.logger=n||{info:console.log,debug:console.log,warn:console.warn,error:console.error},this.contentStorage=new L(e,t),this.adapter=new Y(this.contentStorage),this.resolver=new G(this.adapter)}async initialize(){if(this.isRegistered)this.logger.warn("ContentStoreManager is already initialized");else try{await n.ContentStoreService.setInstance(this.adapter),n.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(),n.ContentStoreService.dispose(),n.ContentResolverRegistry.unregister(),this.isRegistered=!1,this.logger.info("ContentStoreManager disposed and unregistered"))}isInitialized(){return this.isRegistered}}const X=s.z.object({message:s.z.string().describe("The message containing entity references to resolve"),entities:s.z.array(s.z.object({entityId:s.z.string(),entityName:s.z.string(),entityType:s.z.string()})).describe("Available entities in memory")}),Z=s.z.object({response:s.z.string().describe("Agent response text to extract entities from"),userMessage:s.z.string().describe("Original user message for context")});class Q extends i.StructuredTool{constructor(e,t="gpt-4o-mini"){super(),this.name="resolve_entities",this.description='Resolves entity references like "the topic", "it", "that" to actual entity IDs',this.schema=X,this.llm=new g.ChatOpenAI({apiKey:e,modelName:t,temperature:0})}async _call(e){const{message:t,entities:n}=e;if(!n||0===n.length)return t;const s=this.groupEntitiesByType(n),r=`Task: Replace entity references with IDs.\n\n${this.buildEntityContext(s)}\n\nMessage: "${t}"\n\nRules:\n- "the topic" or "that topic" → replace with most recent topic ID\n- "the token" or "that token" → replace with most recent token ID\n- "it" or "that" after action verb → replace with most recent entity ID\n- "airdrop X" without token ID → add most recent token ID as first parameter\n- Token operations without explicit token → use most recent token ID\n\nExamples:\n- "submit on the topic" → "submit on 0.0.6543472"\n- "airdrop the token" → "airdrop 0.0.123456"\n- "airdrop 10 to 0.0.5842697" → "airdrop 0.0.123456 10 to 0.0.5842697"\n- "mint 100" → "mint 0.0.123456 100"\n\nReturn ONLY the resolved message:`;try{return(await this.llm.invoke(r)).content.trim()}catch(o){return console.error("[ResolveEntitiesTool] Failed:",o),t}}groupEntitiesByType(e){return e.reduce((e,t)=>(e[t.entityType]||(e[t.entityType]=[]),e[t.entityType].push(t),e),{})}buildEntityContext(e){let t="Available entities:\n";for(const[n,s]of Object.entries(e)){const e=s[0];t+=`- Most recent ${n}: "${e.entityName}" = ${e.entityId}\n`}return t}}class ee extends i.StructuredTool{constructor(e,t="gpt-4o-mini"){super(),this.name="extract_entities",this.description="Extracts newly created entities from agent responses",this.schema=Z,this.llm=new g.ChatOpenAI({apiKey:e,modelName:t,temperature:0})}async _call(e){const{response:t,userMessage:n}=e,s=`Extract ONLY newly created entities from this response.\n\nUser asked: "${n.substring(0,200)}"\nResponse: ${t.substring(0,3e3)}\n\nLook for:\n- Success messages with new entity IDs\n- Words like "created", "new", "successfully" followed by entity IDs\n\nReturn JSON array of created entities:\n[{"id": "0.0.XXX", "name": "name", "type": "topic|token|account"}]\n\nIf none created, return: []\n\nJSON:`;try{const e=await this.llm.invoke(s),t=e.content.match(/\[[\s\S]*?\]/);return t?t[0]:"[]"}catch(r){return console.error("[ExtractEntitiesTool] Failed:",r),"[]"}}}function te(e,t="gpt-4o-mini"){return{resolveEntities:new Q(e,t),extractEntities:new ee(e,t)}}const ne="gpt-4o",se="testnet",re="autonomous";class oe{constructor(e){if(this.options=e,this.stateManager=e.stateManager||new t.OpenConvaiState,this.hcs10Plugin=new f,this.hcs2Plugin=new y,this.inscribePlugin=new w,this.hbarPlugin=new x,this.logger=new n.Logger({module:"ConversationalAgent",silent:e.disableLogging||!1}),!1!==this.options.entityMemoryEnabled){if(!e.openAIApiKey)throw new Error("OpenAI API key is required when entity memory is enabled");this.memoryManager=new F(this.options.entityMemoryConfig),this.logger.info("Entity memory initialized"),this.entityTools=te(e.openAIApiKey,"gpt-4o-mini"),this.logger.info("LLM-based entity resolver tools initialized")}}async initialize(){const{accountId:t,privateKey:n,network:s=se,openAIApiKey:r,openAIModelName:o=ne,llmProvider:i="openai"}=this.options;this.validateOptions(t,n);try{const a=await this.detectPrivateKeyType(t,n,s),c=new e.ServerSigner(t,a,s);let l;if("anthropic"===i)l=new d.ChatAnthropic({apiKey:r,modelName:o||"claude-3-5-sonnet-20241022",temperature:.1});else{const e=o||"gpt-4o-mini",t=e.toLowerCase().includes("gpt-5")||e.toLowerCase().includes("gpt5");l=new g.ChatOpenAI({apiKey:r,modelName:o,...t?{temperature:1}:{temperature:.1}})}const h=this.preparePlugins(),u=this.createAgentConfig(c,l,h);if(this.agent=q(u),this.configureHCS10Plugin(h),this.contentStoreManager=new V,await this.contentStoreManager.initialize(),this.logger.info("ContentStoreManager initialized for content reference support"),await this.agent.boot(),this.agent){const e=u;e.filtering=e.filtering||{};const t=e.filtering.toolPredicate,n=this.options.toolFilter;e.filtering.toolPredicate=e=>(!e||"hedera-account-transfer-hbar"!==e.name)&&((!e||"hedera-hts-airdrop-token"!==e.name)&&(!(t&&!t(e))&&!(n&&!n(e))))}this.options.mcpServers&&this.options.mcpServers.length>0&&this.connectMCP()}catch(a){throw this.logger.error("Failed to initialize ConversationalAgent:",a),a}}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.");try{const n=this.memoryManager?await this.resolveEntitiesInMessage(e):e,s={messages:t.map(e=>"human"===e.type?new p.HumanMessage(e.content):new p.AIMessage(e.content))},r=await this.agent.chat(n,s);return this.memoryManager&&await this.extractAndStoreEntities(r,e),this.logger.info("Message processed successfully"),r}catch(n){throw this.logger.error("Error processing message:",n),n}}validateOptions(e,t){if(!e||!t)throw new Error("Account ID and private key are required")}preparePlugins(){const{additionalPlugins:t=[],enabledPlugins:n}=this.options,s=[this.hcs10Plugin,this.hcs2Plugin,this.inscribePlugin,this.hbarPlugin],r=e.getAllHederaCorePlugins();if(n){const e=new Set(n);return[...[...s,...r].filter(t=>e.has(t.id)),...t]}return[...s,...r,...t]}createAgentConfig(e,t,n){const{operationalMode:s=re,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"===s?"direct":"bytes",operationalMode:s,...r&&{userAccountId:r},...void 0!==o&&{scheduleUserTransactionsInBytesMode:o,scheduleUserTransactions:o}},ai:{provider:new W(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:n,...g&&{mirrorConfig:g}},...this.options.mcpServers&&{mcp:{servers:this.options.mcpServers,autoConnect:!1}},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 oe({...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 oe({...e,mcpServers:t})}async detectPrivateKeyType(e,t,s){const o=new n.HederaMirrorNode(s),i=await o.requestAccount(e),a=i?.key?._type||"";return a?.toLowerCase()?.includes("ecdsa")?r.PrivateKey.fromStringECDSA(t):r.PrivateKey.fromStringED25519(t)}async resolveEntitiesInMessage(e){if(!this.memoryManager||!this.entityTools)return e;try{const t=this.memoryManager.getEntityAssociations();if(0===t.length)return this.logger.info("No entities in memory, skipping resolution"),e;this.logger.info(`Starting LLM-based entity resolution for: "${e.substring(0,100)}..."`);const n=await this.entityTools.resolveEntities.call({message:e,entities:t.map(e=>({entityId:e.entityId,entityName:e.entityName,entityType:e.entityType}))});return n!==e&&this.logger.info(`Entity resolution completed. Original: "${e}" -> Resolved: "${n}"`),n}catch(t){throw this.logger.error("Entity resolution failed:",t),t}}async extractAndStoreEntities(e,t){if(this.memoryManager&&this.entityTools)try{this.logger.info("Starting LLM-based entity extraction");const s=this.extractResponseText(e),r=await this.entityTools.extractEntities.call({response:s,userMessage:t});try{const t=JSON.parse(r);for(const n of t){this.logger.info(`Storing entity: ${n.name} (${n.type}) -> ${n.id}`);const t=this.extractTransactionId(e);this.memoryManager.storeEntityAssociation(n.id,n.name,n.type,t)}t.length>0?this.logger.info(`Stored ${t.length} entities via LLM extraction`):this.logger.info("No entities found in response via LLM extraction")}catch(n){throw this.logger.error("Failed to parse extracted entities JSON:",n),n}}catch(s){throw this.logger.error("Entity extraction failed:",s),s}}extractTransactionId(e){try{if("object"==typeof e&&e&&"transactionId"in e)return e.transactionId;if("string"==typeof e){const t=e.match(/transaction[\s\w]*ID[\s:"]*([0-9a-fA-F@\.\-]+)/i);return t?t[1]:void 0}return}catch{return}}connectMCP(){this.agent&&this.options.mcpServers&&this.agent.connectMCPServers().catch(e=>{this.logger.error("Failed to connect MCP servers:",e)}).then(()=>{this.logger.info("MCP servers connected successfully")})}getMCPConnectionStatus(){return this.agent?this.agent.getMCPConnectionStatus():new Map}isMCPServerConnected(e){if(this.agent){const t=this.agent.getMCPConnectionStatus().get(e);return t?.connected??!1}return!1}async cleanup(){try{if(this.logger.info("Cleaning up ConversationalAgent..."),this.memoryManager){try{this.memoryManager.dispose(),this.logger.info("Memory manager cleaned up successfully")}catch(e){this.logger.warn("Error cleaning up memory manager:",e)}this.memoryManager=void 0}this.contentStoreManager&&(await this.contentStoreManager.dispose(),this.logger.info("ContentStoreManager cleaned up")),this.logger.info("ConversationalAgent cleanup completed")}catch(e){this.logger.error("Error during cleanup:",e)}}extractResponseText(e){return"string"==typeof e?e:e&&"object"==typeof e&&"output"in e?String(e.output):JSON.stringify(e)}}exports.BaseAgent=A,exports.ContentStorage=L,exports.ContentStoreManager=V,exports.ConversationalAgent=oe,exports.ExtractEntitiesTool=ee,exports.HCS10Plugin=f,exports.HCS2Plugin=y,exports.HbarPlugin=x,exports.InscribePlugin=w,exports.LangChainAgent=j,exports.LangChainProvider=W,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.MemoryWindow=N,exports.OpenConvAIPlugin=f,exports.ResolveEntitiesTool=Q,exports.SmartMemoryManager=F,exports.TokenCounter=B,exports.createAgent=q,exports.createEntityTools=te,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