@hashgraphonline/standards-agent-kit 0.0.33 → 0.0.35
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/standards-agent-kit.cjs +1 -1
- package/dist/cjs/standards-agent-kit.cjs.map +1 -1
- package/dist/{umd/src → cjs}/tools/AcceptConnectionRequestTool.d.ts +6 -6
- package/dist/cjs/{src/tools → tools}/CheckMessagesTool.d.ts +6 -6
- package/dist/{es/src → cjs}/tools/ConnectionMonitorTool.d.ts +34 -34
- package/dist/{umd/src → cjs}/tools/FindRegistrationsTool.d.ts +4 -4
- package/dist/cjs/{src/tools → tools}/InitiateConnectionTool.d.ts +2 -2
- package/dist/{umd/src → cjs}/tools/ListConnectionsTool.d.ts +4 -4
- package/dist/{es/src → cjs}/tools/ListUnapprovedConnectionRequestsTool.d.ts +4 -4
- package/dist/{es/src → cjs}/tools/ManageConnectionRequestsTool.d.ts +4 -4
- package/dist/cjs/{src/tools → tools}/RegisterAgentTool.d.ts +76 -76
- package/dist/{es/src → cjs}/tools/RetrieveProfileTool.d.ts +4 -4
- package/dist/{es/src → cjs}/tools/SendMessageToConnectionTool.d.ts +6 -6
- package/dist/cjs/{src/tools → tools}/SendMessageTool.d.ts +6 -6
- package/dist/es/index.d.ts +5 -2
- package/dist/es/standards-agent-kit.es2.js.map +1 -1
- package/dist/es/standards-agent-kit.es7.js +12 -13
- package/dist/es/standards-agent-kit.es7.js.map +1 -1
- package/dist/es/{src/tools → tools}/AcceptConnectionRequestTool.d.ts +6 -6
- package/dist/{umd/src → es}/tools/CheckMessagesTool.d.ts +6 -6
- package/dist/{umd/src → es}/tools/ConnectionMonitorTool.d.ts +34 -34
- package/dist/{cjs/src → es}/tools/FindRegistrationsTool.d.ts +4 -4
- package/dist/{umd/src → es}/tools/InitiateConnectionTool.d.ts +2 -2
- package/dist/{cjs/src → es}/tools/ListConnectionsTool.d.ts +4 -4
- package/dist/{umd/src → es}/tools/ListUnapprovedConnectionRequestsTool.d.ts +4 -4
- package/dist/{umd/src → es}/tools/ManageConnectionRequestsTool.d.ts +4 -4
- package/dist/{umd/src → es}/tools/RegisterAgentTool.d.ts +76 -76
- package/dist/{cjs/src → es}/tools/RetrieveProfileTool.d.ts +4 -4
- package/dist/{umd/src → es}/tools/SendMessageToConnectionTool.d.ts +6 -6
- package/dist/{umd/src → es}/tools/SendMessageTool.d.ts +6 -6
- package/dist/umd/standards-agent-kit.umd.js +15 -14
- package/dist/umd/standards-agent-kit.umd.js.map +1 -1
- package/dist/{cjs/src → umd}/tools/AcceptConnectionRequestTool.d.ts +6 -6
- package/dist/{es/src → umd}/tools/CheckMessagesTool.d.ts +6 -6
- package/dist/{cjs/src → umd}/tools/ConnectionMonitorTool.d.ts +34 -34
- package/dist/{es/src → umd}/tools/FindRegistrationsTool.d.ts +4 -4
- package/dist/{es/src → umd}/tools/InitiateConnectionTool.d.ts +2 -2
- package/dist/{es/src → umd}/tools/ListConnectionsTool.d.ts +4 -4
- package/dist/{cjs/src → umd}/tools/ListUnapprovedConnectionRequestsTool.d.ts +4 -4
- package/dist/{cjs/src → umd}/tools/ManageConnectionRequestsTool.d.ts +4 -4
- package/dist/{es/src → umd}/tools/RegisterAgentTool.d.ts +76 -76
- package/dist/umd/{src/tools → tools}/RetrieveProfileTool.d.ts +4 -4
- package/dist/{cjs/src → umd}/tools/SendMessageToConnectionTool.d.ts +6 -6
- package/dist/{es/src → umd}/tools/SendMessageTool.d.ts +6 -6
- package/package.json +2 -2
- package/src/hcs10/HCS10Client.ts +3 -7
- package/src/index.ts +1 -1
- package/src/tools/InitiateConnectionTool.ts +13 -13
- package/dist/umd/src/index.d.ts +0 -5
- /package/dist/cjs/{src/agents → agents}/index.d.ts +0 -0
- /package/dist/cjs/{src/hcs10 → hcs10}/HCS10Client.d.ts +0 -0
- /package/dist/cjs/{src/hcs10 → hcs10}/index.d.ts +0 -0
- /package/dist/cjs/{src/hcs10 → hcs10}/types.d.ts +0 -0
- /package/dist/cjs/{src/index.d.ts → index.d.ts} +0 -0
- /package/dist/cjs/{src/init → init}/index.d.ts +0 -0
- /package/dist/cjs/{src/init → init}/init.d.ts +0 -0
- /package/dist/cjs/{src/plugins → plugins}/BasePlugin.d.ts +0 -0
- /package/dist/cjs/{src/plugins → plugins}/GenericPlugin.d.ts +0 -0
- /package/dist/cjs/{src/plugins → plugins}/HCS10Plugin.d.ts +0 -0
- /package/dist/cjs/{src/plugins → plugins}/PluginInterface.d.ts +0 -0
- /package/dist/cjs/{src/plugins → plugins}/PluginLoader.d.ts +0 -0
- /package/dist/cjs/{src/plugins → plugins}/PluginRegistry.d.ts +0 -0
- /package/dist/cjs/{src/plugins → plugins}/defi/index.d.ts +0 -0
- /package/dist/cjs/{src/plugins → plugins}/hedera/HbarPricePlugin.d.ts +0 -0
- /package/dist/cjs/{src/plugins → plugins}/hedera/index.d.ts +0 -0
- /package/dist/cjs/{src/plugins → plugins}/index.d.ts +0 -0
- /package/dist/cjs/{src/plugins → plugins}/openconvai/OpenConvAIPlugin.d.ts +0 -0
- /package/dist/cjs/{src/plugins → plugins}/openconvai/index.d.ts +0 -0
- /package/dist/cjs/{src/plugins → plugins}/weather/index.d.ts +0 -0
- /package/dist/cjs/{src/state → state}/index.d.ts +0 -0
- /package/dist/cjs/{src/state → state}/open-convai-state.d.ts +0 -0
- /package/dist/cjs/{src/state → state}/state-types.d.ts +0 -0
- /package/dist/cjs/{src/tools → tools}/ConnectionTool.d.ts +0 -0
- /package/dist/cjs/{src/tools → tools}/index.d.ts +0 -0
- /package/dist/cjs/{src/utils → utils}/Encryption.d.ts +0 -0
- /package/dist/cjs/{src/utils → utils}/HederaClient.d.ts +0 -0
- /package/dist/cjs/{src/utils → utils}/connectionUtils.d.ts +0 -0
- /package/dist/cjs/{src/utils → utils}/ensure-agent-has-hbar.d.ts +0 -0
- /package/dist/cjs/{src/utils → utils}/state-tools.d.ts +0 -0
- /package/dist/es/{src/agents → agents}/index.d.ts +0 -0
- /package/dist/es/{src/hcs10 → hcs10}/HCS10Client.d.ts +0 -0
- /package/dist/es/{src/hcs10 → hcs10}/index.d.ts +0 -0
- /package/dist/es/{src/hcs10 → hcs10}/types.d.ts +0 -0
- /package/dist/es/{src/init → init}/index.d.ts +0 -0
- /package/dist/es/{src/init → init}/init.d.ts +0 -0
- /package/dist/es/{src/plugins → plugins}/BasePlugin.d.ts +0 -0
- /package/dist/es/{src/plugins → plugins}/GenericPlugin.d.ts +0 -0
- /package/dist/es/{src/plugins → plugins}/HCS10Plugin.d.ts +0 -0
- /package/dist/es/{src/plugins → plugins}/PluginInterface.d.ts +0 -0
- /package/dist/es/{src/plugins → plugins}/PluginLoader.d.ts +0 -0
- /package/dist/es/{src/plugins → plugins}/PluginRegistry.d.ts +0 -0
- /package/dist/es/{src/plugins → plugins}/defi/index.d.ts +0 -0
- /package/dist/es/{src/plugins → plugins}/hedera/HbarPricePlugin.d.ts +0 -0
- /package/dist/es/{src/plugins → plugins}/hedera/index.d.ts +0 -0
- /package/dist/es/{src/plugins → plugins}/index.d.ts +0 -0
- /package/dist/es/{src/plugins → plugins}/openconvai/OpenConvAIPlugin.d.ts +0 -0
- /package/dist/es/{src/plugins → plugins}/openconvai/index.d.ts +0 -0
- /package/dist/es/{src/plugins → plugins}/weather/index.d.ts +0 -0
- /package/dist/es/{src/state → state}/index.d.ts +0 -0
- /package/dist/es/{src/state → state}/open-convai-state.d.ts +0 -0
- /package/dist/es/{src/state → state}/state-types.d.ts +0 -0
- /package/dist/es/{src/tools → tools}/ConnectionTool.d.ts +0 -0
- /package/dist/es/{src/tools → tools}/index.d.ts +0 -0
- /package/dist/es/{src/utils → utils}/Encryption.d.ts +0 -0
- /package/dist/es/{src/utils → utils}/HederaClient.d.ts +0 -0
- /package/dist/es/{src/utils → utils}/connectionUtils.d.ts +0 -0
- /package/dist/es/{src/utils → utils}/ensure-agent-has-hbar.d.ts +0 -0
- /package/dist/es/{src/utils → utils}/state-tools.d.ts +0 -0
- /package/dist/umd/{src/agents → agents}/index.d.ts +0 -0
- /package/dist/umd/{src/hcs10 → hcs10}/HCS10Client.d.ts +0 -0
- /package/dist/umd/{src/hcs10 → hcs10}/index.d.ts +0 -0
- /package/dist/umd/{src/hcs10 → hcs10}/types.d.ts +0 -0
- /package/dist/{es/src → umd}/index.d.ts +0 -0
- /package/dist/umd/{src/init → init}/index.d.ts +0 -0
- /package/dist/umd/{src/init → init}/init.d.ts +0 -0
- /package/dist/umd/{src/plugins → plugins}/BasePlugin.d.ts +0 -0
- /package/dist/umd/{src/plugins → plugins}/GenericPlugin.d.ts +0 -0
- /package/dist/umd/{src/plugins → plugins}/HCS10Plugin.d.ts +0 -0
- /package/dist/umd/{src/plugins → plugins}/PluginInterface.d.ts +0 -0
- /package/dist/umd/{src/plugins → plugins}/PluginLoader.d.ts +0 -0
- /package/dist/umd/{src/plugins → plugins}/PluginRegistry.d.ts +0 -0
- /package/dist/umd/{src/plugins → plugins}/defi/index.d.ts +0 -0
- /package/dist/umd/{src/plugins → plugins}/hedera/HbarPricePlugin.d.ts +0 -0
- /package/dist/umd/{src/plugins → plugins}/hedera/index.d.ts +0 -0
- /package/dist/umd/{src/plugins → plugins}/index.d.ts +0 -0
- /package/dist/umd/{src/plugins → plugins}/openconvai/OpenConvAIPlugin.d.ts +0 -0
- /package/dist/umd/{src/plugins → plugins}/openconvai/index.d.ts +0 -0
- /package/dist/umd/{src/plugins → plugins}/weather/index.d.ts +0 -0
- /package/dist/umd/{src/state → state}/index.d.ts +0 -0
- /package/dist/umd/{src/state → state}/open-convai-state.d.ts +0 -0
- /package/dist/umd/{src/state → state}/state-types.d.ts +0 -0
- /package/dist/umd/{src/tools → tools}/ConnectionTool.d.ts +0 -0
- /package/dist/umd/{src/tools → tools}/index.d.ts +0 -0
- /package/dist/umd/{src/utils → utils}/Encryption.d.ts +0 -0
- /package/dist/umd/{src/utils → utils}/HederaClient.d.ts +0 -0
- /package/dist/umd/{src/utils → utils}/connectionUtils.d.ts +0 -0
- /package/dist/umd/{src/utils → utils}/ensure-agent-has-hbar.d.ts +0 -0
- /package/dist/umd/{src/utils → utils}/state-tools.d.ts +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("@hashgraphonline/standards-sdk"),t=require("@hashgraph/sdk"),n=require("@langchain/core/tools"),o=require("zod"),i=require("fs"),r=require("path"),s=require("axios");function a(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const n in e)if("default"!==n){const o=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,o.get?o:{enumerable:!0,get:()=>e[n]})}return t.default=e,Object.freeze(t)}const c=a(i),g=a(r);class l{constructor(t,n,o,i){this.standardClient=new e.HCS10Client({network:o,operatorId:t,operatorPrivateKey:n,guardedRegistryBaseUrl:i?.registryUrl,logLevel:i?.logLevel}),this.guardedRegistryBaseUrl=i?.registryUrl||"",this.useEncryption=i?.useEncryption||!1;const r="true"===process.env.DISABLE_LOGGING;this.logger=new e.Logger({level:i?.logLevel||"info",silent:r})}getOperatorId(){const e=this.standardClient.getClient().operatorAccountId;if(!e)throw new Error("Operator Account ID not configured in standard client.");return e.toString()}getNetwork(){return this.standardClient.getNetwork()}async handleConnectionRequest(e,t,n,o){try{return await this.standardClient.handleConnectionRequest(e,t,n,o)}catch(i){throw this.logger.error(`Error handling connection request #${n} for topic ${e}:`,i),new Error(`Failed to handle connection request: ${i instanceof Error?i.message:String(i)}`)}}async getAgentProfile(e){return this.standardClient.retrieveProfile(e)}async submitConnectionRequest(e,t){return this.standardClient.submitConnectionRequest(e,t)}async waitForConnectionConfirmation(e,t,n=60,o=2e3){return this.standardClient.waitForConnectionConfirmation(e,t,n,o)}async createAndRegisterAgent(t){const n=(new e.AgentBuilder).setName(t.name).setBio(t.description||"").setCapabilities(t.capabilities?t.capabilities:[e.AIAgentCapability.TEXT_GENERATION]).setType(t.type||"autonomous").setModel(t.model||"agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(e.InboundTopicType.PUBLIC);t?.feeConfig&&(n.setInboundTopicType(e.InboundTopicType.FEE_BASED),n.setFeeConfig(t.feeConfig)),t.pfpBuffer&&t.pfpFileName?0===t.pfpBuffer.byteLength?this.logger.warn("Provided PFP buffer is empty. Skipping profile picture."):(this.logger.info(`Setting profile picture: ${t.pfpFileName} (${t.pfpBuffer.byteLength} bytes)`),n.setProfilePicture(t.pfpBuffer,t.pfpFileName)):this.logger.warn("Profile picture not provided in metadata. Agent creation might fail if required by the underlying SDK builder."),t.social&&Object.entries(t.social).forEach((([e,t])=>{n.addSocial(e,t)})),t.properties&&Object.entries(t.properties).forEach((([e,t])=>{n.addProperty(e,t)}));try{const e=Boolean(t?.feeConfig),o=await this.standardClient.createAndRegisterAgent(n,{initialBalance:e?50:void 0});return o?.metadata?.inboundTopicId&&o?.metadata?.outboundTopicId&&(this.agentChannels={inboundTopicId:o.metadata.inboundTopicId,outboundTopicId:o.metadata.outboundTopicId}),o}catch(o){throw this.logger.error("Error during agent creation/registration:",o),new Error(`Failed to create/register agent: ${o instanceof Error?o.message:String(o)}`)}}async sendMessage(e,t,n,o){this.useEncryption;try{const i=await this.standardClient.sendMessage(e,t,n,o);return i.topicSequenceNumber?.toNumber()}catch(i){throw this.logger.error(`Error sending message to topic ${e}:`,i),new Error(`Failed to send message: ${i instanceof Error?i.message:String(i)}`)}}async getMessages(e){try{const t=(await this.standardClient.getMessages(e)).messages.map((e=>{const t=e?.created?.getTime()||0;return{...e,timestamp:t,data:e.data,sequence_number:e.sequence_number}}));return t.sort(((e,t)=>e.timestamp-t.timestamp)),{messages:t}}catch(t){return this.logger.error(`Error getting messages from topic ${e}:`,t),{messages:[]}}}async getMessageStream(e){return this.standardClient.getMessageStream(e)}async getMessageContent(e){try{return await this.standardClient.getMessageContent(e)}catch(t){throw this.logger.error(`Error retrieving message content for: ${e}`,t),new Error(`Failed to retrieve message content: ${t instanceof Error?t.message:String(t)}`)}}async getInboundTopicId(){try{const e=this.getOperatorId();this.logger.info(`[HCS10Client] Retrieving profile for operator ${e} to find inbound topic...`);const t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.inboundTopic)return this.logger.info(`[HCS10Client] Found inbound topic for operator ${e}: ${t.topicInfo.inboundTopic}`),t.topicInfo.inboundTopic;throw new Error(`Could not retrieve inbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}catch(e){this.logger.error(`[HCS10Client] Error fetching operator's inbound topic ID (${this.getOperatorId()}):`,e);const t=this.getOperatorId();let n=`Failed to get inbound topic ID for operator ${t}.`;throw e instanceof Error&&e.message.includes("does not have a valid HCS-11 memo")?n+=` The account profile may not exist or is invalid. Please ensure this operator account (${t}) is registered as an HCS-10 agent. You might need to register it first (e.g., using the 'register_agent' tool or SDK function).`:e instanceof Error?n+=` Reason: ${e.message}`:n+=` Unexpected error: ${String(e)}`,new Error(n)}}getAccountAndSigner(){const e=this.standardClient.getAccountAndSigner();return{accountId:e.accountId,signer:e.signer}}async getOutboundTopicId(){const e=this.getOperatorId(),t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.outboundTopic)return t.topicInfo.outboundTopic;throw new Error(`Could not retrieve outbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}setClient(t,n){return this.standardClient=new e.HCS10Client({network:this.getNetwork(),operatorId:t,operatorPrivateKey:n,guardedRegistryBaseUrl:this.guardedRegistryBaseUrl}),this.standardClient}async validateOperator(e){try{this.setClient(e.accountId,e.privateKey);return{isValid:!0,operator:{accountId:this.getOperatorId()}}}catch(t){return this.logger.error(`Validation error: ${t}`),{isValid:!1,error:t instanceof Error?t.message:String(t)}}}async initializeWithValidation(e){const t=await this.validateOperator(e);return t.isValid&&e.stateManager&&e.stateManager.initializeConnectionsManager(this.standardClient),t}}class u extends n.StructuredTool{constructor(e,t){super(),this.name="register_agent",this.description="Creates and registers the AI agent on the Hedera network. Returns JSON string with agent details (accountId, privateKey, topics) on success. Optionally supports fee configuration for the agent's inbound topic using HBAR or specific tokens.",this.schema=o.z.object({name:o.z.string().describe("The name of the agent to register"),description:o.z.string().optional().describe("Optional description of the agent"),type:o.z.enum(["autonomous","manual"]).optional().describe("Optional agent type (default: autonomous)"),model:o.z.string().optional().describe("Optional model identifier for the agent"),capabilities:o.z.array(o.z.number()).optional().describe("Optional array of AIAgentCapability enum values (0-18). If not provided, defaults to just TEXT_GENERATION (0)"),profilePicture:o.z.union([o.z.string().describe("Path to a local image file or URL to an image"),o.z.object({url:o.z.string().describe("URL to an image file"),filename:o.z.string().describe("Filename to use for the image")}),o.z.object({path:o.z.string().describe("Path to a local image file"),filename:o.z.string().optional().describe("Optional custom filename")})]).optional().describe("Optional profile picture for the agent (local file path or URL)"),feeCollectorAccountId:o.z.string().optional().describe("The account ID to collect fees. If not specified, the new agent's account ID will be used. Required if any fee is specified."),hbarFee:o.z.number().optional().describe("Optional: The fee amount in HBAR to charge per message on the inbound topic (e.g., 0.5). If specified, inboundTopicType will be set to FEE_BASED."),tokenFee:o.z.object({amount:o.z.number(),tokenId:o.z.string()}).optional().describe('Optional: The fee amount and token ID to charge per message on the inbound topic (e.g., { amount: 10, tokenId: "0.0.12345" }). If specified, inboundTopicType will be set to FEE_BASED.'),hbarFees:o.z.array(o.z.object({amount:o.z.number(),collectorAccount:o.z.string().optional()})).optional().describe("Optional: Array of HBAR fees with different collectors. If specified, inboundTopicType will be set to FEE_BASED."),tokenFees:o.z.array(o.z.object({amount:o.z.number(),tokenId:o.z.string(),collectorAccount:o.z.string().optional()})).optional().describe("Optional: Array of token fees with different collectors. If specified, inboundTopicType will be set to FEE_BASED."),exemptAccountIds:o.z.array(o.z.string()).optional().describe("Optional: Array of account IDs to exempt from ALL fees set for this agent."),setAsCurrent:o.z.boolean().optional().describe("Optional: Whether to set the newly registered agent as the current active agent in the state manager. Default: true"),persistence:o.z.object({prefix:o.z.string().optional()}).optional().describe("Optional: Configuration for persisting agent data to environment variables. The prefix will determine the environment variable names (e.g., PREFIX_ACCOUNT_ID). Defaults to TODD if not specified.")}),this.client=e,this.stateManager=t}async loadProfilePicture(t){const n=e.Logger.getInstance({level:"debug"});try{if(!t)return null;if("string"==typeof t){if(t.startsWith("http://")||t.startsWith("https://")){n.info(`Loading profile picture from URL: ${t}`);const e=await s.get(t,{responseType:"arraybuffer"}),o=globalThis.Buffer.from(e.data),i=new URL(t).pathname;return{buffer:o,filename:r.basename(i)||"profile.png"}}{if(!i.existsSync(t))return n.warn(`Profile picture file not found: ${t}`),null;n.info(`Loading profile picture from file: ${t}`);const e=i.readFileSync(t);return{buffer:e,filename:r.basename(t)}}}if("url"in t){n.info(`Loading profile picture from URL: ${t.url}`);const e=await s.get(t.url,{responseType:"arraybuffer"}),o=globalThis.Buffer.from(e.data);return{buffer:o,filename:t.filename||"profile.png"}}if("path"in t){if(!i.existsSync(t.path))return n.warn(`Profile picture file not found: ${t.path}`),null;n.info(`Loading profile picture from file: ${t.path}`);const e=i.readFileSync(t.path);return{buffer:e,filename:t.filename||r.basename(t.path)}}return null}catch(o){return n.error("Failed to load profile picture:",o),null}}async _call(t){const n=e.Logger.getInstance({level:"debug"}),o={name:t.name,description:t.description,type:t.type,model:t.model,capabilities:t.capabilities||[e.AIAgentCapability.TEXT_GENERATION],properties:{}};let i="";if(t.profilePicture){const e=await this.loadProfilePicture(t.profilePicture);if(e){const{buffer:n,filename:r}=e;o.pfpBuffer=n,o.pfpFileName=r,"string"==typeof t.profilePicture?i=t.profilePicture:"url"in t.profilePicture?i=t.profilePicture.url:"path"in t.profilePicture&&(i=t.profilePicture.path)}}const r=void 0!==t.hbarFee&&t.hbarFee>0,s=this.hasValidTokenFee(t.tokenFee),a=t.hbarFees&&t.hbarFees.length>0,c=t.tokenFees&&t.tokenFees.length>0;if(r||s||a||c){const{accountId:i}=this.client.getAccountAndSigner(),l=t.feeCollectorAccountId||i;if(!l)return"Error: Fee collector account ID is required when specifying fees and could not be determined.";const u=new e.FeeConfigBuilder({network:this.client.getNetwork(),logger:n});try{const e=t.exemptAccountIds?.filter((e=>e!==l&&e.startsWith("0.0")))||[];let i=u;if(r&&(n.info(`Adding HBAR fee: ${t.hbarFee} HBAR to be collected by ${l}`),i=i.addHbarFee(t.hbarFee,l,e)),a)for(const o of t.hbarFees){const t=o.collectorAccount||l;n.info(`Adding HBAR fee: ${o.amount} HBAR to be collected by ${t}`),i=i.addHbarFee(o.amount,t,e)}if(s&&(n.info(`Adding token fee: ${t.tokenFee.amount} of token ${t.tokenFee.tokenId} to be collected by ${l}`),i=await i.addTokenFee(t.tokenFee.amount,t.tokenFee.tokenId,l,void 0,e)),c)for(const o of t.tokenFees){const t=o.collectorAccount||l;n.info(`Adding token fee: ${o.amount} of token ${o.tokenId} to be collected by ${t}`),i=await i.addTokenFee(o.amount,o.tokenId,t,void 0,e)}o.feeConfig=i,n.info("FeeConfigBuilder created successfully")}catch(g){return`Error: Failed to configure fees. Reason: ${g instanceof Error?g.message:String(g)}`}}try{n.info("Registering agent with metadata");const e=await this.client.createAndRegisterAgent(o);return this.processRegistrationResult(e,t,i)}catch(g){return`Error: Failed to create/register agent "${t.name}". Reason: ${g instanceof Error?g.message:String(g)}`}}hasValidTokenFee(e){return!!(e&&e.amount>0&&e.tokenId&&""!==e.tokenId.trim())}async processRegistrationResult(t,n,o=""){const i=t?.metadata?.accountId||"",r=t?.metadata?.inboundTopicId||"",s=t?.metadata?.outboundTopicId||"",a=t?.metadata?.profileTopicId||"",c=t?.metadata?.privateKey||"",g=t?.metadata?.pfpTopicId;if(this.validateRegistrationResult(i,r,s,c),this.stateManager&&c&&i&&r&&s&&(void 0===n.setAsCurrent||n.setAsCurrent)){const t={name:n.name,accountId:i,inboundTopicId:r,outboundTopicId:s,profileTopicId:a,privateKey:c,pfpTopicId:g};if(this.stateManager.setCurrentAgent(t),this.stateManager.persistAgentData&&n.persistence)try{const e={type:"env-file",prefix:n.persistence.prefix};await this.stateManager.persistAgentData(t,e)}catch(h){e.Logger.getInstance().warn("Failed to persist agent data",h)}}await this.ensureAgentHasFunds(i,n.name);const l=this.createFeeDescription(n),u=l?` with ${l} fee on inbound topic`:"",d={success:!0,message:`Successfully registered agent '${n.name}'${u}.`,name:n.name,accountId:i,privateKey:c,inboundTopicId:r,outboundTopicId:s,profileTopicId:a||"N/A",capabilities:n.capabilities||[e.AIAgentCapability.TEXT_GENERATION],hasFees:!(!n.hbarFee&&!this.hasValidTokenFee(n.tokenFee)),hbarFee:n.hbarFee||0,tokenFee:n.tokenFee||null};return(g||o)&&(d.profilePicture={source:o,topicId:g}),JSON.stringify(d)}async ensureAgentHasFunds(n,o){try{await async function(n,o,i,r){try{const c=(await o.requestAccount(i)).balance.balance/1e8;n.info(`${r} account ${i} has ${c} HBAR`);try{const a=new e.HederaMirrorNode("testnet",n),g=await a.getHBARPrice(new Date);if(g){const e=c*g;if(n.info(`${r} balance in USD: $${e.toFixed(2)}`),e<2){n.warn(`${r} account ${i} has less than $2 (${e.toFixed(2)}). Attempting to fund.`);try{const e=o.getAccountAndSigner(),s=10/g,a=Math.max(0,s-c);if(a>0){const s=(new t.TransferTransaction).addHbarTransfer(e.accountId,t.Hbar.fromTinybars(Math.round(-1e8*a))).addHbarTransfer(i,t.Hbar.fromTinybars(Math.round(1e8*a)));n.info(`Funding ${r} account ${i} with ${a.toFixed(2)} HBAR from ${e.accountId}`);const c=await s.execute(o.getClient());await c.getReceipt(o.getClient()),n.info(`Successfully funded ${r} account ${i}.`)}else n.info(`${r} account ${i} does not require additional funding.`)}catch(s){n.error(`Failed to automatically fund ${r} account ${i}:`,s),n.warn(`Please fund the account ${i} manually with at least ${(10/g).toFixed(2)} HBAR.`)}}}else n.warn("Failed to get HBAR price from Mirror Node. Please ensure the account has enough HBAR.")}catch(a){n.warn("Failed to check USD balance. Please ensure the account has enough HBAR.")}}catch(a){n.error(`Failed to check ${r} account balance:`,a)}}(e.Logger.getInstance({module:"RegisterAgentTool"}),this.client.standardClient,n,o)}catch(i){e.Logger.getInstance().error("Failed to auto fund agent",i)}}validateRegistrationResult(e,t,n,o){if(!(e&&t&&n&&o)){const i=[!e&&"accountId",!t&&"inboundTopicId",!n&&"outboundTopicId",!o&&"privateKey"].filter(Boolean).join(", ");throw new Error(`Registration failed. The HCS client returned incomplete details (Missing: ${i}).`)}}createFeeDescription(e){const t=e.hbarFee&&e.hbarFee>0,n=this.hasValidTokenFee(e.tokenFee);if(!t&&!n)return"";let o="";if(t&&(o+=`${e.hbarFee} HBAR`),n&&e.tokenFee){const t=`${e.tokenFee.amount} of token ${e.tokenFee.tokenId}`;o+=o?` and ${t}`:t}return o}}class d extends n.StructuredTool{constructor(t){super(),this.name="send_message",this.description="Sends a message to a specified Hedera topic using HCS-10 and monitors for responses.",this.lastProcessedTimestamp=0,this.schema=o.z.object({topicId:o.z.string().describe("The Hedera topic ID to send the message to"),message:o.z.string().describe("The message content to send"),disableMonitoring:o.z.boolean().optional().describe("Whether to disable monitoring for responses")}),this.client=t,this.logger=e.Logger.getInstance({module:"SendMessageTool"})}async _call(e){try{const t=await this.client.sendMessage(e.topicId,e.message);if(!t)throw new Error("Failed to send message");if(this.logger.info(`Message sent with sequence number ${t}`),e.disableMonitoring)return`Successfully sent message to topic ${e.topicId}`;{const n=await this.monitorResponses(e.topicId,t);return`Successfully sent message to topic ${e.topicId}${n?`\nResponse: ${n}`:""}`}}catch(t){throw new Error(`Failed to send message: ${t instanceof Error?t.message:String(t)}`)}}async monitorResponses(e,t){let n=0;for(;n<10;){try{const n=await this.client.getMessageStream(e);for(const e of n.messages)if(e.created&&e.created.getTime()>this.lastProcessedTimestamp){this.lastProcessedTimestamp=e.created.getTime();const n=await this.client.getMessageContent(e.data||"");let i;try{i=JSON.parse(n)}catch(o){this.logger.error(`Error parsing message content: ${o}`);continue}if(e.sequence_number>t)return i&&"string"==typeof i.data?i.data:JSON.stringify(i)}}catch(o){this.logger.error(`Error monitoring responses: ${o}`)}n++,await new Promise((e=>setTimeout(e,1e3)))}return null}}class h extends n.StructuredTool{constructor({client:t,stateManager:n,...i}){super(i),this.name="monitor_connections",this.description="Starts passively LISTENING on the current agent's own inbound topic for INCOMING HCS-10 connection requests. Handles received requests automatically. Takes NO arguments. DO NOT use this to start a new connection TO someone else.",this.isMonitoring=!1,this.monitoringTopic=null,this.schema=o.z.object({}),this.client=t,this.stateManager=n,this.logger=e.Logger.getInstance({module:"ConnectionTool",level:"info"})}async _call(){let e;try{e=await this.client.getInboundTopicId()}catch(t){const e=`Error getting inbound topic ID for monitoring: ${t instanceof Error?t.message:String(t)}`;return this.logger.error(e),e}return e?this.isMonitoring?this.monitoringTopic===e?`Already monitoring topic ${e}.`:`Error: Already monitoring a different topic (${this.monitoringTopic}). Stop the current monitor first.`:(this.isMonitoring=!0,this.monitoringTopic=e,this.logger.info(`Initiating connection request monitoring for topic ${e}...`),this.monitorIncomingRequests(e).catch((t=>{this.logger.error(`Monitoring loop for ${e} encountered an unrecoverable error:`,t),this.isMonitoring=!1,this.monitoringTopic=null})),`Started monitoring inbound topic ${e} for connection requests in the background.`):"Error: Could not determine the inbound topic ID for the current agent."}async monitorIncomingRequests(e){this.logger.info(`Monitoring inbound topic ${e}...`);let t=0;const n=new Set;for(;this.isMonitoring&&this.monitoringTopic===e;){try{const i=(await this.client.getMessages(e)).messages,r=i.filter((e=>"connection_request"===e.op&&"number"==typeof e.sequence_number));for(const s of r){t=Math.max(t,s.sequence_number||0);const r=s.sequence_number;if(!r)continue;if(i.some((e=>"connection_created"===e.op&&e.connection_id===r))){this.logger.debug(`Connection request #${r} already handled (found connection_created). Skipping.`);continue}const a=s.operator_id||"",c=a.split("@")[1]||null;if(c)if(n.has(r))this.logger.info(`Connection request #${r} already processed in this session. Skipping.`);else{this.logger.info(`Processing connection request #${r} from account ${c}...`);try{const t=await this.client.handleConnectionRequest(e,c,r);n.add(r),this.logger.info(`Connection confirmed for request #${r}. New connection topic: ${t.connectionTopicId}`);const o={targetAccountId:c,targetAgentName:`Agent ${c}`,targetInboundTopicId:"N/A",connectionTopicId:t.connectionTopicId};this.stateManager.addActiveConnection(o),this.logger.info(`Added new active connection to ${c} state.`)}catch(o){this.logger.error(`Error handling connection request #${r} from ${c}:`,o)}}else this.logger.warn(`Could not determine requesting account ID from operator_id '${a}' for request #${r}. Skipping.`)}}catch(i){this.logger.error(`Error fetching or processing messages for topic ${e}:`,i)}await new Promise((e=>setTimeout(e,5e3)))}this.logger.info(`Monitoring loop stopped for topic ${e}.`),this.isMonitoring=!1,this.monitoringTopic=null}stopMonitoring(){this.isMonitoring?(this.logger.info(`Stopping monitoring for topic ${this.monitoringTopic}...`),this.isMonitoring=!1,this.monitoringTopic=null):this.logger.info("Monitor is not currently running.")}}class f extends n.StructuredTool{constructor({hcsClient:t,stateManager:n,...i}){super(i),this.name="send_message_to_connection",this.description="Sends a text message to another agent using an existing active connection. Identify the target agent using their account ID (e.g., 0.0.12345) or the connection number shown in 'list_connections'. Return back the reply from the target agent if possible",this.schema=o.z.object({targetIdentifier:o.z.string().describe("The account ID (e.g., 0.0.12345) of the target agent OR the connection number (e.g., '1', '2') from the 'list_connections' tool."),message:o.z.string().describe("The text message content to send."),disableMonitoring:o.z.boolean().optional().default(!1)}),this.hcsClient=t,this.stateManager=n,this.logger=e.Logger.getInstance({module:"SendMessageToConnectionTool"})}async _call({targetIdentifier:e,message:t,disableMonitoring:n}){const o=this.stateManager.getCurrentAgent();if(!o)return"Error: Cannot send message. No agent is currently active. Please register or select an agent first.";const i=this.stateManager.getConnectionByIdentifier(e);if(!i)return`Error: Could not find an active connection matching identifier "${e}". Use 'list_connections' to see active connections.`;const r=i.connectionTopicId,s=i.targetAgentName,a=`${o.inboundTopicId}@${o.accountId}`;this.logger.info(`Sending message from ${a} to ${s} (${i.targetAccountId}) via connection topic ${r}`);try{const e=await this.hcsClient.sendMessage(r,t,`Agent message from ${o.name}`);if(!e)throw new Error("Failed to send message");if(!n)return`Message sent to ${s} (${i.targetAccountId}) via connection ${r}. Sequence Number: ${e}`;const c=await this.monitorResponses(r,a,e);return c?(this.logger.info(`Got reply from ${s}`,c),`Received reply from ${s}: ${c}`):`Message sent to ${s} (${i.targetAccountId}) via connection ${r}. Sequence Number: ${e}`}catch(c){return this.logger.error(`Failed to send message via connection ${r}: ${c}`),`Error sending message to ${s}: ${c instanceof Error?c.message:String(c)}`}}async monitorResponses(e,t,n){for(;;){try{const o=await this.hcsClient.getMessageStream(e);for(const e of o.messages){if(e.sequence_number<n||e.operator_id===t)continue;return await this.hcsClient.getMessageContent(e.data||"")}}catch(o){this.logger.error(`Error monitoring responses: ${o}`)}await new Promise((e=>setTimeout(e,4e3)))}return null}}class p extends n.StructuredTool{constructor({hcsClient:t,stateManager:n,...i}){super(i),this.name="initiate_connection",this.description="Actively STARTS a NEW HCS-10 connection TO a specific target agent identified by their account ID. Requires the targetAccountId parameter. Use this ONLY to INITIATE an OUTGOING connection request.",this.schema=o.z.object({targetAccountId:o.z.string().describe("The Hedera account ID (e.g., 0.0.12345) of the agent you want to connect with.")}),this.hcsClient=t,this.stateManager=n,this.logger=e.Logger.getInstance({module:"InitiateConnectionTool"})}async _call({targetAccountId:e}){const t=this.stateManager.getCurrentAgent();if(!t)return"Error: Cannot initiate connection. No agent is currently active. Please register or select an agent first.";this.logger.info(`Attempting connection from ${t.accountId} to ${e}`);try{this.logger.debug(`Retrieving profile for ${e}...`);const o=await this.hcsClient.getAgentProfile(e);if(!o?.topicInfo?.inboundTopic)return`Error: Could not retrieve profile or find inbound topic ID for target agent ${e}. They might not be registered or have a public profile.`;const i=o.topicInfo.inboundTopic,r=o.profile.name||`Agent ${e}`,s=await this.hcsClient.submitConnectionRequest(i,t.name);let a=null;const c=s?.topicSequenceNumber;if(null===c)throw new Error("Connection request sequence number not found.");try{if(a=c.toNumber(),isNaN(a))throw new Error("Converted sequence number is NaN.")}catch(n){throw new Error(`Failed to convert connection request sequence number: ${n}`)}const g=6e4,l=2e3,u=Math.ceil(g/l),d=await this.hcsClient.waitForConnectionConfirmation(i,a,u,l);if(!d?.connectionTopicId)return`Error: Connection confirmation not received from ${e} (for request ${a}) within ${g/1e3} seconds.`;const h=d.connectionTopicId;this.logger.info(`Connection confirmed! Topic ID: ${h}`);const f={targetAccountId:e,targetAgentName:r,targetInboundTopicId:i,connectionTopicId:h};this.stateManager.addActiveConnection(f);const p=this.stateManager.listConnections(),m=p.find((e=>e.connectionTopicId===h)),I=m?p.indexOf(m)+1:null;return`Successfully established connection ${I?`#${I}`:""} with ${r} (${e}). Connection Topic: ${h}. You can now send messages using this connection.`}catch(o){return this.logger.error(`Connection initiation failed: ${o}`),`Error initiating connection with ${e}: ${o instanceof Error?o.message:String(o)}`}}}class m extends n.StructuredTool{constructor({stateManager:t,hcsClient:n,...i}){super(i),this.name="list_connections",this.description="Lists the currently active HCS-10 connections with detailed information. Shows connection status, agent details, and recent activity. Use this to get a comprehensive view of all active connections.",this.schema=o.z.object({includeDetails:o.z.boolean().optional().describe("Whether to include detailed information about each connection"),showPending:o.z.boolean().optional().describe("Whether to include pending connection requests")}),this.stateManager=t,this.hcsClient=n,this.logger=new e.Logger({module:"ListConnectionsTool"})}async _call(e){const t=e.includeDetails??!0,n=e.showPending??!0,o=await this.getEnhancedConnections();if(0===o.length)return"There are currently no active connections.";const i=o.filter((e=>"established"===e.status)),r=o.filter((e=>e.isPending)),s=o.filter((e=>e.needsConfirmation));let a="";return i.length>0&&(a+=`🟢 Active Connections (${i.length}):\n`,i.forEach(((e,n)=>{a+=this.formatConnection(e,n,t)})),a+="\n"),n&&s.length>0&&(a+=`🟠 Connections Needing Confirmation (${s.length}):\n`,s.forEach(((e,n)=>{a+=this.formatConnection(e,n,t)})),a+="\n"),n&&r.length>0&&(a+=`⚪ Pending Connection Requests (${r.length}):\n`,r.forEach(((e,n)=>{a+=this.formatConnection(e,n,t)}))),a.trim()}formatConnection(e,t,n){let o=`${t+1}. ${e.profileInfo?.display_name||e.targetAgentName||"Unknown Agent"} (${e.targetAccountId})\n`;o+=` Topic: ${e.isPending?"(Pending Request)":e.connectionTopicId}\n`;if(o+=` Status: ${e.status||"unknown"}\n`,n){if(e.profileInfo?.bio&&(o+=` Bio: ${e.profileInfo.bio.substring(0,100)}${e.profileInfo.bio.length>100?"...":""}\n`),e.created){o+=` ${e.isPending?"Request sent":"Connection established"}: ${e.created.toLocaleString()}\n`}e.lastActivity&&(o+=` Last activity: ${e.lastActivity.toLocaleString()}\n`)}return o}async getEnhancedConnections(){if(!this.hcsClient)return this.stateManager.listConnections();try{const{accountId:e}=this.hcsClient.getAccountAndSigner();if(!e)return this.stateManager.listConnections();const t=this.stateManager.getConnectionsManager();if(!t)return this.logger.error("ConnectionsManager not initialized"),this.stateManager.listConnections();const n=await t.fetchConnectionData(e);for(const o of n)this.stateManager.updateOrAddConnection(o);return n}catch(e){return console.error("Error fetching connection data:",e),this.stateManager.listConnections()}}}class I extends n.StructuredTool{constructor({hcsClient:t,stateManager:n,...i}){super(i),this.name="check_messages",this.description="Checks for and retrieves messages from an active connection. \nIdentify the target agent using their account ID (e.g., 0.0.12345) or the connection number shown in 'list_connections'. \nBy default, it only retrieves messages newer than the last check. \nUse 'fetchLatest: true' to get the most recent messages regardless of when they arrived. \nUse 'lastMessagesCount' to specify how many latest messages to retrieve (default 1 when fetchLatest is true).",this.schema=o.z.object({targetIdentifier:o.z.string().describe("The account ID (e.g., 0.0.12345) of the target agent OR the connection number (e.g., '1', '2') from the 'list_connections' tool to check messages for."),fetchLatest:o.z.boolean().optional().default(!1).describe("Set to true to fetch the latest messages even if they have been seen before, ignoring the last checked timestamp. Defaults to false (fetching only new messages)."),lastMessagesCount:o.z.number().int().positive().optional().describe("When fetchLatest is true, specifies how many of the most recent messages to retrieve. Defaults to 1.")}),this.hcsClient=t,this.stateManager=n,this.logger=e.Logger.getInstance({module:"CheckMessagesTool"})}async _call({targetIdentifier:e,fetchLatest:t,lastMessagesCount:n}){const o=this.stateManager.getConnectionByIdentifier(e);if(!o)return`Error: Could not find an active connection matching identifier "${e}". Use 'list_connections' to see active connections.`;const i=o.connectionTopicId,r=o.targetAgentName,s=this.stateManager.getLastTimestamp(i);this.logger.info(`Checking messages for connection with ${r} (${o.targetAccountId}) on topic ${i} (fetchLatest: ${t}, lastCount: ${n}, since: ${s})`);try{const e=(await this.hcsClient.getMessages(i)).messages;if(!e||0===e.length)return`No messages found on connection topic ${i}.`;let o=[],g=s;const l=!0===t;if(l){this.logger.info("Fetching latest messages regardless of timestamp.");const t=n??1;o=e.slice(-t)}else this.logger.info(`Filtering for messages newer than ${s}`),o=e.filter((e=>1e6*e.timestamp>s)),o.length>0&&(g=o.reduce(((e,t)=>Math.max(e,1e6*t.timestamp)),s));if(0===o.length)return l?`Could not retrieve the latest message(s). No messages found on topic ${i}.`:`No new messages found for connection with ${r} since last check.`;this.logger.info(`Processing ${o.length} message(s).`);let u=l?`Latest message(s) from ${r}:\n`:`New messages from ${r}:\n`;for(const t of o){let e=t.data;try{"string"==typeof e&&e.startsWith("hcs://")&&(this.logger.debug(`Resolving inscribed message: ${e}`),e=await this.hcsClient.getMessageContent(e),this.logger.debug(`Resolved content length: ${e?.length}`));let n=e;try{const t=JSON.parse(e||"{}");if("hcs-10"===t.p&&"message"===t.op&&t.data){n=`[${t.operator_id||"unknown_sender"}]: ${t.data}`}else n=e}catch(a){n=e}u+=`\n[${new Date(t.timestamp).toLocaleString()}] (Seq: ${t.sequence_number})\n${n}\n`}catch(c){const e=`Error processing message (Seq: ${t.sequence_number}): ${c instanceof Error?c.message:String(c)}`;this.logger.error(e),u+=`\n[Error processing message Seq: ${t.sequence_number}]\n`}}return!l&&g>s&&(this.logger.debug(`Updating timestamp for topic ${i} to ${g}`),this.stateManager.updateTimestamp(i,g)),u.trim()}catch(c){return this.logger.error(`Failed to check messages for topic ${i}: ${c}`),`Error checking messages for ${r}: ${c instanceof Error?c.message:String(c)}`}}}class C extends n.StructuredTool{constructor({hcsClient:t,...n}){super(n),this.name="find_registrations",this.description="Searches the configured agent registry for HCS-10 agents. You can filter by account ID or tags. Returns basic registration info.",this.schema=o.z.object({accountId:o.z.string().optional().describe("Optional: Filter registrations by a specific Hedera account ID (e.g., 0.0.12345)."),tags:o.z.array(o.z.nativeEnum(e.AIAgentCapability)).optional().describe("Optional: Filter registrations by a list of tags (API filter only).")}),this.hcsClient=t,this.logger=e.Logger.getInstance({module:"FindRegistrationsTool"})}async _call({accountId:e,tags:t}){this.logger.info("Searching registrations with filters - Account ID",JSON.stringify({accountId:e,tags:t}));const n={};e&&(n.accountId=e),t&&t.length>0&&(n.tags=t),n.network=this.hcsClient.getNetwork();try{if(!this.hcsClient.standardClient)throw new Error("Standard SDK client instance is not available in HCS10Client wrapper.");const e=await this.hcsClient.standardClient.findRegistrations(n);if(!e.success||e.error)return`Error finding registrations: ${e.error||"Unknown error"}`;if(!e.registrations||0===e.registrations.length)return"No registrations found matching the criteria.";let t=`Found ${e.registrations.length} registration(s):\n`;return e.registrations.forEach(((e,n)=>{const o=e.metadata;t+=`${n+1}. Name: ${o.alias||"N/A"}\n`,t+=`Description: ${o.bio||"N/A"}\n`,t+=` Account ID: ${e.accountId}\n`,t+=` Status: ${e.status}\n`,t+=` Model: ${o.properties?.model||"N/A"}\n`,o.properties?.capabilities&&o.properties.capabilities.length>0&&(t+=` Capabilities: ${o.properties.capabilities.join(", ")}\n`),o.properties&&(t+=` Properties: ${JSON.stringify(o.properties)}\n`),t+=` Inbound Topic: ${e.inboundTopicId}\n`,t+=` Outbound Topic: ${e.outboundTopicId}\n`,t+=` Created At: ${e.createdAt}\n`})),t.trim()}catch(o){return this.logger.error(`Failed to execute findRegistrations: ${o}`),`Error searching registrations: ${o instanceof Error?o.message:String(o)}`}}}class b extends n.StructuredTool{constructor({hcsClient:t,stateManager:n,...i}){super(i),this.name="monitor_connections",this.description="Monitors for incoming connection requests and accepts them with optional fee settings. Use this to watch for connection requests and accept them, optionally setting HBAR or token fees on the connection.",this.schema=o.z.object({acceptAll:o.z.boolean().optional().describe("Whether to automatically accept all incoming connection requests. Default is false."),targetAccountId:o.z.string().optional().describe("If provided, only accept connection requests from this specific account ID."),hbarFees:o.z.array(o.z.object({amount:o.z.number(),collectorAccount:o.z.string().optional()})).optional().describe("Array of HBAR fee amounts to charge per message (with optional collector accounts)."),tokenFees:o.z.array(o.z.object({amount:o.z.number(),tokenId:o.z.string(),collectorAccount:o.z.string().optional()})).optional().describe("Array of token fee amounts and IDs to charge per message (with optional collector accounts)."),exemptAccountIds:o.z.array(o.z.string()).optional().describe("Array of account IDs to exempt from ALL fees set in this request."),monitorDurationSeconds:o.z.number().optional().describe("How long to monitor for incoming requests in seconds. Default is 60."),defaultCollectorAccount:o.z.string().optional().describe("Default account to collect fees if not specified at the fee level. Defaults to the agent account.")}),this.isMonitoring=!1,this.hcsClient=t,this.stateManager=n,this.logger=e.Logger.getInstance({module:"ConnectionMonitorTool",level:"error"}),this.listConnectionsTool=new m({stateManager:n,hcsClient:t,...i})}updateClient(e){this.hcsClient=e,this.logger.info("Updated HCS10Client instance for ConnectionMonitorTool"),this.listConnectionsTool=new m({stateManager:this.stateManager,hcsClient:e})}async call(e){return this._call(e)}async _call({acceptAll:e=!1,targetAccountId:t,hbarFees:n=[],tokenFees:o=[],exemptAccountIds:i,monitorDurationSeconds:r=60,defaultCollectorAccount:s}){if(!this.stateManager.getCurrentAgent())return"Error: Cannot monitor for connections. No agent is currently active. Please register or select an agent first.";if(this.isMonitoring)return"Already monitoring for connection requests. Please wait for the current monitoring session to complete.";try{this.isMonitoring=!0;const c=await this.hcsClient.getInboundTopicId();if(!c)return this.isMonitoring=!1,"Error: Could not find inbound topic ID for the current agent.";this.logger.info(`Starting to monitor inbound topic ${c} for connection requests...`);const g=this.createFeeConfig(n,o,i,t,s),l=Date.now()+1e3*r,u=3e3;let d=0,h=0,f=0,p=0;for(;Date.now()<l;)try{await this.listConnectionsTool.invoke({includeDetails:!1,showPending:!1});const n=this.stateManager.listConnections(),o=new Map;n.filter((e=>"established"===e.status&&!e.isPending)).forEach((e=>{o.has(e.targetAccountId)||o.set(e.targetAccountId,new Set),e.connectionRequestId&&o.get(e.targetAccountId)?.add(String(e.connectionRequestId))}));const i=(await this.hcsClient.getMessages(c)).messages.filter((e=>!(!e.sequence_number||e.sequence_number<=d)&&(d=Math.max(d,e.sequence_number),"connection_request"===e.op)));for(const r of i){const n=r.sequence_number;if(!n)continue;h++;const i=await this.hcsClient.getInboundTopicId()||"",s=this.stateManager.getConnectionsManager();if(!s){this.logger.error("ConnectionsManager not initialized in state manager");continue}if(s.isConnectionRequestProcessed(i,n)){this.logger.info(`Request #${n} already processed, skipping`),p++;continue}const a=this.extractAccountId(r);if(!a){s.markConnectionRequestProcessed(i,n);continue}if(t&&a!==t){this.logger.info(`Request #${n} doesn't match target ${t}`);continue}const c=o.get(a);if(c?.has(String(n)))this.logger.info(`Already processed connection request #${n} from ${a}, skipping`),s.markConnectionRequestProcessed(i,n),p++;else if(e){const e=await this.acceptConnectionRequest(n,a,g);s.markConnectionRequestProcessed(i,n),e.success&&(f++,this.logger.info(`Successfully accepted connection with ${a} for request #${n}`))}else this.logger.info(`Found request #${n} from ${a} (not auto-accepting)`)}await new Promise((e=>setTimeout(e,u)))}catch(a){this.logger.error(`Error polling for messages: ${a}`),await new Promise((e=>setTimeout(e,u)))}return this.isMonitoring=!1,0===h?`No connection requests received during the ${r} second monitoring period.`:e?`Monitored for ${r} seconds. Found ${h} connection requests, accepted ${f} connections, skipped ${p} existing connections${this.formatFeeString(n,o)}.`:`Monitored for ${r} seconds. Found ${h} connection requests. To accept them, call this tool again with acceptAll=true.`}catch(a){return this.isMonitoring=!1,this.logger.error(`Connection monitoring failed: ${a}`),`Error monitoring for connections: ${a instanceof Error?a.message:String(a)}`}}createFeeConfig(t=[],n=[],o,i,r){if(0!==t.length||0!==n.length)try{const s=this.hcsClient.getAccountAndSigner().accountId,a=r||s,c=new e.FeeConfigBuilder({network:this.hcsClient.getNetwork(),logger:this.logger,defaultCollectorAccountId:a}),g=[...o||[]];i&&!g.includes(i)&&g.push(i);for(const e of t)if(e.amount>0){const t=e.collectorAccount||a;c.addHbarFee(e.amount,t,g),this.logger.info(`Added HBAR fee: ${e.amount} HBAR to be collected by ${t}`)}for(const e of n)if(e.amount>0&&e.tokenId){const t=e.collectorAccount||a;c.addTokenFee(e.amount,e.tokenId,t,void 0,g),this.logger.info(`Added token fee: ${e.amount} of token ${e.tokenId} to be collected by ${t}`)}return c}catch(s){return void this.logger.error(`Error creating fee configuration: ${s}`)}}extractAccountId(e){if(e.operator_id)return this.hcsClient.standardClient.extractAccountFromOperatorId(e.operator_id)}async acceptConnectionRequest(e,t,n){try{const i=await this.hcsClient.getInboundTopicId();this.logger.info(`Accepting connection request #${e} from ${t}`);const r=await this.hcsClient.handleConnectionRequest(i,t,e,n);if(!r?.connectionTopicId)return{success:!1,error:"Connection acceptance returned no connection topic ID"};const s=r.connectionTopicId;let a;this.logger.info(`Connection established! Topic ID: ${s}`);try{const e=await this.hcsClient.getAgentProfile(t);e.success&&e.profile&&(a=e.profile)}catch(o){this.logger.warn(`Could not fetch profile for ${t}: ${o}`)}const c=(await this.hcsClient.getAgentProfile(t))?.topicInfo?.inboundTopic||"",g={targetAccountId:t,targetAgentName:a?.display_name||`Agent ${t}`,targetInboundTopicId:c,connectionTopicId:s,profileInfo:a,created:new Date,status:"established",metadata:{requestId:e}};return this.stateManager.addActiveConnection(g),{success:!0,connectionTopicId:s}}catch(i){return this.logger.error(`Error accepting connection request: ${i}`),{success:!1,error:i instanceof Error?i.message:String(i)}}}formatFeeString(e=[],t=[]){if(0===e.length&&0===t.length)return"";let n=" with fees: ";if(e.length>0){const t=e.filter((e=>e.amount>0)).map((e=>{const t=e.collectorAccount?` to ${e.collectorAccount}`:"";return`${e.amount} HBAR${t}`})).join(", ");t&&(n+=t)}if(t.length>0){e.length>0&&(n+=" and ");const o=t.filter((e=>e.amount>0&&e.tokenId)).map((e=>{const t=e.collectorAccount?` to ${e.collectorAccount}`:"";return`${e.amount} of token ${e.tokenId}${t}`})).join(", ");o&&(n+=o)}return" with fees: "===n?"":n}update(){this.listConnectionsTool.invoke({includeDetails:!0,showPending:!0}).catch((e=>{this.logger.error(`Error updating connections: ${e}`)}))}}class $ extends n.StructuredTool{constructor({hcsClient:t,stateManager:n,...i}){super(i),this.name="manage_connection_requests",this.description='Manage incoming connection requests. List pending requests, view details about requesting agents, and reject connection requests. Use the separate "accept_connection_request" tool to accept.',this.schema=o.z.object({action:o.z.enum(["list","view","reject"]).describe("The action to perform: list all requests, view details of a specific request, or reject a request"),requestKey:o.z.string().optional().describe("The unique request key to view or reject (required for view and reject actions)")}),this.lastRefreshTime=0,this.refreshIntervalMs=3e4,this.hcsClient=t,this.stateManager=n,this.logger=e.Logger.getInstance({module:"ManageConnectionRequestsTool",level:"debug"})}async _call({action:e,requestKey:t}){if(!this.stateManager.getCurrentAgent())return"Error: Cannot manage connection requests. No agent is currently active. Please register or select an agent first.";if(("view"===e||"reject"===e)&&void 0===t)return`Error: Request key is required for the "${e}" action. Use the "list" action first to see available requests.`;try{switch(await this.refreshRequestsIfNeeded(),e){case"list":return this.listRequests();case"view":return this.viewRequest(t);case"reject":return this.rejectRequest(t);default:return`Error: Unsupported action: ${e}`}}catch(n){return this.logger.error(`Error in ManageConnectionRequestsTool: ${n}`),`Error managing connection requests: ${n instanceof Error?n.message:String(n)}`}}async refreshRequestsIfNeeded(){const e=Date.now();e-this.lastRefreshTime>this.refreshIntervalMs&&(await this.refreshRequests(),this.lastRefreshTime=e)}async refreshRequests(){try{const{accountId:e}=this.hcsClient.getAccountAndSigner();if(!e)throw new Error("Could not determine account ID for current agent");const t=this.stateManager.getConnectionsManager();if(!t)throw new Error("ConnectionsManager not initialized");await t.fetchConnectionData(e)}catch(e){throw this.logger.error(`Error refreshing connection requests: ${e}`),e}}listRequests(){const e=this.stateManager.getConnectionsManager();if(!e)return"Error: ConnectionsManager not initialized";const t=[...e.getPendingRequests(),...e.getConnectionsNeedingConfirmation()];if(0===t.length)return console.log("No pending connection requests found.",t),"No pending connection requests found.";let n=`Found ${t.length} pending connection request(s):\n\n`;return[...t].sort(((e,t)=>t.created.getTime()-e.created.getTime())).forEach(((e,t)=>{const o=e.needsConfirmation?"🟠 Incoming":"⚪️ Outgoing",i=e.uniqueRequestKey||`${e.connectionRequestId||e.inboundRequestId||"unknown"}`;n+=`${t+1}. ${o} - Key: ${i}\n`,n+=` ${e.needsConfirmation?"From":"To"}: ${e.targetAgentName||`Agent ${e.targetAccountId}`} (${e.targetAccountId})\n`,n+=` Sent/Rcvd: ${e.created.toLocaleString()}\n`,e.memo&&(n+=` Memo: ${e.memo}\n`),e.profileInfo&&e.profileInfo.bio&&(n+=` Bio: ${e.profileInfo.bio}\n`),n+="\n"})),n+='To view more details about a request, use action="view" with the specific requestKey.\n',n+='To reject a request, use action="reject" with the specific requestKey.',n}viewRequest(e){const t=this.stateManager.getConnectionsManager();if(!t)return"Error: ConnectionsManager not initialized";const n=[...t.getPendingRequests(),...t.getConnectionsNeedingConfirmation()].find((t=>t.uniqueRequestKey===e||t.connectionRequestId?.toString()===e||t.inboundRequestId?.toString()===e));if(!n)return`Error: Request with key ${e} not found or no longer pending.`;const o=n.needsConfirmation?"Incoming":"Outgoing",i=n.uniqueRequestKey||`${n.connectionRequestId||n.inboundRequestId||"unknown"}`;let r=`Details for ${o} connection request: ${i}\n\n`;return r+=`${n.needsConfirmation?"Requestor":"Target"} ID: ${n.targetAccountId}\n`,r+=`${n.needsConfirmation?"Requestor":"Target"} Name: ${n.targetAgentName||`Agent ${n.targetAccountId}`}\n`,r+=`Received: ${n.created.toLocaleString()}\n`,n.memo&&(r+=`Memo: ${n.memo}\n`),n.profileInfo&&(r+="\nAgent Profile Information:\n",(n.profileInfo.display_name||n.profileInfo.alias)&&(r+=`Name: ${n.profileInfo.display_name||n.profileInfo.alias}\n`),void 0!==n.profileInfo.type&&(r+=`Type: ${n.profileInfo.type}\n`),n.profileInfo.bio&&(r+=`Bio: ${n.profileInfo.bio}\n`)),r+="\nActions:\n",r+=`- To reject this request: action="reject", requestKey="${i}"\n`,r+='Use the separate "accept_connection_request" tool to accept requests.',r}async rejectRequest(e){const t=this.stateManager.getConnectionsManager();if(!t)return"Error: ConnectionsManager not initialized";const n=[...t.getPendingRequests(),...t.getConnectionsNeedingConfirmation()].find((t=>t.uniqueRequestKey===e||t.connectionRequestId?.toString()===e||t.inboundRequestId?.toString()===e));return n?(n.inboundRequestId?t.markConnectionRequestProcessed(n.targetInboundTopicId||"",n.inboundRequestId):n.connectionRequestId&&t.markConnectionRequestProcessed(n.originTopicId||"",n.connectionRequestId),`Connection request from ${n.targetAgentName||`Agent ${n.targetAccountId}`} was rejected.`):`Error: Request with key ${e} not found or no longer pending.`}}class w extends n.StructuredTool{constructor({hcsClient:t,stateManager:n,...i}){super(i),this.name="accept_connection_request",this.description="Accepts a specific pending connection request from another agent, establishing a communication channel.",this.schema=o.z.object({requestKey:o.z.string().describe('The unique request key of the specific request to accept. Use the "manage_connection_requests" tool with action="list" first to get valid keys.'),hbarFee:o.z.number().optional().describe("Optional HBAR fee amount to charge the connecting agent per message on the new connection topic."),exemptAccountIds:o.z.array(o.z.string()).optional().describe("Optional list of account IDs to exempt from any configured fees on the new connection topic.")}),this.hcsClient=t,this.stateManager=n,this.logger=e.Logger.getInstance({module:"AcceptConnectionRequestTool"})}async _call({requestKey:t,hbarFee:n,exemptAccountIds:o}){const i=this.stateManager.getCurrentAgent();if(!i)return"Error: Cannot accept connection request. No agent is currently active. Please register or select an agent first.";const r=this.stateManager.getConnectionsManager();if(!r)return"Error: ConnectionsManager not initialized";await r.fetchConnectionData(i.accountId);const s=[...r.getPendingRequests(),...r.getConnectionsNeedingConfirmation()].find((e=>e.uniqueRequestKey===t||e.connectionRequestId?.toString()===t||e.inboundRequestId?.toString()===t));if(!s)return`Error: Request with key ${t} not found or no longer pending. Use the manage_connection_requests tool with action="list" to verify.`;const a=s.connectionRequestId||s.inboundRequestId;if(!a)return`Error: Could not determine a valid request ID for the request with key ${t}.`;try{const l=await this.hcsClient.getInboundTopicId();let u;if(n&&n>0){const t=this.hcsClient.getAccountAndSigner().accountId;try{u=new e.FeeConfigBuilder({network:this.hcsClient.getNetwork(),logger:this.logger,defaultCollectorAccountId:t});const r=[...o||[],i.accountId];u.addHbarFee(n,t,r),this.logger.info(`Setting HBAR fee: ${n} HBAR to be collected by ${t}`)}catch(c){this.logger.error(`Error creating fee configuration: ${c}`),u=void 0,this.logger.warn("Proceeding to accept request without fees due to configuration error.")}}this.logger.info(`Attempting to accept request Key: ${t} (ID: ${a}) from ${s.targetAccountId}`);const d=await this.hcsClient.handleConnectionRequest(l,s.targetAccountId,a,u);if(!d?.connectionTopicId)return`Error: Failed to accept connection request with key ${t}. The SDK did not return a connection topic ID.`;this.logger.info(`Successfully created connection topic: ${d.connectionTopicId}`);const h=d.connectionTopicId;let f="";try{const e=await this.hcsClient.standardClient.retrieveProfile(s.targetAccountId);f=e?.topicInfo?.inboundTopic||"",f||this.logger.warn(`Could not resolve target inbound topic for ${s.targetAccountId}`)}catch(g){this.logger.warn(`Error fetching target profile/topic for ${s.targetAccountId}: ${g}`)}const p=s.profileInfo?.display_name||s.profileInfo?.alias||`Agent ${s.targetAccountId}`,m={targetAccountId:s.targetAccountId,targetAgentName:p,targetInboundTopicId:f,connectionTopicId:h,profileInfo:s.profileInfo,created:new Date,status:"established"};this.stateManager.addActiveConnection(m),r.fetchConnectionData(s.targetAccountId),this.logger.info(`Removed request ${t} from pending requests`);let I="";n&&n>0&&u&&(I=` with a ${n} HBAR fee per message`);return`Successfully accepted connection request ${s.uniqueRequestKey||t} from ${p} ${I}. Connection established on topic: ${h}.`}catch(l){return this.logger.error(`Error accepting connection request ${t}: ${l}`),`Error accepting connection request ${t}: ${l instanceof Error?l.message:String(l)}`}}}class y extends n.StructuredTool{constructor(t){super(),this.name="retrieve_profile",this.description="Retrieves the HCS-11 profile data associated with a given Hedera account ID. If no account ID is provided, it defaults to the current operator account ID. Returns the profile object as a JSON string on success.",this.schema=o.z.object({accountId:o.z.string().optional().describe("The Hedera account ID (e.g., 0.0.12345) to retrieve the profile for. If omitted, defaults to the current operator account ID."),disableCache:o.z.boolean().optional().describe("Optional: Set to true to bypass the cache and fetch fresh profile data.")}),this.client=t,this.logger=e.Logger.getInstance({module:this.name})}async _call(e){let t;try{if(e.accountId?t=e.accountId:(this.logger.info("accountId not provided, defaulting to operator ID."),t=this.client.getOperatorId()),!t)throw new Error("Could not determine target account ID.");this.logger.info(`Attempting to retrieve profile for account: ${t}, Disable Cache: ${!!e.disableCache}`);const n=await this.client.standardClient.retrieveProfile(t,e.disableCache);if(n.success&&n.profile)return this.logger.info(`Successfully retrieved profile for ${t}.`),JSON.stringify(n.profile,null,2);{const e=`Error retrieving profile for ${t}: ${n.error||"Profile not found or invalid."}`;return this.logger.error(e),e}}catch(n){const t=`Unexpected error retrieving profile for ${e.accountId||"operator default"}: ${n instanceof Error?n.message:String(n)}`;return this.logger.error(t,n),t}}}class T extends n.StructuredTool{constructor({hcsClient:t,stateManager:n,...i}){super(i),this.name="list_unapproved_connection_requests",this.description="Lists all connection requests that are not fully established, including incoming requests needing approval and outgoing requests waiting for confirmation.",this.schema=o.z.object({sortBy:o.z.enum(["time_asc","time_desc","name_asc","name_desc"]).optional().describe("Optional sorting criteria for the requests list (default: time_desc, newest first)"),limit:o.z.number().optional().describe("Optional limit on the number of requests to return (default: all)")}),this.hcsClient=t,this.stateManager=n,this.logger=e.Logger.getInstance({module:"ListPendingRequestsTool",level:"debug"})}async _call({sortBy:e="time_desc",limit:t}){if(!this.stateManager.getCurrentAgent())return"Error: Cannot list pending requests. No agent is currently active. Please register or select an agent first.";try{const n=await this.findAllPendingRequests();return this.formatRequestsList(n,e,t)}catch(n){return this.logger.error(`Error in ${this.name}: ${n}`),`Error listing pending requests: ${n instanceof Error?n.message:String(n)}`}}async findAllPendingRequests(){const e=this.stateManager.getConnectionsManager();if(!e)return[];const t=this.stateManager.getCurrentAgent();if(!t)return[];await e.fetchConnectionData(t.accountId);return[...e.getPendingRequests(),...e.getConnectionsNeedingConfirmation()]}formatRequestsList(e,t,n){if(0===e.length)return"No pending connection requests found (incoming or outgoing).";const o=this.sortRequests(e,t),i=n?o.slice(0,n):o;let r=`Found ${e.length} pending connection request(s):\n\n`;return i.forEach(((e,t)=>{const n="needs_confirmation"===e.status?"🟠 Incoming":"⚪️ Outgoing";r+=`${t+1}. ${n} - ID: ${e.uniqueRequestKey}\n`,r+=` ${"needs_confirmation"===e.status?"From:":"To: "} ${e.targetAgentName} (${e.targetAccountId})\n`,r+=` Sent/Rcvd: ${e.created.toLocaleString()}\n`,e.memo&&(r+=` Memo: ${e.memo}\n`),e.profileInfo?.bio&&(r+=` Bio: ${e.profileInfo.bio.substring(0,100)}${e.profileInfo.bio.length>100?"...":""}\n`),r+="\n"})),r+="Use related tools (manage_requests, accept_request) to handle these items.",r}sortRequests(e,t){const n=[...e];switch(t){case"time_asc":return n.sort(((e,t)=>e.created.getTime()-t.created.getTime()));case"time_desc":default:return n.sort(((e,t)=>t.created.getTime()-e.created.getTime()));case"name_asc":return n.sort(((e,t)=>e.targetAgentName?.localeCompare(t?.targetAgentName||"")||0));case"name_desc":return n.sort(((e,t)=>t.targetAgentName?.localeCompare(e?.targetAgentName||"")||0))}}}const A=r.join(process.cwd(),".env");class q{constructor(t){this.currentAgent=null,this.connectionMessageTimestamps={},this.connectionsManager=null,this.defaultEnvFilePath=t?.defaultEnvFilePath,this.defaultPrefix=t?.defaultPrefix??"TODD";const n=t?.disableLogging||"true"===process.env.DISABLE_LOGGING;this.logger=new e.Logger({module:"OpenConvaiState",silent:n}),t?.baseClient&&this.initializeConnectionsManager(t.baseClient)}initializeConnectionsManager(t){return this.connectionsManager?this.logger.debug("ConnectionsManager already initialized"):(this.logger.debug("Initializing ConnectionsManager"),this.connectionsManager=new e.ConnectionsManager({baseClient:t,logLevel:"error"})),this.connectionsManager}getConnectionsManager(){return this.connectionsManager}setCurrentAgent(e){this.currentAgent=e,this.connectionMessageTimestamps={},this.connectionsManager&&this.connectionsManager.clearAll()}getCurrentAgent(){return this.currentAgent}addActiveConnection(e){if(!this.connectionsManager)throw this.logger.error("ConnectionsManager not initialized. Call initializeConnectionsManager before adding connections."),new Error("ConnectionsManager not initialized. Call initializeConnectionsManager before adding connections.");const t={connectionTopicId:e.connectionTopicId,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName,targetInboundTopicId:e.targetInboundTopicId,status:this.convertConnectionStatus(e.status||"established"),isPending:e.isPending||!1,needsConfirmation:e.needsConfirmation||!1,created:e.created||new Date,lastActivity:e.lastActivity,profileInfo:e.profileInfo,connectionRequestId:e.connectionRequestId,processed:!0};this.connectionsManager.updateOrAddConnection(t),this.initializeTimestampIfNeeded(e.connectionTopicId)}updateOrAddConnection(e){this.addActiveConnection(e)}listConnections(){return this.connectionsManager?this.connectionsManager.getAllConnections().map((e=>this.convertToActiveConnection(e))):(this.logger.debug("ConnectionsManager not initialized, returning empty connections list"),[])}getConnectionByIdentifier(e){if(!this.connectionsManager)return;const t=this.listConnections(),n=parseInt(e)-1;if(!isNaN(n)&&n>=0&&n<t.length)return t[n];const o=this.connectionsManager.getConnectionByTopicId(e);if(o)return this.convertToActiveConnection(o);const i=this.connectionsManager.getConnectionByAccountId(e);return i?this.convertToActiveConnection(i):void 0}getLastTimestamp(e){return this.connectionMessageTimestamps[e]||0}updateTimestamp(e,t){if(!(e in this.connectionMessageTimestamps))return void(this.connectionMessageTimestamps[e]=t);t>this.connectionMessageTimestamps[e]&&(this.connectionMessageTimestamps[e]=t)}initializeTimestampIfNeeded(e){e in this.connectionMessageTimestamps||(this.connectionMessageTimestamps[e]=1e6*Date.now())}convertConnectionStatus(e){switch(e){case"pending":return"pending";case"established":default:return"established";case"needs confirmation":return"needs_confirmation"}}convertToActiveConnection(e){return{targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName||`Agent ${e.targetAccountId}`,targetInboundTopicId:e.targetInboundTopicId||"",connectionTopicId:e.connectionTopicId,status:this.convertToStateStatus(e.status),created:e.created,lastActivity:e.lastActivity,isPending:e.isPending,needsConfirmation:e.needsConfirmation,profileInfo:e.profileInfo,connectionRequestId:e.connectionRequestId}}convertToStateStatus(e){switch(e){case"pending":return"pending";case"established":case"closed":return"established";case"needs_confirmation":return"needs confirmation";default:return"unknown"}}async persistAgentData(e,t){if(t?.type&&"env-file"!==t.type)throw new Error(`Unsupported persistence type: ${t.type}. Only 'env-file' is supported.`);const n=t?.envFilePath||this.defaultEnvFilePath||process.env.ENV_FILE_PATH||".env",o=t?.prefix||this.defaultPrefix;if(!e.accountId||!e.inboundTopicId||!e.outboundTopicId)throw new Error("Agent data incomplete, cannot persist to environment");const r={[`${o}_ACCOUNT_ID`]:e.accountId,[`${o}_INBOUND_TOPIC_ID`]:e.inboundTopicId,[`${o}_OUTBOUND_TOPIC_ID`]:e.outboundTopicId};e.privateKey&&(r[`${o}_PRIVATE_KEY`]=e.privateKey),e.profileTopicId&&(r[`${o}_PROFILE_TOPIC_ID`]=e.profileTopicId),await async function(e,t){let n="";i.existsSync(e)&&(n=i.readFileSync(e,"utf8"));const o=[...n.split("\n")];for(const[i,r]of Object.entries(t)){const e=o.findIndex((e=>e.startsWith(`${i}=`)));-1!==e?o[e]=`${i}=${r}`:o.push(`${i}=${r}`)}i.writeFileSync(e,o.join("\n"))}(n,r)}}class v{async initialize(e){this.context=e}async cleanup(){}}const M=o.z.object({current_rate:o.z.object({cent_equivalent:o.z.number(),hbar_equivalent:o.z.number(),expiration_time:o.z.number()}),next_rate:o.z.object({cent_equivalent:o.z.number(),hbar_equivalent:o.z.number(),expiration_time:o.z.number()}),timestamp:o.z.string()});class E extends n.StructuredTool{constructor(){super(...arguments),this.name="getHbarPrice",this.description="Retrieves the current price of HBAR in USD from the Hedera Mirror Node.",this.schema=o.z.object({})}async _call(){try{const e=(await s.get("https://mainnet.mirrornode.hedera.com/api/v1/network/exchangerate")).data,t=M.safeParse(e);if(!t.success)throw console.error("Failed to parse exchange rate response:",t.error),new Error("Invalid API response format");const{current_rate:n}=t.data;return`The current price of HBAR is $${(n.cent_equivalent/n.hbar_equivalent/100).toFixed(6)} USD.`}catch(e){console.error("Error fetching HBAR price:",e);let t="An unknown error occurred";return s.isAxiosError(e)?(t=e.message,e.response&&(t+=` (Status: ${e.response.status})`)):e instanceof Error&&(t=e.message),`Failed to retrieve HBAR price: ${t}`}}}class R extends v{}exports.AcceptConnectionRequestTool=w,exports.BasePlugin=v,exports.CheckMessagesTool=I,exports.ConnectionMonitorTool=b,exports.ConnectionTool=h,exports.FindRegistrationsTool=C,exports.GenericPlugin=R,exports.GetHbarPriceTool=E,exports.HCS10Client=l,exports.HbarPricePlugin=class{constructor(){this.id="hedera-hbar-price",this.name="Hedera HBAR Price Plugin",this.description="Provides tools to interact with Hedera network data, specifically HBAR price.",this.version="1.0.0",this.author="Hedera Agent",this.tools=[new E]}async initialize(){return Promise.resolve()}getTools(){return this.tools}async cleanup(){return Promise.resolve()}},exports.InitiateConnectionTool=p,exports.ListConnectionsTool=m,exports.ListUnapprovedConnectionRequestsTool=T,exports.ManageConnectionRequestsTool=$,exports.OpenConvAIPlugin=class extends R{constructor(){super(...arguments),this.id="openconvai-standards-agent-kit",this.name="OpenConvAI Standards Agent Kit Plugin",this.description="Comprehensive plugin providing all HCS-10 agent tools for registration, connections, and messaging",this.version="1.0.0",this.author="Hashgraph Online",this.namespace="openconvai",this.tools=[]}async initialize(e){if(await super.initialize(e),!(e.client instanceof l))throw new Error("OpenConvAIPlugin requires an HCS10Client instance");this.hcs10Client=e.client,this.stateManager=e.stateManager||new q,this.initializeTools(),this.context.logger.info("OpenConvAI Standards Agent Kit Plugin initialized successfully")}initializeTools(){if(!this.hcs10Client||!this.stateManager)throw new Error("HCS10Client and StateManager must be initialized before creating tools");this.tools=[new u(this.hcs10Client,this.stateManager),new d(this.hcs10Client),new h({client:this.hcs10Client,stateManager:this.stateManager}),new C({hcsClient:this.hcs10Client}),new y(this.hcs10Client),new p({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new m({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new f({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new I({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new b({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new $({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new w({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new T({stateManager:this.stateManager,hcsClient:this.hcs10Client})]}getTools(){return this.tools}async cleanup(){this.tools=[],this.hcs10Client=void 0,this.stateManager=void 0,this.context.logger.info("OpenConvAI Standards Agent Kit Plugin cleaned up")}},exports.OpenConvaiState=q,exports.PluginLoader=class{static async loadFromDirectory(e,t,n={initialize:!0}){const o=g.join(e,"plugin.json");if(!c.existsSync(o))throw new Error(`Plugin manifest not found at ${o}`);try{const i=c.readFileSync(o,"utf8"),r=JSON.parse(i);if(!r.id||!r.main)throw new Error("Invalid plugin manifest: missing required fields (id, main)");const s=g.join(e,r.main);if(!c.existsSync(s))throw new Error(`Plugin main file not found at ${s}`);const a=await import(s),l=a.default||a[r.id];if(!l)throw new Error(`Could not find plugin class in ${s}`);const u=new l;if(!this.isValidPlugin(u))throw new Error("Plugin does not implement the IPlugin interface correctly");return n.initialize&&await u.initialize(t),u}catch(i){throw new Error(`Failed to load plugin from directory ${e}: ${i instanceof Error?i.message:String(i)}`)}}static async loadFromPackage(e,t,n={initialize:!0}){try{const o=require.resolve(e),i=g.dirname(o);return this.loadFromDirectory(i,t,n)}catch(o){throw new Error(`Failed to load plugin from package ${e}: ${o instanceof Error?o.message:String(o)}`)}}static isValidPlugin(e){return e&&"string"==typeof e.id&&"string"==typeof e.name&&"string"==typeof e.description&&"string"==typeof e.version&&"string"==typeof e.author&&"function"==typeof e.initialize&&"function"==typeof e.getTools}},exports.PluginRegistry=class{constructor(e){this.plugins=new Map,this.context=e,this.logger=e.logger}async registerPlugin(e){if(this.plugins.has(e.id))throw new Error(`Plugin with ID ${e.id} is already registered`);await e.initialize(this.context),this.plugins.set(e.id,e),this.logger.info(`Plugin registered: ${e.name} (${e.id}) v${e.version}`)}getPlugin(e){return this.plugins.get(e)}getAllPlugins(){return Array.from(this.plugins.values())}getAllTools(){return this.getAllPlugins().flatMap((e=>e.getTools()))}async unregisterPlugin(e){const t=this.plugins.get(e);if(!t)return!1;if(t.cleanup)try{await t.cleanup()}catch(o){this.logger.error(`Error during plugin cleanup: ${o}`)}const n=this.plugins.delete(e);return n&&this.logger.info(`Plugin unregistered: ${t.name} (${t.id})`),n}async unregisterAllPlugins(){const e=Array.from(this.plugins.keys());for(const t of e)await this.unregisterPlugin(t)}},exports.RegisterAgentTool=u,exports.RetrieveProfileTool=y,exports.SendMessageToConnectionTool=f,exports.SendMessageTool=d,exports.initializeStandardsAgentKit=t=>{const n=t?.clientConfig||{},o=n.operatorId||process.env.HEDERA_OPERATOR_ID,i=n.operatorKey||process.env.HEDERA_OPERATOR_KEY,r=n.network||process.env.HEDERA_NETWORK||"testnet";let s;if("mainnet"===r?s="mainnet":("testnet"===r||console.warn(`Unsupported network specified: '${r}'. Defaulting to 'testnet'.`),s="testnet"),!o||!i)throw new Error("Operator ID and private key must be provided either through options or environment variables.");const a="true"===process.env.DISABLE_LOGGING,c=e.Logger.getInstance({level:n.logLevel||"info",silent:a}),g=t?.stateManager||new q({defaultEnvFilePath:A,defaultPrefix:"TODD"});c.info("State manager initialized");const v=new l(o,i,s,{useEncryption:n.useEncryption,registryUrl:n.registryUrl});let M;c.info(`HCS10Client initialized for ${o} on ${s}`),t?.monitoringClient&&(M=new l(o,i,s,{useEncryption:n.useEncryption,registryUrl:n.registryUrl,logLevel:"error"}),c.info("Monitoring client initialized"));const E={};return E.registerAgentTool=new u(v,g),E.sendMessageTool=new d(v),E.connectionTool=new h({client:M||v,stateManager:g}),t?.createAllTools&&(E.findRegistrationsTool=new C({hcsClient:v}),E.retrieveProfileTool=new y(v),E.initiateConnectionTool=new p({hcsClient:v,stateManager:g}),E.listConnectionsTool=new m({hcsClient:v,stateManager:g}),E.sendMessageToConnectionTool=new f({hcsClient:v,stateManager:g}),E.checkMessagesTool=new I({hcsClient:v,stateManager:g}),E.connectionMonitorTool=new b({hcsClient:M||v,stateManager:g}),E.manageConnectionRequestsTool=new $({hcsClient:v,stateManager:g}),E.acceptConnectionRequestTool=new w({hcsClient:v,stateManager:g}),E.listUnapprovedConnectionRequestsTool=new T({stateManager:g,hcsClient:v}),c.info("All tools initialized")),{hcs10Client:v,monitoringClient:M,tools:E,stateManager:g}};
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("@hashgraphonline/standards-sdk"),t=require("@hashgraph/sdk"),n=require("@langchain/core/tools"),o=require("zod"),i=require("fs"),r=require("path"),s=require("axios");function a(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const n in e)if("default"!==n){const o=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,o.get?o:{enumerable:!0,get:()=>e[n]})}return t.default=e,Object.freeze(t)}const c=a(i),g=a(r);class l{constructor(t,n,o,i){this.standardClient=new e.HCS10Client({network:o,operatorId:t,operatorPrivateKey:n,guardedRegistryBaseUrl:i?.registryUrl,logLevel:i?.logLevel}),this.guardedRegistryBaseUrl=i?.registryUrl||"",this.useEncryption=i?.useEncryption||!1;const r="true"===process.env.DISABLE_LOGGING;this.logger=new e.Logger({level:i?.logLevel||"info",silent:r})}getOperatorId(){const e=this.standardClient.getClient().operatorAccountId;if(!e)throw new Error("Operator Account ID not configured in standard client.");return e.toString()}getNetwork(){return this.standardClient.getNetwork()}async handleConnectionRequest(e,t,n,o){try{return await this.standardClient.handleConnectionRequest(e,t,n,o)}catch(i){throw this.logger.error(`Error handling connection request #${n} for topic ${e}:`,i),new Error(`Failed to handle connection request: ${i instanceof Error?i.message:String(i)}`)}}async getAgentProfile(e){return this.standardClient.retrieveProfile(e)}async submitConnectionRequest(e,t){return this.standardClient.submitConnectionRequest(e,t)}async waitForConnectionConfirmation(e,t,n=60,o=2e3){return this.standardClient.waitForConnectionConfirmation(e,t,n,o)}async createAndRegisterAgent(t){const n=(new e.AgentBuilder).setName(t.name).setBio(t.description||"").setCapabilities(t.capabilities?t.capabilities:[e.AIAgentCapability.TEXT_GENERATION]).setType(t.type||"autonomous").setModel(t.model||"agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(e.InboundTopicType.PUBLIC);t?.feeConfig&&(n.setInboundTopicType(e.InboundTopicType.FEE_BASED),n.setFeeConfig(t.feeConfig)),t.pfpBuffer&&t.pfpFileName?0===t.pfpBuffer.byteLength?this.logger.warn("Provided PFP buffer is empty. Skipping profile picture."):(this.logger.info(`Setting profile picture: ${t.pfpFileName} (${t.pfpBuffer.byteLength} bytes)`),n.setProfilePicture(t.pfpBuffer,t.pfpFileName)):this.logger.warn("Profile picture not provided in metadata. Agent creation might fail if required by the underlying SDK builder."),t.social&&Object.entries(t.social).forEach((([e,t])=>{n.addSocial(e,t)})),t.properties&&Object.entries(t.properties).forEach((([e,t])=>{n.addProperty(e,t)}));try{const e=Boolean(t?.feeConfig),o=await this.standardClient.createAndRegisterAgent(n,{initialBalance:e?50:void 0});return o?.metadata?.inboundTopicId&&o?.metadata?.outboundTopicId&&(this.agentChannels={inboundTopicId:o.metadata.inboundTopicId,outboundTopicId:o.metadata.outboundTopicId}),o}catch(o){throw this.logger.error("Error during agent creation/registration:",o),new Error(`Failed to create/register agent: ${o instanceof Error?o.message:String(o)}`)}}async sendMessage(e,t,n,o){this.useEncryption;try{const i=await this.standardClient.sendMessage(e,t,n,o);return i.topicSequenceNumber?.toNumber()}catch(i){throw this.logger.error(`Error sending message to topic ${e}:`,i),new Error(`Failed to send message: ${i instanceof Error?i.message:String(i)}`)}}async getMessages(e){try{const t=(await this.standardClient.getMessages(e)).messages.map((e=>{const t=e?.created?.getTime()||0;return{...e,timestamp:t,data:e.data,sequence_number:e.sequence_number}}));return t.sort(((e,t)=>e.timestamp-t.timestamp)),{messages:t}}catch(t){return this.logger.error(`Error getting messages from topic ${e}:`,t),{messages:[]}}}async getMessageStream(e){return this.standardClient.getMessageStream(e)}async getMessageContent(e){try{return await this.standardClient.getMessageContent(e)}catch(t){throw this.logger.error(`Error retrieving message content for: ${e}`,t),new Error(`Failed to retrieve message content: ${t instanceof Error?t.message:String(t)}`)}}async getInboundTopicId(){try{const e=this.getOperatorId();this.logger.info(`[HCS10Client] Retrieving profile for operator ${e} to find inbound topic...`);const t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.inboundTopic)return this.logger.info(`[HCS10Client] Found inbound topic for operator ${e}: ${t.topicInfo.inboundTopic}`),t.topicInfo.inboundTopic;throw new Error(`Could not retrieve inbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}catch(e){this.logger.error(`[HCS10Client] Error fetching operator's inbound topic ID (${this.getOperatorId()}):`,e);const t=this.getOperatorId();let n=`Failed to get inbound topic ID for operator ${t}.`;throw e instanceof Error&&e.message.includes("does not have a valid HCS-11 memo")?n+=` The account profile may not exist or is invalid. Please ensure this operator account (${t}) is registered as an HCS-10 agent. You might need to register it first (e.g., using the 'register_agent' tool or SDK function).`:e instanceof Error?n+=` Reason: ${e.message}`:n+=` Unexpected error: ${String(e)}`,new Error(n)}}getAccountAndSigner(){const e=this.standardClient.getAccountAndSigner();return{accountId:e.accountId,signer:e.signer}}async getOutboundTopicId(){const e=this.getOperatorId(),t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.outboundTopic)return t.topicInfo.outboundTopic;throw new Error(`Could not retrieve outbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}setClient(t,n){return this.standardClient=new e.HCS10Client({network:this.getNetwork(),operatorId:t,operatorPrivateKey:n,guardedRegistryBaseUrl:this.guardedRegistryBaseUrl}),this.standardClient}async validateOperator(e){try{this.setClient(e.accountId,e.privateKey);return{isValid:!0,operator:{accountId:this.getOperatorId()}}}catch(t){return this.logger.error(`Validation error: ${t}`),{isValid:!1,error:t instanceof Error?t.message:String(t)}}}async initializeWithValidation(e){const t=await this.validateOperator(e);return t.isValid&&e.stateManager&&e.stateManager.initializeConnectionsManager(this.standardClient),t}}class u extends n.StructuredTool{constructor(e,t){super(),this.name="register_agent",this.description="Creates and registers the AI agent on the Hedera network. Returns JSON string with agent details (accountId, privateKey, topics) on success. Optionally supports fee configuration for the agent's inbound topic using HBAR or specific tokens.",this.schema=o.z.object({name:o.z.string().describe("The name of the agent to register"),description:o.z.string().optional().describe("Optional description of the agent"),type:o.z.enum(["autonomous","manual"]).optional().describe("Optional agent type (default: autonomous)"),model:o.z.string().optional().describe("Optional model identifier for the agent"),capabilities:o.z.array(o.z.number()).optional().describe("Optional array of AIAgentCapability enum values (0-18). If not provided, defaults to just TEXT_GENERATION (0)"),profilePicture:o.z.union([o.z.string().describe("Path to a local image file or URL to an image"),o.z.object({url:o.z.string().describe("URL to an image file"),filename:o.z.string().describe("Filename to use for the image")}),o.z.object({path:o.z.string().describe("Path to a local image file"),filename:o.z.string().optional().describe("Optional custom filename")})]).optional().describe("Optional profile picture for the agent (local file path or URL)"),feeCollectorAccountId:o.z.string().optional().describe("The account ID to collect fees. If not specified, the new agent's account ID will be used. Required if any fee is specified."),hbarFee:o.z.number().optional().describe("Optional: The fee amount in HBAR to charge per message on the inbound topic (e.g., 0.5). If specified, inboundTopicType will be set to FEE_BASED."),tokenFee:o.z.object({amount:o.z.number(),tokenId:o.z.string()}).optional().describe('Optional: The fee amount and token ID to charge per message on the inbound topic (e.g., { amount: 10, tokenId: "0.0.12345" }). If specified, inboundTopicType will be set to FEE_BASED.'),hbarFees:o.z.array(o.z.object({amount:o.z.number(),collectorAccount:o.z.string().optional()})).optional().describe("Optional: Array of HBAR fees with different collectors. If specified, inboundTopicType will be set to FEE_BASED."),tokenFees:o.z.array(o.z.object({amount:o.z.number(),tokenId:o.z.string(),collectorAccount:o.z.string().optional()})).optional().describe("Optional: Array of token fees with different collectors. If specified, inboundTopicType will be set to FEE_BASED."),exemptAccountIds:o.z.array(o.z.string()).optional().describe("Optional: Array of account IDs to exempt from ALL fees set for this agent."),setAsCurrent:o.z.boolean().optional().describe("Optional: Whether to set the newly registered agent as the current active agent in the state manager. Default: true"),persistence:o.z.object({prefix:o.z.string().optional()}).optional().describe("Optional: Configuration for persisting agent data to environment variables. The prefix will determine the environment variable names (e.g., PREFIX_ACCOUNT_ID). Defaults to TODD if not specified.")}),this.client=e,this.stateManager=t}async loadProfilePicture(t){const n=e.Logger.getInstance({level:"debug"});try{if(!t)return null;if("string"==typeof t){if(t.startsWith("http://")||t.startsWith("https://")){n.info(`Loading profile picture from URL: ${t}`);const e=await s.get(t,{responseType:"arraybuffer"}),o=globalThis.Buffer.from(e.data),i=new URL(t).pathname;return{buffer:o,filename:r.basename(i)||"profile.png"}}{if(!i.existsSync(t))return n.warn(`Profile picture file not found: ${t}`),null;n.info(`Loading profile picture from file: ${t}`);const e=i.readFileSync(t);return{buffer:e,filename:r.basename(t)}}}if("url"in t){n.info(`Loading profile picture from URL: ${t.url}`);const e=await s.get(t.url,{responseType:"arraybuffer"}),o=globalThis.Buffer.from(e.data);return{buffer:o,filename:t.filename||"profile.png"}}if("path"in t){if(!i.existsSync(t.path))return n.warn(`Profile picture file not found: ${t.path}`),null;n.info(`Loading profile picture from file: ${t.path}`);const e=i.readFileSync(t.path);return{buffer:e,filename:t.filename||r.basename(t.path)}}return null}catch(o){return n.error("Failed to load profile picture:",o),null}}async _call(t){const n=e.Logger.getInstance({level:"debug"}),o={name:t.name,description:t.description,type:t.type,model:t.model,capabilities:t.capabilities||[e.AIAgentCapability.TEXT_GENERATION],properties:{}};let i="";if(t.profilePicture){const e=await this.loadProfilePicture(t.profilePicture);if(e){const{buffer:n,filename:r}=e;o.pfpBuffer=n,o.pfpFileName=r,"string"==typeof t.profilePicture?i=t.profilePicture:"url"in t.profilePicture?i=t.profilePicture.url:"path"in t.profilePicture&&(i=t.profilePicture.path)}}const r=void 0!==t.hbarFee&&t.hbarFee>0,s=this.hasValidTokenFee(t.tokenFee),a=t.hbarFees&&t.hbarFees.length>0,c=t.tokenFees&&t.tokenFees.length>0;if(r||s||a||c){const{accountId:i}=this.client.getAccountAndSigner(),l=t.feeCollectorAccountId||i;if(!l)return"Error: Fee collector account ID is required when specifying fees and could not be determined.";const u=new e.FeeConfigBuilder({network:this.client.getNetwork(),logger:n});try{const e=t.exemptAccountIds?.filter((e=>e!==l&&e.startsWith("0.0")))||[];let i=u;if(r&&(n.info(`Adding HBAR fee: ${t.hbarFee} HBAR to be collected by ${l}`),i=i.addHbarFee(t.hbarFee,l,e)),a)for(const o of t.hbarFees){const t=o.collectorAccount||l;n.info(`Adding HBAR fee: ${o.amount} HBAR to be collected by ${t}`),i=i.addHbarFee(o.amount,t,e)}if(s&&(n.info(`Adding token fee: ${t.tokenFee.amount} of token ${t.tokenFee.tokenId} to be collected by ${l}`),i=await i.addTokenFee(t.tokenFee.amount,t.tokenFee.tokenId,l,void 0,e)),c)for(const o of t.tokenFees){const t=o.collectorAccount||l;n.info(`Adding token fee: ${o.amount} of token ${o.tokenId} to be collected by ${t}`),i=await i.addTokenFee(o.amount,o.tokenId,t,void 0,e)}o.feeConfig=i,n.info("FeeConfigBuilder created successfully")}catch(g){return`Error: Failed to configure fees. Reason: ${g instanceof Error?g.message:String(g)}`}}try{n.info("Registering agent with metadata");const e=await this.client.createAndRegisterAgent(o);return this.processRegistrationResult(e,t,i)}catch(g){return`Error: Failed to create/register agent "${t.name}". Reason: ${g instanceof Error?g.message:String(g)}`}}hasValidTokenFee(e){return!!(e&&e.amount>0&&e.tokenId&&""!==e.tokenId.trim())}async processRegistrationResult(t,n,o=""){const i=t?.metadata?.accountId||"",r=t?.metadata?.inboundTopicId||"",s=t?.metadata?.outboundTopicId||"",a=t?.metadata?.profileTopicId||"",c=t?.metadata?.privateKey||"",g=t?.metadata?.pfpTopicId;if(this.validateRegistrationResult(i,r,s,c),this.stateManager&&c&&i&&r&&s&&(void 0===n.setAsCurrent||n.setAsCurrent)){const t={name:n.name,accountId:i,inboundTopicId:r,outboundTopicId:s,profileTopicId:a,privateKey:c,pfpTopicId:g};if(this.stateManager.setCurrentAgent(t),this.stateManager.persistAgentData&&n.persistence)try{const e={type:"env-file",prefix:n.persistence.prefix};await this.stateManager.persistAgentData(t,e)}catch(h){e.Logger.getInstance().warn("Failed to persist agent data",h)}}await this.ensureAgentHasFunds(i,n.name);const l=this.createFeeDescription(n),u=l?` with ${l} fee on inbound topic`:"",d={success:!0,message:`Successfully registered agent '${n.name}'${u}.`,name:n.name,accountId:i,privateKey:c,inboundTopicId:r,outboundTopicId:s,profileTopicId:a||"N/A",capabilities:n.capabilities||[e.AIAgentCapability.TEXT_GENERATION],hasFees:!(!n.hbarFee&&!this.hasValidTokenFee(n.tokenFee)),hbarFee:n.hbarFee||0,tokenFee:n.tokenFee||null};return(g||o)&&(d.profilePicture={source:o,topicId:g}),JSON.stringify(d)}async ensureAgentHasFunds(n,o){try{await async function(n,o,i,r){try{const c=(await o.requestAccount(i)).balance.balance/1e8;n.info(`${r} account ${i} has ${c} HBAR`);try{const a=new e.HederaMirrorNode("testnet",n),g=await a.getHBARPrice(new Date);if(g){const e=c*g;if(n.info(`${r} balance in USD: $${e.toFixed(2)}`),e<2){n.warn(`${r} account ${i} has less than $2 (${e.toFixed(2)}). Attempting to fund.`);try{const e=o.getAccountAndSigner(),s=10/g,a=Math.max(0,s-c);if(a>0){const s=(new t.TransferTransaction).addHbarTransfer(e.accountId,t.Hbar.fromTinybars(Math.round(-1e8*a))).addHbarTransfer(i,t.Hbar.fromTinybars(Math.round(1e8*a)));n.info(`Funding ${r} account ${i} with ${a.toFixed(2)} HBAR from ${e.accountId}`);const c=await s.execute(o.getClient());await c.getReceipt(o.getClient()),n.info(`Successfully funded ${r} account ${i}.`)}else n.info(`${r} account ${i} does not require additional funding.`)}catch(s){n.error(`Failed to automatically fund ${r} account ${i}:`,s),n.warn(`Please fund the account ${i} manually with at least ${(10/g).toFixed(2)} HBAR.`)}}}else n.warn("Failed to get HBAR price from Mirror Node. Please ensure the account has enough HBAR.")}catch(a){n.warn("Failed to check USD balance. Please ensure the account has enough HBAR.")}}catch(a){n.error(`Failed to check ${r} account balance:`,a)}}(e.Logger.getInstance({module:"RegisterAgentTool"}),this.client.standardClient,n,o)}catch(i){e.Logger.getInstance().error("Failed to auto fund agent",i)}}validateRegistrationResult(e,t,n,o){if(!(e&&t&&n&&o)){const i=[!e&&"accountId",!t&&"inboundTopicId",!n&&"outboundTopicId",!o&&"privateKey"].filter(Boolean).join(", ");throw new Error(`Registration failed. The HCS client returned incomplete details (Missing: ${i}).`)}}createFeeDescription(e){const t=e.hbarFee&&e.hbarFee>0,n=this.hasValidTokenFee(e.tokenFee);if(!t&&!n)return"";let o="";if(t&&(o+=`${e.hbarFee} HBAR`),n&&e.tokenFee){const t=`${e.tokenFee.amount} of token ${e.tokenFee.tokenId}`;o+=o?` and ${t}`:t}return o}}class d extends n.StructuredTool{constructor(t){super(),this.name="send_message",this.description="Sends a message to a specified Hedera topic using HCS-10 and monitors for responses.",this.lastProcessedTimestamp=0,this.schema=o.z.object({topicId:o.z.string().describe("The Hedera topic ID to send the message to"),message:o.z.string().describe("The message content to send"),disableMonitoring:o.z.boolean().optional().describe("Whether to disable monitoring for responses")}),this.client=t,this.logger=e.Logger.getInstance({module:"SendMessageTool"})}async _call(e){try{const t=await this.client.sendMessage(e.topicId,e.message);if(!t)throw new Error("Failed to send message");if(this.logger.info(`Message sent with sequence number ${t}`),e.disableMonitoring)return`Successfully sent message to topic ${e.topicId}`;{const n=await this.monitorResponses(e.topicId,t);return`Successfully sent message to topic ${e.topicId}${n?`\nResponse: ${n}`:""}`}}catch(t){throw new Error(`Failed to send message: ${t instanceof Error?t.message:String(t)}`)}}async monitorResponses(e,t){let n=0;for(;n<10;){try{const n=await this.client.getMessageStream(e);for(const e of n.messages)if(e.created&&e.created.getTime()>this.lastProcessedTimestamp){this.lastProcessedTimestamp=e.created.getTime();const n=await this.client.getMessageContent(e.data||"");let i;try{i=JSON.parse(n)}catch(o){this.logger.error(`Error parsing message content: ${o}`);continue}if(e.sequence_number>t)return i&&"string"==typeof i.data?i.data:JSON.stringify(i)}}catch(o){this.logger.error(`Error monitoring responses: ${o}`)}n++,await new Promise((e=>setTimeout(e,1e3)))}return null}}class h extends n.StructuredTool{constructor({client:t,stateManager:n,...i}){super(i),this.name="monitor_connections",this.description="Starts passively LISTENING on the current agent's own inbound topic for INCOMING HCS-10 connection requests. Handles received requests automatically. Takes NO arguments. DO NOT use this to start a new connection TO someone else.",this.isMonitoring=!1,this.monitoringTopic=null,this.schema=o.z.object({}),this.client=t,this.stateManager=n,this.logger=e.Logger.getInstance({module:"ConnectionTool",level:"info"})}async _call(){let e;try{e=await this.client.getInboundTopicId()}catch(t){const e=`Error getting inbound topic ID for monitoring: ${t instanceof Error?t.message:String(t)}`;return this.logger.error(e),e}return e?this.isMonitoring?this.monitoringTopic===e?`Already monitoring topic ${e}.`:`Error: Already monitoring a different topic (${this.monitoringTopic}). Stop the current monitor first.`:(this.isMonitoring=!0,this.monitoringTopic=e,this.logger.info(`Initiating connection request monitoring for topic ${e}...`),this.monitorIncomingRequests(e).catch((t=>{this.logger.error(`Monitoring loop for ${e} encountered an unrecoverable error:`,t),this.isMonitoring=!1,this.monitoringTopic=null})),`Started monitoring inbound topic ${e} for connection requests in the background.`):"Error: Could not determine the inbound topic ID for the current agent."}async monitorIncomingRequests(e){this.logger.info(`Monitoring inbound topic ${e}...`);let t=0;const n=new Set;for(;this.isMonitoring&&this.monitoringTopic===e;){try{const i=(await this.client.getMessages(e)).messages,r=i.filter((e=>"connection_request"===e.op&&"number"==typeof e.sequence_number));for(const s of r){t=Math.max(t,s.sequence_number||0);const r=s.sequence_number;if(!r)continue;if(i.some((e=>"connection_created"===e.op&&e.connection_id===r))){this.logger.debug(`Connection request #${r} already handled (found connection_created). Skipping.`);continue}const a=s.operator_id||"",c=a.split("@")[1]||null;if(c)if(n.has(r))this.logger.info(`Connection request #${r} already processed in this session. Skipping.`);else{this.logger.info(`Processing connection request #${r} from account ${c}...`);try{const t=await this.client.handleConnectionRequest(e,c,r);n.add(r),this.logger.info(`Connection confirmed for request #${r}. New connection topic: ${t.connectionTopicId}`);const o={targetAccountId:c,targetAgentName:`Agent ${c}`,targetInboundTopicId:"N/A",connectionTopicId:t.connectionTopicId};this.stateManager.addActiveConnection(o),this.logger.info(`Added new active connection to ${c} state.`)}catch(o){this.logger.error(`Error handling connection request #${r} from ${c}:`,o)}}else this.logger.warn(`Could not determine requesting account ID from operator_id '${a}' for request #${r}. Skipping.`)}}catch(i){this.logger.error(`Error fetching or processing messages for topic ${e}:`,i)}await new Promise((e=>setTimeout(e,5e3)))}this.logger.info(`Monitoring loop stopped for topic ${e}.`),this.isMonitoring=!1,this.monitoringTopic=null}stopMonitoring(){this.isMonitoring?(this.logger.info(`Stopping monitoring for topic ${this.monitoringTopic}...`),this.isMonitoring=!1,this.monitoringTopic=null):this.logger.info("Monitor is not currently running.")}}class f extends n.StructuredTool{constructor({hcsClient:t,stateManager:n,...i}){super(i),this.name="send_message_to_connection",this.description="Sends a text message to another agent using an existing active connection. Identify the target agent using their account ID (e.g., 0.0.12345) or the connection number shown in 'list_connections'. Return back the reply from the target agent if possible",this.schema=o.z.object({targetIdentifier:o.z.string().describe("The account ID (e.g., 0.0.12345) of the target agent OR the connection number (e.g., '1', '2') from the 'list_connections' tool."),message:o.z.string().describe("The text message content to send."),disableMonitoring:o.z.boolean().optional().default(!1)}),this.hcsClient=t,this.stateManager=n,this.logger=e.Logger.getInstance({module:"SendMessageToConnectionTool"})}async _call({targetIdentifier:e,message:t,disableMonitoring:n}){const o=this.stateManager.getCurrentAgent();if(!o)return"Error: Cannot send message. No agent is currently active. Please register or select an agent first.";const i=this.stateManager.getConnectionByIdentifier(e);if(!i)return`Error: Could not find an active connection matching identifier "${e}". Use 'list_connections' to see active connections.`;const r=i.connectionTopicId,s=i.targetAgentName,a=`${o.inboundTopicId}@${o.accountId}`;this.logger.info(`Sending message from ${a} to ${s} (${i.targetAccountId}) via connection topic ${r}`);try{const e=await this.hcsClient.sendMessage(r,t,`Agent message from ${o.name}`);if(!e)throw new Error("Failed to send message");if(!n)return`Message sent to ${s} (${i.targetAccountId}) via connection ${r}. Sequence Number: ${e}`;const c=await this.monitorResponses(r,a,e);return c?(this.logger.info(`Got reply from ${s}`,c),`Received reply from ${s}: ${c}`):`Message sent to ${s} (${i.targetAccountId}) via connection ${r}. Sequence Number: ${e}`}catch(c){return this.logger.error(`Failed to send message via connection ${r}: ${c}`),`Error sending message to ${s}: ${c instanceof Error?c.message:String(c)}`}}async monitorResponses(e,t,n){for(;;){try{const o=await this.hcsClient.getMessageStream(e);for(const e of o.messages){if(e.sequence_number<n||e.operator_id===t)continue;return await this.hcsClient.getMessageContent(e.data||"")}}catch(o){this.logger.error(`Error monitoring responses: ${o}`)}await new Promise((e=>setTimeout(e,4e3)))}return null}}class p extends n.StructuredTool{constructor({hcsClient:t,stateManager:n,...i}){super(i),this.name="initiate_connection",this.description="Actively STARTS a NEW HCS-10 connection TO a specific target agent identified by their account ID. Requires the targetAccountId parameter. Use this ONLY to INITIATE an OUTGOING connection request.",this.schema=o.z.object({targetAccountId:o.z.string().describe("The Hedera account ID (e.g., 0.0.12345) of the agent you want to connect with.")}),this.hcsClient=t,this.stateManager=n,this.logger=e.Logger.getInstance({module:"InitiateConnectionTool"})}async _call({targetAccountId:e}){const t=this.stateManager.getCurrentAgent();if(!t)return"Error: Cannot initiate connection. No agent is currently active. Please register or select an agent first.";this.logger.info(`Attempting connection from ${t.accountId} to ${e}`);try{this.logger.debug(`Retrieving profile for ${e}...`);const o=await this.hcsClient.getAgentProfile(e);if(!o?.topicInfo?.inboundTopic)return`Error: Could not retrieve profile or find inbound topic ID for target agent ${e}. They might not be registered or have a public profile.`;const i=o.topicInfo.inboundTopic,r=o.profile.name||`Agent ${e}`,s=await this.hcsClient.submitConnectionRequest(i,t.name),a=s?.topicSequenceNumber;if(!a)throw new Error("Connection request sequence number not found.");let c;try{if(c=a.toNumber(),isNaN(c))throw new Error("Converted sequence number is NaN.")}catch(n){throw new Error(`Failed to convert connection request sequence number: ${n}`)}const g=6e4,l=2e3,u=Math.ceil(g/l),d=await this.hcsClient.waitForConnectionConfirmation(i,c,u,l);if(!d?.connectionTopicId)return`Error: Connection confirmation not received from ${e} (for request ${c}) within ${g/1e3} seconds.`;const h=d.connectionTopicId;this.logger.info(`Connection confirmed! Topic ID: ${h}`);const f={targetAccountId:e,targetAgentName:r,targetInboundTopicId:i,connectionTopicId:h};this.stateManager.addActiveConnection(f);const p=this.stateManager.listConnections(),m=p.find((e=>e.connectionTopicId===h)),I=m?p.indexOf(m)+1:null;return`Successfully established connection ${I?`#${I}`:""} with ${r} (${e}). Connection Topic: ${h}. You can now send messages using this connection.`}catch(o){return this.logger.error(`Connection initiation failed: ${o}`),`Error initiating connection with ${e}: ${o instanceof Error?o.message:String(o)}`}}}class m extends n.StructuredTool{constructor({stateManager:t,hcsClient:n,...i}){super(i),this.name="list_connections",this.description="Lists the currently active HCS-10 connections with detailed information. Shows connection status, agent details, and recent activity. Use this to get a comprehensive view of all active connections.",this.schema=o.z.object({includeDetails:o.z.boolean().optional().describe("Whether to include detailed information about each connection"),showPending:o.z.boolean().optional().describe("Whether to include pending connection requests")}),this.stateManager=t,this.hcsClient=n,this.logger=new e.Logger({module:"ListConnectionsTool"})}async _call(e){const t=e.includeDetails??!0,n=e.showPending??!0,o=await this.getEnhancedConnections();if(0===o.length)return"There are currently no active connections.";const i=o.filter((e=>"established"===e.status)),r=o.filter((e=>e.isPending)),s=o.filter((e=>e.needsConfirmation));let a="";return i.length>0&&(a+=`🟢 Active Connections (${i.length}):\n`,i.forEach(((e,n)=>{a+=this.formatConnection(e,n,t)})),a+="\n"),n&&s.length>0&&(a+=`🟠 Connections Needing Confirmation (${s.length}):\n`,s.forEach(((e,n)=>{a+=this.formatConnection(e,n,t)})),a+="\n"),n&&r.length>0&&(a+=`⚪ Pending Connection Requests (${r.length}):\n`,r.forEach(((e,n)=>{a+=this.formatConnection(e,n,t)}))),a.trim()}formatConnection(e,t,n){let o=`${t+1}. ${e.profileInfo?.display_name||e.targetAgentName||"Unknown Agent"} (${e.targetAccountId})\n`;o+=` Topic: ${e.isPending?"(Pending Request)":e.connectionTopicId}\n`;if(o+=` Status: ${e.status||"unknown"}\n`,n){if(e.profileInfo?.bio&&(o+=` Bio: ${e.profileInfo.bio.substring(0,100)}${e.profileInfo.bio.length>100?"...":""}\n`),e.created){o+=` ${e.isPending?"Request sent":"Connection established"}: ${e.created.toLocaleString()}\n`}e.lastActivity&&(o+=` Last activity: ${e.lastActivity.toLocaleString()}\n`)}return o}async getEnhancedConnections(){if(!this.hcsClient)return this.stateManager.listConnections();try{const{accountId:e}=this.hcsClient.getAccountAndSigner();if(!e)return this.stateManager.listConnections();const t=this.stateManager.getConnectionsManager();if(!t)return this.logger.error("ConnectionsManager not initialized"),this.stateManager.listConnections();const n=await t.fetchConnectionData(e);for(const o of n)this.stateManager.updateOrAddConnection(o);return n}catch(e){return console.error("Error fetching connection data:",e),this.stateManager.listConnections()}}}class I extends n.StructuredTool{constructor({hcsClient:t,stateManager:n,...i}){super(i),this.name="check_messages",this.description="Checks for and retrieves messages from an active connection. \nIdentify the target agent using their account ID (e.g., 0.0.12345) or the connection number shown in 'list_connections'. \nBy default, it only retrieves messages newer than the last check. \nUse 'fetchLatest: true' to get the most recent messages regardless of when they arrived. \nUse 'lastMessagesCount' to specify how many latest messages to retrieve (default 1 when fetchLatest is true).",this.schema=o.z.object({targetIdentifier:o.z.string().describe("The account ID (e.g., 0.0.12345) of the target agent OR the connection number (e.g., '1', '2') from the 'list_connections' tool to check messages for."),fetchLatest:o.z.boolean().optional().default(!1).describe("Set to true to fetch the latest messages even if they have been seen before, ignoring the last checked timestamp. Defaults to false (fetching only new messages)."),lastMessagesCount:o.z.number().int().positive().optional().describe("When fetchLatest is true, specifies how many of the most recent messages to retrieve. Defaults to 1.")}),this.hcsClient=t,this.stateManager=n,this.logger=e.Logger.getInstance({module:"CheckMessagesTool"})}async _call({targetIdentifier:e,fetchLatest:t,lastMessagesCount:n}){const o=this.stateManager.getConnectionByIdentifier(e);if(!o)return`Error: Could not find an active connection matching identifier "${e}". Use 'list_connections' to see active connections.`;const i=o.connectionTopicId,r=o.targetAgentName,s=this.stateManager.getLastTimestamp(i);this.logger.info(`Checking messages for connection with ${r} (${o.targetAccountId}) on topic ${i} (fetchLatest: ${t}, lastCount: ${n}, since: ${s})`);try{const e=(await this.hcsClient.getMessages(i)).messages;if(!e||0===e.length)return`No messages found on connection topic ${i}.`;let o=[],g=s;const l=!0===t;if(l){this.logger.info("Fetching latest messages regardless of timestamp.");const t=n??1;o=e.slice(-t)}else this.logger.info(`Filtering for messages newer than ${s}`),o=e.filter((e=>1e6*e.timestamp>s)),o.length>0&&(g=o.reduce(((e,t)=>Math.max(e,1e6*t.timestamp)),s));if(0===o.length)return l?`Could not retrieve the latest message(s). No messages found on topic ${i}.`:`No new messages found for connection with ${r} since last check.`;this.logger.info(`Processing ${o.length} message(s).`);let u=l?`Latest message(s) from ${r}:\n`:`New messages from ${r}:\n`;for(const t of o){let e=t.data;try{"string"==typeof e&&e.startsWith("hcs://")&&(this.logger.debug(`Resolving inscribed message: ${e}`),e=await this.hcsClient.getMessageContent(e),this.logger.debug(`Resolved content length: ${e?.length}`));let n=e;try{const t=JSON.parse(e||"{}");if("hcs-10"===t.p&&"message"===t.op&&t.data){n=`[${t.operator_id||"unknown_sender"}]: ${t.data}`}else n=e}catch(a){n=e}u+=`\n[${new Date(t.timestamp).toLocaleString()}] (Seq: ${t.sequence_number})\n${n}\n`}catch(c){const e=`Error processing message (Seq: ${t.sequence_number}): ${c instanceof Error?c.message:String(c)}`;this.logger.error(e),u+=`\n[Error processing message Seq: ${t.sequence_number}]\n`}}return!l&&g>s&&(this.logger.debug(`Updating timestamp for topic ${i} to ${g}`),this.stateManager.updateTimestamp(i,g)),u.trim()}catch(c){return this.logger.error(`Failed to check messages for topic ${i}: ${c}`),`Error checking messages for ${r}: ${c instanceof Error?c.message:String(c)}`}}}class C extends n.StructuredTool{constructor({hcsClient:t,...n}){super(n),this.name="find_registrations",this.description="Searches the configured agent registry for HCS-10 agents. You can filter by account ID or tags. Returns basic registration info.",this.schema=o.z.object({accountId:o.z.string().optional().describe("Optional: Filter registrations by a specific Hedera account ID (e.g., 0.0.12345)."),tags:o.z.array(o.z.nativeEnum(e.AIAgentCapability)).optional().describe("Optional: Filter registrations by a list of tags (API filter only).")}),this.hcsClient=t,this.logger=e.Logger.getInstance({module:"FindRegistrationsTool"})}async _call({accountId:e,tags:t}){this.logger.info("Searching registrations with filters - Account ID",JSON.stringify({accountId:e,tags:t}));const n={};e&&(n.accountId=e),t&&t.length>0&&(n.tags=t),n.network=this.hcsClient.getNetwork();try{if(!this.hcsClient.standardClient)throw new Error("Standard SDK client instance is not available in HCS10Client wrapper.");const e=await this.hcsClient.standardClient.findRegistrations(n);if(!e.success||e.error)return`Error finding registrations: ${e.error||"Unknown error"}`;if(!e.registrations||0===e.registrations.length)return"No registrations found matching the criteria.";let t=`Found ${e.registrations.length} registration(s):\n`;return e.registrations.forEach(((e,n)=>{const o=e.metadata;t+=`${n+1}. Name: ${o.alias||"N/A"}\n`,t+=`Description: ${o.bio||"N/A"}\n`,t+=` Account ID: ${e.accountId}\n`,t+=` Status: ${e.status}\n`,t+=` Model: ${o.properties?.model||"N/A"}\n`,o.properties?.capabilities&&o.properties.capabilities.length>0&&(t+=` Capabilities: ${o.properties.capabilities.join(", ")}\n`),o.properties&&(t+=` Properties: ${JSON.stringify(o.properties)}\n`),t+=` Inbound Topic: ${e.inboundTopicId}\n`,t+=` Outbound Topic: ${e.outboundTopicId}\n`,t+=` Created At: ${e.createdAt}\n`})),t.trim()}catch(o){return this.logger.error(`Failed to execute findRegistrations: ${o}`),`Error searching registrations: ${o instanceof Error?o.message:String(o)}`}}}class b extends n.StructuredTool{constructor({hcsClient:t,stateManager:n,...i}){super(i),this.name="monitor_connections",this.description="Monitors for incoming connection requests and accepts them with optional fee settings. Use this to watch for connection requests and accept them, optionally setting HBAR or token fees on the connection.",this.schema=o.z.object({acceptAll:o.z.boolean().optional().describe("Whether to automatically accept all incoming connection requests. Default is false."),targetAccountId:o.z.string().optional().describe("If provided, only accept connection requests from this specific account ID."),hbarFees:o.z.array(o.z.object({amount:o.z.number(),collectorAccount:o.z.string().optional()})).optional().describe("Array of HBAR fee amounts to charge per message (with optional collector accounts)."),tokenFees:o.z.array(o.z.object({amount:o.z.number(),tokenId:o.z.string(),collectorAccount:o.z.string().optional()})).optional().describe("Array of token fee amounts and IDs to charge per message (with optional collector accounts)."),exemptAccountIds:o.z.array(o.z.string()).optional().describe("Array of account IDs to exempt from ALL fees set in this request."),monitorDurationSeconds:o.z.number().optional().describe("How long to monitor for incoming requests in seconds. Default is 60."),defaultCollectorAccount:o.z.string().optional().describe("Default account to collect fees if not specified at the fee level. Defaults to the agent account.")}),this.isMonitoring=!1,this.hcsClient=t,this.stateManager=n,this.logger=e.Logger.getInstance({module:"ConnectionMonitorTool",level:"error"}),this.listConnectionsTool=new m({stateManager:n,hcsClient:t,...i})}updateClient(e){this.hcsClient=e,this.logger.info("Updated HCS10Client instance for ConnectionMonitorTool"),this.listConnectionsTool=new m({stateManager:this.stateManager,hcsClient:e})}async call(e){return this._call(e)}async _call({acceptAll:e=!1,targetAccountId:t,hbarFees:n=[],tokenFees:o=[],exemptAccountIds:i,monitorDurationSeconds:r=60,defaultCollectorAccount:s}){if(!this.stateManager.getCurrentAgent())return"Error: Cannot monitor for connections. No agent is currently active. Please register or select an agent first.";if(this.isMonitoring)return"Already monitoring for connection requests. Please wait for the current monitoring session to complete.";try{this.isMonitoring=!0;const c=await this.hcsClient.getInboundTopicId();if(!c)return this.isMonitoring=!1,"Error: Could not find inbound topic ID for the current agent.";this.logger.info(`Starting to monitor inbound topic ${c} for connection requests...`);const g=this.createFeeConfig(n,o,i,t,s),l=Date.now()+1e3*r,u=3e3;let d=0,h=0,f=0,p=0;for(;Date.now()<l;)try{await this.listConnectionsTool.invoke({includeDetails:!1,showPending:!1});const n=this.stateManager.listConnections(),o=new Map;n.filter((e=>"established"===e.status&&!e.isPending)).forEach((e=>{o.has(e.targetAccountId)||o.set(e.targetAccountId,new Set),e.connectionRequestId&&o.get(e.targetAccountId)?.add(String(e.connectionRequestId))}));const i=(await this.hcsClient.getMessages(c)).messages.filter((e=>!(!e.sequence_number||e.sequence_number<=d)&&(d=Math.max(d,e.sequence_number),"connection_request"===e.op)));for(const r of i){const n=r.sequence_number;if(!n)continue;h++;const i=await this.hcsClient.getInboundTopicId()||"",s=this.stateManager.getConnectionsManager();if(!s){this.logger.error("ConnectionsManager not initialized in state manager");continue}if(s.isConnectionRequestProcessed(i,n)){this.logger.info(`Request #${n} already processed, skipping`),p++;continue}const a=this.extractAccountId(r);if(!a){s.markConnectionRequestProcessed(i,n);continue}if(t&&a!==t){this.logger.info(`Request #${n} doesn't match target ${t}`);continue}const c=o.get(a);if(c?.has(String(n)))this.logger.info(`Already processed connection request #${n} from ${a}, skipping`),s.markConnectionRequestProcessed(i,n),p++;else if(e){const e=await this.acceptConnectionRequest(n,a,g);s.markConnectionRequestProcessed(i,n),e.success&&(f++,this.logger.info(`Successfully accepted connection with ${a} for request #${n}`))}else this.logger.info(`Found request #${n} from ${a} (not auto-accepting)`)}await new Promise((e=>setTimeout(e,u)))}catch(a){this.logger.error(`Error polling for messages: ${a}`),await new Promise((e=>setTimeout(e,u)))}return this.isMonitoring=!1,0===h?`No connection requests received during the ${r} second monitoring period.`:e?`Monitored for ${r} seconds. Found ${h} connection requests, accepted ${f} connections, skipped ${p} existing connections${this.formatFeeString(n,o)}.`:`Monitored for ${r} seconds. Found ${h} connection requests. To accept them, call this tool again with acceptAll=true.`}catch(a){return this.isMonitoring=!1,this.logger.error(`Connection monitoring failed: ${a}`),`Error monitoring for connections: ${a instanceof Error?a.message:String(a)}`}}createFeeConfig(t=[],n=[],o,i,r){if(0!==t.length||0!==n.length)try{const s=this.hcsClient.getAccountAndSigner().accountId,a=r||s,c=new e.FeeConfigBuilder({network:this.hcsClient.getNetwork(),logger:this.logger,defaultCollectorAccountId:a}),g=[...o||[]];i&&!g.includes(i)&&g.push(i);for(const e of t)if(e.amount>0){const t=e.collectorAccount||a;c.addHbarFee(e.amount,t,g),this.logger.info(`Added HBAR fee: ${e.amount} HBAR to be collected by ${t}`)}for(const e of n)if(e.amount>0&&e.tokenId){const t=e.collectorAccount||a;c.addTokenFee(e.amount,e.tokenId,t,void 0,g),this.logger.info(`Added token fee: ${e.amount} of token ${e.tokenId} to be collected by ${t}`)}return c}catch(s){return void this.logger.error(`Error creating fee configuration: ${s}`)}}extractAccountId(e){if(e.operator_id)return this.hcsClient.standardClient.extractAccountFromOperatorId(e.operator_id)}async acceptConnectionRequest(e,t,n){try{const i=await this.hcsClient.getInboundTopicId();this.logger.info(`Accepting connection request #${e} from ${t}`);const r=await this.hcsClient.handleConnectionRequest(i,t,e,n);if(!r?.connectionTopicId)return{success:!1,error:"Connection acceptance returned no connection topic ID"};const s=r.connectionTopicId;let a;this.logger.info(`Connection established! Topic ID: ${s}`);try{const e=await this.hcsClient.getAgentProfile(t);e.success&&e.profile&&(a=e.profile)}catch(o){this.logger.warn(`Could not fetch profile for ${t}: ${o}`)}const c=(await this.hcsClient.getAgentProfile(t))?.topicInfo?.inboundTopic||"",g={targetAccountId:t,targetAgentName:a?.display_name||`Agent ${t}`,targetInboundTopicId:c,connectionTopicId:s,profileInfo:a,created:new Date,status:"established",metadata:{requestId:e}};return this.stateManager.addActiveConnection(g),{success:!0,connectionTopicId:s}}catch(i){return this.logger.error(`Error accepting connection request: ${i}`),{success:!1,error:i instanceof Error?i.message:String(i)}}}formatFeeString(e=[],t=[]){if(0===e.length&&0===t.length)return"";let n=" with fees: ";if(e.length>0){const t=e.filter((e=>e.amount>0)).map((e=>{const t=e.collectorAccount?` to ${e.collectorAccount}`:"";return`${e.amount} HBAR${t}`})).join(", ");t&&(n+=t)}if(t.length>0){e.length>0&&(n+=" and ");const o=t.filter((e=>e.amount>0&&e.tokenId)).map((e=>{const t=e.collectorAccount?` to ${e.collectorAccount}`:"";return`${e.amount} of token ${e.tokenId}${t}`})).join(", ");o&&(n+=o)}return" with fees: "===n?"":n}update(){this.listConnectionsTool.invoke({includeDetails:!0,showPending:!0}).catch((e=>{this.logger.error(`Error updating connections: ${e}`)}))}}class $ extends n.StructuredTool{constructor({hcsClient:t,stateManager:n,...i}){super(i),this.name="manage_connection_requests",this.description='Manage incoming connection requests. List pending requests, view details about requesting agents, and reject connection requests. Use the separate "accept_connection_request" tool to accept.',this.schema=o.z.object({action:o.z.enum(["list","view","reject"]).describe("The action to perform: list all requests, view details of a specific request, or reject a request"),requestKey:o.z.string().optional().describe("The unique request key to view or reject (required for view and reject actions)")}),this.lastRefreshTime=0,this.refreshIntervalMs=3e4,this.hcsClient=t,this.stateManager=n,this.logger=e.Logger.getInstance({module:"ManageConnectionRequestsTool",level:"debug"})}async _call({action:e,requestKey:t}){if(!this.stateManager.getCurrentAgent())return"Error: Cannot manage connection requests. No agent is currently active. Please register or select an agent first.";if(("view"===e||"reject"===e)&&void 0===t)return`Error: Request key is required for the "${e}" action. Use the "list" action first to see available requests.`;try{switch(await this.refreshRequestsIfNeeded(),e){case"list":return this.listRequests();case"view":return this.viewRequest(t);case"reject":return this.rejectRequest(t);default:return`Error: Unsupported action: ${e}`}}catch(n){return this.logger.error(`Error in ManageConnectionRequestsTool: ${n}`),`Error managing connection requests: ${n instanceof Error?n.message:String(n)}`}}async refreshRequestsIfNeeded(){const e=Date.now();e-this.lastRefreshTime>this.refreshIntervalMs&&(await this.refreshRequests(),this.lastRefreshTime=e)}async refreshRequests(){try{const{accountId:e}=this.hcsClient.getAccountAndSigner();if(!e)throw new Error("Could not determine account ID for current agent");const t=this.stateManager.getConnectionsManager();if(!t)throw new Error("ConnectionsManager not initialized");await t.fetchConnectionData(e)}catch(e){throw this.logger.error(`Error refreshing connection requests: ${e}`),e}}listRequests(){const e=this.stateManager.getConnectionsManager();if(!e)return"Error: ConnectionsManager not initialized";const t=[...e.getPendingRequests(),...e.getConnectionsNeedingConfirmation()];if(0===t.length)return console.log("No pending connection requests found.",t),"No pending connection requests found.";let n=`Found ${t.length} pending connection request(s):\n\n`;return[...t].sort(((e,t)=>t.created.getTime()-e.created.getTime())).forEach(((e,t)=>{const o=e.needsConfirmation?"🟠 Incoming":"⚪️ Outgoing",i=e.uniqueRequestKey||`${e.connectionRequestId||e.inboundRequestId||"unknown"}`;n+=`${t+1}. ${o} - Key: ${i}\n`,n+=` ${e.needsConfirmation?"From":"To"}: ${e.targetAgentName||`Agent ${e.targetAccountId}`} (${e.targetAccountId})\n`,n+=` Sent/Rcvd: ${e.created.toLocaleString()}\n`,e.memo&&(n+=` Memo: ${e.memo}\n`),e.profileInfo&&e.profileInfo.bio&&(n+=` Bio: ${e.profileInfo.bio}\n`),n+="\n"})),n+='To view more details about a request, use action="view" with the specific requestKey.\n',n+='To reject a request, use action="reject" with the specific requestKey.',n}viewRequest(e){const t=this.stateManager.getConnectionsManager();if(!t)return"Error: ConnectionsManager not initialized";const n=[...t.getPendingRequests(),...t.getConnectionsNeedingConfirmation()].find((t=>t.uniqueRequestKey===e||t.connectionRequestId?.toString()===e||t.inboundRequestId?.toString()===e));if(!n)return`Error: Request with key ${e} not found or no longer pending.`;const o=n.needsConfirmation?"Incoming":"Outgoing",i=n.uniqueRequestKey||`${n.connectionRequestId||n.inboundRequestId||"unknown"}`;let r=`Details for ${o} connection request: ${i}\n\n`;return r+=`${n.needsConfirmation?"Requestor":"Target"} ID: ${n.targetAccountId}\n`,r+=`${n.needsConfirmation?"Requestor":"Target"} Name: ${n.targetAgentName||`Agent ${n.targetAccountId}`}\n`,r+=`Received: ${n.created.toLocaleString()}\n`,n.memo&&(r+=`Memo: ${n.memo}\n`),n.profileInfo&&(r+="\nAgent Profile Information:\n",(n.profileInfo.display_name||n.profileInfo.alias)&&(r+=`Name: ${n.profileInfo.display_name||n.profileInfo.alias}\n`),void 0!==n.profileInfo.type&&(r+=`Type: ${n.profileInfo.type}\n`),n.profileInfo.bio&&(r+=`Bio: ${n.profileInfo.bio}\n`)),r+="\nActions:\n",r+=`- To reject this request: action="reject", requestKey="${i}"\n`,r+='Use the separate "accept_connection_request" tool to accept requests.',r}async rejectRequest(e){const t=this.stateManager.getConnectionsManager();if(!t)return"Error: ConnectionsManager not initialized";const n=[...t.getPendingRequests(),...t.getConnectionsNeedingConfirmation()].find((t=>t.uniqueRequestKey===e||t.connectionRequestId?.toString()===e||t.inboundRequestId?.toString()===e));return n?(n.inboundRequestId?t.markConnectionRequestProcessed(n.targetInboundTopicId||"",n.inboundRequestId):n.connectionRequestId&&t.markConnectionRequestProcessed(n.originTopicId||"",n.connectionRequestId),`Connection request from ${n.targetAgentName||`Agent ${n.targetAccountId}`} was rejected.`):`Error: Request with key ${e} not found or no longer pending.`}}class w extends n.StructuredTool{constructor({hcsClient:t,stateManager:n,...i}){super(i),this.name="accept_connection_request",this.description="Accepts a specific pending connection request from another agent, establishing a communication channel.",this.schema=o.z.object({requestKey:o.z.string().describe('The unique request key of the specific request to accept. Use the "manage_connection_requests" tool with action="list" first to get valid keys.'),hbarFee:o.z.number().optional().describe("Optional HBAR fee amount to charge the connecting agent per message on the new connection topic."),exemptAccountIds:o.z.array(o.z.string()).optional().describe("Optional list of account IDs to exempt from any configured fees on the new connection topic.")}),this.hcsClient=t,this.stateManager=n,this.logger=e.Logger.getInstance({module:"AcceptConnectionRequestTool"})}async _call({requestKey:t,hbarFee:n,exemptAccountIds:o}){const i=this.stateManager.getCurrentAgent();if(!i)return"Error: Cannot accept connection request. No agent is currently active. Please register or select an agent first.";const r=this.stateManager.getConnectionsManager();if(!r)return"Error: ConnectionsManager not initialized";await r.fetchConnectionData(i.accountId);const s=[...r.getPendingRequests(),...r.getConnectionsNeedingConfirmation()].find((e=>e.uniqueRequestKey===t||e.connectionRequestId?.toString()===t||e.inboundRequestId?.toString()===t));if(!s)return`Error: Request with key ${t} not found or no longer pending. Use the manage_connection_requests tool with action="list" to verify.`;const a=s.connectionRequestId||s.inboundRequestId;if(!a)return`Error: Could not determine a valid request ID for the request with key ${t}.`;try{const l=await this.hcsClient.getInboundTopicId();let u;if(n&&n>0){const t=this.hcsClient.getAccountAndSigner().accountId;try{u=new e.FeeConfigBuilder({network:this.hcsClient.getNetwork(),logger:this.logger,defaultCollectorAccountId:t});const r=[...o||[],i.accountId];u.addHbarFee(n,t,r),this.logger.info(`Setting HBAR fee: ${n} HBAR to be collected by ${t}`)}catch(c){this.logger.error(`Error creating fee configuration: ${c}`),u=void 0,this.logger.warn("Proceeding to accept request without fees due to configuration error.")}}this.logger.info(`Attempting to accept request Key: ${t} (ID: ${a}) from ${s.targetAccountId}`);const d=await this.hcsClient.handleConnectionRequest(l,s.targetAccountId,a,u);if(!d?.connectionTopicId)return`Error: Failed to accept connection request with key ${t}. The SDK did not return a connection topic ID.`;this.logger.info(`Successfully created connection topic: ${d.connectionTopicId}`);const h=d.connectionTopicId;let f="";try{const e=await this.hcsClient.standardClient.retrieveProfile(s.targetAccountId);f=e?.topicInfo?.inboundTopic||"",f||this.logger.warn(`Could not resolve target inbound topic for ${s.targetAccountId}`)}catch(g){this.logger.warn(`Error fetching target profile/topic for ${s.targetAccountId}: ${g}`)}const p=s.profileInfo?.display_name||s.profileInfo?.alias||`Agent ${s.targetAccountId}`,m={targetAccountId:s.targetAccountId,targetAgentName:p,targetInboundTopicId:f,connectionTopicId:h,profileInfo:s.profileInfo,created:new Date,status:"established"};this.stateManager.addActiveConnection(m),r.fetchConnectionData(s.targetAccountId),this.logger.info(`Removed request ${t} from pending requests`);let I="";n&&n>0&&u&&(I=` with a ${n} HBAR fee per message`);return`Successfully accepted connection request ${s.uniqueRequestKey||t} from ${p} ${I}. Connection established on topic: ${h}.`}catch(l){return this.logger.error(`Error accepting connection request ${t}: ${l}`),`Error accepting connection request ${t}: ${l instanceof Error?l.message:String(l)}`}}}class y extends n.StructuredTool{constructor(t){super(),this.name="retrieve_profile",this.description="Retrieves the HCS-11 profile data associated with a given Hedera account ID. If no account ID is provided, it defaults to the current operator account ID. Returns the profile object as a JSON string on success.",this.schema=o.z.object({accountId:o.z.string().optional().describe("The Hedera account ID (e.g., 0.0.12345) to retrieve the profile for. If omitted, defaults to the current operator account ID."),disableCache:o.z.boolean().optional().describe("Optional: Set to true to bypass the cache and fetch fresh profile data.")}),this.client=t,this.logger=e.Logger.getInstance({module:this.name})}async _call(e){let t;try{if(e.accountId?t=e.accountId:(this.logger.info("accountId not provided, defaulting to operator ID."),t=this.client.getOperatorId()),!t)throw new Error("Could not determine target account ID.");this.logger.info(`Attempting to retrieve profile for account: ${t}, Disable Cache: ${!!e.disableCache}`);const n=await this.client.standardClient.retrieveProfile(t,e.disableCache);if(n.success&&n.profile)return this.logger.info(`Successfully retrieved profile for ${t}.`),JSON.stringify(n.profile,null,2);{const e=`Error retrieving profile for ${t}: ${n.error||"Profile not found or invalid."}`;return this.logger.error(e),e}}catch(n){const t=`Unexpected error retrieving profile for ${e.accountId||"operator default"}: ${n instanceof Error?n.message:String(n)}`;return this.logger.error(t,n),t}}}class T extends n.StructuredTool{constructor({hcsClient:t,stateManager:n,...i}){super(i),this.name="list_unapproved_connection_requests",this.description="Lists all connection requests that are not fully established, including incoming requests needing approval and outgoing requests waiting for confirmation.",this.schema=o.z.object({sortBy:o.z.enum(["time_asc","time_desc","name_asc","name_desc"]).optional().describe("Optional sorting criteria for the requests list (default: time_desc, newest first)"),limit:o.z.number().optional().describe("Optional limit on the number of requests to return (default: all)")}),this.hcsClient=t,this.stateManager=n,this.logger=e.Logger.getInstance({module:"ListPendingRequestsTool",level:"debug"})}async _call({sortBy:e="time_desc",limit:t}){if(!this.stateManager.getCurrentAgent())return"Error: Cannot list pending requests. No agent is currently active. Please register or select an agent first.";try{const n=await this.findAllPendingRequests();return this.formatRequestsList(n,e,t)}catch(n){return this.logger.error(`Error in ${this.name}: ${n}`),`Error listing pending requests: ${n instanceof Error?n.message:String(n)}`}}async findAllPendingRequests(){const e=this.stateManager.getConnectionsManager();if(!e)return[];const t=this.stateManager.getCurrentAgent();if(!t)return[];await e.fetchConnectionData(t.accountId);return[...e.getPendingRequests(),...e.getConnectionsNeedingConfirmation()]}formatRequestsList(e,t,n){if(0===e.length)return"No pending connection requests found (incoming or outgoing).";const o=this.sortRequests(e,t),i=n?o.slice(0,n):o;let r=`Found ${e.length} pending connection request(s):\n\n`;return i.forEach(((e,t)=>{const n="needs_confirmation"===e.status?"🟠 Incoming":"⚪️ Outgoing";r+=`${t+1}. ${n} - ID: ${e.uniqueRequestKey}\n`,r+=` ${"needs_confirmation"===e.status?"From:":"To: "} ${e.targetAgentName} (${e.targetAccountId})\n`,r+=` Sent/Rcvd: ${e.created.toLocaleString()}\n`,e.memo&&(r+=` Memo: ${e.memo}\n`),e.profileInfo?.bio&&(r+=` Bio: ${e.profileInfo.bio.substring(0,100)}${e.profileInfo.bio.length>100?"...":""}\n`),r+="\n"})),r+="Use related tools (manage_requests, accept_request) to handle these items.",r}sortRequests(e,t){const n=[...e];switch(t){case"time_asc":return n.sort(((e,t)=>e.created.getTime()-t.created.getTime()));case"time_desc":default:return n.sort(((e,t)=>t.created.getTime()-e.created.getTime()));case"name_asc":return n.sort(((e,t)=>e.targetAgentName?.localeCompare(t?.targetAgentName||"")||0));case"name_desc":return n.sort(((e,t)=>t.targetAgentName?.localeCompare(e?.targetAgentName||"")||0))}}}const A=r.join(process.cwd(),".env");class q{constructor(t){this.currentAgent=null,this.connectionMessageTimestamps={},this.connectionsManager=null,this.defaultEnvFilePath=t?.defaultEnvFilePath,this.defaultPrefix=t?.defaultPrefix??"TODD";const n=t?.disableLogging||"true"===process.env.DISABLE_LOGGING;this.logger=new e.Logger({module:"OpenConvaiState",silent:n}),t?.baseClient&&this.initializeConnectionsManager(t.baseClient)}initializeConnectionsManager(t){return this.connectionsManager?this.logger.debug("ConnectionsManager already initialized"):(this.logger.debug("Initializing ConnectionsManager"),this.connectionsManager=new e.ConnectionsManager({baseClient:t,logLevel:"error"})),this.connectionsManager}getConnectionsManager(){return this.connectionsManager}setCurrentAgent(e){this.currentAgent=e,this.connectionMessageTimestamps={},this.connectionsManager&&this.connectionsManager.clearAll()}getCurrentAgent(){return this.currentAgent}addActiveConnection(e){if(!this.connectionsManager)throw this.logger.error("ConnectionsManager not initialized. Call initializeConnectionsManager before adding connections."),new Error("ConnectionsManager not initialized. Call initializeConnectionsManager before adding connections.");const t={connectionTopicId:e.connectionTopicId,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName,targetInboundTopicId:e.targetInboundTopicId,status:this.convertConnectionStatus(e.status||"established"),isPending:e.isPending||!1,needsConfirmation:e.needsConfirmation||!1,created:e.created||new Date,lastActivity:e.lastActivity,profileInfo:e.profileInfo,connectionRequestId:e.connectionRequestId,processed:!0};this.connectionsManager.updateOrAddConnection(t),this.initializeTimestampIfNeeded(e.connectionTopicId)}updateOrAddConnection(e){this.addActiveConnection(e)}listConnections(){return this.connectionsManager?this.connectionsManager.getAllConnections().map((e=>this.convertToActiveConnection(e))):(this.logger.debug("ConnectionsManager not initialized, returning empty connections list"),[])}getConnectionByIdentifier(e){if(!this.connectionsManager)return;const t=this.listConnections(),n=parseInt(e)-1;if(!isNaN(n)&&n>=0&&n<t.length)return t[n];const o=this.connectionsManager.getConnectionByTopicId(e);if(o)return this.convertToActiveConnection(o);const i=this.connectionsManager.getConnectionByAccountId(e);return i?this.convertToActiveConnection(i):void 0}getLastTimestamp(e){return this.connectionMessageTimestamps[e]||0}updateTimestamp(e,t){if(!(e in this.connectionMessageTimestamps))return void(this.connectionMessageTimestamps[e]=t);t>this.connectionMessageTimestamps[e]&&(this.connectionMessageTimestamps[e]=t)}initializeTimestampIfNeeded(e){e in this.connectionMessageTimestamps||(this.connectionMessageTimestamps[e]=1e6*Date.now())}convertConnectionStatus(e){switch(e){case"pending":return"pending";case"established":default:return"established";case"needs confirmation":return"needs_confirmation"}}convertToActiveConnection(e){return{targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName||`Agent ${e.targetAccountId}`,targetInboundTopicId:e.targetInboundTopicId||"",connectionTopicId:e.connectionTopicId,status:this.convertToStateStatus(e.status),created:e.created,lastActivity:e.lastActivity,isPending:e.isPending,needsConfirmation:e.needsConfirmation,profileInfo:e.profileInfo,connectionRequestId:e.connectionRequestId}}convertToStateStatus(e){switch(e){case"pending":return"pending";case"established":case"closed":return"established";case"needs_confirmation":return"needs confirmation";default:return"unknown"}}async persistAgentData(e,t){if(t?.type&&"env-file"!==t.type)throw new Error(`Unsupported persistence type: ${t.type}. Only 'env-file' is supported.`);const n=t?.envFilePath||this.defaultEnvFilePath||process.env.ENV_FILE_PATH||".env",o=t?.prefix||this.defaultPrefix;if(!e.accountId||!e.inboundTopicId||!e.outboundTopicId)throw new Error("Agent data incomplete, cannot persist to environment");const r={[`${o}_ACCOUNT_ID`]:e.accountId,[`${o}_INBOUND_TOPIC_ID`]:e.inboundTopicId,[`${o}_OUTBOUND_TOPIC_ID`]:e.outboundTopicId};e.privateKey&&(r[`${o}_PRIVATE_KEY`]=e.privateKey),e.profileTopicId&&(r[`${o}_PROFILE_TOPIC_ID`]=e.profileTopicId),await async function(e,t){let n="";i.existsSync(e)&&(n=i.readFileSync(e,"utf8"));const o=[...n.split("\n")];for(const[i,r]of Object.entries(t)){const e=o.findIndex((e=>e.startsWith(`${i}=`)));-1!==e?o[e]=`${i}=${r}`:o.push(`${i}=${r}`)}i.writeFileSync(e,o.join("\n"))}(n,r)}}class v{async initialize(e){this.context=e}async cleanup(){}}const M=o.z.object({current_rate:o.z.object({cent_equivalent:o.z.number(),hbar_equivalent:o.z.number(),expiration_time:o.z.number()}),next_rate:o.z.object({cent_equivalent:o.z.number(),hbar_equivalent:o.z.number(),expiration_time:o.z.number()}),timestamp:o.z.string()});class E extends n.StructuredTool{constructor(){super(...arguments),this.name="getHbarPrice",this.description="Retrieves the current price of HBAR in USD from the Hedera Mirror Node.",this.schema=o.z.object({})}async _call(){try{const e=(await s.get("https://mainnet.mirrornode.hedera.com/api/v1/network/exchangerate")).data,t=M.safeParse(e);if(!t.success)throw console.error("Failed to parse exchange rate response:",t.error),new Error("Invalid API response format");const{current_rate:n}=t.data;return`The current price of HBAR is $${(n.cent_equivalent/n.hbar_equivalent/100).toFixed(6)} USD.`}catch(e){console.error("Error fetching HBAR price:",e);let t="An unknown error occurred";return s.isAxiosError(e)?(t=e.message,e.response&&(t+=` (Status: ${e.response.status})`)):e instanceof Error&&(t=e.message),`Failed to retrieve HBAR price: ${t}`}}}class R extends v{}exports.AcceptConnectionRequestTool=w,exports.BasePlugin=v,exports.CheckMessagesTool=I,exports.ConnectionMonitorTool=b,exports.ConnectionTool=h,exports.FindRegistrationsTool=C,exports.GenericPlugin=R,exports.GetHbarPriceTool=E,exports.HCS10Client=l,exports.HbarPricePlugin=class{constructor(){this.id="hedera-hbar-price",this.name="Hedera HBAR Price Plugin",this.description="Provides tools to interact with Hedera network data, specifically HBAR price.",this.version="1.0.0",this.author="Hedera Agent",this.tools=[new E]}async initialize(){return Promise.resolve()}getTools(){return this.tools}async cleanup(){return Promise.resolve()}},exports.InitiateConnectionTool=p,exports.ListConnectionsTool=m,exports.ListUnapprovedConnectionRequestsTool=T,exports.ManageConnectionRequestsTool=$,exports.OpenConvAIPlugin=class extends R{constructor(){super(...arguments),this.id="openconvai-standards-agent-kit",this.name="OpenConvAI Standards Agent Kit Plugin",this.description="Comprehensive plugin providing all HCS-10 agent tools for registration, connections, and messaging",this.version="1.0.0",this.author="Hashgraph Online",this.namespace="openconvai",this.tools=[]}async initialize(e){if(await super.initialize(e),!(e.client instanceof l))throw new Error("OpenConvAIPlugin requires an HCS10Client instance");this.hcs10Client=e.client,this.stateManager=e.stateManager||new q,this.initializeTools(),this.context.logger.info("OpenConvAI Standards Agent Kit Plugin initialized successfully")}initializeTools(){if(!this.hcs10Client||!this.stateManager)throw new Error("HCS10Client and StateManager must be initialized before creating tools");this.tools=[new u(this.hcs10Client,this.stateManager),new d(this.hcs10Client),new h({client:this.hcs10Client,stateManager:this.stateManager}),new C({hcsClient:this.hcs10Client}),new y(this.hcs10Client),new p({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new m({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new f({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new I({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new b({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new $({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new w({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new T({stateManager:this.stateManager,hcsClient:this.hcs10Client})]}getTools(){return this.tools}async cleanup(){this.tools=[],this.hcs10Client=void 0,this.stateManager=void 0,this.context.logger.info("OpenConvAI Standards Agent Kit Plugin cleaned up")}},exports.OpenConvaiState=q,exports.PluginLoader=class{static async loadFromDirectory(e,t,n={initialize:!0}){const o=g.join(e,"plugin.json");if(!c.existsSync(o))throw new Error(`Plugin manifest not found at ${o}`);try{const i=c.readFileSync(o,"utf8"),r=JSON.parse(i);if(!r.id||!r.main)throw new Error("Invalid plugin manifest: missing required fields (id, main)");const s=g.join(e,r.main);if(!c.existsSync(s))throw new Error(`Plugin main file not found at ${s}`);const a=await import(s),l=a.default||a[r.id];if(!l)throw new Error(`Could not find plugin class in ${s}`);const u=new l;if(!this.isValidPlugin(u))throw new Error("Plugin does not implement the IPlugin interface correctly");return n.initialize&&await u.initialize(t),u}catch(i){throw new Error(`Failed to load plugin from directory ${e}: ${i instanceof Error?i.message:String(i)}`)}}static async loadFromPackage(e,t,n={initialize:!0}){try{const o=require.resolve(e),i=g.dirname(o);return this.loadFromDirectory(i,t,n)}catch(o){throw new Error(`Failed to load plugin from package ${e}: ${o instanceof Error?o.message:String(o)}`)}}static isValidPlugin(e){return e&&"string"==typeof e.id&&"string"==typeof e.name&&"string"==typeof e.description&&"string"==typeof e.version&&"string"==typeof e.author&&"function"==typeof e.initialize&&"function"==typeof e.getTools}},exports.PluginRegistry=class{constructor(e){this.plugins=new Map,this.context=e,this.logger=e.logger}async registerPlugin(e){if(this.plugins.has(e.id))throw new Error(`Plugin with ID ${e.id} is already registered`);await e.initialize(this.context),this.plugins.set(e.id,e),this.logger.info(`Plugin registered: ${e.name} (${e.id}) v${e.version}`)}getPlugin(e){return this.plugins.get(e)}getAllPlugins(){return Array.from(this.plugins.values())}getAllTools(){return this.getAllPlugins().flatMap((e=>e.getTools()))}async unregisterPlugin(e){const t=this.plugins.get(e);if(!t)return!1;if(t.cleanup)try{await t.cleanup()}catch(o){this.logger.error(`Error during plugin cleanup: ${o}`)}const n=this.plugins.delete(e);return n&&this.logger.info(`Plugin unregistered: ${t.name} (${t.id})`),n}async unregisterAllPlugins(){const e=Array.from(this.plugins.keys());for(const t of e)await this.unregisterPlugin(t)}},exports.RegisterAgentTool=u,exports.RetrieveProfileTool=y,exports.SendMessageToConnectionTool=f,exports.SendMessageTool=d,exports.initializeStandardsAgentKit=t=>{const n=t?.clientConfig||{},o=n.operatorId||process.env.HEDERA_OPERATOR_ID,i=n.operatorKey||process.env.HEDERA_OPERATOR_KEY,r=n.network||process.env.HEDERA_NETWORK||"testnet";let s;if("mainnet"===r?s="mainnet":("testnet"===r||console.warn(`Unsupported network specified: '${r}'. Defaulting to 'testnet'.`),s="testnet"),!o||!i)throw new Error("Operator ID and private key must be provided either through options or environment variables.");const a="true"===process.env.DISABLE_LOGGING,c=e.Logger.getInstance({level:n.logLevel||"info",silent:a}),g=t?.stateManager||new q({defaultEnvFilePath:A,defaultPrefix:"TODD"});c.info("State manager initialized");const v=new l(o,i,s,{useEncryption:n.useEncryption,registryUrl:n.registryUrl});let M;c.info(`HCS10Client initialized for ${o} on ${s}`),t?.monitoringClient&&(M=new l(o,i,s,{useEncryption:n.useEncryption,registryUrl:n.registryUrl,logLevel:"error"}),c.info("Monitoring client initialized"));const E={};return E.registerAgentTool=new u(v,g),E.sendMessageTool=new d(v),E.connectionTool=new h({client:M||v,stateManager:g}),t?.createAllTools&&(E.findRegistrationsTool=new C({hcsClient:v}),E.retrieveProfileTool=new y(v),E.initiateConnectionTool=new p({hcsClient:v,stateManager:g}),E.listConnectionsTool=new m({hcsClient:v,stateManager:g}),E.sendMessageToConnectionTool=new f({hcsClient:v,stateManager:g}),E.checkMessagesTool=new I({hcsClient:v,stateManager:g}),E.connectionMonitorTool=new b({hcsClient:M||v,stateManager:g}),E.manageConnectionRequestsTool=new $({hcsClient:v,stateManager:g}),E.acceptConnectionRequestTool=new w({hcsClient:v,stateManager:g}),E.listUnapprovedConnectionRequestsTool=new T({stateManager:g,hcsClient:v}),c.info("All tools initialized")),{hcs10Client:v,monitoringClient:M,tools:E,stateManager:g}};
|
|
2
2
|
//# sourceMappingURL=standards-agent-kit.cjs.map
|