@hashgraphonline/conversational-agent 0.1.215 → 0.1.217
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/conversational-agent.d.ts +8 -0
- package/dist/cjs/core/ToolRegistry.d.ts +130 -0
- package/dist/cjs/execution/ExecutionPipeline.d.ts +81 -0
- package/dist/cjs/forms/FormEngine.d.ts +121 -0
- package/dist/cjs/forms/form-generator.d.ts +39 -2
- package/dist/cjs/forms/types.d.ts +21 -2
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.ts +3 -4
- package/dist/cjs/langchain/FormAwareAgentExecutor.d.ts +53 -4
- package/dist/cjs/langchain/FormValidatingToolWrapper.d.ts +43 -6
- package/dist/cjs/langchain-agent.d.ts +49 -0
- package/dist/cjs/memory/ContentStorage.d.ts +7 -0
- package/dist/cjs/memory/SmartMemoryManager.d.ts +1 -0
- package/dist/cjs/services/ContentStoreManager.d.ts +11 -1
- package/dist/cjs/utils/ResponseFormatter.d.ts +26 -0
- package/dist/esm/index.js +2 -6
- package/dist/esm/index12.js +1 -1
- package/dist/esm/index12.js.map +1 -1
- package/dist/esm/index14.js +23 -5
- package/dist/esm/index14.js.map +1 -1
- package/dist/esm/index15.js +25 -4
- package/dist/esm/index15.js.map +1 -1
- package/dist/esm/index16.js +4 -2
- package/dist/esm/index16.js.map +1 -1
- package/dist/esm/index17.js +2 -7
- package/dist/esm/index17.js.map +1 -1
- package/dist/esm/index18.js +292 -150
- package/dist/esm/index18.js.map +1 -1
- package/dist/esm/index19.js +158 -65
- package/dist/esm/index19.js.map +1 -1
- package/dist/esm/index20.js +94 -270
- package/dist/esm/index20.js.map +1 -1
- package/dist/esm/index21.js +1 -1
- package/dist/esm/index23.js +14 -0
- package/dist/esm/index23.js.map +1 -1
- package/dist/esm/index24.js +508 -12
- package/dist/esm/index24.js.map +1 -1
- package/dist/esm/index25.js +1 -1
- package/dist/esm/index25.js.map +1 -1
- package/dist/esm/index26.js +1 -1
- package/dist/esm/index26.js.map +1 -1
- package/dist/esm/index27.js +189 -128
- package/dist/esm/index27.js.map +1 -1
- package/dist/esm/index28.js +164 -45
- package/dist/esm/index28.js.map +1 -1
- package/dist/esm/index29.js +302 -24
- package/dist/esm/index29.js.map +1 -1
- package/dist/esm/index30.js +144 -80
- package/dist/esm/index30.js.map +1 -1
- package/dist/esm/index31.js +63 -7
- package/dist/esm/index31.js.map +1 -1
- package/dist/esm/index32.js +24 -236
- package/dist/esm/index32.js.map +1 -1
- package/dist/esm/index33.js +95 -0
- package/dist/esm/index33.js.map +1 -0
- package/dist/esm/index34.js +245 -0
- package/dist/esm/index34.js.map +1 -0
- package/dist/esm/index5.js.map +1 -1
- package/dist/esm/index6.js +61 -22
- package/dist/esm/index6.js.map +1 -1
- package/dist/esm/index8.js +653 -131
- package/dist/esm/index8.js.map +1 -1
- package/dist/types/conversational-agent.d.ts +8 -0
- package/dist/types/core/ToolRegistry.d.ts +130 -0
- package/dist/types/execution/ExecutionPipeline.d.ts +81 -0
- package/dist/types/forms/FormEngine.d.ts +121 -0
- package/dist/types/forms/form-generator.d.ts +39 -2
- package/dist/types/forms/types.d.ts +21 -2
- package/dist/types/index.d.ts +3 -4
- package/dist/types/langchain/FormAwareAgentExecutor.d.ts +53 -4
- package/dist/types/langchain/FormValidatingToolWrapper.d.ts +43 -6
- package/dist/types/langchain-agent.d.ts +49 -0
- package/dist/types/memory/ContentStorage.d.ts +7 -0
- package/dist/types/memory/SmartMemoryManager.d.ts +1 -0
- package/dist/types/services/ContentStoreManager.d.ts +11 -1
- package/dist/types/utils/ResponseFormatter.d.ts +26 -0
- package/package.json +13 -10
- package/src/config/system-message.ts +14 -0
- package/src/context/ReferenceContextManager.ts +1 -1
- package/src/conversational-agent.ts +91 -36
- package/src/core/ToolRegistry.ts +358 -0
- package/src/execution/ExecutionPipeline.ts +301 -0
- package/src/forms/FormEngine.ts +443 -0
- package/src/forms/field-type-registry.ts +1 -13
- package/src/forms/form-generator.ts +394 -237
- package/src/forms/types.ts +20 -3
- package/src/index.ts +6 -10
- package/src/langchain/FormAwareAgentExecutor.ts +653 -22
- package/src/langchain/FormValidatingToolWrapper.ts +216 -93
- package/src/langchain-agent.ts +924 -185
- package/src/mcp/ContentProcessor.ts +20 -4
- package/src/mcp/MCPClientManager.ts +1 -1
- package/src/mcp/adapters/langchain.ts +1 -1
- package/src/memory/ContentStorage.ts +25 -5
- package/src/memory/SmartMemoryManager.ts +27 -4
- package/src/memory/TokenCounter.ts +1 -1
- package/src/plugins/hbar/HbarPlugin.ts +0 -1
- package/src/scripts/test-external-tool-wrapper.ts +3 -12
- package/src/scripts/test-hedera-kit-wrapper.ts +6 -22
- package/src/scripts/test-inscribe-form-generation.ts +24 -42
- package/src/scripts/test-inscribe-wrapper-verification.ts +1 -7
- package/src/services/ContentStoreManager.ts +23 -9
- package/src/services/EntityResolver.ts +2 -9
- package/src/tools/EntityResolverTool.ts +5 -8
- package/src/utils/ResponseFormatter.ts +146 -0
- package/dist/cjs/examples/external-tool-wrapper-example.d.ts +0 -131
- package/dist/cjs/langchain/ContentAwareAgentExecutor.d.ts +0 -14
- package/dist/cjs/langchain/external-tool-wrapper.d.ts +0 -179
- package/dist/cjs/scripts/test-external-tool-wrapper.d.ts +0 -5
- package/dist/cjs/scripts/test-hedera-kit-wrapper.d.ts +0 -36
- package/dist/cjs/scripts/test-inscribe-form-generation.d.ts +0 -15
- package/dist/cjs/scripts/test-inscribe-wrapper-verification.d.ts +0 -13
- package/dist/types/examples/external-tool-wrapper-example.d.ts +0 -131
- package/dist/types/langchain/ContentAwareAgentExecutor.d.ts +0 -14
- package/dist/types/langchain/external-tool-wrapper.d.ts +0 -179
- package/dist/types/scripts/test-external-tool-wrapper.d.ts +0 -5
- package/dist/types/scripts/test-hedera-kit-wrapper.d.ts +0 -36
- package/dist/types/scripts/test-inscribe-form-generation.d.ts +0 -15
- package/dist/types/scripts/test-inscribe-wrapper-verification.d.ts +0 -13
- package/src/examples/external-tool-wrapper-example.ts +0 -227
- package/src/langchain/ContentAwareAgentExecutor.ts +0 -19
- package/src/langchain/external-tool-wrapper.ts +0 -486
package/dist/cjs/index.cjs
CHANGED
|
@@ -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"),n=require("@hashgraphonline/standards-sdk"),r=require("zod"),o=require("@hashgraph/sdk"),s=require("bignumber.js"),i=require("@langchain/core/tools"),a=require("langchain/agents"),c=require("@langchain/core/prompts"),l=require("@langchain/openai"),g=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 r=e.config.hederaKit;if(r)try{this.stateManager=e.stateManager||e.config.stateManager||this.appConfig?.stateManager||new t.OpenConvaiState;const i=r.signer.getAccountId().toString();let a="",c="";try{const e=r.signer.getOperatorPrivateKey(),t="function"==typeof e?.toStringRaw?e.toStringRaw():"function"==typeof e?.toString?e.toString():String(e),o=new n.HCS10Client({network:r.network,operatorId:i,operatorPrivateKey:t,logLevel:"error"}),s=await o.retrieveProfile(i);s.success&&s.topicInfo&&(a=s.topicInfo.inboundTopic,c=s.topicInfo.outboundTopic)}catch(o){this.context.logger.warn("Could not retrieve profile topics:",o)}if(this.stateManager.setCurrentAgent({name:`Agent ${i}`,accountId:i,inboundTopicId:a,outboundTopicId:c,privateKey:(()=>{const e=r.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=r.signer.getOperatorPrivateKey(),t="function"==typeof e?.toStringRaw?e.toStringRaw():"function"==typeof e?.toString?e.toString():String(e),o=new n.HCS10Client({network:r.network,operatorId:i,operatorPrivateKey:t,logLevel:"error"});this.stateManager.initializeConnectionsManager(o),this.context.logger.info("ConnectionsManager initialized in HCS10Plugin")}catch(s){this.context.logger.warn("Could not initialize ConnectionsManager:",s)}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 T 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 w extends e.BaseServiceBuilder{constructor(e){super(e)}transferHbar(e,t=!0){this.clearNotes();const n=new o.TransferTransaction;if(!e.transfers||0===e.transfers.length)throw new Error("HbarTransferParams must include at least one transfer.");let r=new s(0),i=!1;if(t&&this.kit.userAccountId&&"provideBytes"===this.kit.operationalMode&&1===e.transfers.length){const t=e.transfers[0],r="string"==typeof t.amount||"number"==typeof t.amount?t.amount:t.amount.toString(),a=new s(r);if(a.isPositive()){const e="string"==typeof t.accountId?o.AccountId.fromString(t.accountId):t.accountId,r=a.toFixed(8,s.ROUND_DOWN),c=o.Hbar.fromString(r);this.logger.info(`[AccountBuilder.transferHbar] Configuring user-initiated scheduled transfer: ${c.toString()} from ${this.kit.userAccountId} to ${e.toString()}`),this.addNote(`Configured HBAR transfer from your account (${this.kit.userAccountId}) to ${e.toString()} for ${c.toString()}.`),n.addHbarTransfer(e,c),n.addHbarTransfer(o.AccountId.fromString(this.kit.userAccountId),c.negated()),i=!0}}if(!i){const t=[];for(const n of e.transfers){const e="string"==typeof n.accountId?o.AccountId.fromString(n.accountId):n.accountId,i="string"==typeof n.amount||"number"==typeof n.amount?n.amount:n.amount.toString(),a=new s(i),c=a.toFixed(8,s.ROUND_DOWN);this.logger.info(`Processing transfer: ${i} HBAR (rounded to ${c}) for account ${e.toString()}`);const l=o.Hbar.fromString(c);t.push({accountId:e,amount:a,hbar:l});const g=l.toTinybars();r=r.plus(g.toString())}if(!r.isZero()&&(this.logger.warn(`Transfer sum not zero: ${r.toString()} tinybars off. Adjusting last transfer.`),t.length>0)){const e=t[t.length-1],n=r.dividedBy(-1e8),i=e.amount.plus(n).toFixed(8,s.ROUND_DOWN);e.hbar=o.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=r.z.object({accountId:r.z.string().describe('Account ID for the transfer (e.g., "0.0.xxxx").'),amount:r.z.union([r.z.number(),r.z.string()]).describe("HBAR amount 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=r.z.object({transfers:r.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:r.z.string().optional().describe("Optional. Memo for the transaction.")});class x 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 w(this.hederaKit)}async callBuilderMethod(e,t){await e.transferHbar(t)}}class b 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=r.z.object({tokenId:r.z.string().describe('The ID of the fungible token to airdrop (e.g., "0.0.yyyy").'),recipients:r.z.array(r.z.object({accountId:r.z.string().describe('Recipient account ID (e.g., "0.0.xxxx").'),amount:r.z.union([r.z.number(),r.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:r.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,r=this.convertToSmallestUnits(n,t);return this.logger.info(`Converting amount for ${e.accountId}: ${n} tokens → ${r} smallest units`),{...e,amount:r.toString()}}),r={...e,recipients:n};return this.logger.info("Calling original airdrop tool with converted amounts"),await this.originalTool._call(r)}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(),r=parseInt(String(t.decimals||"0"));return this.logger.info(`Token ${e} found with ${r} decimals via API`),{...t,decimals:r}}}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 v 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 x({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}),r=new b(n,t);this.tools.push(r),this.context.logger.info("Added wrapped airdrop tool to HBAR Plugin")}catch(r){this.context.logger.error("Error creating airdrop tool wrapper:",r)}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 M{constructor(){this.patterns=new Map,this.initializeDefaultPatterns()}static getInstance(){return M.instance||(M.instance=new M),M.instance}initializeDefaultPatterns(){this.register("numeric-supply-exact",{pattern:["maxSupply","minSupply","totalSupply"],type:"number",priority:15}),this.register("numeric-supply",{pattern:/supply$/i,type:"number",priority:10}),this.register("numeric-amounts",{pattern:/(?:amount|quantity|count|total|sum|value)$/i,type:"number",priority:8}),this.register("numeric-time",{pattern:/(?:period|duration|time|timeout|delay|interval)$/i,type:"number",priority:8}),this.register("numeric-limits",{pattern:/(?:limit|max|min|threshold|size|length)$/i,type:"number",priority:7}),this.register("currency",{pattern:/(?:price|cost|fee|payment|balance|amount)$/i,type:"currency",priority:9}),this.register("percentage",{pattern:/(?:percent|percentage|rate|ratio)$/i,type:"percentage",priority:9}),this.register("boolean-freeze",{pattern:["freezeDefault","freeze"],type:"checkbox",priority:10}),this.register("boolean-flags",{pattern:/(?:is|has|can|should|enable|disable|active|default|allow)(?:[A-Z]|$)/,type:"checkbox",priority:8}),this.register("textarea",{pattern:/(?:memo|description|notes|comment|message|content|body|text)$/i,type:"textarea",priority:8}),this.register("array-fees",{pattern:["customFees","fees"],type:"array",priority:10}),this.register("array-general",{pattern:/(?:list|items|array|collection)$/i,type:"array",priority:7}),this.register("object-options",{pattern:["metaOptions","options"],type:"object",priority:10}),this.register("object-config",{pattern:/(?:config|settings|configuration|metadata|data|info)$/i,type:"object",priority:7}),this.register("select-type",{pattern:/(?:type|kind|category|status|state|mode)$/i,type:"select",priority:7})}register(e,t){this.patterns.set(e,t)}unregister(e){return this.patterns.delete(e)}detectType(e){const t=[];for(const n of this.patterns.values()){let r=!1;Array.isArray(n.pattern)?r=n.pattern.some(t=>e===t||e.toLowerCase()===t.toLowerCase()):n.pattern instanceof RegExp&&(r=n.pattern.test(e)),r&&t.push({type:n.type,priority:n.priority??5})}return t.length>0?(t.sort((e,t)=>t.priority-e.priority),t[0].type):null}getPatterns(){return new Map(this.patterns)}clear(){this.patterns.clear()}reset(){this.clear(),this.initializeDefaultPatterns()}}const A=M.getInstance();class I{constructor(){this.logger=new n.Logger({module:"FormGenerator"})}generateFormFromError(e,t,n,r){const o=this.extractValidationErrors(e),s=this.identifyMissingFields(o,t),i=this.createFormConfig(t,s,n);return{type:"form",id:`form_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,formConfig:i,originalPrompt:r,toolName:n,validationErrors:o}}async generateFormFromSchema(e,t,n){const r=new Set;if(e&&e.shape){const n=e.shape;for(const e of Object.keys(n))void 0!==t[e]&&""!==t[e]||r.add(e)}const o=this.createFormConfig(e,r,n.toolName);return{type:"form",id:`form_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,formConfig:o,originalPrompt:n.toolDescription||`Complete ${n.toolName}`,toolName:n.toolName,validationErrors:[]}}extractValidationErrors(e){return e.issues.map(e=>({path:e.path.map(e=>String(e)),message:e.message,code:e.code}))}identifyMissingFields(e,t){const n=new Set;return e.forEach(e=>{const t=e.path.join(".");t&&n.add(t)}),n}createFormConfig(e,t,n){const r=this.extractRenderConfigsSafely(e),o=this.generateFieldOrderingSafely(e),s=this.generateFormFields(e,r,t,o);return{title:this.generateFormTitle(n),description:this.generateFormDescription(n,t.size),fields:s,submitLabel:"Continue",cancelLabel:"Cancel",metadata:{toolName:n,missingFieldCount:t.size}}}extractRenderConfigsSafely(e){try{if("function"==typeof t.extractRenderConfigs)return t.extractRenderConfigs(e)}catch(n){this.logger.warn("Could not extract render configs:",n)}return{fields:{},groups:{},order:[],metadata:{}}}generateFieldOrderingSafely(e){try{if("function"==typeof t.generateFieldOrdering){const n=t.generateFieldOrdering(e);return{sections:Object.values(n.sections).map(e=>({fields:e.fields}))}}}catch(n){this.logger.warn("Could not generate field ordering:",n)}return{sections:[]}}generateFormFields(e,t,n,r){const o=[],s=this.extractFieldsFromSchema(e),i=new Set;if(s.forEach(t=>{const r=["tokenSymbol","treasuryAccountId","maxSupply","tokenName","name","description","contentRef"].includes(o=t)?"essential":["creator","type","fileStandard","supplyType"].includes(o)?"common":["apiKey","chunkSize","timeoutMs","quoteOnly","waitForConfirmation"].includes(o)?"expert":(o.toLowerCase().includes("key")||o.includes("Period")||o.includes("Fees")||o.includes("autoRenew"),"advanced");var o;const s=this.isFieldRequired(e,t);(n.has(t)&&s||"essential"===r)&&i.add(t)}),r.sections.length>0){r.sections.flatMap(e=>e.fields).forEach(n=>{if(i.has(n)){const r=this.createFormField(n,t.fields[n],e,n);r&&o.push(r)}})}return i.forEach(n=>{if(!o.some(e=>e.name===n)){const r=this.createFormField(n,t.fields[n],e,n);r&&o.push(r)}}),0===o.length&&n.forEach(n=>{const r=this.createFormField(n,t.fields[n],e,n);r&&o.push(r)}),o}createFormField(e,t,n,r){const o=this.mapFieldType(t?.fieldType,n,r),s=this.isFieldRequired(n,r||e),i={name:e,label:t?.ui?.label||this.humanizeFieldName(e),type:o,required:s,priority:(a=e,["tokenSymbol","treasuryAccountId","maxSupply","tokenName","name","description","contentRef"].includes(a)?"essential":["creator","type","fileStandard","supplyType"].includes(a)?"common":["apiKey","chunkSize","timeoutMs","quoteOnly","waitForConfirmation"].includes(a)?"expert":(a.toLowerCase().includes("key")||a.includes("Period")||a.includes("Fees")||a.includes("autoRenew"),"advanced"))};var a;if(t&&(i.renderConfig=t),t?.ui?.placeholder&&(i.placeholder=t.ui.placeholder),t?.ui?.helpText&&(i.helpText=t.ui.helpText),t?.constraints){const e={};void 0!==t.constraints.min&&(e.min=t.constraints.min),void 0!==t.constraints.max&&(e.max=t.constraints.max),void 0!==t.constraints.minLength&&(e.minLength=t.constraints.minLength),void 0!==t.constraints.maxLength&&(e.maxLength=t.constraints.maxLength),void 0!==t.constraints.pattern&&(e.pattern=t.constraints.pattern),Object.keys(e).length>0&&(i.validation=e)}return t?.options&&(i.options=t.options.map(e=>({value:String(e.value),label:e.label,...void 0!==e.disabled&&{disabled:e.disabled}}))),i}mapFieldType(e,t,n){if(!e&&t&&n){const e=this.inferTypeFromSchema(t,n);if(e)return e}if(!e&&n){const e=A.detectType(n);if(e)return e}if(!e)return"text";const r=e.toLowerCase();return["text","string"].includes(r)?"text":["number","integer","float","decimal"].includes(r)?"number":["select","enum","dropdown"].includes(r)?"select":["checkbox","boolean","bool"].includes(r)?"checkbox":["textarea","longtext","multiline"].includes(r)?"textarea":["file","upload","attachment"].includes(r)?"file":["array","list"].includes(r)?"array":["object","json"].includes(r)?"object":["currency","money","price"].includes(r)?"currency":["percentage","percent"].includes(r)?"percentage":"text"}humanizeFieldName(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\./g," ").trim().split(" ").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}generateFormTitle(e){return`Complete ${e.replace(/Tool$/,"").replace(/Hedera/g,"").replace(/([A-Z])/g," $1").trim()} Information`}extractFieldsFromSchema(e){const t=[];try{if(e&&e._def){const n=e._def;if("ZodObject"===n.typeName&&n.shape)t.push(...Object.keys(n.shape));else if("ZodUnion"===n.typeName&&n.options){const e=n.options[0];e&&e._def&&e._def.shape&&t.push(...Object.keys(e._def.shape))}}}catch(n){this.logger.debug("Could not extract fields from schema structure:",n)}return t}inferTypeFromSchema(e,t){try{const n=e._def;if(n&&"ZodObject"===n.typeName){let e;if(e="function"==typeof n.shape?n.shape():n.shape,e){let n=e[t];if(n&&n._def&&"ZodOptional"===n._def.typeName&&(n=n._def.innerType),n&&n._def){switch(n._def.typeName){case"ZodString":return t.toLowerCase().includes("memo")||t.toLowerCase().includes("description")?"textarea":"text";case"ZodNumber":return t.toLowerCase().includes("percent")?"percentage":t.toLowerCase().includes("price")||t.toLowerCase().includes("cost")?"currency":"number";case"ZodBoolean":return"checkbox";case"ZodEnum":case"ZodNativeEnum":return"select";case"ZodArray":return"array";case"ZodObject":return"object";default:return"text"}}}}}catch(n){this.logger.debug("Could not infer type from schema:",n)}return null}isFieldRequired(e,t){if(!e||!t)return!1;try{const n=e._def;if(n&&"ZodObject"===n.typeName){let e;if(e="function"==typeof n.shape?n.shape():n.shape,e&&e[t]){const n=e[t];return(!n||!n._def||"ZodOptional"!==n._def.typeName)&&((!n||!n._def||void 0===n._def.defaultValue)&&(!n||!n._def||"ZodDefault"!==n._def.typeName))}}}catch(n){this.logger.debug(`Could not determine if field ${t} is required:`,n)}return!1}generateFormDescription(e,t){return 0===t?"Please provide the required information to continue with your request.":`Please provide the following ${t} required field${1!==t?"s":""} to continue with your request.`}}class P extends k{constructor(...e){super(...e),this.pendingForms=new Map,this.formGenerator=new I,this.formLogger=new n.Logger({module:"FormAwareAgentExecutor"})}async _call(e){try{const t=await super._call(e);if(t.intermediateSteps&&Array.isArray(t.intermediateSteps))for(const e of t.intermediateSteps)if(e.observation)try{const n="string"==typeof e.observation?JSON.parse(e.observation):e.observation;if(n.requiresForm&&n.formMessage)return this.formLogger.info("Tool requested form generation",{toolName:e.action?.tool,hasForm:!0}),{...t,requiresForm:!0,formMessage:n.formMessage,output:n.message||"Please complete the form to continue."}}catch{}return t}catch(t){if(t instanceof r.ZodError)return this.formLogger.info("Intercepted ZodError during agent execution"),this.handleValidationError(t,e,[]);throw t}}async handleValidationError(e,t,n){this.formLogger.info("Zod validation error detected, generating form",{errorIssues:e.issues.length,inputKeys:Object.keys(t)});let r=this.extractToolInfoFromError(e,t,n);if(!r){this.formLogger.warn("Could not extract tool info from validation error, trying fallback detection");const n=this.detectToolFromErrorContext(e,t);if(!n)throw this.formLogger.error("No tool detected for form generation, rethrowing error"),e;r=n}this.formLogger.info("Generating form for tool:",{toolName:r.toolName,hasSchema:!!r.schema});const o=this.formGenerator.generateFormFromError(e,r.schema,r.toolName,t.input||"");return this.pendingForms.set(o.id,{toolName:r.toolName,originalInput:t,schema:r.schema}),{output:this.formatFormResponse(o),formMessage:o,requiresForm:!0,intermediateSteps:n||[]}}async processFormSubmission(e){const t=this.pendingForms.get(e.formId);if(!t)throw new Error(`No pending form found for ID: ${e.formId}`);this.pendingForms.delete(e.formId);const n=Object.assign({},t.originalInput,e.data);try{const t=await super._call(n);return Object.assign({},t,{formCompleted:!0,originalFormId:e.formId})}catch(o){if(o instanceof r.ZodError)return this.handleValidationError(o,n,[]);throw o}}extractToolInfoFromError(e,t,n){try{if(n.length>0){const e=n[n.length-1];if(e.action&&e.action.tool){const t=this.tools.find(t=>t.name===e.action.tool);if(t&&"schema"in t)return this.formLogger.info("Found tool from intermediate steps:",e.action.tool),{toolName:e.action.tool,schema:t.schema}}}const e=t.intermediateSteps||[];if(e.length>0){const t=e[e.length-1];let n;if(n=Array.isArray(t)&&t.length>0?t[0]:t.action?t.action:t,n&&n.tool){const e=this.tools.find(e=>e.name===n.tool);if(e&&"schema"in e)return this.formLogger.info("Found tool from input steps:",n.tool),{toolName:n.tool,schema:e.schema}}}const r=this.findToolFromContext(t);return r?(this.formLogger.info("Found tool from context:",r.toolName),r):null}catch(r){return this.formLogger.error("Error extracting tool info:",r),null}}findToolFromContext(e){const t=e.input||"";for(const n of this.tools){if(this.extractToolKeywords(n.name).some(e=>t.toLowerCase().includes(e.toLowerCase()))&&"schema"in n)return{toolName:n.name,schema:n.schema}}return null}detectToolFromErrorContext(e,t){const n=e.issues.map(e=>e.path.join("."));for(const r of this.tools)if("schema"in r){const e=r.schema;if(this.schemaMatchesErrorPaths(e,n))return this.formLogger.info("Detected tool from error path analysis:",r.name),{toolName:r.name,schema:e}}return null}schemaMatchesErrorPaths(e,t){const n=e;if(!n||!n._def)return!1;try{const e=n._def;if("ZodObject"===e.typeName){const n=e.shape,r=Object.keys(n||{});return t.some(e=>{const t=e.split(".")[0];return r.includes(t)})}}catch(r){this.formLogger.debug("Error analyzing schema structure:",r)}return!1}extractToolKeywords(e){return[...e.replace(/([A-Z])/g," $1").toLowerCase().split(/[\s_-]+/).filter(e=>e.length>2),e.toLowerCase()]}formatFormResponse(e){const t=e.formConfig.fields.length,n=e.formConfig.fields.slice(0,3).map(e=>`• ${e.label}`).join("\n");return`I need some additional information to complete your request.\n\n${e.formConfig.description}\n\nRequired fields:\n${n}${t>3?`\n... and ${t-3} more`:""}\n\nPlease fill out the form below to continue.`}hasPendingForms(){return this.pendingForms.size>0}getPendingFormsInfo(){return Array.from(this.pendingForms.entries()).map(([e,t])=>({formId:e,toolName:t.toolName}))}}class R{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 E{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 r=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:r}}async processResponse(e,t,n){try{const r=this.analyzeResponse(e);if(!r.shouldProcess)return{content:e,wasProcessed:!1};return await this.createReferencedResponse(e,r,t,n)}catch(r){return this.logger.error("Error processing MCP response:",r),{content:e,wasProcessed:!1,errors:[r instanceof Error?r.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,r){const o=this.deepClone(e),s=[];let i=!1,a=0;for(const g of t.contents)if(this.contentStorage.shouldUseReference("string"==typeof g.content?g.content:JSON.stringify(g.content)))try{const e=globalThis.Buffer.from("string"==typeof g.content?g.content:JSON.stringify(g.content),"utf8"),t={contentType:this.mapMimeTypeToContentType(g.mimeType),source:"mcp_tool",mcpToolName:`${n}::${r}`,tags:["mcp_response",n,r]};void 0!==g.mimeType&&(t.mimeType=g.mimeType);const s=await this.contentStorage.storeContentIfLarge(e,t);s&&(this.replaceContentInResponse(o,g.content,this.createLightweightReference(s)),i=!0,a+=e.length)}catch(l){s.push(`Failed to create reference: ${l instanceof Error?l.message:"Unknown error"}`)}const c={content:o,wasProcessed:!0,referenceCreated:i,originalSize:a};return s.length>0&&(c.errors=s),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 r=0;r<e.length;r++)e[r]===t?e[r]=n:this.replaceContentInResponse(e[r],t,n);else if("object"==typeof e){const r=e;if("text"===r.type&&r.text===t){for(const e of Object.keys(r))delete r[e];for(const e of Object.keys(n))r[e]=n[e];return}for(const e in r)r[e]===t?r[e]=n:this.replaceContentInResponse(r[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 O{constructor(e,t){this.clients=new Map,this.tools=new Map,this.logger=e,t&&(this.contentProcessor=new E(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 g.Client({name:`conversational-agent-${e.name}`,version:"1.0.0"},{capabilities:{}});await n.connect(t),this.clients.set(e.name,n);const r=(await n.listTools()).tools.map(t=>({...t,serverName:e.name}));return this.tools.set(e.name,r),this.logger.info(`Connected to MCP server ${e.name} with ${r.length} tools`),{serverName:e.name,connected:!0,tools:r}}catch(t){return this.logger.error(`Failed to connect to MCP server ${e.name}:`,t),{serverName:e.name,connected:!1,error:t instanceof Error?t.message:"Unknown error",tools:[]}}}async executeTool(e,t,n){const r=this.clients.get(e);if(!r)throw new Error(`MCP server ${e} not connected`);this.logger.debug(`Executing MCP tool ${t} on server ${e}`,n);try{const o=await r.callTool({name:t,arguments:n});if(this.contentProcessor){const n=await this.contentProcessor.processResponse(o,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 o}catch(o){throw this.logger.error(`Error executing MCP tool ${t}:`,o),o}}async disconnectAll(){for(const[t,n]of this.clients)try{await n.close(),this.logger.info(`Disconnected from MCP server ${t}`)}catch(e){this.logger.error(`Error disconnecting MCP server ${t}:`,e)}this.clients.clear(),this.tools.clear()}getAllTools(){const e=[];for(const t of this.tools.values())e.push(...t);return e}getServerTools(e){return this.tools.get(e)||[]}isServerConnected(e){return this.clients.has(e)}getConnectedServers(){return Array.from(this.clients.keys())}enableContentProcessing(e){this.contentProcessor=new E(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 N(e,t,r){const o=F(e.inputSchema),s=`${e.serverName}_${e.name}`.replace(/[^a-zA-Z0-9_]/g,"_");let a=e.description||`MCP tool ${e.name} from ${e.serverName}`;return r?.toolDescriptions?.[e.name]&&(a=`${a}\n\n${r.toolDescriptions[e.name]}`),r?.additionalContext&&(a=`${a}\n\nContext: ${r.additionalContext}`),new i.DynamicStructuredTool({name:s,description:a,schema:o,func:async r=>{try{const s=await t.executeTool(e.serverName,e.name,r);let i="";if("string"==typeof s)i=s;else if(s&&"object"==typeof s&&"content"in s){const e=s.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(s);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(o){}}return i}catch(s){const t=s instanceof Error?s.message:"Unknown error";return`Error executing MCP tool ${e.name}: ${t}`}}})}function F(e){if(!e||"object"!=typeof e)return r.z.object({});const t=e;if(t.type&&"object"!==t.type)return $(t);if(!t.properties||"object"!=typeof t.properties)return r.z.object({});const n={};for(const[r,o]of Object.entries(t.properties)){let e=$(o);Array.isArray(t.required)&&t.required.includes(r)||(e=e.optional()),n[r]=e}return r.z.object(n)}function $(e){if(!e||"object"!=typeof e||!("type"in e))return r.z.unknown();const t=e;let n;switch(t.type){case"string":n=r.z.string(),t.enum&&Array.isArray(t.enum)&&(n=r.z.enum(t.enum));break;case"number":n=r.z.number(),"minimum"in t&&"number"==typeof t.minimum&&(n=n.min(t.minimum)),"maximum"in t&&"number"==typeof t.maximum&&(n=n.max(t.maximum));break;case"integer":n=r.z.number().int(),"minimum"in t&&"number"==typeof t.minimum&&(n=n.min(t.minimum)),"maximum"in t&&"number"==typeof t.maximum&&(n=n.max(t.maximum));break;case"boolean":n=r.z.boolean();break;case"array":n=t.items?r.z.array($(t.items)):r.z.array(r.z.unknown());break;case"object":n="properties"in t?F(t):r.z.object({}).passthrough();break;default:n=r.z.unknown()}return"description"in t&&"string"==typeof t.description&&(n=n.describe(t.description)),n}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 H=z;const _=class e{constructor(t=e.DEFAULT_MAX_TOKENS,n=e.DEFAULT_RESERVE_TOKENS,r){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=r||new H}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()}};_.DEFAULT_MAX_TOKENS=8e3,_.DEFAULT_RESERVE_TOKENS=1e3,_.PRUNING_BATCH_SIZE=2;let L=_;class B{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 D={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 j extends Error{constructor(e,t,n,r){super(e),this.type=t,this.referenceId=n,this.suggestedActions=r,this.name="ContentReferenceError"}}const K=class e{constructor(t=e.DEFAULT_MAX_STORAGE,n){this.messages=[],this.idCounter=0,this.contentStore=new Map,this.maxStorage=t,this.referenceConfig={...D,...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 r=e.map(e=>({message:e,storedAt:t,id:this.generateId()}));for(this.messages.push(...r);this.messages.length>this.maxStorage;)this.messages.shift(),n++;return{stored:r.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:r,useRegex:o=!1}=t;let s=[];if(o)try{const t=new RegExp(e,n?"g":"gi");s=this.messages.filter(e=>t.test(e.message.content)).map(e=>e.message)}catch(i){return[]}else{const t=n?e:e.toLowerCase();s=this.messages.filter(e=>{const r=e.message.content;return(n?r:r.toLowerCase()).includes(t)}).map(e=>e.message)}return r?s.slice(0,r):s}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,r;return e>0&&(n=this.messages[0].storedAt,r=this.messages[e-1].storedAt),{totalMessages:e,maxStorageLimit:this.maxStorage,usagePercentage:t,oldestMessageTime:n,newestMessageTime:r}}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 r={contentType:t.contentType||this.detectContentType(n,t.mimeType),sizeBytes:n.length,source:t.source,tags:[]};return void 0!==t.mimeType&&(r.mimeType=t.mimeType),void 0!==t.mcpToolName&&(r.mcpToolName=t.mcpToolName),void 0!==t.fileName&&(r.fileName=t.fileName),void 0!==t.tags&&(r.tags=t.tags),void 0!==t.customMetadata&&(r.customMetadata=t.customMetadata),await this.storeContent(n,r)}async storeContent(e,t){const n=Date.now();try{const r=new Date,o=B.generateId(e),s={...t,createdAt:r,lastAccessedAt:r,accessCount:0},i={content:e,metadata:s,state:"active"},a=this.calculateExpirationTime(t.source);void 0!==a&&(i.expiresAt=a),this.contentStore.set(o,i),this.updateStatsAfterStore(e.length),await this.enforceReferenceStorageLimits();const c=this.createContentPreview(e,s.contentType),l={contentType:s.contentType,sizeBytes:s.sizeBytes,source:s.source};void 0!==s.fileName&&(l.fileName=s.fileName),void 0!==s.mimeType&&(l.mimeType=s.mimeType);const g={referenceId:o,state:"active",preview:c,metadata:l,createdAt:r,format:"ref://{id}"},h=Date.now()-n;return this.recordPerformanceMetric("creation",h),g}catch(r){const e=Date.now()-n;throw this.recordPerformanceMetric("creation",e),new j(`Failed to store content: ${r instanceof Error?r.message:"Unknown error"}`,"system_error",void 0,["Try again","Check storage limits","Contact administrator"])}}async resolveReference(e){const t=Date.now();try{if(!B.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 r=Date.now()-t;return this.recordPerformanceMetric("resolution",r),{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(!B.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 o=new Date,s=[];for(const[e,t]of this.contentStore.entries()){let n=!1;t.expiresAt&&t.expiresAt<o&&(n=!0,t.state="expired");const r=o.getTime()-t.metadata.createdAt.getTime();r>this.getCleanupPolicy(t.metadata.source).maxAgeMs&&(n=!0),"cleanup_pending"===t.state&&(n=!0),n&&s.push(e)}s.sort((e,t)=>{const n=this.contentStore.get(e),r=this.contentStore.get(t),o=this.getCleanupPolicy(n.metadata.source).priority;return this.getCleanupPolicy(r.metadata.source).priority-o});for(const e of s)try{await this.cleanupReference(e)&&n++}catch(r){t.push(`Failed to cleanup ${e}: ${r instanceof Error?r.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()),o=this.contentStore.size-this.referenceConfig.maxReferences;for(let s=0;s<o&&s<e.length;s++){const[o]=e[s];try{await this.cleanupReference(o)&&n++}catch(r){t.push(`Failed to cleanup excess reference ${o}: ${r instanceof Error?r.message:"Unknown error"}`)}}}const i=Date.now()-e;return this.recordPerformanceMetric("cleanup",i),{cleanedUp:n,errors:t}}catch(r){const o=Date.now()-e;this.recordPerformanceMetric("cleanup",o);const s=`Cleanup process failed: ${r instanceof Error?r.message:"Unknown error"}`;return t.push(s),{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,r]of this.contentStore.entries())r.metadata.accessCount>t&&(t=r.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()}};K.DEFAULT_MAX_STORAGE=1e3;let U=K;const q='"isEntityAssociation":true',W=class e{constructor(t={}){this.config={...e.DEFAULT_CONFIG,...t},this.tokenCounter=new H(this.config.modelName),this._contentStorage=new U(this.config.storageLimit),this.memoryWindow=new L(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,r){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 o=e.trim(),s=t.trim().substring(0,100),i=n.trim().toLowerCase(),a={entityId:o,entityName:s,entityType:i,createdAt:new Date,isEntityAssociation:!0,...null!=r&&""!==r.trim()?{transactionId:r.trim()}:{}},c={_getType:()=>"system",content:JSON.stringify(a),id:`entity_${o}_${Date.now()}`,name:"entity_association",additional_kwargs:{entityId:o,entityName:s,entityType:i,isEntityAssociation:!0}};this._contentStorage.storeMessages([c])}catch(o){}}resolveEntityReference(e,t={}){try{if(!e||"string"!=typeof e)return[];const n=e.trim();if(0===n.length)return[];n.length;const{entityType:r,limit:o=10,fuzzyMatch:s=!0}=t,i=Math.max(1,Math.min(o||10,100)),a=/^0\.0\.\d+$/.test(n),c=this._contentStorage.searchMessages(n.substring(0,200),{caseSensitive:!1,limit:2*i}),l=[];for(const e of c)try{const t=e.content;if(t.includes(q)||t.includes("entityId")){const e=JSON.parse(t);if(e.entityId&&e.entityName&&e.entityType){if(r&&e.entityType!==r)continue;if(a&&e.entityId!==n)continue;l.push(e)}}}catch{continue}if(s&&0===l.length&&!a){const t=[e.toLowerCase(),"token","account",r||""].filter(Boolean);for(const n of t){if(n===e.toLowerCase())continue;const t=this._contentStorage.searchMessages(n,{caseSensitive:!1,limit:o});for(const e of t)try{const t=e.content;if(t.includes(q)){const e=JSON.parse(t);if(e.entityId&&e.entityName&&e.entityType){if(r&&e.entityType!==r)continue;l.push(e)}}}catch{continue}}}const g=l.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 g.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 r=n||"entityId",o=this._contentStorage.searchMessages(r,{caseSensitive:!1,limit:100}),s=[];for(const e of o)try{const t=e.content;if(t.includes(q)){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)),s.push(e)}}}catch(t){continue}return s.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(),r=n(e.createdAt);return n(t.createdAt)-r})}catch(n){return[]}}dispose(){this.memoryWindow.dispose(),this._contentStorage.dispose(),this.tokenCounter.dispose()}};W.DEFAULT_CONFIG={maxTokens:8e3,reserveTokens:1e3,modelName:"gpt-4o",storageLimit:1e3};let V=W;class G extends i.StructuredTool{constructor(e,t,r={}){super(),this.originalTool=e,this.formGenerator=t,this.validationConfig=r,this.logger=new n.Logger({module:"FormValidatingToolWrapper"}),this.name=e.name,this.description=e.description,this.schema=e.schema}checkMissingFields(e){const t=[],n=this.schema.shape;if(!n)return t;for(const[r,o]of Object.entries(n)){if(this.validationConfig.skipFields?.includes(r))continue;const n=o._def;if(!("function"==typeof o.isOptional?o.isOptional():"ZodOptional"===n?.typeName)){const n=e[r];null!=n&&""!==n||t.push(r)}}return t}validateInput(e){try{return this.schema.parse(e),{isValid:!0}}catch(t){if(t instanceof r.z.ZodError){return{isValid:!1,errors:t.errors.filter(e=>{const t=e.path[0];return!this.validationConfig.skipFields?.includes(t)}).map(e=>`${e.path.join(".")}: ${e.message}`)}}return{isValid:!1,errors:["Validation failed"]}}}shouldGenerateForm(e){if(this.logger.info(`shouldGenerateForm called for ${this.name}/${this.originalTool.name}`,{input:e,hasCustomValidation:!!this.validationConfig.customValidation}),this.validationConfig.customValidation){const t=!this.validationConfig.customValidation(e);return this.logger.info(`Custom validation result: ${t}`),t}if("inscribeHashinal"===this.originalTool.name){this.logger.info("InscribeHashinalTool: Checking all required fields for form generation",{inputKeys:Object.keys(e),inputValues:e});const t=this.validateInput(e);if(this.logger.info("InscribeHashinalTool: Schema validation result",{isValid:t.isValid,errors:t.errors}),!t.isValid)return this.logger.info("InscribeHashinalTool: Schema validation failed, generating form",{errors:t.errors}),!0;const n=!(!e.name||!e.description);return this.logger.info("InscribeHashinalTool: Metadata check",{hasName:!!e.name,hasDescription:!!e.description,hasMinimalMetadata:n,nameValue:e.name,descriptionValue:e.description}),n?(this.logger.info("InscribeHashinalTool: All required fields present, allowing execution"),!1):(this.logger.info("InscribeHashinalTool: Missing minimal metadata (name/description), generating form"),!0)}this.logger.info(`Non-InscribeHashinal tool (${this.originalTool.name}): Using schema validation only`);const t=this.validateInput(e);return this.logger.info(`Schema validation for ${this.originalTool.name}:`,{isValid:t.isValid,errors:t.errors}),!t.isValid}async _call(e,t){this.logger.info(`FormValidatingToolWrapper intercepting ${this.name}`,{input:e,hasRenderConfig:!!this.schema._renderConfig,inputKeys:Object.keys(e),schemaShape:Object.keys(this.schema?.shape||{})});const n=this.shouldGenerateForm(e);if(this.logger.info(`FormValidatingToolWrapper decision for ${this.name}:`,{shouldGenerateForm:n,toolName:this.name,originalToolName:this.originalTool.name}),n){this.logger.info(`Generating form for incomplete input in ${this.name}`);try{const t=await this.formGenerator.generateFormFromSchema(this.schema,e,{toolName:this.name,toolDescription:this.description});t.partialInput=e;const n={requiresForm:!0,formMessage:t,message:`Please complete the form to provide the required information for ${this.name}.`};return this.logger.info(`FormValidatingToolWrapper returning form result for ${this.name}`),JSON.stringify(n)}catch(r){this.logger.error("Failed to generate form:",r)}}this.logger.info(`FormValidatingToolWrapper passing through to original tool ${this.name}`);return this.originalTool._call(e,t)}}function J(e,t,n={}){return new G(e,t,n)}class Z extends R{constructor(){super(...arguments),this.systemMessage="",this.mcpConnectionStatus=new Map}async boot(){if(console.log("🚨🚨🚨 LANGCHAIN AGENT BOOT METHOD CALLED 🚨🚨🚨"),this.logger.info("🚨🚨🚨 LANGCHAIN AGENT BOOT METHOD CALLED 🚨🚨🚨"),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.logger.info("=== TOOL WRAPPING DEBUG START ==="),this.logger.info("All tools from agentKit:",n.map(e=>e.name));const o=this.filterTools(n);this.logger.info("All filtered tools:",o.map(e=>e.name));const s=new I;this.tools=o.map(e=>{this.logger.info(`Processing tool: ${e.name}`),console.log(`🔧 Processing tool: ${e.name}`),"inscribeHashinal"===e.name&&this.logger.info("Debug InscribeHashinalTool schema:",{hasSchema:!!e.schema,schemaType:e.schema?.constructor?.name,hasRenderConfig:!!e.schema?._renderConfig,renderConfig:e.schema?._renderConfig});const t=e.schema;let n=t?._renderConfig;"inscribeHashinal"===e.name&&(this.logger.info("InscribeHashinalTool detected",{hasRenderConfig:!!n,schemaType:t?.constructor?.name}),n||(t._renderConfig={fieldType:"object",ui:{label:"Inscribe Hashinal NFT",description:"Create a Hashinal inscription for NFT minting"}},n=!0,this.logger.info("Added render config to InscribeHashinalTool for form generation")));return n&&((o=e.schema)&&"object"==typeof o&&(o instanceof r.z.ZodObject||"ZodObject"===o._def?.typeName||"shape"in o&&"object"==typeof o.shape))?(this.logger.info(`Wrapping tool ${e.name} with form validation`),J(e,s,{requireAllFields:!1,skipFields:["metaOptions"]})):e;var o}),console.log(`🚀 TOOLS ASSIGNED: ${this.tools.length} tools`),this.logger.info(`🚀 TOOLS ASSIGNED: ${this.tools.length} tools`),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 O(this.logger))),this.smartMemory=new V({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:o}=await import("@langchain/core/messages");this.smartMemory.addMessage(new o(t));const s=this.smartMemory.getMemoryStats();this.logger.info("Memory stats before execution:",{totalMessages:s.totalActiveMessages,currentTokens:s.currentTokenCount,maxTokens:s.maxTokens,usagePercentage:s.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);const a="string"==typeof i.output?i.output:i.output?JSON.stringify(i.output):"";let c={output:a,message:a,notes:[],intermediateSteps:i.intermediateSteps};if(i.requiresForm&&i.formMessage&&(c.formMessage=i.formMessage,c.requiresForm=!0),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&&(c.tool_calls=e)}const l=i?.intermediateSteps?.[0]?.observation;if(l&&"string"==typeof l&&this.isJSON(l))try{const e=JSON.parse(l);c={...c,...e}}catch(r){this.logger.error("Error parsing intermediate steps:",r)}if(c.output&&""!==c.output.trim()||(c.output="Agent action complete."),c.output){const{AIMessage:e}=await import("@langchain/core/messages");this.smartMemory.addMessage(new e(c.output))}if(this.tokenTracker){const t=this.tokenTracker.getLatestTokenUsage();t&&(c.tokenUsage=t,c.cost=e.calculateTokenCostSync(t))}const g=this.smartMemory.getMemoryStats();return c.metadata={...c.metadata,memoryStats:{activeMessages:g.totalActiveMessages,tokenUsage:g.currentTokenCount,maxTokens:g.maxTokens,usagePercentage:g.usagePercentage}},this.logger.info("LangChainAgent.chat returning response:",c),c}catch(r){return this.logger.error("LangChainAgent.chat error:",r),this.handleError(r)}}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 processFormSubmission(t,n){if(!this.initialized||!this.executor||!this.smartMemory)throw new Error("Agent not initialized. Call boot() first.");try{if(this.logger.info("Processing form submission:",{formId:t.formId,dataKeys:Object.keys(t.data)}),n?.messages&&n.messages.length>0){this.smartMemory.clear();for(const e of n.messages)this.smartMemory.addMessage(e)}const o=await this.executor.processFormSubmission(t),s="string"==typeof o.output?o.output:o.output?JSON.stringify(o.output):"Form processed successfully.";let i={output:s,message:s,notes:[],intermediateSteps:o.intermediateSteps};if(o.requiresForm&&o.formMessage&&(i.formMessage=o.formMessage,i.requiresForm=!0),o.intermediateSteps&&Array.isArray(o.intermediateSteps)){const e=o.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&&(i.tool_calls=e)}const a=o?.intermediateSteps?.[0]?.observation;if(a&&"string"==typeof a&&this.isJSON(a))try{const e=JSON.parse(a);i={...i,...e}}catch(r){this.logger.error("Error parsing intermediate steps:",r)}if(i.output){const{AIMessage:e}=await import("@langchain/core/messages");this.smartMemory.addMessage(new e(i.output))}if(this.tokenTracker){const t=this.tokenTracker.getLatestTokenUsage();t&&(i.tokenUsage=t,i.cost=e.calculateTokenCostSync(t))}const c=this.smartMemory.getMemoryStats();return i.metadata={...i.metadata,memoryStats:{activeMessages:c.totalActiveMessages,tokenUsage:c.currentTokenCount,maxTokens:c.maxTokens,usagePercentage:c.usagePercentage}},i}catch(r){return this.logger.error("Form submission processing error:",r),this.handleError(r)}}hasPendingForms(){return!!this.executor&&this.executor.hasPendingForms()}getPendingFormsInfo(){return this.executor?this.executor.getPendingFormsInfo():[]}async createAgentKit(){const t=[...e.getAllHederaCorePlugins(),...this.config.extensions?.plugins||[]],n=this.config.execution?.operationalMode||"returnBytes",r=this.config.ai?.modelName||"gpt-4o";return new e.HederaAgentKit(this.config.signer,{plugins:t},n,this.config.execution?.userAccountId,this.config.execution?.scheduleUserTransactionsInBytesMode??!1,void 0,r,this.config.extensions?.mirrorConfig,this.config.debug?.silent??!1)}async createExecutor(){let e;if(this.config.ai?.provider&&this.config.ai.provider.getModel)e=this.config.ai.provider.getModel();else if(this.config.ai?.llm)e=this.config.ai.llm;else{const t=this.config.ai?.apiKey||process.env.OPENAI_API_KEY;if(!t)throw new Error("OpenAI API key required");const n=this.config.ai?.modelName||"gpt-4o-mini",r=n.toLowerCase().includes("gpt-5")||n.toLowerCase().includes("gpt5");e=new l.ChatOpenAI({apiKey:t,modelName:n,callbacks:this.tokenTracker?[this.tokenTracker]:[],...r?{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,r=await a.createOpenAIToolsAgent({llm:e,tools:n,prompt:t});this.executor=new P({agent:r,tools:n,verbose:this.config.debug?.verbose??!1,returnIntermediateSteps:!0})}handleError(t){const n=t instanceof Error?t.message:"Unknown error";let r,o;this.logger.error("Chat error:",t),this.tokenTracker&&(r=this.tokenTracker.getLatestTokenUsage(),r&&(o=e.calculateTokenCostSync(r)));let s=n,i=n;n.includes("429")?n.includes("quota")?(s="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."):(s="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")?(s="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")?(s="Request timed out. Please try again.",i="The request took too long to process. Please try again."):n.includes("network")||n.includes("fetch")?(s="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")&&(s=n,i=n);const a={output:i,message:s,error:n,notes:[]};return r&&(a.tokenUsage=r),o&&(a.cost=o),a}async initializeMCP(){this.mcpManager=new O(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=N(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 O(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=N(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 Y(e){const t=e.framework||"langchain";switch(t){case"langchain":return new Z(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 X{constructor(e){this.model=e}async generate(e,t){const n=await this.model.invoke(e,t);return"string"==typeof n?n:n.toString()}async*stream(e,t){const n=await this.model.stream(e,t);for await(const r of n)yield"string"==typeof r?r:r.toString()}getModel(){return this.model}}const Q=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 ee{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 te{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 ne{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 U(e,t),this.adapter=new ee(this.contentStorage),this.resolver=new te(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 re=r.z.object({message:r.z.string().describe("The message containing entity references to resolve"),entities:r.z.array(r.z.object({entityId:r.z.string(),entityName:r.z.string(),entityType:r.z.string()})).describe("Available entities in memory")}),oe=r.z.object({response:r.z.string().describe("Agent response text to extract entities from"),userMessage:r.z.string().describe("Original user message for context")});class se 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=re,this.llm=new l.ChatOpenAI({apiKey:e,modelName:t,temperature:0})}async _call(e){const{message:t,entities:n}=e;if(!n||0===n.length)return t;const r=this.groupEntitiesByType(n),o=`Task: Replace entity references with IDs.\n\n${this.buildEntityContext(r)}\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(o)).content.trim()}catch(s){return console.error("[ResolveEntitiesTool] Failed:",s),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,r]of Object.entries(e)){const e=r[0];t+=`- Most recent ${n}: "${e.entityName}" = ${e.entityId}\n`}return t}}class ie 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=oe,this.llm=new l.ChatOpenAI({apiKey:e,modelName:t,temperature:0})}async _call(e){const{response:t,userMessage:n}=e,r=`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(r),t=e.content.match(/\[[\s\S]*?\]/);return t?t[0]:"[]"}catch(o){return console.error("[ExtractEntitiesTool] Failed:",o),"[]"}}}function ae(e,t="gpt-4o-mini"){return{resolveEntities:new se(e,t),extractEntities:new ie(e,t)}}const ce="gpt-4o",le="testnet",ge="autonomous";class he{constructor(e){if(this.options=e,this.stateManager=e.stateManager||new t.OpenConvaiState,this.hcs10Plugin=new f,this.hcs2Plugin=new y,this.inscribePlugin=new T,this.hbarPlugin=new v,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 V(this.options.entityMemoryConfig),this.logger.info("Entity memory initialized"),this.entityTools=ae(e.openAIApiKey,"gpt-4o-mini"),this.logger.info("LLM-based entity resolver tools initialized")}}async initialize(){const{accountId:t,privateKey:n,network:r=le,openAIApiKey:o,openAIModelName:s=ce,llmProvider:i="openai"}=this.options;this.validateOptions(t,n);try{const a=new e.ServerSigner(t,n,r);let c;if("anthropic"===i)c=new d.ChatAnthropic({apiKey:o,modelName:s||"claude-3-5-sonnet-20241022",temperature:.1});else{const e=s||"gpt-4o-mini",t=e.toLowerCase().includes("gpt-5")||e.toLowerCase().includes("gpt5");c=new l.ChatOpenAI({apiKey:o,modelName:s,...t?{temperature:1}:{temperature:.1}})}console.log("🟡 Preparing plugins...");const g=this.preparePlugins();console.log("🟡 Creating agent config...");const h=this.createAgentConfig(a,c,g);if(console.log("🟡 Creating agent..."),this.agent=Y(h),console.log("🟡 Agent created"),console.log("🟡 Configuring HCS10 plugin..."),this.configureHCS10Plugin(g),console.log("🟡 HCS10 plugin configured"),this.contentStoreManager=new ne,await this.contentStoreManager.initialize(),this.logger.info("ContentStoreManager initialized for content reference support"),console.log("🔥 About to call agent.boot()"),this.logger.info("🔥 About to call agent.boot()"),await this.agent.boot(),console.log("🔥 agent.boot() completed"),this.logger.info("🔥 agent.boot() completed"),this.agent){const e=h;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,r={messages:t.map(e=>"human"===e.type?new p.HumanMessage(e.content):new p.AIMessage(e.content))},o=await this.agent.chat(n,r);return this.memoryManager&&await this.extractAndStoreEntities(o,e),this.logger.info("Message processed successfully"),o}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");if("string"!=typeof e)throw new Error("Account ID must be a string, received "+typeof e);if("string"!=typeof t)throw new Error(`Private key must be a string, received ${typeof t}: ${JSON.stringify(t)}`);if(t.length<10)throw new Error("Private key appears to be invalid (too short)")}preparePlugins(){const{additionalPlugins:t=[],enabledPlugins:n}=this.options,r=[this.hcs10Plugin,this.hcs2Plugin,this.inscribePlugin,this.hbarPlugin],o=e.getAllHederaCorePlugins();if(n){const e=new Set(n);return[...[...r,...o].filter(t=>e.has(t.id)),...t]}return[...r,...o,...t]}createAgentConfig(e,t,n){const{operationalMode:r=ge,userAccountId:o,scheduleUserTransactionsInBytesMode:s,customSystemMessagePreamble:i,customSystemMessagePostamble:a,verbose:c=!1,mirrorNodeConfig:l,disableLogging:g,accountId:h=""}=this.options;return{framework:"langchain",signer:e,execution:{mode:"autonomous"===r?"direct":"bytes",operationalMode:r,...o&&{userAccountId:o},...void 0!==s&&{scheduleUserTransactionsInBytesMode:s,scheduleUserTransactions:s}},ai:{provider:new X(t),temperature:.1},filtering:{toolPredicate:e=>"hedera-account-transfer-hbar"!==e.name&&!(this.options.toolFilter&&!this.options.toolFilter(e))},messaging:{systemPreamble:i||Q(h),...a&&{systemPostamble:a},conciseMode:!0},extensions:{plugins:n,...l&&{mirrorConfig:l}},...this.options.mcpServers&&{mcp:{servers:this.options.mcpServers,autoConnect:!1}},debug:{verbose:c,silent:g??!1}}}configureHCS10Plugin(e){const t=e.find(e=>"hcs-10"===e.id);t&&(t.appConfig={stateManager:this.stateManager})}static withPlugins(e,t){return new he({...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 he({...e,mcpServers: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 r=this.extractResponseText(e),o=await this.entityTools.extractEntities.call({response:r,userMessage:t});try{const t=JSON.parse(o);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(r){throw this.logger.error("Entity extraction failed:",r),r}}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)}}class ue extends i.StructuredTool{constructor(e,t={}){super(),this.originalTool=e,this.wrapperConfig=t,this.logger=new n.Logger({module:"ExternalToolWrapper"}),this.name=e.name,this.description=t.ui?.description||e.description,this.enhancedSchema=this.createEnhancedSchema(e.schema,t),this.schema=this.enhancedSchema,this.logger.info(`Wrapped external tool: ${this.name}`,{hasRenderConfig:!!t.renderConfig,fieldConfigCount:Object.keys(t.fieldConfigs||{}).length,preserveOriginal:t.preserveOriginalSchema})}createEnhancedSchema(e,t){if(null===(n=e)||"object"!=typeof n||!("_def"in n)||"object"!=typeof n._def||"ZodObject"!==n._def.typeName||!("shape"in n._def))return this.logger.warn("Original schema is not a ZodObject, returning as-is"),e;var n;try{let n=e;return t.fieldConfigs&&Object.keys(t.fieldConfigs).length>0&&(n=this.addFieldRenderConfigs(n,t.fieldConfigs)),t.renderConfig&&(n=this.addToolRenderConfig(n,t.renderConfig)),n}catch(r){return this.logger.error("Failed to create enhanced schema:",r),e}}addFieldRenderConfigs(e,t){const n=e._def.shape(),o={};for(const[r,s]of Object.entries(n)){let e=s;t[r]&&(e=this.addRenderConfigToField(s,t[r])),o[r]=e}return r.z.object(o)}addRenderConfigToField(e,t){const n=e.describe(e.description||t.ui?.helpText||"");return n._renderConfig=t,n}addToolRenderConfig(e,t){const n=e.describe(e.description||t.ui?.helpText||"");return n._renderConfig=t,n}async _call(e,t){this.logger.debug(`Delegating call to original tool: ${this.name}`,{input:e});return this.originalTool._call(e,t)}}const me={text:(e,t,n)=>({fieldType:"text",ui:{label:e,...t&&{placeholder:t},...n&&{helpText:n}}}),number:(e,t,n,r)=>({fieldType:"number",ui:{label:e,...r&&{placeholder:r}},...void 0!==t||void 0!==n?{constraints:{...void 0!==t&&{min:t},...void 0!==n&&{max:n}}}:{}}),select:(e,t,n)=>({fieldType:"select",ui:{label:e,...n&&{helpText:n}},options:t}),textarea:(e,t,n)=>({fieldType:"textarea",ui:{label:e,...t&&{placeholder:t}},...void 0!==n?{constraints:{maxLength:n}}:{}}),checkbox:(e,t)=>({fieldType:"checkbox",ui:{label:e,...t&&{helpText:t}}}),currency:(e,t="HBAR",n,r)=>({fieldType:"currency",ui:{label:e,placeholder:`Amount in ${t}`},...void 0!==n||void 0!==r?{constraints:{...void 0!==n&&{min:n},...void 0!==r&&{max:r}}}:{}}),accountId:(e="Account ID")=>({fieldType:"text",ui:{label:e,placeholder:"0.0.123456",helpText:"Hedera account ID in format 0.0.accountNum"},constraints:{pattern:"^0\\.0\\.[0-9]+$"}}),tokenId:(e="Token ID")=>({fieldType:"text",ui:{label:e,placeholder:"0.0.789012",helpText:"Hedera token ID in format 0.0.tokenNum"},constraints:{pattern:"^0\\.0\\.[0-9]+$"}}),privateKey:(e="Private Key")=>({fieldType:"text",ui:{label:e,placeholder:"Enter private key",helpText:"DER-encoded private key as hex string"},constraints:{minLength:64,maxLength:128}})};function de(e,t={}){return new ue(e,t)}const pe={hbarTransfer:()=>({ui:{label:"Transfer HBAR",description:"Transfer HBAR between accounts"},fieldConfigs:{fromAccountId:me.accountId("From Account"),toAccountId:me.accountId("To Account"),amount:me.currency("Amount","HBAR",1e-8),memo:me.text("Memo","Optional memo","Transaction memo (optional)")}}),tokenCreation:()=>({ui:{label:"Create Token",description:"Create a new Hedera token"},fieldConfigs:{treasuryAccountId:me.accountId("Treasury Account"),tokenName:me.text("Token Name","My Token"),tokenSymbol:me.text("Token Symbol","MTK"),maxSupply:me.number("Max Supply",1,Number.MAX_SAFE_INTEGER),decimals:me.number("Decimals",0,18),memo:me.textarea("Memo","Token description")}}),accountCreation:()=>({ui:{label:"Create Account",description:"Create a new Hedera account"},fieldConfigs:{publicKey:me.text("Public Key","ED25519 public key"),initialBalance:me.currency("Initial Balance","HBAR",0),memo:me.text("Memo","Account memo","Optional account memo")}}),smartContract:()=>({ui:{label:"Smart Contract",description:"Deploy or call smart contract"},fieldConfigs:{contractId:me.text("Contract ID","0.0.123456"),gas:me.number("Gas Limit",1e3,1e6),payableAmount:me.currency("Payable Amount","HBAR",0)}})};exports.BaseAgent=R,exports.ContentStorage=U,exports.ContentStoreManager=ne,exports.ConversationalAgent=he,exports.ExternalToolWrapper=ue,exports.ExtractEntitiesTool=ie,exports.FormGenerator=I,exports.FormValidatingToolWrapper=G,exports.HCS10Plugin=f,exports.HCS2Plugin=y,exports.HbarPlugin=v,exports.InscribePlugin=T,exports.LangChainAgent=Z,exports.LangChainProvider=X,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=L,exports.OpenConvAIPlugin=f,exports.ResolveEntitiesTool=se,exports.SmartMemoryManager=V,exports.TokenCounter=H,exports.createAgent=Y,exports.createEntityTools=ae,exports.createMCPConfig=function(e,t=!0){return{mcpServers:e.map(e=>({...e,autoConnect:e.autoConnect??t}))}},exports.hederaToolConfigs=pe,exports.renderConfigs=me,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},exports.wrapExternalToolWithRenderConfig=de,exports.wrapExternalTools=function(e){return e.map(({tool:e,config:t={}})=>de(e,t))},exports.wrapToolWithFormValidation=J,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.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("hedera-agent-kit"),t=require("@hashgraphonline/standards-agent-kit"),r=require("@hashgraphonline/standards-sdk"),o=require("zod"),s=require("@hashgraph/sdk"),n=require("bignumber.js"),i=require("@langchain/core/tools"),a=require("langchain/agents"),c=require("zod-to-json-schema"),l=require("@langchain/core/prompts"),g=require("@langchain/openai"),h=require("@modelcontextprotocol/sdk/client/index.js"),m=require("@modelcontextprotocol/sdk/client/stdio.js"),u=require("tiktoken"),d=require("crypto"),p=require("@langchain/core/messages"),f=require("@langchain/anthropic");class y 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 o=e.config.hederaKit;if(o)try{this.stateManager=e.stateManager||e.config.stateManager||this.appConfig?.stateManager||new t.OpenConvaiState;const i=o.signer.getAccountId().toString();let a="",c="";try{const e=o.signer.getOperatorPrivateKey(),t="function"==typeof e?.toStringRaw?e.toStringRaw():"function"==typeof e?.toString?e.toString():String(e),s=new r.HCS10Client({network:o.network,operatorId:i,operatorPrivateKey:t,logLevel:"error"}),n=await s.retrieveProfile(i);n.success&&n.topicInfo&&(a=n.topicInfo.inboundTopic,c=n.topicInfo.outboundTopic)}catch(s){this.context.logger.warn("Could not retrieve profile topics:",s)}if(this.stateManager.setCurrentAgent({name:`Agent ${i}`,accountId:i,inboundTopicId:a,outboundTopicId:c,privateKey:(()=>{const e=o.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=o.signer.getOperatorPrivateKey(),t="function"==typeof e?.toStringRaw?e.toStringRaw():"function"==typeof e?.toString?e.toString():String(e),s=new r.HCS10Client({network:o.network,operatorId:i,operatorPrivateKey:t,logLevel:"error"});this.stateManager.initializeConnectionsManager(s),this.context.logger.info("ConnectionsManager initialized in HCS10Plugin")}catch(n){this.context.logger.warn("Could not initialize ConnectionsManager:",n)}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 r=new t.HCS10Builder(e,this.stateManager);this.tools=[new t.RegisterAgentTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger}),new t.FindRegistrationsTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger}),new t.RetrieveProfileTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger}),new t.InitiateConnectionTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger}),new t.ListConnectionsTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger}),new t.SendMessageToConnectionTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger}),new t.CheckMessagesTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger}),new t.ConnectionMonitorTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger}),new t.ManageConnectionRequestsTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger}),new t.AcceptConnectionRequestTool({hederaKit:e,hcs10Builder:r,logger:this.context.logger}),new t.ListUnapprovedConnectionRequestsTool({hederaKit:e,hcs10Builder:r,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 T 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 r=new t.HCS2Builder(e);this.tools=[new t.CreateRegistryTool({hederaKit:e,hcs2Builder:r,logger:this.context.logger}),new t.RegisterEntryTool({hederaKit:e,hcs2Builder:r,logger:this.context.logger}),new t.UpdateEntryTool({hederaKit:e,hcs2Builder:r,logger:this.context.logger}),new t.DeleteEntryTool({hederaKit:e,hcs2Builder:r,logger:this.context.logger}),new t.MigrateRegistryTool({hederaKit:e,hcs2Builder:r,logger:this.context.logger}),new t.QueryRegistryTool({hederaKit:e,hcs2Builder:r,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 r=new t.InscriberBuilder(e);this.tools=[new t.InscribeFromUrlTool({hederaKit:e,inscriberBuilder:r,logger:this.context.logger}),new t.InscribeFromFileTool({hederaKit:e,inscriberBuilder:r,logger:this.context.logger}),new t.InscribeFromBufferTool({hederaKit:e,inscriberBuilder:r,logger:this.context.logger}),new t.InscribeHashinalTool({hederaKit:e,inscriberBuilder:r,logger:this.context.logger}),new t.RetrieveInscriptionTool({hederaKit:e,inscriberBuilder:r,logger:this.context.logger})]}getTools(){return this.tools}async cleanup(){this.tools=[],this.context?.logger&&this.context.logger.info("Inscribe Plugin cleaned up")}}class S extends e.BaseServiceBuilder{constructor(e){super(e)}transferHbar(e,t=!0){this.clearNotes();const r=new s.TransferTransaction;if(!e.transfers||0===e.transfers.length)throw new Error("HbarTransferParams must include at least one transfer.");let o=new n(0),i=!1;if(t&&this.kit.userAccountId&&"provideBytes"===this.kit.operationalMode&&1===e.transfers.length){const t=e.transfers[0],o="string"==typeof t.amount||"number"==typeof t.amount?t.amount:t.amount.toString(),a=new n(o);if(a.isPositive()){const e="string"==typeof t.accountId?s.AccountId.fromString(t.accountId):t.accountId,o=a.toFixed(8,n.ROUND_DOWN),c=s.Hbar.fromString(o);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()}.`),r.addHbarTransfer(e,c),r.addHbarTransfer(s.AccountId.fromString(this.kit.userAccountId),c.negated()),i=!0}}if(!i){const t=[];for(const r of e.transfers){const e="string"==typeof r.accountId?s.AccountId.fromString(r.accountId):r.accountId,i="string"==typeof r.amount||"number"==typeof r.amount?r.amount:r.amount.toString(),a=new n(i),c=a.toFixed(8,n.ROUND_DOWN);this.logger.info(`Processing transfer: ${i} HBAR (rounded to ${c}) for account ${e.toString()}`);const l=s.Hbar.fromString(c);t.push({accountId:e,amount:a,hbar:l});const g=l.toTinybars();o=o.plus(g.toString())}if(!o.isZero()&&(this.logger.warn(`Transfer sum not zero: ${o.toString()} tinybars off. Adjusting last transfer.`),t.length>0)){const e=t[t.length-1],r=o.dividedBy(-1e8),i=e.amount.plus(r).toFixed(8,n.ROUND_DOWN);e.hbar=s.Hbar.fromString(i),this.logger.info(`Adjusted last transfer for ${e.accountId.toString()} to ${i} HBAR`)}for(const e of t)r.addHbarTransfer(e.accountId,e.hbar)}return void 0!==e.memo&&(null===e.memo?this.logger.warn("Received null for memo in transferHbar."):r.setTransactionMemo(e.memo)),this.setCurrentTransaction(r),this}}const b=o.z.object({accountId:o.z.string().describe('Account ID for the transfer (e.g., "0.0.xxxx").'),amount:o.z.union([o.z.number(),o.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=o.z.object({transfers:o.z.array(b).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:o.z.string().optional().describe("Optional. Memo for the transaction.")});class k 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 S(this.hederaKit)}async callBuilderMethod(e,t){await e.transferHbar(t)}}class x 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=o.z.object({tokenId:o.z.string().describe('The ID of the fungible token to airdrop (e.g., "0.0.yyyy").'),recipients:o.z.array(o.z.object({accountId:o.z.string().describe('Recipient account ID (e.g., "0.0.xxxx").'),amount:o.z.union([o.z.number(),o.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:o.z.string().optional().describe("Optional. Memo for the transaction.")}),this.originalTool=e,this.agentKit=t,this.logger=new r.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 r=e.recipients.map(e=>{const r="string"==typeof e.amount?parseFloat(e.amount):e.amount,o=this.convertToSmallestUnits(r,t);return this.logger.info(`Converting amount for ${e.accountId}: ${r} tokens → ${o} smallest units`),{...e,amount:o.toString()}}),o={...e,recipients:r};return this.logger.info("Calling original airdrop tool with converted amounts"),await this.originalTool._call(o)}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 r=await t.getTokenInfo(e);if(r&&void 0!==r.decimals){const t=parseInt(r.decimals.toString())||0;return this.logger.info(`Token ${e} found with ${t} decimals`),{...r,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",r=await fetch(`${t}/api/v1/tokens/${e}`);if(r.ok){const t=await r.json(),o=parseInt(String(t.decimals||"0"));return this.logger.info(`Token ${e} found with ${o} decimals via API`),{...t,decimals:o}}}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 M 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 r=new k({hederaKit:t,logger:this.context.logger});this.tools=[r];try{this.context.logger.info("Creating wrapper for passed original airdrop tool");const r=new e.HederaAirdropTokenTool({hederaKit:t,logger:this.context.logger}),o=new x(r,t);this.tools.push(o),this.context.logger.info("Added wrapped airdrop tool to HBAR Plugin")}catch(o){this.context.logger.error("Error creating airdrop tool wrapper:",o)}this.context.logger.info(`HBAR Plugin tools initialized with ${this.tools.length} tools`)}getTools(){return this.tools}async shutdown(){this.tools=[]}}class v{constructor(){this.patterns=new Map,this.initializeDefaultPatterns()}static getInstance(){return v.instance||(v.instance=new v),v.instance}initializeDefaultPatterns(){this.register("numeric-supply-exact",{pattern:["maxSupply","minSupply","totalSupply"],type:"number",priority:15}),this.register("numeric-supply",{pattern:/supply$/i,type:"number",priority:10}),this.register("numeric-amounts",{pattern:/(?:amount|quantity|count|total|sum|value)$/i,type:"number",priority:8}),this.register("numeric-time",{pattern:/(?:period|duration|time|timeout|delay|interval)$/i,type:"number",priority:8}),this.register("numeric-limits",{pattern:/(?:limit|max|min|threshold|size|length)$/i,type:"number",priority:7}),this.register("currency",{pattern:/(?:price|cost|fee|payment|balance|amount)$/i,type:"currency",priority:9}),this.register("percentage",{pattern:/(?:percent|percentage|rate|ratio)$/i,type:"percentage",priority:9}),this.register("boolean-freeze",{pattern:["freezeDefault","freeze"],type:"checkbox",priority:10}),this.register("boolean-flags",{pattern:/(?:is|has|can|should|enable|disable|active|default|allow)(?:[A-Z]|$)/,type:"checkbox",priority:8}),this.register("textarea",{pattern:/(?:memo|description|notes|comment|message|content|body|text)$/i,type:"textarea",priority:8}),this.register("array-fees",{pattern:["customFees","fees"],type:"array",priority:10}),this.register("array-general",{pattern:/(?:list|items|array|collection)$/i,type:"array",priority:7}),this.register("object-options",{pattern:["metaOptions","options"],type:"object",priority:10}),this.register("object-config",{pattern:/(?:config|settings|configuration|metadata|data|info)$/i,type:"object",priority:7}),this.register("select-type",{pattern:/(?:type|kind|category|status|state|mode)$/i,type:"select",priority:7})}register(e,t){this.patterns.set(e,t)}unregister(e){return this.patterns.delete(e)}detectType(e){const t=[];for(const r of this.patterns.values()){let o=!1;Array.isArray(r.pattern)?o=r.pattern.some(t=>e===t||e.toLowerCase()===t.toLowerCase()):r.pattern instanceof RegExp&&(o=r.pattern.test(e)),o&&t.push({type:r.type,priority:r.priority??5})}return t.length>0?(t.sort((e,t)=>t.priority-e.priority),t[0].type):null}getPatterns(){return new Map(this.patterns)}clear(){this.patterns.clear()}reset(){this.clear(),this.initializeDefaultPatterns()}}const F=v.getInstance();class I{constructor(){this.logger=new r.Logger({module:"FormGenerator"})}generateFormFromError(e,t,r,o){const s=this.extractValidationErrors(e),n=this.identifyMissingFields(s,t),i=this.createFormConfig(t,n,r);return{type:"form",id:`form_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,formConfig:i,originalPrompt:o,toolName:r,validationErrors:s}}async generateFormFromSchema(e,t,r,o){let s;if(this.logger.info("🏁 FormGenerator.generateFormFromSchema starting",{toolName:r.toolName,partialInput:t,hasSchema:!!e,hasShape:!(!e||!e.shape),hasPreCalculatedFields:void 0!==o,preCalculatedFieldsSize:o?.size||0}),void 0!==o)s=o,this.logger.info("📋 Using pre-calculated missing fields",{missingFieldsCount:s.size,missingFields:Array.from(s)});else{s=new Set;const t=this.extractZodObject(e);if(t){const e=t.shape;for(const t of Object.keys(e))s.add(t),this.logger.info(`⭐ Including all fields from focused schema: ${t}`)}this.logger.info("📋 Using ALL fields from focused schema",{totalFields:t?Object.keys(t.shape).length:0,missingFieldsCount:s.size,missingFields:Array.from(s)})}const n=this.createFormConfig(e,s,r.toolName,o);return{type:"form",id:`form_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,formConfig:n,originalPrompt:r.toolDescription||`Complete ${r.toolName}`,toolName:r.toolName,validationErrors:[]}}extractValidationErrors(e){return e.issues.map(e=>({path:e.path.map(e=>String(e)),message:e.message,code:e.code}))}identifyMissingFields(e,t){const r=new Set;return e.forEach(e=>{const t=e.path.join(".");t&&r.add(t)}),r}createFormConfig(e,t,r,o){const s=this.extractRenderConfigsSafely(e),n=this.generateFieldOrderingSafely(e),i=this.generateFormFields(e,s,t,n,o);return{title:this.generateFormTitle(r),description:this.generateFormDescription(r,t.size),fields:i,submitLabel:"Continue",cancelLabel:"Cancel",metadata:{toolName:r,missingFieldCount:t.size}}}extractRenderConfigsSafely(e){try{if("function"==typeof t.extractRenderConfigs)return t.extractRenderConfigs(e)}catch(r){this.logger.warn("Could not extract render configs:",r)}return{fields:{},groups:{},order:[],metadata:{}}}generateFieldOrderingSafely(e){try{if("function"==typeof t.generateFieldOrdering){const r=t.generateFieldOrdering(e);return{sections:Object.values(r.sections).map(e=>({fields:e.fields}))}}}catch(r){this.logger.warn("Could not generate field ordering:",r)}return{sections:[]}}getFieldPriority(e,t,r){if(t?.ui?.priority){const e=t.ui.priority;if(["essential","common","advanced","expert"].includes(e))return e}if(!0===r)return"essential";const o=t?.ui;return!0===o?.advanced?"advanced":!0===o?.expert?"expert":"common"}determineFieldsToInclude(e,t,r){const o=new Set;if(void 0===r){this.logger.info("⭐ Focused schema mode - including ALL fields from schema");this.extractFieldsFromSchema(e).forEach(e=>{o.add(e),this.logger.info(`✅ Including focused schema field: ${e}`)})}else r.size>0?(this.logger.info(`📋 Using ONLY pre-calculated missing fields (${r.size} fields)`,{fields:Array.from(r)}),r.forEach(e=>{o.add(e),this.logger.info(`✅ Including pre-calculated field: ${e}`)})):(this.logger.info("⚠️ No pre-calculated fields, falling back to schema analysis"),this.includeRequiredMissingFields(e,t,o));return o}includeRequiredMissingFields(e,t,r){this.extractFieldsFromSchema(e).forEach(o=>{const s=this.isFieldRequired(e,o),n=t.has(o),i=n&&s;this.logger.info(`🔍 FormGenerator field inclusion check: ${o}`,{isRequired:s,isMissing:n,shouldInclude:i}),i&&r.add(o)})}createOrderedFields(e,t,r,o){const s=[],n=new Set;if(t.sections.length>0){t.sections.flatMap(e=>e.fields).forEach(t=>{if(e.has(t)&&!n.has(t)){const e=this.createFormField(t,r.fields[t],o,t);e&&(s.push(e),n.add(t))}})}return e.forEach(e=>{if(!n.has(e)){const t=this.createFormField(e,r.fields[e],o,e);t&&s.push(t)}}),s}generateFormFields(e,t,r,o,s){const n=this.determineFieldsToInclude(e,r,s);let i=this.createOrderedFields(n,o,t,e);return 0===i.length&&r.size>0&&(i=Array.from(r).map(r=>this.createFormField(r,t.fields[r],e,r)).filter(e=>null!=e)),i}createFormField(e,t,r,o){const s=this.mapFieldType(t?.fieldType,r,o),n=this.isFieldRequired(r,o||e),i={name:e,label:t?.ui?.label||this.humanizeFieldName(e),type:s,required:n,priority:this.getFieldPriority(e,t,n)};if(t&&(i.renderConfig=t),t?.ui?.placeholder&&(i.placeholder=t.ui.placeholder),t?.ui?.helpText&&(i.helpText=t.ui.helpText),t?.constraints){const e={};void 0!==t.constraints.min&&(e.min=t.constraints.min),void 0!==t.constraints.max&&(e.max=t.constraints.max),void 0!==t.constraints.minLength&&(e.minLength=t.constraints.minLength),void 0!==t.constraints.maxLength&&(e.maxLength=t.constraints.maxLength),void 0!==t.constraints.pattern&&(e.pattern=t.constraints.pattern),Object.keys(e).length>0&&(i.validation=e)}return t?.options&&(i.options=t.options.map(e=>({value:String(e.value),label:e.label,...void 0!==e.disabled&&{disabled:e.disabled}}))),i}mapFieldType(e,t,r){if(!e&&t&&r){const e=this.inferTypeFromSchema(t,r);if(e)return e}if(!e&&r){const e=F.detectType(r);if(e)return e}if(!e)return"text";const o=e.toLowerCase();return["text","string"].includes(o)?"text":["number","integer","float","decimal"].includes(o)?"number":["select","enum","dropdown"].includes(o)?"select":["checkbox","boolean","bool"].includes(o)?"checkbox":["textarea","longtext","multiline"].includes(o)?"textarea":["file","upload","attachment"].includes(o)?"file":["array","list"].includes(o)?"array":["object","json"].includes(o)?"object":["currency","money","price"].includes(o)?"currency":["percentage","percent"].includes(o)?"percentage":"text"}humanizeFieldName(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\./g," ").trim().split(" ").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}generateFormTitle(e){return`Complete ${e.replace(/Tool$/,"").replace(/Hedera/g,"").replace(/([A-Z])/g," $1").trim()} Information`}extractZodObject(e){try{const t=e._def;if(t&&"ZodObject"===t.typeName)return e}catch(t){this.logger.debug("Could not extract ZodObject from schema:",t)}return null}extractFieldsFromSchema(e){const t=[],r=this.extractZodObject(e);if(r)return t.push(...Object.keys(r.shape)),t;try{const r=e._def;if(r&&"ZodUnion"===r.typeName&&r.options){const e=r.options[0],o=this.extractZodObject(e);o&&t.push(...Object.keys(o.shape))}}catch(o){this.logger.debug("Could not extract fields from schema structure:",o)}return t}inferTypeFromSchema(e,t){try{const r=this.extractZodObject(e);if(!r)return null;const o=r.shape;if(!o)return null;let s=o[t];if(!s)return null;const n=s._def;if(n&&"ZodOptional"===n.typeName&&n.innerType&&(s=n.innerType),!s||!s._def)return null;const i=s._def.typeName,a=t.toLowerCase();switch(i){case"ZodString":return a.includes("memo")||a.includes("description")?"textarea":"text";case"ZodNumber":return a.includes("percent")?"percentage":a.includes("price")||a.includes("cost")?"currency":"number";case"ZodBoolean":return"checkbox";case"ZodEnum":case"ZodNativeEnum":return"select";case"ZodArray":return"array";case"ZodObject":return"object";default:return"text"}}catch(r){this.logger.debug("Could not infer type from schema:",r)}return null}isFieldRequired(e,t){if(!e||!t)return!1;try{const r=this.extractZodObject(e);if(!r)return!1;const o=r.shape;if(!o||!o[t])return!1;const s=o[t];if(!s||!s._def)return!0;const n=s._def,i=n.typeName;return"ZodOptional"!==i&&("ZodDefault"!==i&&void 0===n.defaultValue)}catch(r){this.logger.debug(`Could not determine if field ${t} is required:`,r)}return!1}generateFormDescription(e,t){return 0===t?"Please provide the required information to continue with your request.":`Please provide the following ${t} required field${1!==t?"s":""} to continue with your request.`}generateJsonSchemaForm(e,t,r){const o=c.zodToJsonSchema(e,{target:"jsonSchema7"}),s={};let n=o;if(r&&r.size>0){const e=o;if(e.properties&&"object"==typeof e.properties){const t={...e,type:"object",properties:{},required:[]};let o=0;r.forEach(r=>{e.properties&&e.properties[r]&&(t.properties[r]=e.properties[r],o++)}),Array.isArray(e.required)&&(t.required=e.required.filter(e=>r.has(e))),o>0&&(n=t)}}return this.extractFieldsFromSchema(e).forEach(t=>{const r=this.isFieldRequired(e,t),o=this.getFieldPriority(t,void 0,r),n=t.toLowerCase();switch("attributes"!==n&&"metadata"!==n&&"properties"!==n||(s[t]={"ui:options":{collapsible:!0,collapsed:!0}}),o){case"essential":r&&(s[t]={...s[t],"ui:help":"Required field"});break;case"advanced":case"expert":s[t]={...s[t],"ui:options":{...s[t]?.["ui:options"],collapsed:!0}}}}),{jsonSchema:n,uiSchema:s}}}class A{constructor(e){this.formGenerator=new I,this.logger=e||new r.Logger({module:"FormEngine"})}async generateForm(e,r,s,n){const i={tool:r,input:s,...n};try{return t.isFormValidatable(r)?await this.generateFormValidatableForm(r,s,i):s instanceof o.ZodError?await this.generateErrorBasedForm(r,s,i):this.hasRenderConfig(r)?await this.generateRenderConfigForm(r,s,i):this.isZodObject(r.schema)?await this.generateSchemaBasedForm(r,s,i):null}catch(a){throw this.logger.error(`Failed to generate form for tool: ${e}`,{error:a instanceof Error?a.message:String(a)}),a}}async processSubmission(e,t){this.validateSubmission(e);const r=this.extractBaseToolInput(t),o=this.extractSubmissionData(e);return this.mergeInputData(r,o)}shouldGenerateForm(e,r){const o=r;if(!0===o?.__fromForm||!1===o?.renderForm)return!1;if(t.isFormValidatable(e))try{return e.shouldGenerateForm(r)}catch(s){return this.logger.error(`Error calling shouldGenerateForm() on ${e.name}:`,s),!1}return!this.validateInput(e,r).isValid}async generateFormFromError(e,t,r,o){return this.formGenerator.generateFormFromError(e,r,t,o)}async generateFormValidatableForm(e,t,r){const{schemaToUse:o,isFocusedSchema:s}=this.resolveFormSchema(e),n=this.determineMissingFields(e,t,o,s);return this.generateFormWithSchema(e,t,o,n)}async generateSchemaBasedForm(e,t,r){const o=e.schema,s=await this.formGenerator.generateFormFromSchema(o,t,{toolName:e.name,toolDescription:e.description},r.missingFields);if(this.isZodObject(o))try{const{jsonSchema:e,uiSchema:n}=this.formGenerator.generateJsonSchemaForm(o,t,r.missingFields||new Set);s.jsonSchema=e,s.uiSchema=n}catch(n){this.logger.warn("Failed to generate JSON Schema for schema-based tool:",n)}return s.partialInput=t,s}async generateRenderConfigForm(e,t,r){const o=e.schema,s=this.extractRenderConfig(e),n=await this.formGenerator.generateFormFromSchema(o,t,{toolName:e.name,toolDescription:e.description},r.missingFields);return s&&(n.formConfig.metadata={...n.formConfig.metadata,renderConfig:s}),n.partialInput=t,n}async generateErrorBasedForm(e,t,r){return this.formGenerator.generateFormFromError(t,e.schema,e.name,r.input?String(r.input):"")}validateInput(e,t){try{return e.schema.parse(t),{isValid:!0}}catch(r){if(r instanceof o.ZodError){return{isValid:!1,errors:r.errors.map(e=>`${e.path.join(".")}: ${e.message}`)}}return{isValid:!1,errors:["Validation failed"]}}}isZodObject(e){if(!e||"object"!=typeof e)return!1;const t=e;return Boolean(t._def&&"ZodObject"===t._def.typeName)}hasRenderConfig(e){const t=e.schema;return!(!t||!t._renderConfig)}extractRenderConfig(e){const t=e.schema;return t?._renderConfig}resolveFormSchema(e){const t=e;if(t.getFormSchema){const e=t.getFormSchema();if(e)return{schemaToUse:e,isFocusedSchema:!0}}return{schemaToUse:e.schema,isFocusedSchema:!1}}determineMissingFields(e,t,r,o){const s=new Set;if(!t||"object"!=typeof t)return s;const n=t,i=e;if(i.getEssentialFields){const e=i.getEssentialFields();for(const t of e)(!(t in n)||i.isFieldEmpty&&i.isFieldEmpty(t,n[t]))&&s.add(t)}return s}async generateFormWithSchema(e,t,r,o){const s=await this.formGenerator.generateFormFromSchema(r,t,{toolName:e.name,toolDescription:e.description},o);if(this.isZodObject(r))try{const{jsonSchema:e,uiSchema:n}=this.formGenerator.generateJsonSchemaForm(r,t,o);s.jsonSchema=e,s.uiSchema=n}catch(n){this.logger.warn("Failed to generate JSON Schema:",n)}return s.partialInput=t,s}validateSubmission(e){if(!e.toolName)throw new Error("Tool name is required in form submission");if(!e.parameters)throw new Error("Parameters are required in form submission")}extractBaseToolInput(e){return e?.originalInput||{}}extractSubmissionData(e){return{...e.parameters,__fromForm:!0}}mergeInputData(e,t){return{...e,...t}}getRegisteredStrategies(){return["FormValidatable","SchemaBased","RenderConfig","ZodErrorBased"]}getRegisteredMiddleware(){return["FormSubmissionValidator"]}}class E{static isHashLinkResponse(e){if(!e||"object"!=typeof e)return!1;const t=e;return!(!0!==t.success||"inscription"!==t.type||!t.hashLinkBlock||"object"!=typeof t.hashLinkBlock)}static formatHashLinkResponse(e){const t=e.hashLinkBlock,r=e.metadata||{},o=e.inscription||{};let s="✅ Interactive content created successfully!\n\n";return r.name&&(s+=`**${r.name}**\n`),r.description&&(s+=`${r.description}\n\n`),(o.topicId||t.attributes.topicId)&&(s+=`📍 **Topic ID:** ${o.topicId||t.attributes.topicId}\n`),(o.hrl||t.attributes.hrl)&&(s+=`🔗 **HRL:** ${o.hrl||t.attributes.hrl}\n`),o.cdnUrl&&(s+=`🌐 **CDN URL:** ${o.cdnUrl}\n`),r.creator&&(s+=`👤 **Creator:** ${r.creator}\n`),s+="\n⚡ Interactive content will load below",s.trim()}static isInscriptionResponse(e){if(!e||"object"!=typeof e)return!1;const t=e;return!(!0!==t.success||"inscription"!==t.type||!t.inscription||"object"!=typeof t.inscription)}static formatInscriptionResponse(e){const t=e.inscription,r=e.metadata||{};let o=`✅ ${e.title||"Inscription Complete"}\n\n`;return r.name&&(o+=`**${r.name}**\n`),r.description&&(o+=`${r.description}\n\n`),t.topicId&&(o+=`📍 **Topic ID:** ${t.topicId}\n`),t.hrl&&(o+=`🔗 **HRL:** ${t.hrl}\n`),t.cdnUrl&&(o+=`🌐 **CDN URL:** ${t.cdnUrl}\n`),r.creator&&(o+=`👤 **Creator:** ${r.creator}\n`),o.trim()}static formatResponse(e){try{const t=JSON.parse(e);return E.isHashLinkResponse(t)?E.formatHashLinkResponse(t):E.isInscriptionResponse(t)?E.formatInscriptionResponse(t):e}catch{return e}}}const R=new Map;class L extends a.AgentExecutor{constructor(...e){super(...e),this.pendingForms=new Map,this.formGenerator=new I,this.formEngine=new A(new r.Logger({module:"FormAwareAgentExecutor.FormEngine"})),this.formLogger=new r.Logger({module:"FormAwareAgentExecutor"})}async _takeNextStep(e,r,o,s,n){this.formLogger.info("🛡️ BULLETPROOF INTERCEPTION: _takeNextStep called",{availableTools:Object.keys(e),inputKeys:Object.keys(r)});const i=await this.agent.plan(o,r,s?.getChild());if("returnValues"in i)return this.formLogger.info("Agent returned finish action, passing through"),i;const a=i,c=a.tool,l=a.toolInput;this.formLogger.info(`🎯 INTERCEPTING TOOL CALL: ${c}`,{toolInput:l,hasInNameToolMap:c in e,toolInputKeys:Object.keys(l||{})});const g=e[c]||this.tools.find(e=>e.name===c);if(!g)throw this.formLogger.error(`Tool ${c} not found in registry`),new Error(`Tool "${c}" not found`);let h=!1;if(t.isFormValidatable(g)){this.formLogger.info(`🔍 Tool ${c} implements FormValidatable, checking shouldGenerateForm()`,{toolInput:l});try{h=g.shouldGenerateForm(l),this.formLogger.info(`FormValidatable.shouldGenerateForm() result: ${h}`,{toolName:c,toolInput:l})}catch(m){this.formLogger.error(`Error calling shouldGenerateForm() on ${c}:`,m),h=!1}}if(h){this.formLogger.info(`🚨 FORM GENERATION TRIGGERED for ${c}`);try{let e,o=!1;if(t.isFormValidatable(g)){this.formLogger.info(`🎯 Tool ${c} is FormValidatable, attempting to get focused schema`);try{const t=g.getFormSchema();t?(e=t,o=!0,this.formLogger.info(`✅ Successfully obtained focused schema for ${c}`)):(this.formLogger.warn(`getFormSchema() returned null/undefined for ${c}, using default schema`),e=g.schema,o=!1)}catch(m){this.formLogger.error(`Failed to get focused schema from ${c}:`,m),this.formLogger.info(`Falling back to default schema for ${c}`),e=g.schema,o=!1}}else this.formLogger.info(`Tool ${c} is not FormValidatable, using default schema`),e=g.schema,o=!1;let s,n="unknown";try{if(e&&"object"==typeof e&&"shape"in e){const t=e.shape;t&&"object"==typeof t&&(n=Object.keys(t).length.toString())}}catch{}if(this.formLogger.info(`📋 Generating form with ${o?"FOCUSED":"DEFAULT"} schema`,{toolName:c,schemaType:e?.constructor?.name,estimatedFieldCount:n,isFocusedSchema:o}),o)this.formLogger.info("⭐ Using focused schema - letting FormGenerator determine fields from schema"),s=void 0;else{if(s=new Set,this.isZodObject(e)){const r=e.shape||{};for(const o of Object.keys(r)){const r=(l||{})[o],n=t.isFormValidatable(g)&&g.isFieldEmpty?g.isFieldEmpty(o,r):void 0===r||""===r||null===r||Array.isArray(r)&&0===r.length,i=this.isFieldRequired(e,o),a=!(!t.isFormValidatable(g)||!g.getEssentialFields)&&g.getEssentialFields().includes(o);this.formLogger.info(`🔍 Field analysis: ${o}`,{value:r,isEmpty:n,isRequired:i,isEssential:a,willAddToMissingFields:n&&(i||a)}),n&&(i||a)&&s.add(o)}}this.formLogger.info("📋 Missing fields analysis complete",{totalFields:this.isZodObject(e)?Object.keys(e.shape).length:0,missingFieldsCount:s.size,missingFields:Array.from(s)})}const i=await this.formGenerator.generateFormFromSchema(e,l,{toolName:c,toolDescription:g.description},s);if(this.isZodObject(e))try{const{jsonSchema:t,uiSchema:r}=this.formGenerator.generateJsonSchemaForm(e,l,s);i.jsonSchema=t,i.uiSchema=r}catch(m){this.formLogger.warn("Failed to generate JSON Schema for RJSF:",m)}i.partialInput=l;const h={toolName:c,originalInput:r,originalToolInput:l,schema:e,toolRef:g,originalToolRef:g.originalTool};this.pendingForms.set(i.id,h),R.set(i.id,h),this.formLogger.info(`✅ FORM INTERCEPT SUCCESS for ${c}`);const u={requiresForm:!0,formMessage:i};return[{action:a,observation:JSON.stringify(u)}]}catch(m){this.formLogger.error(`Form generation failed for ${c}:`,m)}}return this.formLogger.info(`⚪ Passing through to normal tool execution for ${c}`),super._takeNextStep(e,r,o,s,n)}isZodObject(e){if(!e||"object"!=typeof e)return!1;const t=e;return Boolean(t._def&&"ZodObject"===t._def.typeName)}isFieldRequired(e,t){if(!e||!t)return!1;try{const r=e._def;if(!r||"ZodObject"!==r.typeName)return!1;const o="function"==typeof r.shape?r.shape():r.shape;if(!o||"object"!=typeof o)return!1;const s=o[t];if(!s)return!1;const n=(e=>{const t=e._def;return t&&"ZodOptional"===t.typeName&&t.innerType?t.innerType:e})(s)._def;return!n||"ZodOptional"!==n.typeName&&"ZodDefault"!==n.typeName&&void 0===n.defaultValue}catch(r){this.formLogger.debug(`Could not determine if field ${t} is required:`,r)}return!1}async _call(e){try{const t=await super._call(e);if(t.intermediateSteps&&Array.isArray(t.intermediateSteps))for(const r of t.intermediateSteps)if(r.observation)try{const o="string"==typeof r.observation?JSON.parse(r.observation):r.observation;if(o.requiresForm&&o.formMessage){this.formLogger.info("Tool requested form generation",{toolName:r.action?.tool,hasForm:!0});const s=r.action?.tool||"unknown",n=this.tools.find(e=>e.name===s),i=n||{},a={toolName:s,originalInput:e,originalToolInput:r.action?.toolInput,schema:null,toolRef:n,originalToolRef:i?.originalTool};return this.pendingForms.set(o.formMessage.id,a),R.set(o.formMessage.id,a),{...t,requiresForm:!0,formMessage:o.formMessage,output:o.message||"Please complete the form to continue."}}if(o.hashLinkBlock||o.success&&o.inscription&&o.hashLinkBlock){this.formLogger.info("Tool returned HashLink blocks",{toolName:r.action?.tool,hasHashLink:!0,blockId:o.hashLinkBlock?.blockId});const e=this.processHashLinkResponse(o);return{...t,hasHashLinkBlocks:!0,hashLinkBlock:e.hashLinkBlock,output:e.message}}}catch{}return t}catch(t){if(t instanceof o.ZodError)return this.formLogger.info("Intercepted ZodError during agent execution"),this.handleValidationError(t,e,[]);throw t}}async handleValidationError(e,t,r){this.formLogger.info("Zod validation error detected, generating form",{errorIssues:e.issues.length,inputKeys:Object.keys(t)});let o=this.extractToolInfoFromError(e,t,r);if(!o){this.formLogger.warn("Could not extract tool info from validation error, trying fallback detection");const t=this.detectToolFromErrorContext(e);if(!t)throw this.formLogger.error("No tool detected for form generation, rethrowing error"),e;o=t}this.formLogger.info("Generating form for tool:",{toolName:o.toolName,hasSchema:!!o.schema});const s=this.formGenerator.generateFormFromError(e,o.schema,o.toolName,t.input||"");return this.pendingForms.set(s.id,{toolName:o.toolName,originalInput:t,schema:o.schema}),R.set(s.id,{toolName:o.toolName,originalInput:t,schema:o.schema}),{output:this.formatFormResponse(s),formMessage:s,requiresForm:!0,intermediateSteps:r||[]}}getPendingForms(){return new Map(this.pendingForms)}restorePendingForms(e){for(const[t,r]of e)this.pendingForms.set(t,r)}async processFormSubmission(e){if(this.formLogger.info("🚀 FormAwareAgentExecutor.processFormSubmission called!",{submissionFormId:e.formId,submissionToolName:e.toolName}),!e)throw new Error("Form submission is null or undefined");if(!e.formId)throw new Error("Form submission missing formId");if(!e.parameters||null===e.parameters||"object"!=typeof e.parameters||Array.isArray(e.parameters))throw new Error(`Form submission parameters are invalid: ${typeof e.parameters}, isNull: ${null===e.parameters}, isArray: ${Array.isArray(e.parameters)}, parameters: ${JSON.stringify(e.parameters)}`);this.formLogger.info("Processing form submission:",{formId:e.formId,toolName:e.toolName,parameterKeys:Object.keys(e.parameters),parametersType:typeof e.parameters,parametersIsNull:null===e.parameters,parametersIsUndefined:void 0===e.parameters,hasContext:!!e.context});let t=this.pendingForms.get(e.formId);if(!t&&(t=R.get(e.formId),!t))throw new Error(`No pending form found for ID: ${e.formId}`);this.pendingForms.delete(e.formId),R.delete(e.formId);const r=t.toolRef||this.tools.find(e=>e.name===t.toolName);if(!r)throw new Error(`Tool not found for form submission: ${t.toolName}`);let s={};try{t.originalToolInput&&"object"==typeof t.originalToolInput&&(s={...t.originalToolInput})}catch(a){this.formLogger.warn("Failed to extract base tool input, using empty object:",a),s={}}let n={};try{e.parameters&&"object"==typeof e.parameters&&(n={...e.parameters})}catch(a){this.formLogger.warn("Failed to extract submission parameters, using empty object:",a),n={}}const i={};try{Object.keys(s).forEach(e=>{const t=s[e];null!=t&&(i[e]=t)}),Object.keys(n).forEach(e=>{const t=n[e];null!=t&&(i[e]=t)}),i.renderForm=!1,i.__fromForm=!0,this.formLogger.info("Successfully merged tool input:",{baseKeys:Object.keys(s),submissionKeys:Object.keys(n),mergedKeys:Object.keys(i)})}catch(a){throw this.formLogger.error("Failed to merge tool input data:",a),new Error(`Failed to merge tool input data: ${a instanceof Error?a.message:"Unknown error"}`)}try{const t=r;let o;if("function"==typeof t.executeOriginal)o=await t.executeOriginal(i);else if("function"==typeof t.getOriginalTool){const e=t.getOriginalTool(),s=e;if(e&&"function"==typeof s._call)o=await s._call(i);else if(e&&"function"==typeof s.call)o=await s.call(i);else{const e=r;if("function"!=typeof e.call)throw new Error("No callable tool implementation found for form submission");o=await e.call(i)}}else if(t.originalTool&&"function"==typeof t.originalTool._call)o=await t.originalTool._call(i);else if(t.originalTool&&"function"==typeof t.originalTool.call)o=await t.originalTool.call(i);else{if("function"!=typeof r.call)throw new Error("No callable tool implementation found for form submission");o=await r.call(i)}let s,n={};this.formLogger.info("🔍 METADATA EXTRACTION: Analyzing tool output",{outputType:typeof o,outputLength:o?.length||0,isString:"string"==typeof o,firstChars:"string"==typeof o?o.substring(0,100):"not-string"});try{const e=JSON.parse(o);this.formLogger.info("✅ METADATA EXTRACTION: Successfully parsed JSON",{jsonKeys:Object.keys(e),hasHashLinkBlock:!!e.hashLinkBlock}),e&&"object"==typeof e?E.isHashLinkResponse(e)?(this.formLogger.info("🔗 HASHLINK DETECTED: Processing HashLink response separately to preserve metadata"),n={...n,hashLinkBlock:e.hashLinkBlock},s=E.formatHashLinkResponse(e),this.formLogger.info("🔗 METADATA PRESERVED: HashLink metadata extracted for component rendering",{blockId:n.hashLinkBlock?.blockId,hasTemplate:!!n.hashLinkBlock?.template})):(s=E.formatResponse(o),n={...n,hashLinkBlock:e.hashLinkBlock}):s=E.formatResponse(o)}catch(a){this.formLogger.warn("❌ METADATA EXTRACTION: Tool output is not JSON",{error:a instanceof Error?a.message:"unknown error",outputSample:"string"==typeof o?o.substring(0,200):"not-string"}),s=E.formatResponse(o)}return{output:s,formCompleted:!0,originalFormId:e.formId,intermediateSteps:[],metadata:n}}catch(a){if(a instanceof o.ZodError)return this.handleValidationError(a,i,[]);throw a}}extractToolInfoFromError(e,t,r){try{if(r.length>0){const e=r[r.length-1];if(e.action&&e.action.tool){const t=this.tools.find(t=>t.name===e.action.tool);if(t&&"schema"in t)return this.formLogger.info("Found tool from intermediate steps:",e.action.tool),{toolName:e.action.tool,schema:t.schema}}}const e=t.intermediateSteps||[];if(e.length>0){const t=e[e.length-1];let r;if(r=Array.isArray(t)&&t.length>0?t[0]:t.action?t.action:t,r&&r.tool){const e=this.tools.find(e=>e.name===r.tool);if(e&&"schema"in e)return this.formLogger.info("Found tool from input steps:",r.tool),{toolName:r.tool,schema:e.schema}}}const o=this.findToolFromContext(t);return o?(this.formLogger.info("Found tool from context:",o.toolName),o):null}catch(o){return this.formLogger.error("Error extracting tool info:",o),null}}findToolFromContext(e){const t=e.input||"";for(const r of this.tools){if(this.extractToolKeywords(r.name).some(e=>t.toLowerCase().includes(e.toLowerCase()))&&"schema"in r)return{toolName:r.name,schema:r.schema}}return null}detectToolFromErrorContext(e){const t=e.issues.map(e=>e.path.join("."));for(const r of this.tools)if("schema"in r){const e=r.schema;if(this.schemaMatchesErrorPaths(e,t))return this.formLogger.info("Detected tool from error path analysis:",r.name),{toolName:r.name,schema:e}}return null}schemaMatchesErrorPaths(e,t){const r=e;if(!r||!r._def)return!1;try{const e=r._def;if("ZodObject"===e.typeName){const r=e.shape,o=Object.keys(r||{});return t.some(e=>{const t=e.split(".")[0];return o.includes(t)})}}catch(o){this.formLogger.debug("Error analyzing schema structure:",o)}return!1}extractToolKeywords(e){return[...e.replace(/([A-Z])/g," $1").toLowerCase().split(/[\s_-]+/).filter(e=>e.length>2),e.toLowerCase()]}formatFormResponse(e){const t=e.formConfig.fields.length,r=e.formConfig.fields.slice(0,3).map(e=>`• ${e.label}`).join("\n");return`I need some additional information to complete your request.\n\n${e.formConfig.description}\n\nRequired fields:\n${r}${t>3?`\n... and ${t-3} more`:""}\n\nPlease fill out the form below to continue.`}hasPendingForms(){return this.pendingForms.size>0}getPendingFormsInfo(){return Array.from(this.pendingForms.entries()).map(([e,t])=>({formId:e,toolName:t.toolName}))}processHashLinkResponse(e){try{let t;if((e.hashLinkBlock||e.success&&e.inscription&&e.hashLinkBlock)&&(t=e.hashLinkBlock),!t)throw new Error("HashLink block data not found in response");if(!t.blockId||!t.hashLink||!t.attributes)throw new Error("Invalid HashLink block structure - missing required fields");let r="Content processed successfully!";if(e.success&&e.inscription){const t=e.inscription,o=e.metadata||{};r=`✅ ${t.standard} Hashinal inscription completed!\n\n`,o.name&&(r+=`**${o.name}**\n`),o.description&&(r+=`${o.description}\n\n`),r+=`📍 **Topic ID:** ${t.topicId}\n`,r+=`🔗 **HRL:** ${t.hrl}\n`,t.cdnUrl&&(r+=`🌐 **CDN URL:** ${t.cdnUrl}\n`),o.creator&&(r+=`👤 **Creator:** ${o.creator}\n`)}return this.formLogger.info("Processed HashLink response",{blockId:t.blockId,hashLink:t.hashLink,hasTemplate:!!t.template,attributeCount:Object.keys(t.attributes||{}).length}),{hasHashLinkBlocks:!0,hashLinkBlock:t,message:r}}catch(t){return this.formLogger.error("Error processing HashLink response:",t),{hasHashLinkBlocks:!1,message:"Content processed, but interactive display is not available."}}}getFormEngineStatistics(){return{strategies:this.formEngine.getRegisteredStrategies(),middleware:this.formEngine.getRegisteredMiddleware()}}}class P{constructor(e){this.config=e,this.tools=[],this.initialized=!1,this.logger=new r.Logger({module:"BaseAgent",silent:e.debug?.silent||!1})}getCore(){return this.agentKit}filterTools(e){let t=[...e];const r=this.config.filtering;return r?(r.namespaceWhitelist?.length&&(t=t.filter(e=>{const t=e.namespace;return!t||r.namespaceWhitelist.includes(t)})),r.toolBlacklist?.length&&(t=t.filter(e=>!r.toolBlacklist.includes(e.name))),r.toolPredicate&&(t=t.filter(r.toolPredicate)),this.logger.debug(`Filtered tools: ${e.length} → ${t.length}`),t):t}buildSystemPrompt(){const e=[],t=this.config.signer.getAccountId().toString(),r=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.`),r&&e.push(`The user you are assisting has a personal Hedera account ID: ${r}. IMPORTANT: When the user says things like "I want to send HBAR" or "transfer my tokens", you MUST use ${r} 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 ${r} 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 (${r||"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&&r?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 ${r}) 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 ${r||"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 O{constructor(e,t){this.contentStorage=e,this.logger=t}analyzeResponse(e){const t=[];let r=0;this.extractContentFromResponse(e,t),r=t.reduce((e,t)=>e+t.sizeBytes,0);const o=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:r,largestContentSize:o}}async processResponse(e,t,r){try{const o=this.analyzeResponse(e);if(!o.shouldProcess)return{content:e,wasProcessed:!1};return await this.createReferencedResponse(e,o,t,r)}catch(o){return this.logger.error("Error processing MCP response:",o),{content:e,wasProcessed:!1,errors:[o instanceof Error?o.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 r=e;if("text"===r.type&&"string"==typeof r.text)return void t.push({content:r.text,type:"text",sizeBytes:globalThis.Buffer.byteLength(r.text,"utf8"),mimeType:this.detectMimeType(r.text)});if("image"===r.type&&"string"==typeof r.data)return void t.push({content:r.data,type:"image",sizeBytes:Math.ceil(.75*r.data.length),mimeType:r.mimeType||"image/jpeg"});if("resource"===r.type&&r.resource){const e=JSON.stringify(r.resource);return void t.push({content:e,type:"resource",sizeBytes:globalThis.Buffer.byteLength(e,"utf8"),mimeType:"application/json"})}return void Object.values(r).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,r,o){const s=this.deepClone(e),n=[];let i=!1,a=0;for(const g of t.contents)if(this.contentStorage.shouldUseReference("string"==typeof g.content?g.content:JSON.stringify(g.content)))try{const e=globalThis.Buffer.from("string"==typeof g.content?g.content:JSON.stringify(g.content),"utf8"),t={contentType:this.mapMimeTypeToContentType(g.mimeType),source:"mcp_tool",mcpToolName:`${r}::${o}`,tags:["mcp_response",r,o]};void 0!==g.mimeType&&(t.mimeType=g.mimeType);const n=await this.contentStorage.storeContentIfLarge(e,t);n&&(this.replaceContentInResponse(s,g.content,this.createLightweightReference(n)),i=!0,a+=e.length)}catch(l){n.push(`Failed to create reference: ${l instanceof Error?l.message:"Unknown error"}`)}const c={content:s,wasProcessed:!0,referenceCreated:i,originalSize:a};return n.length>0&&(c.errors=n),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,r){if(null!=e)if(Array.isArray(e))for(let o=0;o<e.length;o++)e[o]===t?e[o]=r:this.replaceContentInResponse(e[o],t,r);else if("object"==typeof e){const o=e;if("text"===o.type&&o.text===t){for(const e of Object.keys(o))delete o[e];if("object"==typeof r&&null!==r){const e=r;for(const t of Object.keys(e))o[t]=e[t]}return}for(const e in o)o[e]===t?o[e]=r:this.replaceContentInResponse(o[e],t,r)}}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 r in e)e.hasOwnProperty(r)&&(t[r]=this.deepClone(e[r]));return t}}class N{constructor(e,t){this.clients=new Map,this.tools=new Map,this.logger=e,t&&(this.contentProcessor=new O(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 m.StdioClientTransport({command:e.command,args:e.args,...e.env&&{env:e.env}}),r=new h.Client({name:`conversational-agent-${e.name}`,version:"1.0.0"},{capabilities:{}});await r.connect(t),this.clients.set(e.name,r);const o=(await r.listTools()).tools.map(t=>({...t,serverName:e.name}));return this.tools.set(e.name,o),this.logger.info(`Connected to MCP server ${e.name} with ${o.length} tools`),{serverName:e.name,connected:!0,tools:o}}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,r){const o=this.clients.get(e);if(!o)throw new Error(`MCP server ${e} not connected`);this.logger.debug(`Executing MCP tool ${t} on server ${e}`,r);try{const s=await o.callTool({name:t,arguments:r});if(this.contentProcessor){const r=await this.contentProcessor.processResponse(s,e,t);return r.wasProcessed&&(this.logger.debug(`Processed MCP response from ${e}::${t}`,{referenceCreated:r.referenceCreated,originalSize:r.originalSize,errors:r.errors}),r.errors&&r.errors.length>0&&this.logger.warn(`Content processing warnings for ${e}::${t}:`,r.errors)),r.content}return s}catch(s){throw this.logger.error(`Error executing MCP tool ${t}:`,s),s}}async disconnectAll(){for(const[t,r]of this.clients)try{await r.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 O(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 $(e,t,o){const s=B(e.inputSchema),n=`${e.serverName}_${e.name}`.replace(/[^a-zA-Z0-9_]/g,"_");let a=e.description||`MCP tool ${e.name} from ${e.serverName}`;return o?.toolDescriptions?.[e.name]&&(a=`${a}\n\n${o.toolDescriptions[e.name]}`),o?.additionalContext&&(a=`${a}\n\nContext: ${o.additionalContext}`),new i.DynamicStructuredTool({name:n,description:a,schema:s,func:async o=>{try{const s=await t.executeTool(e.serverName,e.name,o);let n="";if("string"==typeof s)n=s;else if(s&&"object"==typeof s&&"content"in s){const e=s.content;if(Array.isArray(e)){n=e.filter(e=>"object"==typeof e&&null!==e&&"type"in e&&"text"===e.type&&"text"in e).map(e=>e.text).join("\n")}else n=JSON.stringify(e)}else n=JSON.stringify(s);const i=globalThis.Buffer.from(n,"utf8"),a=10240;if(i.length>a||r.shouldUseReference(i)){const t=r.ContentStoreService.getInstance();if(t)try{return`content-ref:${await t.storeContent(i,{contentType:"text",source:"mcp",mcpToolName:`${e.serverName}_${e.name}`,originalSize:i.length})}`}catch{}}return n}catch(s){const t=s instanceof Error?s.message:"Unknown error";return`Error executing MCP tool ${e.name}: ${t}`}}})}function B(e){if(!e||"object"!=typeof e)return o.z.object({});const t=e;if(t.type&&"object"!==t.type)return z(t);if(!t.properties||"object"!=typeof t.properties)return o.z.object({});const r={};for(const[o,s]of Object.entries(t.properties)){let e=z(s);Array.isArray(t.required)&&t.required.includes(o)||(e=e.optional()),r[o]=e}return o.z.object(r)}function z(e){if(!e||"object"!=typeof e||!("type"in e))return o.z.unknown();const t=e;let r;switch(t.type){case"string":r=o.z.string(),t.enum&&Array.isArray(t.enum)&&(r=o.z.enum(t.enum));break;case"number":r=o.z.number(),"minimum"in t&&"number"==typeof t.minimum&&(r=r.min(t.minimum)),"maximum"in t&&"number"==typeof t.maximum&&(r=r.max(t.maximum));break;case"integer":r=o.z.number().int(),"minimum"in t&&"number"==typeof t.minimum&&(r=r.min(t.minimum)),"maximum"in t&&"number"==typeof t.maximum&&(r=r.max(t.maximum));break;case"boolean":r=o.z.boolean();break;case"array":r=t.items?o.z.array(z(t.items)):o.z.array(o.z.unknown());break;case"object":r="properties"in t?B(t):o.z.object({}).passthrough();break;default:r=o.z.unknown()}return"description"in t&&"string"==typeof t.description&&(r=r.describe(t.description)),r}const j=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{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 r of e)t+=this.countMessageTokens(r);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{}}};j.MESSAGE_OVERHEAD=3,j.ROLE_OVERHEAD=1;let D=j;const H=class e{constructor(t=e.DEFAULT_MAX_TOKENS,r=e.DEFAULT_RESERVE_TOKENS,o){if(this.messages=[],this.systemPrompt="",this.systemPromptTokens=0,r>=t)throw new Error("Reserve tokens must be less than max tokens");this.maxTokens=t,this.reserveTokens=r,this.tokenCounter=o||new D}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=[],r=this.maxTokens-this.reserveTokens;for(;this.getCurrentTokenCount()>r&&this.messages.length>0;){const r=Math.min(e.PRUNING_BATCH_SIZE,this.messages.length);for(let e=0;e<r;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),r=this.getCurrentTokenCount()+t>this.maxTokens-this.reserveTokens;return!(t>this.maxTokens)&&(!r||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,r=e/t*100;return{totalMessages:this.messages.length,currentTokens:e,maxTokens:t,reserveTokens:this.reserveTokens,systemPromptTokens:this.systemPromptTokens,usagePercentage:Math.round(100*r)/100,remainingCapacity:this.getRemainingTokenCapacity(),canAcceptMore:this.getRemainingTokenCapacity()>this.reserveTokens}}dispose(){this.clear(),this.tokenCounter.dispose()}};H.DEFAULT_MAX_TOKENS=8e3,H.DEFAULT_RESERVE_TOKENS=1e3,H.PRUNING_BATCH_SIZE=2;let _=H;class U{static generateId(e){const t=d.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 K={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 q extends Error{constructor(e,t,r,o){super(e),this.type=t,this.referenceId=r,this.suggestedActions=o,this.name="ContentReferenceError"}}const V=class e{constructor(t=e.DEFAULT_MAX_STORAGE,r){this.messages=[],this.idCounter=0,this.contentStore=new Map,this.maxStorage=t,this.referenceConfig={...K,...r},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 r=0;const o=e.map(e=>({message:e,storedAt:t,id:this.generateId()}));for(this.messages.push(...o);this.messages.length>this.maxStorage;)this.messages.shift(),r++;return{stored:o.length,dropped:r}}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:r=!1,limit:o,useRegex:s=!1}=t;let n=[];if(s)try{const t=new RegExp(e,r?"g":"gi");n=this.messages.filter(e=>t.test(e.message.content)).map(e=>e.message)}catch{return[]}else{const t=r?e:e.toLowerCase();n=this.messages.filter(e=>{const o=e.message.content;return(r?o:o.toLowerCase()).includes(t)}).map(e=>e.message)}return o?n.slice(0,o):n}getMessagesFromTimeRange(e,t){return e>t||0===this.messages.length?[]:this.messages.filter(r=>r.storedAt>=e&&r.storedAt<=t).map(e=>e.message)}getStorageStats(){const e=this.messages.length,t=e>0?Math.round(e/this.maxStorage*100):0;let r,o;return e>0&&(r=this.messages[0].storedAt,o=this.messages[e-1].storedAt),{totalMessages:e,maxStorageLimit:this.maxStorage,usagePercentage:t,oldestMessageTime:r,newestMessageTime:o}}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 r=this.messages.filter(t=>t.message._getType()===e).map(e=>e.message);return t?r.slice(0,t):r}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 r=globalThis.Buffer.isBuffer(e)?e:globalThis.Buffer.from(e,"utf8");if(!this.isImageContent(t.mimeType,t.fileName)&&!this.shouldUseReference(r))return null;const o={contentType:t.contentType||this.detectContentType(r,t.mimeType),sizeBytes:r.length,source:t.source,tags:[]};return void 0!==t.mimeType&&(o.mimeType=t.mimeType),void 0!==t.mcpToolName&&(o.mcpToolName=t.mcpToolName),void 0!==t.fileName&&(o.fileName=t.fileName),void 0!==t.tags&&(o.tags=t.tags),void 0!==t.customMetadata&&(o.customMetadata=t.customMetadata),await this.storeContent(r,o)}async storeContent(e,t){const r=Date.now();try{const o=new Date,s=U.generateId(e),n={...t,createdAt:o,lastAccessedAt:o,accessCount:0},i={content:e,metadata:n,state:"active"},a=this.calculateExpirationTime(t.source);void 0!==a&&(i.expiresAt=a),this.contentStore.set(s,i),this.updateStatsAfterStore(e.length),await this.enforceReferenceStorageLimits();const c=this.createContentPreview(e,n.contentType),l={contentType:n.contentType,sizeBytes:n.sizeBytes,source:n.source};void 0!==n.fileName&&(l.fileName=n.fileName),void 0!==n.mimeType&&(l.mimeType=n.mimeType);const g={referenceId:s,state:"active",preview:c,metadata:l,createdAt:o,format:"ref://{id}"},h=Date.now()-r;return this.recordPerformanceMetric("creation",h),g}catch(o){const e=Date.now()-r;throw this.recordPerformanceMetric("creation",e),new q(`Failed to store content: ${o instanceof Error?o.message:"Unknown error"}`,"system_error",void 0,["Try again","Check storage limits","Contact administrator"])}}async resolveReference(e){const t=Date.now();try{if(!U.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 r=this.contentStore.get(e);if(!r)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(r.expiresAt&&r.expiresAt<new Date)return r.state="expired",this.referenceStats.failedResolutions++,{success:!1,error:"Reference has expired",errorType:"expired",suggestedActions:["Request fresh content","Use alternative content source"]};if("active"!==r.state)return this.referenceStats.failedResolutions++,{success:!1,error:`Reference is ${r.state}`,errorType:"expired"===r.state?"expired":"corrupted",suggestedActions:["Request fresh content","Check reference validity"]};r.metadata.lastAccessedAt=new Date,r.metadata.accessCount++,this.referenceStats.totalResolutions++;const o=Date.now()-t;return this.recordPerformanceMetric("resolution",o),{success:!0,content:r.content,metadata:r.metadata}}catch(r){const e=Date.now()-t;return this.recordPerformanceMetric("resolution",e),this.referenceStats.failedResolutions++,{success:!1,error:`System error resolving reference: ${r instanceof Error?r.message:"Unknown error"}`,errorType:"system_error",suggestedActions:["Try again","Contact administrator"]}}}async hasReference(e){if(!U.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 r=0;try{const s=new Date,n=[];for(const[e,t]of this.contentStore.entries()){let r=!1;t.expiresAt&&t.expiresAt<s&&(r=!0,t.state="expired");const o=s.getTime()-t.metadata.createdAt.getTime();o>this.getCleanupPolicy(t.metadata.source).maxAgeMs&&(r=!0),"cleanup_pending"===t.state&&(r=!0),r&&n.push(e)}n.sort((e,t)=>{const r=this.contentStore.get(e),o=this.contentStore.get(t),s=this.getCleanupPolicy(r.metadata.source).priority;return this.getCleanupPolicy(o.metadata.source).priority-s});for(const e of n)try{await this.cleanupReference(e)&&r++}catch(o){t.push(`Failed to cleanup ${e}: ${o instanceof Error?o.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()),s=this.contentStore.size-this.referenceConfig.maxReferences;for(let n=0;n<s&&n<e.length;n++){const[s]=e[n];try{await this.cleanupReference(s)&&r++}catch(o){t.push(`Failed to cleanup excess reference ${s}: ${o instanceof Error?o.message:"Unknown error"}`)}}}const i=Date.now()-e;return this.recordPerformanceMetric("cleanup",i),{cleanedUp:r,errors:t}}catch(o){const s=Date.now()-e;this.recordPerformanceMetric("cleanup",s);const n=`Cleanup process failed: ${o instanceof Error?o.message:"Unknown error"}`;return t.push(n),{cleanedUp:r,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 r=e.toString("utf8",0,Math.min(e.length,1e3));return r.startsWith("{")||r.startsWith("[")?"json":r.includes("<html>")||r.includes("<!DOCTYPE")?"html":r.includes("#")&&r.includes("\n")?"markdown":"text"}createContentPreview(e,t){let r=e.toString("utf8",0,Math.min(e.length,400));if("html"===t)r=r.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim();else if("json"===t)try{const e=JSON.parse(r);r=JSON.stringify(e,null,0)}catch{}return r=r.trim(),r.length>200&&(r=r.substring(0,200)+"..."),r||"[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[r,o]of this.contentStore.entries())o.metadata.accessCount>t&&(t=o.metadata.accessCount,e=r);void 0!==e?this.referenceStats.mostAccessedReferenceId=e:delete this.referenceStats.mostAccessedReferenceId}isImageContent(e,t){if(e&&e.startsWith("image/"))return!0;if(t){const e=t.toLowerCase();return[".png",".jpg",".jpeg",".gif",".bmp",".webp",".svg",".tiff",".ico"].some(t=>e.endsWith(t))}return!1}recordPerformanceMetric(e,t){const r=this.referenceStats.performanceMetrics;switch(e){case"creation":r.creationTimes.push(t),r.creationTimes.length>100&&r.creationTimes.shift();break;case"resolution":r.resolutionTimes.push(t),r.resolutionTimes.length>100&&r.resolutionTimes.shift();break;case"cleanup":r.cleanupTimes.push(t),r.cleanupTimes.length>100&&r.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{}},this.referenceConfig.cleanupIntervalMs)}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),delete this.cleanupTimer),this.contentStore.clear(),this.clear()}};V.DEFAULT_MAX_STORAGE=1e3;let G=V;const W='"isEntityAssociation":true',Z=class e{constructor(t={}){this.config={...e.DEFAULT_CONFIG,...t},this.logger=new r.Logger({module:"SmartMemoryManager"}),this.tokenCounter=new D(this.config.modelName),this._contentStorage=new G(this.config.storageLimit),this.memoryWindow=new _(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(),r={activeMessageCount:t.length,systemPrompt:this.getSystemPrompt(),recentMessages:t.slice(-5),memoryUtilization:this.getMemoryStats().usagePercentage,hasStoredHistory:this.getStorageStats().totalMessages>0};return e?{...r,recentStoredMessages:this.getRecentHistory(10),storageStats:this.getStorageStats()}:r}performMaintenance(){}storeEntityAssociation(e,t,r,o){try{if(!e||"string"!=typeof e||0===e.trim().length)return;if(!t||"string"!=typeof t||0===t.trim().length)return;if(!r||"string"!=typeof r||0===r.trim().length)return;const s=e.trim(),n=t.trim().substring(0,100),i=r.trim().toLowerCase(),a={entityId:s,entityName:n,entityType:i,createdAt:new Date,isEntityAssociation:!0,...null!=o&&""!==o.trim()?{transactionId:o.trim()}:{}},c={_getType:()=>"system",content:JSON.stringify(a),id:`entity_${s}_${Date.now()}`,name:"entity_association",additional_kwargs:{entityId:s,entityName:n,entityType:i,isEntityAssociation:!0}};this._contentStorage.storeMessages([c])}catch(s){this.logger.error("Failed to store entity association",{entityId:e,entityName:t,entityType:r,error:s instanceof Error?s.message:String(s)})}}resolveEntityReference(e,t={}){try{if(!e||"string"!=typeof e)return[];const r=e.trim();if(0===r.length)return[];r.length;const{entityType:o,limit:s=10,fuzzyMatch:n=!0}=t,i=Math.max(1,Math.min(s||10,100)),a=/^0\.0\.\d+$/.test(r),c=this._contentStorage.searchMessages(r.substring(0,200),{caseSensitive:!1,limit:2*i}),l=[];for(const e of c)try{const t=e.content;if(t.includes(W)||t.includes("entityId")){const e=JSON.parse(t);if(e.entityId&&e.entityName&&e.entityType){if(o&&e.entityType!==o)continue;if(a&&e.entityId!==r)continue;l.push(e)}}}catch{continue}if(n&&0===l.length&&!a){const t=[e.toLowerCase(),"token","account",o||""].filter(Boolean);for(const r of t){if(r===e.toLowerCase())continue;const t=this._contentStorage.searchMessages(r,{caseSensitive:!1,limit:s});for(const e of t)try{const t=e.content;if(t.includes(W)){const e=JSON.parse(t);if(e.entityId&&e.entityName&&e.entityType){if(o&&e.entityType!==o)continue;l.push(e)}}}catch{continue}}}const g=l.filter((e,t,r)=>r.findIndex(t=>t.entityId===e.entityId)===t).sort((e,t)=>new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime());return g.slice(0,i)}catch(r){return this.logger.error("Failed to resolve entity reference",{query:e,options:t,error:r instanceof Error?r.message:String(r)}),[]}}getEntityAssociations(e){try{const r=e?e.trim().toLowerCase():void 0;if(e&&(!r||0===r.length))return[];const o=r||"entityId",s=this._contentStorage.searchMessages(o,{caseSensitive:!1,limit:100}),n=[];for(const e of s)try{const t=e.content;if(t.includes(W)){const e=JSON.parse(t);if(e.entityId&&e.entityName&&e.entityType){if(r&&e.entityType!==r)continue;e.createdAt&&"string"==typeof e.createdAt&&(e.createdAt=new Date(e.createdAt)),n.push(e)}}}catch(t){this.logger.warn("Failed to parse entity association from message",{messageContent:"string"==typeof e.content?e.content.substring(0,100):"non-string",error:t instanceof Error?t.message:String(t)});continue}return n.filter((e,t,r)=>r.findIndex(t=>t.entityId===e.entityId)===t).sort((e,t)=>{const r=e=>e instanceof Date?e.getTime():new Date(e).getTime(),o=r(e.createdAt);return r(t.createdAt)-o})}catch(r){return this.logger.error("Failed to get entity associations",{entityType:e,error:r instanceof Error?r.message:String(r)}),[]}}dispose(){this.memoryWindow.dispose(),this._contentStorage.dispose(),this.tokenCounter.dispose()}};Z.DEFAULT_CONFIG={maxTokens:8e3,reserveTokens:1e3,modelName:"gpt-4o",storageLimit:1e3};let J=Z;class Y extends i.StructuredTool{constructor(e,t,o={}){super(),this.originalTool=e,this.formGenerator=t,this.validationConfig=o,this.logger=new r.Logger({module:"FormValidatingToolWrapper"}),this.name=e.name,this.description=e.description,this.schema=e.schema,this.logger.info(`🔧 FormValidatingToolWrapper created for tool: ${this.name}`,{originalToolName:e.name,originalToolType:e.constructor.name,wrapperType:this.constructor.name})}validateInput(e){try{return this.schema.parse(e),{isValid:!0}}catch(t){if(t instanceof o.z.ZodError){return{isValid:!1,errors:t.errors.filter(e=>{const t=e.path[0];return!this.validationConfig.skipFields?.includes(t)}).map(e=>`${e.path.join(".")}: ${e.message}`)}}return{isValid:!1,errors:["Validation failed"]}}}getSchemaShape(){return this.isZodObject(this.schema)?Object.keys(this.schema.shape):[]}async executeOriginal(e,t){const r=this.originalTool;if("_call"in r&&"function"==typeof r._call)return r._call(e,t);if("call"in r&&"function"==typeof r.call)return r.call(e,t);throw new Error("Original tool has no callable implementation")}getOriginalTool(){return this.originalTool}hasFormValidatableMethod(e,t){return null!==e&&"object"==typeof e&&t in e&&"function"==typeof e[t]}getFormSchema(){return this.hasFormValidatableMethod(this.originalTool,"getFormSchema")?this.originalTool.getFormSchema():this.schema}getEssentialFields(){return this.hasFormValidatableMethod(this.originalTool,"getEssentialFields")?this.originalTool.getEssentialFields():[]}isFieldEmpty(e,t){return this.hasFormValidatableMethod(this.originalTool,"isFieldEmpty")?this.originalTool.isFieldEmpty(e,t):null==t||""===t||!(!Array.isArray(t)||0!==t.length)}calculateMissingFields(e,t){const r=new Set;if(!t)return r;const o=this.getEssentialFields();for(const s of o){const t=e[s];this.isFieldEmpty(s,t)&&r.add(s)}return r}async createFormMessage(e,t,r){let o=await this.formGenerator.generateFormFromSchema(e,t,{toolName:this.name,toolDescription:this.description},r);if(this.isZodObject(e))try{const{jsonSchema:s,uiSchema:n}=this.formGenerator.generateJsonSchemaForm(e,t,r);o={...o,jsonSchema:s,uiSchema:n}}catch(s){this.logger.warn("Failed to generate JSON Schema for RJSF:",s)}return o.partialInput=t,o}isZodObject(e){const t=e._def;return!(!t||"ZodObject"!==t.typeName)}shouldGenerateForm(e){if(this.logger.info(`shouldGenerateForm called for ${this.name}/${this.originalTool.name}`,{input:e,hasCustomValidation:!!this.validationConfig.customValidation}),this.validationConfig.customValidation){const t=!this.validationConfig.customValidation(e);return this.logger.info(`Custom validation result: ${t}`),t}if(t.isFormValidatable(this.originalTool))return this.logger.info(`Tool ${this.originalTool.name} implements FormValidatable, using custom logic`),this.originalTool.shouldGenerateForm(e);this.logger.info(`Tool ${this.originalTool.name} using schema validation only`);const r=this.validateInput(e);return this.logger.info(`Schema validation for ${this.originalTool.name}:`,{isValid:r.isValid,errors:r.errors}),!r.isValid}hasFormBypassFlags(e){return!0===e.__fromForm||!1===e.renderForm}async _call(e,r){this.logger.info(`🚨🚨🚨 FormValidatingToolWrapper._call INTERCEPTING ${this.name} 🚨🚨🚨`,{input:e,inputKeys:Object.keys(e),schemaShape:this.getSchemaShape(),stackTrace:(new Error).stack?.split("\n").slice(0,5)});const o=e;if(this.hasFormBypassFlags(o))return this.logger.info("Bypassing form generation and executing original tool due to submission flags"),this.executeOriginal(o,r);const s=this.shouldGenerateForm(e);if(this.logger.info(`FormValidatingToolWrapper decision for ${this.name}:`,{shouldGenerateForm:s,toolName:this.name,originalToolName:this.originalTool.name}),s){this.logger.info(`Generating form for incomplete input in ${this.name}`);try{const r=t.isFormValidatable(this.originalTool),o=r?this.getFormSchema():this.schema,s=this.calculateMissingFields(e,r),n=this.isZodObject(o)?Object.keys(o.shape):[];this.logger.info(`Using ${r?"CUSTOM":"DEFAULT"} schema for form generation`,{toolName:this.originalTool.name,schemaType:o.constructor?.name,schemaFields:n,isCustomSchema:r});const i={requiresForm:!0,formMessage:await this.createFormMessage(o,e,s),message:`Please complete the form to provide the required information for ${this.name}.`};return this.logger.info(`FormValidatingToolWrapper returning form result for ${this.name}`),JSON.stringify(i)}catch(n){this.logger.error("Failed to generate form:",n)}}return this.logger.info(`FormValidatingToolWrapper passing through to original tool ${this.name}`),this.executeOriginal(e,r)}}function X(e,t,r={}){return new Y(e,t,r)}class Q{constructor(e){this.tools=new Map,this.formGenerator=new I,this.logger=e||new r.Logger({module:"ToolRegistry"})}registerTool(e,t={}){const r=this.analyzeToolCapabilities(e),o={name:e.name,version:"1.0.0",category:t.metadata?.category||"core",description:e.description,capabilities:r,dependencies:[],schema:e.schema,...t.metadata};let s,n=e;this.shouldWrapTool(e,r,t)&&(s=X(e,this.formGenerator,{requireAllFields:!1,skipFields:["metaOptions"],...t.wrapperConfig}),n=s);const i={tool:n,metadata:o,wrapper:s,originalTool:e};this.tools.set(e.name,i)}getTool(e){return this.tools.get(e)||null}getToolsByCapability(e,t){const r=[];for(const o of this.tools.values())void 0!==t?o.metadata.capabilities[e]===t&&r.push(o):o.metadata.capabilities[e]&&r.push(o);return r}getToolsByQuery(e){const t=[];for(const r of this.tools.values()){let o=!0;if(e.name&&r.metadata.name!==e.name&&(o=!1),e.category&&r.metadata.category!==e.category&&(o=!1),e.capabilities)for(const[t,s]of Object.entries(e.capabilities))if(r.metadata.capabilities[t]!==s){o=!1;break}o&&t.push(r)}return t}getAllTools(){return Array.from(this.tools.values()).map(e=>e.tool)}getAllRegistryEntries(){return Array.from(this.tools.values())}getToolNames(){return Array.from(this.tools.keys())}hasTool(e){return this.tools.has(e)}unregisterTool(e){return this.tools.delete(e)}clear(){this.tools.clear()}analyzeToolCapabilities(e){const r=t.isFormValidatable(e),o=this.hasRenderConfig(e),s=this.isZodObjectLike(e.schema),n=r||o,i=n&&s;let a="medium",c="core";n&&i?a="critical":n?a="high":(e.description?.toLowerCase().includes("query")||e.description?.toLowerCase().includes("search"))&&(a="low");const l=e;return e.constructor.name.includes("MCP")||l.isMCPTool?c="mcp":(l.isExtension||e.constructor.name.includes("Extension"))&&(c="extension"),{supportsFormValidation:n,requiresWrapper:i,priority:a,category:c}}hasRenderConfig(e){const t=e.schema;return!(!t||!t._renderConfig)}shouldWrapTool(e,t,r){return!r.skipWrapper&&(!!r.forceWrapper||t.requiresWrapper)}isZodObjectLike(e){if(!e||"object"!=typeof e)return!1;const t=e,r=t._def;return e instanceof o.z.ZodObject||"ZodObject"===r?.typeName||"shape"in t&&"object"==typeof t.shape}getStatistics(){const e={totalTools:this.tools.size,wrappedTools:0,unwrappedTools:0,categoryCounts:{core:0,extension:0,mcp:0},priorityCounts:{low:0,medium:0,high:0,critical:0}};for(const t of this.tools.values())t.wrapper?e.wrappedTools++:e.unwrappedTools++,e.categoryCounts[t.metadata.category]++,e.priorityCounts[t.metadata.capabilities.priority]++;return e}}class ee{constructor(e,t,o,s){this.toolRegistry=e,this.formEngine=t,this.memory=o,this.logger=s||new r.Logger({module:"ExecutionPipeline"})}async execute(e,t,r){const o=`trace-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,s=Date.now(),n=this.toolRegistry.getTool(e);if(!n)throw new Error(`Tool not found in registry: ${e}`);const i={toolName:e,input:t,session:r||this.buildDefaultSession(),memory:this.memory,traceId:o,toolEntry:n};try{const e=await this.checkFormGeneration(i);if(e.requiresForm&&e.formMessage)return{success:!1,output:"Form generation required",requiresForm:!0,formMessage:e.formMessage,traceId:o,executionTime:Date.now()-s};return{success:!0,output:await this.executeToolDirect(i),traceId:o,executionTime:Date.now()-s}}catch(a){return this.handleExecutionError(a,i,o,Date.now()-s)}}async executeWithValidation(e,t,r){return this.execute(e,t,r)}async processFormSubmission(e,t,r,o){const s=`form-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,n=Date.now();try{const s={formId:t,toolName:e,parameters:r,timestamp:Date.now()},n=await this.formEngine.processSubmission(s);return this.execute(e,n,o)}catch(i){return{success:!1,output:"Form submission processing failed",error:i instanceof Error?i.message:String(i),traceId:s,executionTime:Date.now()-n}}}async checkFormGeneration(e){const t=e.input;if(!0===t?.__fromForm||!1===t?.renderForm)return{requiresForm:!1};if(!this.formEngine.shouldGenerateForm(e.toolEntry.tool,e.input))return{requiresForm:!1};const r=await this.formEngine.generateForm(e.toolName,e.toolEntry.tool,e.input);return r?{requiresForm:!0,formMessage:r}:{requiresForm:!1}}async executeToolDirect(e){const{toolEntry:t,input:r}=e,o={...r||{},renderForm:!1};return t.wrapper?this.executeWrappedTool(t,o):await t.tool.call(o)}async executeWrappedTool(e,t){const r=e.wrapper;if(!r)throw new Error("Tool wrapper not found");const o=r;return o.executeOriginal?await o.executeOriginal(t):o.originalTool?.call?await o.originalTool.call(t):await e.originalTool.call(t)}handleExecutionError(e,t,r,s){const n=e instanceof Error?e.message:String(e);return e instanceof o.ZodError?{success:!1,output:"Validation error occurred",error:n,traceId:r,executionTime:s}:(this.logger.error(`Tool execution failed: ${t.toolName}`,{traceId:r,error:n}),{success:!1,output:"Tool execution failed",error:n,traceId:r,executionTime:s})}buildDefaultSession(){return{sessionId:`session-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,timestamp:Date.now()}}getStatistics(){return{totalMiddleware:0,registeredMiddleware:[]}}}class te extends P{constructor(){super(...arguments),this.systemMessage="",this.mcpConnectionStatus=new Map}getInscriptionTool(){const e=this.toolRegistry.getToolsByCapability("priority","critical");for(const r of e){const e=r.tool,t=e.name.toLowerCase(),o=e.description?.toLowerCase()||"";if(t.includes("inscribe")||t.includes("hashinal")||o.includes("inscribe")||o.includes("hashinal"))return e}const t=this.toolRegistry.getAllRegistryEntries();for(const r of t){const e=r.tool,t=e.name.toLowerCase(),o=e.description?.toLowerCase()||"";if(t.includes("inscribe")||t.includes("hashinal")||o.includes("inscribe")||o.includes("hashinal"))return e}return null}getTool(e){const t=this.toolRegistry.getTool(e);return t?t.tool:null}async executeToolDirect(e,t,r=!1){if(r&&this.executionPipeline&&this.smartMemory){const r={sessionId:`session-${Date.now()}`,timestamp:Date.now()},o=await this.executionPipeline.execute(e,t,r);if(!o.success)throw new Error(o.error||"Pipeline execution failed");return o.output}const o=this.toolRegistry.getTool(e);if(!o)throw new Error(`Tool not found: ${e}`);const s={...t,renderForm:!1};if(o.wrapper){const e=o.tool;if(e.originalTool?.call)return await e.originalTool.call(s)}return await o.tool.call(s)}createToolResponse(e){return{output:e,message:e,notes:[]}}async handleToolExecution(e,t){let r=!1,o=null;try{if(e.includes("TOOL_EXECUTION")){const t=JSON.parse(e);"TOOL_EXECUTION"===t.type&&(r=!0,o=t)}}catch{}if(!r||!o?.formId)return null;try{const e=o.parameters||{},t=o.toolName;if(t){const r=await this.executeToolDirect(t,e);return this.createToolResponse(r)}}catch{}const s={formId:o.formId,toolName:o.toolName||"",parameters:o.parameters||{},timestamp:Date.now()};return this.executor&&"processFormSubmission"in this.executor&&"function"==typeof this.executor.processFormSubmission?this.processFormSubmission(s,t):null}async handleDirectToolExecution(e){if("string"!=typeof e||!e.includes("Please execute the following tool:"))return null;try{const t=e.match(/Tool:\s*(.+)/),r=e.indexOf("Arguments:");if(t&&-1!==r){const o=t[1].trim(),s=e.slice(r+10).trim();let n={};try{n=JSON.parse(s)}catch{}const i=await this.executeToolDirect(o,n);return this.createToolResponse(i)}}catch{}return null}async handleJsonToolCalls(e,t){if("string"!=typeof e)return null;try{const r=e.trim();if(!(r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]")))return null;const o=JSON.parse(r),s=o.formId,n=o.toolName||"",i=o.parameters||{};if(s&&this.executor&&"processFormSubmission"in this.executor&&"function"==typeof this.executor.processFormSubmission)return this.processFormSubmission({formId:s,toolName:n,parameters:i,timestamp:Date.now()},t);if(n){const e=await this.executeToolDirect(n,i);return this.createToolResponse(e)}}catch{}return null}async handleContentRefMessages(e){if("string"!=typeof e||!e.includes("content-ref:"))return null;try{const t=this.getInscriptionTool();if(!t)return null;const r=e.match(/content-ref:([A-Za-z0-9_\-]+)/i)||e.match(/content-ref:([^\s)]+)/i),o=r&&r[1]?`content-ref:${r[1]}`:e.match(/content-ref:[^\s)]+/i)?.[0]||void 0,s=o?{contentRef:o,renderForm:!0,withHashLinkBlocks:!0}:{renderForm:!0,withHashLinkBlocks:!0},n=await t.call(s);let i;try{i="string"==typeof n?JSON.parse(n):n}catch{}if(i&&i.requiresForm&&i.formMessage){const r=new Map,o={input:e,chat_history:this.smartMemory.getMessages()},n=i.formMessage;r.set(n.id,{toolName:t.name,originalInput:o,originalToolInput:s,schema:null});const a=this.executor;"function"==typeof a.restorePendingForms&&a.restorePendingForms(r);const c=i.message||"Please complete the form to continue.";return{output:c,message:c,notes:[],requiresForm:!0,formMessage:n}}}catch{}return null}async processExecutorResult(t){let r="";if("string"==typeof t.output)r=t.output;else if(t.output)try{r=JSON.stringify(t.output)}catch{r=String(t.output)}let o={output:r,message:r,notes:[],intermediateSteps:t.intermediateSteps};if(t.requiresForm&&t.formMessage&&(o.formMessage=t.formMessage,o.requiresForm=!0),t.intermediateSteps&&Array.isArray(t.intermediateSteps)){const e=t.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&&(o.tool_calls=e)}const s=t?.intermediateSteps?.[0]?.observation;if(s&&"string"==typeof s&&this.isJSON(s))try{const e=JSON.parse(s);if(E.isInscriptionResponse(e)){const t=E.formatInscriptionResponse(e);o.output=t,o.message=t,e.inscription&&(o.inscription=e.inscription),e.metadata&&(o.metadata={...o.metadata,...e.metadata})}else o={...o,...e};const t=this.processHashLinkBlocks(e);t.hashLinkBlock&&(o.metadata={...o.metadata,...t})}catch(i){this.logger.error("Error parsing intermediate steps:",i)}if(o.output&&""!==o.output.trim()||(o.output="Agent action complete."),o.output&&this.smartMemory.addMessage(new p.AIMessage(o.output)),this.tokenTracker){const t=this.tokenTracker.getLatestTokenUsage();t&&(o.tokenUsage=t,o.cost=e.calculateTokenCostSync(t))}const n=this.smartMemory.getMemoryStats();return o.metadata={...o.metadata,memoryStats:{activeMessages:n.totalActiveMessages,tokenUsage:n.currentTokenCount,maxTokens:n.maxTokens,usagePercentage:n.usagePercentage}},this.logger.info("LangChainAgent.chat returning response:",o),o}loadContextMessages(e){if(!this.smartMemory)return;if(!e?.messages||0===e.messages.length)return;this.smartMemory.clear();const t=e.messages;for(const r of t)if(r instanceof p.HumanMessage||r instanceof p.AIMessage)this.smartMemory.addMessage(r);else if(r&&"object"==typeof r&&"content"in r&&"type"in r){const e=String(r.content);"human"===String(r.type)?this.smartMemory.addMessage(new p.HumanMessage(e)):this.smartMemory.addMessage(new p.AIMessage(e))}}async boot(){if(this.logger.info("🚨🚨🚨 LANGCHAIN AGENT BOOT METHOD CALLED 🚨🚨🚨"),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),this.toolRegistry=new Q(this.logger);const r=this.agentKit.getAggregatedLangChainTools();this.logger.info("=== TOOL REGISTRATION START ==="),this.logger.info("All tools from agentKit:",r.map(e=>e.name));const o=this.filterTools(r);this.logger.info("Filtered tools for registration:",o.map(e=>e.name));for(const e of o){this.logger.info(`🔧 Registering tool: ${e.name}`);const t={},r=e.name.toLowerCase(),o=e.description?.toLowerCase()||"";(r.includes("inscribe")||r.includes("hashinal")||o.includes("inscribe")||o.includes("hashinal"))&&(t.forceWrapper=!0,t.metadata={category:"core",version:"1.0.0",dependencies:[]},this.logger.info(`🎯 CRITICAL TOOL DEBUG - ${e.name} schema:`,{hasSchema:!!e.schema,schemaType:e.schema?.constructor?.name,hasRenderConfig:!!e.schema?._renderConfig,renderConfig:e.schema?._renderConfig})),this.toolRegistry.registerTool(e,t)}this.tools=this.toolRegistry.getAllTools(),this.logger.info(`🚀 TOOLS REGISTERED: ${this.tools.length} tools`);const s=this.toolRegistry.getStatistics();this.logger.info("📊 Tool Registry Statistics:",{total:s.totalTools,wrapped:s.wrappedTools,unwrapped:s.unwrappedTools,categories:s.categoryCounts,priorities:s.priorityCounts});const n=this.getInscriptionTool();if(n){const e=this.toolRegistry.getTool(n.name);if(e){if(this.logger.info(`🔒 FINAL SECURITY CHECK - ${n.name} tool type: ${e.tool.constructor.name}`),"FormValidatingToolWrapper"!==e.tool.constructor.name)throw this.logger.error(`🚨 SECURITY BREACH: ${n.name} tool is NOT wrapped!`),new Error(`Critical security failure: ${n.name} tool bypassed FormValidatingToolWrapper`);this.logger.info(`✅ SECURITY VALIDATED: ${n.name} tool is properly wrapped`)}}const i=this.toolRegistry.getToolNames(),a=new Set(i);if(i.length!==a.size){this.logger.error("DUPLICATE TOOL NAMES DETECTED in registry!");const e=i.filter((e,t)=>i.indexOf(e)!==t);throw new Error(`Duplicate tool names detected: ${e.join(", ")}`)}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 N(this.logger))),this.smartMemory=new J({modelName:t,maxTokens:9e4,reserveTokens:1e4,storageLimit:1e3}),this.logger.info("SmartMemoryManager initialized:",{modelName:t,toolsCount:this.tools.length,maxTokens:9e4,reserveTokens:1e4}),this.formEngine=new A(this.logger),this.executionPipeline=new ee(this.toolRegistry,this.formEngine,this.smartMemory,this.logger),this.systemMessage=this.buildSystemPrompt(),this.smartMemory.setSystemPrompt(this.systemMessage),await this.createExecutor(),this.initialized=!0,this.logger.info("LangChain Hedera agent initialized with ToolRegistry")}catch(t){throw this.logger.error("Failed to initialize agent:",t),t}}async chat(e,t){if(!this.initialized||!this.executor||!this.smartMemory)throw new Error("Agent not initialized. Call boot() first.");try{const r=await this.handleToolExecution(e,t);if(r)return r;const o=await this.handleDirectToolExecution(e);if(o)return o;const s=await this.handleJsonToolCalls(e,t);if(s)return s;const n=await this.handleContentRefMessages(e);if(n)return n;this.logger.info("LangChainAgent.chat called with:",{message:e,contextLength:t?.messages?.length||0}),this.loadContextMessages(t),this.smartMemory.addMessage(new p.HumanMessage(e));const i=this.smartMemory.getMemoryStats();this.logger.info("Memory stats before execution:",{totalMessages:i.totalActiveMessages,currentTokens:i.currentTokenCount,maxTokens:i.maxTokens,usagePercentage:i.usagePercentage,toolsCount:this.tools.length});const a=await this.executor.invoke({input:e,chat_history:this.smartMemory.getMessages()});return this.logger.info("LangChainAgent executor result:",a),this.processExecutorResult(a)}catch(r){return this.logger.error("LangChainAgent.chat error:",r),this.handleError(r)}}async shutdown(){this.mcpManager&&await this.mcpManager.disconnectAll(),this.smartMemory&&(this.smartMemory.dispose(),this.smartMemory=void 0),this.toolRegistry&&this.toolRegistry.clear(),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(),r=e.calculateTokenCostSync(t);return{...t,cost:r}}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 processFormSubmission(t,r){if(this.logger.info("🔥 LangChainAgent.processFormSubmission START"),!this.initialized||!this.executor||!this.smartMemory)throw this.logger.error("🔥 LangChainAgent.processFormSubmission - Agent not initialized"),new Error("Agent not initialized. Call boot() first.");this.logger.info("🔥 LangChainAgent.processFormSubmission - After initialization check");try{if(this.logger.info("🔥 LangChainAgent.processFormSubmission - About to log submission info"),this.logger.info("Processing form submission:",{formId:t.formId,toolName:t.toolName,parameterKeys:Object.keys(t.parameters||{}),hasParameters:!!t.parameters,parametersType:typeof t.parameters,parametersIsNull:null===t.parameters,parametersIsUndefined:void 0===t.parameters,hasContext:!!t.context}),this.logger.info("🔥 LangChainAgent.processFormSubmission - After submission info logged"),!t.parameters||"object"!=typeof t.parameters){this.logger.error("Invalid form submission parameters:",{parameters:t.parameters,type:typeof t.parameters});const e=JSON.stringify(t,null,2);return this.handleError(new Error(`Invalid form submission parameters: ${e}`))}this.logger.info("🔥 LangChainAgent.processFormSubmission - Parameters validated"),this.loadContextMessages(r),this.logger.info("🔥 LangChainAgent.processFormSubmission - Context loaded");const s={...t,parameters:t.parameters||{}};this.logger.info("🔥 LangChainAgent.processFormSubmission - Safe submission created"),this.logger.info("About to call executor.processFormSubmission with:",{formId:s.formId,toolName:s.toolName,parameterKeys:Object.keys(s.parameters),parameterCount:Object.keys(s.parameters).length});const n=await this.executor.processFormSubmission(s);this.logger.info("🔍 DEBUG: Raw result from FormAwareAgentExecutor:",{hasResult:!!n,resultKeys:n?Object.keys(n):[],hasMetadata:!!n?.metadata,metadataKeys:n?.metadata?Object.keys(n.metadata):[],hasHashLinkBlock:!!n?.metadata?.hashLinkBlock,hashLinkBlockContent:n?.metadata?.hashLinkBlock}),n?.metadata&&this.logger.info("🔍 DEBUG: Full metadata from executor:",JSON.stringify(n.metadata));const i=n?.metadata?{...n.metadata}:{};this.logger.info("Executor processFormSubmission result:",{hasResult:!!n,hasOutput:!!n.output,hasError:!!n.error,hasMetadata:!!n.metadata,outputType:typeof n.output});let a="Form processed successfully.";if("string"==typeof n.output)a=n.output;else if(n.output)try{a=JSON.stringify(n.output)}catch{a=String(n.output)}let c={output:a,message:a,notes:[],intermediateSteps:n.intermediateSteps};if(n.metadata&&(c.metadata={...c.metadata,...n.metadata},this.logger.info("🔍 DEBUG: Metadata after merge from result:",{hasMetadata:!!c.metadata,metadataKeys:c.metadata?Object.keys(c.metadata):[],hasHashLinkBlock:!!c.metadata?.hashLinkBlock,hashLinkBlockContent:c.metadata?.hashLinkBlock})),n.requiresForm&&n.formMessage&&(c.formMessage=n.formMessage,c.requiresForm=!0),n.intermediateSteps&&Array.isArray(n.intermediateSteps)){const e=n.intermediateSteps.map((e,t)=>{const r=e?.action?.tool||"unknown",o=e?.action?.toolInput||{},s=e?.observation;let n="";if("string"==typeof s)n=s;else if(s&&"object"==typeof s)try{n=JSON.stringify(s)}catch{n=String(s)}else void 0!==s&&(n=String(s));return{id:`call_${t}`,name:r,args:o,output:n}});e.length>0&&(c.tool_calls=e)}const l=n?.intermediateSteps?.[0]?.observation;if(l&&"string"==typeof l&&this.isJSON(l))try{const e=JSON.parse(l);c={...c,...e};const t=this.processHashLinkBlocks(e);t.hashLinkBlock&&(c.metadata={...c.metadata,...t})}catch(o){this.logger.error("Error parsing intermediate steps:",o)}if(c.output&&this.smartMemory.addMessage(new p.AIMessage(c.output)),this.tokenTracker){const t=this.tokenTracker.getLatestTokenUsage();t&&(c.tokenUsage=t,c.cost=e.calculateTokenCostSync(t))}const g=this.smartMemory.getMemoryStats();return this.logger.info("🔍 DEBUG: Metadata before memoryStats merge:",{hasMetadata:!!c.metadata,metadataKeys:c.metadata?Object.keys(c.metadata):[],hasHashLinkBlock:!!c.metadata?.hashLinkBlock}),c.metadata={...i,...c.metadata,memoryStats:{activeMessages:g.totalActiveMessages,tokenUsage:g.currentTokenCount,maxTokens:g.maxTokens,usagePercentage:g.usagePercentage}},this.logger.info("🔍 DEBUG: Final response metadata before return:",{hasMetadata:!!c.metadata,metadataKeys:c.metadata?Object.keys(c.metadata):[],hasHashLinkBlock:!!c.metadata?.hashLinkBlock,fullMetadata:c.metadata}),i?.hashLinkBlock&&!c.metadata?.hashLinkBlock&&(this.logger.error("❌ CRITICAL: HashLink metadata was lost during processing!"),this.logger.error("Original metadata had hashLinkBlock:",i.hashLinkBlock),this.logger.error("Final metadata missing hashLinkBlock")),c}catch(o){return this.logger.error("Form submission processing error:",o),this.handleError(o)}}hasPendingForms(){return!!this.executor&&this.executor.hasPendingForms()}getPendingFormsInfo(){return this.executor?this.executor.getPendingFormsInfo():[]}async createAgentKit(){const t=[...e.getAllHederaCorePlugins(),...this.config.extensions?.plugins||[]],r=this.config.execution?.operationalMode||"returnBytes",o=this.config.ai?.modelName||"gpt-4o";return new e.HederaAgentKit(this.config.signer,{plugins:t},r,this.config.execution?.userAccountId,this.config.execution?.scheduleUserTransactionsInBytesMode??!1,void 0,o,this.config.extensions?.mirrorConfig,this.config.debug?.silent??!1)}async createExecutor(){const e=this.executor?.getPendingForms()||new Map;let t;if(this.config.ai?.provider&&this.config.ai.provider.getModel)t=this.config.ai.provider.getModel();else if(this.config.ai?.llm)t=this.config.ai.llm;else{const e=this.config.ai?.apiKey||process.env.OPENAI_API_KEY;if(!e)throw new Error("OpenAI API key required");const r=this.config.ai?.modelName||"gpt-4o-mini",o=r.toLowerCase().includes("gpt-5")||r.toLowerCase().includes("gpt5");t=new g.ChatOpenAI({apiKey:e,modelName:r,callbacks:this.tokenTracker?[this.tokenTracker]:[],...o?{temperature:1}:{}})}const r=l.ChatPromptTemplate.fromMessages([["system",this.systemMessage],new l.MessagesPlaceholder("chat_history"),["human","{input}"],new l.MessagesPlaceholder("agent_scratchpad")]),o=this.tools,s=this.getInscriptionTool();if(s){const e=this.toolRegistry.getTool(s.name);if(e){if(this.logger.info(`🔒 FINAL SECURITY CHECK - ${s.name} tool type: ${e.tool.constructor.name}`),"FormValidatingToolWrapper"!==e.tool.constructor.name)throw this.logger.error(`🚨 SECURITY BREACH: ${s.name} tool is NOT wrapped!`),new Error(`Critical security failure: ${s.name} tool bypassed FormValidatingToolWrapper`);this.logger.info(`✅ SECURITY VALIDATED: ${s.name} tool is properly wrapped`)}}const n=this.toolRegistry.getStatistics();this.logger.info("🛡️ TOOL SECURITY REPORT:",{totalTools:n.totalTools,wrappedTools:n.wrappedTools,unwrappedTools:n.unwrappedTools,categories:n.categoryCounts,priorities:n.priorityCounts}),this.logger.info(`📊 Tool Security Summary: ${n.wrappedTools} wrapped, ${n.unwrappedTools} unwrapped`);const i=await a.createOpenAIToolsAgent({llm:t,tools:o,prompt:r});this.executor=new L({agent:i,tools:o,verbose:this.config.debug?.verbose??!1,returnIntermediateSteps:!0}),e.size>0&&(this.logger.info(`Restoring ${e.size} pending forms to new executor`),this.executor.restorePendingForms(e))}handleError(t){const r=t instanceof Error?t.message:"Unknown error";let o,s;this.logger.error("Chat error:",t),this.tokenTracker&&(o=this.tokenTracker.getLatestTokenUsage(),o&&(s=e.calculateTokenCostSync(o)));let n=r,i=r;r.includes("429")?r.includes("quota")?(n="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."):(n="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."):r.includes("401")||r.includes("unauthorized")?(n="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."):r.includes("timeout")?(n="Request timed out. Please try again.",i="The request took too long to process. Please try again."):r.includes("network")||r.includes("fetch")?(n="Network error. Please check your internet connection and try again.",i="There was a network error. Please check your internet connection and try again."):r.includes("400")&&(n=r,i=r);const a={output:i,message:n,error:r,notes:[]};return o&&(a.tokenUsage=o),s&&(a.cost=s),a}async initializeMCP(){this.mcpManager=new N(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 r of t.tools){const t=$(r,this.mcpManager,e);this.toolRegistry.registerTool(t,{metadata:{category:"mcp",version:"1.0.0",dependencies:[e.name]}})}this.tools=this.toolRegistry.getAllTools()}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 N(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 r=await this.mcpManager.connectServer(e);if(this.mcpConnectionStatus.set(t,r),r.connected){this.logger.info(`Successfully connected to MCP server ${r.serverName} with ${r.tools.length} tools`);for(const t of r.tools){const r=$(t,this.mcpManager,e);this.toolRegistry.registerTool(r,{metadata:{category:"mcp",version:"1.0.0",dependencies:[e.name]}})}this.tools=this.toolRegistry.getAllTools(),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 ${r.serverName}: ${r.error}`)}catch(r){this.logger.error(`Background connection failed for MCP server ${t}:`,r),this.mcpConnectionStatus.set(t,{connected:!1,serverName:t,tools:[],error:r instanceof Error?r.message:"Connection failed"})}},1e3)}processHashLinkBlocks(e){try{const t=e;if(e&&"object"==typeof e&&t.hashLinkBlock&&"object"==typeof t.hashLinkBlock){const e=t.hashLinkBlock;if(e.blockId&&e.hashLink&&e.template&&e.attributes&&"string"==typeof e.blockId&&"string"==typeof e.hashLink&&"string"==typeof e.template&&"object"==typeof e.attributes)return this.logger.info("HashLink block detected:",{blockId:e.blockId,hashLink:e.hashLink,template:e.template,attributeKeys:Object.keys(e.attributes)}),{hashLinkBlock:{blockId:e.blockId,hashLink:e.hashLink,template:e.template,attributes:e.attributes}};this.logger.warn("Invalid HashLink block structure detected:",e)}}catch(t){this.logger.error("Error processing HashLink blocks:",t)}return{}}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 re(e){const t=e.framework||"langchain";switch(t){case"langchain":return new te(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 oe{constructor(e){this.model=e}async generate(e,t){const r=await this.model.invoke(e,t);return"string"==typeof r?r:r.toString()}async*stream(e,t){const r=await this.model.stream(e,t);for await(const o of r)yield"string"==typeof o?o:o.toString()}getModel(){return this.model}}const se=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*** CRITICAL NFT METADATA RULES ***\nWhen creating NFT inscriptions (Hashinals), NEVER auto-generate meaningless technical attributes like:\n- "File Type": "image/jpeg" (technical metadata, not valuable to collectors)\n- "Origin": "User Upload" (meaningless for NFT traits)\n- "MIME Type", "Source", "Upload Source", etc. (all technical, not collectible traits)\n\nInstead, if the user hasn't provided meaningful NFT attributes, use the form generation system to ask them for proper metadata like:\n- Rarity traits (Common, Rare, Epic, Legendary)\n- Visual attributes (Color, Style, Background, Theme)\n- Collection-specific traits (Power Level, Element, Character Type, etc.)\n- Edition information (Series, Variant, Special Edition)\n\nQuality NFT metadata enhances collectibility and value. Technical file information does not.\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 ne{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 ie{constructor(e){this.adapter=e}async resolveReference(e){return await this.adapter.resolveReference(e)}shouldUseReference(e){return r.shouldUseReference(e)}extractReferenceId(e){return r.extractReferenceId(e)}}class ae{constructor(e=1e3,t,o){this.isRegistered=!1,this.logger=o||new r.Logger({module:"ContentStoreManager"}),this.contentStorage=new G(e,t),this.adapter=new ne(this.contentStorage),this.resolver=new ie(this.adapter)}async initialize(){if(this.isRegistered)this.logger.warn("ContentStoreManager is already initialized");else try{await r.ContentStoreService.setInstance(this.adapter),r.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(),r.ContentStoreService.dispose(),r.ContentResolverRegistry.unregister(),this.isRegistered=!1,this.logger.info("ContentStoreManager disposed and unregistered"))}isInitialized(){return this.isRegistered}}const ce=new r.Logger({module:"EntityResolverTool"}),le=o.z.object({message:o.z.string().describe("The message containing entity references to resolve"),entities:o.z.array(o.z.object({entityId:o.z.string(),entityName:o.z.string(),entityType:o.z.string()})).describe("Available entities in memory")}),ge=o.z.object({response:o.z.string().describe("Agent response text to extract entities from"),userMessage:o.z.string().describe("Original user message for context")});class he 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=le,this.llm=new g.ChatOpenAI({apiKey:e,modelName:t,temperature:0})}async _call(e){const{message:t,entities:r}=e;if(!r||0===r.length)return t;const o=this.groupEntitiesByType(r),s=`Task: Replace entity references with IDs.\n\n${this.buildEntityContext(o)}\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(s)).content.trim()}catch(n){return ce.error("ResolveEntitiesTool failed:",n),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[r,o]of Object.entries(e)){const e=o[0];t+=`- Most recent ${r}: "${e.entityName}" = ${e.entityId}\n`}return t}}class me 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=ge,this.llm=new g.ChatOpenAI({apiKey:e,modelName:t,temperature:0})}async _call(e){const{response:t,userMessage:r}=e,o=`Extract ONLY newly created entities from this response.\n\nUser asked: "${r.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(o),t=e.content.match(/\[[\s\S]*?\]/);return t?t[0]:"[]"}catch(s){return ce.error("ExtractEntitiesTool failed:",s),"[]"}}}function ue(e,t="gpt-4o-mini"){return{resolveEntities:new he(e,t),extractEntities:new me(e,t)}}const de="gpt-4o",pe="testnet",fe="autonomous";class ye{constructor(e){if(this.options=e,this.stateManager=e.stateManager||new t.OpenConvaiState,this.hcs10Plugin=new y,this.hcs2Plugin=new T,this.inscribePlugin=new w,this.hbarPlugin=new M,this.logger=new r.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 J(this.options.entityMemoryConfig),this.logger.info("Entity memory initialized"),this.entityTools=ue(e.openAIApiKey,"gpt-4o-mini"),this.logger.info("LLM-based entity resolver tools initialized")}}async initialize(){const{accountId:t,privateKey:r,network:o=pe,openAIApiKey:s,openAIModelName:n=de,llmProvider:i="openai"}=this.options;this.validateOptions(t,r);try{const a=new e.ServerSigner(t,r,o);let c;if("anthropic"===i)c=new f.ChatAnthropic({apiKey:s,modelName:n||"claude-3-5-sonnet-20241022",temperature:.1});else{const e=n||"gpt-4o-mini",t=e.toLowerCase().includes("gpt-5")||e.toLowerCase().includes("gpt5");c=new g.ChatOpenAI({apiKey:s,modelName:n,...t?{temperature:1}:{temperature:.1}})}this.logger.info("Preparing plugins...");const l=this.preparePlugins();this.logger.info("Creating agent config...");const h=this.createAgentConfig(a,c,l);if(this.logger.info("Creating agent..."),this.agent=re(h),this.logger.info("Agent created"),this.logger.info("Configuring HCS10 plugin..."),this.configureHCS10Plugin(l),this.logger.info("HCS10 plugin configured"),this.contentStoreManager=new ae,await this.contentStoreManager.initialize(),this.logger.info("ContentStoreManager initialized for content reference support"),this.logger.info("About to call agent.boot()"),this.logger.info("🔥 About to call agent.boot()"),await this.agent.boot(),this.logger.info("agent.boot() completed"),this.logger.info("🔥 agent.boot() completed"),this.agent){const e=h;e.filtering=e.filtering||{};const t=e.filtering.toolPredicate,r=this.options.toolFilter;e.filtering.toolPredicate=e=>(!e||"hedera-account-transfer-hbar"!==e.name)&&((!e||"hedera-hts-airdrop-token"!==e.name)&&(!(t&&!t(e))&&!(r&&!r(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 r=this.memoryManager?await this.resolveEntitiesInMessage(e):e,o={messages:t.map(e=>"human"===e.type?new p.HumanMessage(e.content):new p.AIMessage(e.content))},s=await this.agent.chat(r,o);return this.memoryManager&&await this.extractAndStoreEntities(s,e),this.logger.info("Message processed successfully"),s}catch(r){throw this.logger.error("Error processing message:",r),r}}async processFormSubmission(e){if(!this.agent)throw new Error("Agent not initialized. Call initialize() first.");const t=this.agent;if(!t.processFormSubmission||"function"!=typeof t.processFormSubmission)throw new Error("processFormSubmission not available on internal agent");try{this.logger.info("Processing form submission:",{formId:e.formId,toolName:e.toolName,parameterKeys:Object.keys(e.parameters||{}),hasContext:!!e.context});const r=await t.processFormSubmission(e);return this.logger.info("Form submission processed successfully"),r}catch(r){throw this.logger.error("Error processing form submission:",r),r}}validateOptions(e,t){if(!e||!t)throw new Error("Account ID and private key are required");if("string"!=typeof e)throw new Error("Account ID must be a string, received "+typeof e);if("string"!=typeof t)throw new Error(`Private key must be a string, received ${typeof t}: ${JSON.stringify(t)}`);if(t.length<10)throw new Error("Private key appears to be invalid (too short)")}preparePlugins(){const{additionalPlugins:t=[],enabledPlugins:r}=this.options,o=[this.hcs10Plugin,this.hcs2Plugin,this.inscribePlugin,this.hbarPlugin],s=e.getAllHederaCorePlugins();if(r){const e=new Set(r);return[...[...o,...s].filter(t=>e.has(t.id)),...t]}return[...o,...s,...t]}createAgentConfig(e,t,r){const{operationalMode:o=fe,userAccountId:s,scheduleUserTransactionsInBytesMode:n,customSystemMessagePreamble:i,customSystemMessagePostamble:a,verbose:c=!1,mirrorNodeConfig:l,disableLogging:g,accountId:h=""}=this.options;return{framework:"langchain",signer:e,execution:{mode:"autonomous"===o?"direct":"bytes",operationalMode:o,...s&&{userAccountId:s},...void 0!==n&&{scheduleUserTransactionsInBytesMode:n,scheduleUserTransactions:n}},ai:{provider:new oe(t),temperature:.1},filtering:{toolPredicate:e=>"hedera-account-transfer-hbar"!==e.name&&!(this.options.toolFilter&&!this.options.toolFilter(e))},messaging:{systemPreamble:i||se(h),...a&&{systemPostamble:a},conciseMode:!0},extensions:{plugins:r,...l&&{mirrorConfig:l}},...this.options.mcpServers&&{mcp:{servers:this.options.mcpServers,autoConnect:!1}},debug:{verbose:c,silent:g??!1}}}configureHCS10Plugin(e){const t=e.find(e=>"hcs-10"===e.id);t&&(t.appConfig={stateManager:this.stateManager})}static withPlugins(e,t){return new ye({...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 ye({...e,mcpServers: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 r=await this.entityTools.resolveEntities.call({message:e,entities:t.map(e=>({entityId:e.entityId,entityName:e.entityName,entityType:e.entityType}))});return r!==e&&this.logger.info(`Entity resolution completed. Original: "${e}" -> Resolved: "${r}"`),r}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 o=this.extractResponseText(e),s=await this.entityTools.extractEntities.call({response:o,userMessage:t});try{const t=JSON.parse(s);for(const r of t)if(r&&"object"==typeof r&&"name"in r&&"type"in r&&"id"in r){this.logger.info(`Storing entity: ${r.name} (${r.type}) -> ${r.id}`);const t=this.extractTransactionId(e);this.memoryManager.storeEntityAssociation(String(r.id),String(r.name),String(r.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(r){throw this.logger.error("Failed to parse extracted entities JSON:",r),r}}catch(o){throw this.logger.error("Entity extraction failed:",o),o}}extractTransactionId(e){try{if("object"==typeof e&&e&&"transactionId"in e){const t=e;return"string"==typeof t.transactionId?t.transactionId:void 0}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){if("string"==typeof e)return e;if(e&&"object"==typeof e&&"output"in e){return String(e.output)}return JSON.stringify(e)}}exports.BaseAgent=P,exports.ContentStorage=G,exports.ContentStoreManager=ae,exports.ConversationalAgent=ye,exports.ExtractEntitiesTool=me,exports.FormGenerator=I,exports.FormValidatingToolWrapper=Y,exports.HCS10Plugin=y,exports.HCS2Plugin=T,exports.HbarPlugin=M,exports.InscribePlugin=w,exports.LangChainAgent=te,exports.LangChainProvider=oe,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=_,exports.OpenConvAIPlugin=y,exports.ResolveEntitiesTool=he,exports.ResponseFormatter=E,exports.SmartMemoryManager=J,exports.TokenCounter=D,exports.createAgent=re,exports.createEntityTools=ue,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},exports.wrapToolWithFormValidation=X,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
|