@hashgraphonline/standards-agent-kit 0.2.124 → 0.2.127

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("hedera-agent-kit"),t=require("@hashgraphonline/standards-sdk"),i=require("fs"),n=require("path"),r=require("axios"),o=require("zod"),s=require("fs/promises");function a(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const i in e)if("default"!==i){const n=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,n.get?n:{enumerable:!0,get:()=>e[i]})}return t.default=e,Object.freeze(t)}const c=a(n),l=a(s);class d extends e.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}class u extends e.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}const g=class{static parseCapabilities(e){if(!e)return[t.AIAgentCapability.TEXT_GENERATION];const i=e.toLowerCase(),n=new Set;for(const[t,r]of Object.entries(this.CAPABILITY_MAPPINGS))i.includes(t)&&r.forEach(e=>n.add(e));return 0===n.size&&n.add(t.AIAgentCapability.TEXT_GENERATION),Array.from(n)}static parseTagsOrCapabilities(e){if(Array.isArray(e)&&e.every(e=>"number"==typeof e))return e;if(Array.isArray(e)&&e.every(e=>"string"==typeof e)){const t=new Set;return e.forEach(e=>{this.parseCapabilities(e).forEach(e=>t.add(e))}),Array.from(t)}return"string"==typeof e?this.parseCapabilities(e):[t.AIAgentCapability.TEXT_GENERATION]}static getCapabilityName(e){return{[t.AIAgentCapability.TEXT_GENERATION]:"Text Generation",[t.AIAgentCapability.IMAGE_GENERATION]:"Image Generation",[t.AIAgentCapability.AUDIO_GENERATION]:"Audio Generation",[t.AIAgentCapability.VIDEO_GENERATION]:"Video Generation",[t.AIAgentCapability.CODE_GENERATION]:"Code Generation",[t.AIAgentCapability.LANGUAGE_TRANSLATION]:"Language Translation",[t.AIAgentCapability.SUMMARIZATION_EXTRACTION]:"Summarization & Extraction",[t.AIAgentCapability.KNOWLEDGE_RETRIEVAL]:"Knowledge Retrieval",[t.AIAgentCapability.DATA_INTEGRATION]:"Data Integration",[t.AIAgentCapability.MARKET_INTELLIGENCE]:"Market Intelligence",[t.AIAgentCapability.TRANSACTION_ANALYTICS]:"Transaction Analytics",[t.AIAgentCapability.SMART_CONTRACT_AUDIT]:"Smart Contract Audit",[t.AIAgentCapability.GOVERNANCE_FACILITATION]:"Governance Facilitation",[t.AIAgentCapability.SECURITY_MONITORING]:"Security Monitoring",[t.AIAgentCapability.COMPLIANCE_ANALYSIS]:"Compliance Analysis",[t.AIAgentCapability.FRAUD_DETECTION]:"Fraud Detection",[t.AIAgentCapability.MULTI_AGENT_COORDINATION]:"Multi-Agent Coordination",[t.AIAgentCapability.API_INTEGRATION]:"API Integration",[t.AIAgentCapability.WORKFLOW_AUTOMATION]:"Workflow Automation"}[e]||"Unknown Capability"}};g.CAPABILITY_MAPPINGS={ai:[t.AIAgentCapability.TEXT_GENERATION],"artificial intelligence":[t.AIAgentCapability.TEXT_GENERATION],chat:[t.AIAgentCapability.TEXT_GENERATION],conversation:[t.AIAgentCapability.TEXT_GENERATION],text:[t.AIAgentCapability.TEXT_GENERATION],"text generation":[t.AIAgentCapability.TEXT_GENERATION],image:[t.AIAgentCapability.IMAGE_GENERATION],picture:[t.AIAgentCapability.IMAGE_GENERATION],visual:[t.AIAgentCapability.IMAGE_GENERATION],photo:[t.AIAgentCapability.IMAGE_GENERATION],audio:[t.AIAgentCapability.AUDIO_GENERATION],sound:[t.AIAgentCapability.AUDIO_GENERATION],voice:[t.AIAgentCapability.AUDIO_GENERATION],speech:[t.AIAgentCapability.AUDIO_GENERATION],video:[t.AIAgentCapability.VIDEO_GENERATION],movie:[t.AIAgentCapability.VIDEO_GENERATION],animation:[t.AIAgentCapability.VIDEO_GENERATION],code:[t.AIAgentCapability.CODE_GENERATION],programming:[t.AIAgentCapability.CODE_GENERATION],development:[t.AIAgentCapability.CODE_GENERATION],coding:[t.AIAgentCapability.CODE_GENERATION],translate:[t.AIAgentCapability.LANGUAGE_TRANSLATION],translation:[t.AIAgentCapability.LANGUAGE_TRANSLATION],language:[t.AIAgentCapability.LANGUAGE_TRANSLATION],summarize:[t.AIAgentCapability.SUMMARIZATION_EXTRACTION],summary:[t.AIAgentCapability.SUMMARIZATION_EXTRACTION],extract:[t.AIAgentCapability.SUMMARIZATION_EXTRACTION],extraction:[t.AIAgentCapability.SUMMARIZATION_EXTRACTION],knowledge:[t.AIAgentCapability.KNOWLEDGE_RETRIEVAL],search:[t.AIAgentCapability.KNOWLEDGE_RETRIEVAL],retrieve:[t.AIAgentCapability.KNOWLEDGE_RETRIEVAL],lookup:[t.AIAgentCapability.KNOWLEDGE_RETRIEVAL],data:[t.AIAgentCapability.DATA_INTEGRATION],"data processing":[t.AIAgentCapability.DATA_INTEGRATION],"data integration":[t.AIAgentCapability.DATA_INTEGRATION],etl:[t.AIAgentCapability.DATA_INTEGRATION],market:[t.AIAgentCapability.MARKET_INTELLIGENCE],trading:[t.AIAgentCapability.MARKET_INTELLIGENCE],finance:[t.AIAgentCapability.MARKET_INTELLIGENCE],financial:[t.AIAgentCapability.MARKET_INTELLIGENCE],analytics:[t.AIAgentCapability.TRANSACTION_ANALYTICS],analysis:[t.AIAgentCapability.TRANSACTION_ANALYTICS],analyze:[t.AIAgentCapability.TRANSACTION_ANALYTICS],transactions:[t.AIAgentCapability.TRANSACTION_ANALYTICS],audit:[t.AIAgentCapability.SMART_CONTRACT_AUDIT],contract:[t.AIAgentCapability.SMART_CONTRACT_AUDIT],"smart contract":[t.AIAgentCapability.SMART_CONTRACT_AUDIT],governance:[t.AIAgentCapability.GOVERNANCE_FACILITATION],voting:[t.AIAgentCapability.GOVERNANCE_FACILITATION],dao:[t.AIAgentCapability.GOVERNANCE_FACILITATION],security:[t.AIAgentCapability.SECURITY_MONITORING],monitoring:[t.AIAgentCapability.SECURITY_MONITORING],threat:[t.AIAgentCapability.SECURITY_MONITORING],compliance:[t.AIAgentCapability.COMPLIANCE_ANALYSIS],regulatory:[t.AIAgentCapability.COMPLIANCE_ANALYSIS],regulation:[t.AIAgentCapability.COMPLIANCE_ANALYSIS],fraud:[t.AIAgentCapability.FRAUD_DETECTION],detection:[t.AIAgentCapability.FRAUD_DETECTION],anomaly:[t.AIAgentCapability.FRAUD_DETECTION],coordination:[t.AIAgentCapability.MULTI_AGENT_COORDINATION],"multi-agent":[t.AIAgentCapability.MULTI_AGENT_COORDINATION],orchestration:[t.AIAgentCapability.MULTI_AGENT_COORDINATION],api:[t.AIAgentCapability.API_INTEGRATION],integration:[t.AIAgentCapability.API_INTEGRATION],webhook:[t.AIAgentCapability.API_INTEGRATION],workflow:[t.AIAgentCapability.WORKFLOW_AUTOMATION],automation:[t.AIAgentCapability.WORKFLOW_AUTOMATION],process:[t.AIAgentCapability.WORKFLOW_AUTOMATION]};let p=g;const h=o.z.object({name:o.z.string().min(1).max(50).describe("A unique name for the agent (1-50 characters)"),description:o.z.string().max(500).optional().describe("Optional bio description for the agent (max 500 characters)"),alias:o.z.string().optional().transform(e=>{if(!e||e.toLowerCase().includes("random")){return`bot${Date.now().toString(36)}${Math.random().toString(36)}`}return e}).describe('Optional custom username/alias for the agent. Use "random" to generate a unique alias'),type:o.z.enum(["autonomous","manual"]).optional().describe("Agent type (default: autonomous)"),model:o.z.string().optional().describe("AI model identifier (default: agent-model-2024)"),capabilities:o.z.union([o.z.array(o.z.nativeEnum(t.AIAgentCapability)),o.z.array(o.z.string()),o.z.string()]).optional().transform(e=>{if(e)return"string"==typeof e?p.parseCapabilities(e):Array.isArray(e)&&e.length>0&&"string"==typeof e[0]?p.parseTagsOrCapabilities(e):e}).describe('Agent capabilities - can be capability names (e.g. "ai", "data processing"), capability enum values, or array of either. Common values: "ai"/"text" (TEXT_GENERATION), "data" (DATA_INTEGRATION), "analytics" (TRANSACTION_ANALYTICS)'),tags:o.z.union([o.z.array(o.z.string()),o.z.string()]).optional().transform(e=>{if(e)return"string"==typeof e?p.parseCapabilities(e):p.parseTagsOrCapabilities(e)}).describe('Tags for the agent (alternative to capabilities) - e.g. "ai", "data", "analytics". Will be converted to appropriate capabilities.'),creator:o.z.string().optional().describe("Creator attribution for the agent"),socials:o.z.record(o.z.enum(["twitter","github","discord","telegram","linkedin","youtube","website","x"]),o.z.string()).optional().describe('Social media links (e.g., {"twitter": "@handle", "discord": "username"})'),properties:o.z.record(o.z.unknown()).optional().describe("Custom metadata properties for the agent"),profilePicture:o.z.union([o.z.string().describe("URL or local file path to profile picture"),o.z.object({url:o.z.string().optional(),path:o.z.string().optional(),filename:o.z.string().optional()})]).optional().describe("Optional profile picture as URL, file path, or object with url/path/filename"),existingProfilePictureTopicId:o.z.string().optional().describe("Topic ID of an existing profile picture to reuse (e.g., 0.0.12345)"),initialBalance:o.z.number().positive().optional().describe("Optional initial HBAR balance for the new agent account (will create new account if provided)"),userAccountId:o.z.string().optional().describe("Optional account ID (e.g., 0.0.12345) to use as the agent account instead of creating a new one"),hbarFee:o.z.number().positive().optional().describe("Optional HBAR fee amount to charge per message on the inbound topic"),tokenFees:o.z.array(o.z.object({amount:o.z.number().positive(),tokenId:o.z.string()})).optional().describe("Optional token fees to charge per message"),exemptAccountIds:o.z.array(o.z.string()).optional().describe("Optional account IDs to exempt from fees"),setAsCurrent:o.z.boolean().optional().describe("Whether to set as current agent (default: true)"),persistence:o.z.object({prefix:o.z.string().optional()}).optional().describe("Optional persistence configuration")});class m extends d{constructor(e){super(e),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. Supports natural language for capabilities/tags like "ai", "data processing", "analytics". Note: This tool requires multiple transactions and cannot be used in returnBytes mode. If alias is set to "random" or contains "random", a unique alias will be generated.',this.specificInputSchema=h,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const i=e;this.specificArgs=t;const n={name:t.name};if(void 0!==t.description&&(n.bio=t.description),void 0!==t.alias)n.alias=t.alias;else{const e=Date.now().toString(36);n.alias=`${t.name}${e}`}if(void 0!==t.type&&(n.type=t.type),void 0!==t.model&&(n.model=t.model),void 0!==t.tags?n.capabilities=t.tags:void 0!==t.capabilities&&(n.capabilities=t.capabilities),void 0!==t.creator&&(n.creator=t.creator),void 0!==t.socials&&(n.socials=t.socials),void 0!==t.properties&&(n.properties=t.properties),void 0!==t.profilePicture)if("string"==typeof t.profilePicture)n.profilePicture=t.profilePicture;else{const e={};void 0!==t.profilePicture.url&&(e.url=t.profilePicture.url),void 0!==t.profilePicture.path&&(e.path=t.profilePicture.path),void 0!==t.profilePicture.filename&&(e.filename=t.profilePicture.filename),n.profilePicture=e}void 0!==t.existingProfilePictureTopicId&&(n.existingProfilePictureTopicId=t.existingProfilePictureTopicId),void 0!==t.userAccountId&&(n.userAccountId=t.userAccountId),void 0!==t.hbarFee&&(n.hbarFee=t.hbarFee),void 0!==t.tokenFees&&(n.tokenFees=t.tokenFees),void 0!==t.exemptAccountIds&&(n.exemptAccountIds=t.exemptAccountIds),void 0!==t.initialBalance&&(n.initialBalance=t.initialBalance),await i.registerAgent(n)}async _call(e,t){const i=await super._call(e,t),n=!1!==this.specificArgs?.setAsCurrent;if(this.specificArgs&&n)try{const e=JSON.parse(i);e.rawResult?this._handleRegistrationResult(e.rawResult):(e.state||e.accountId||e.metadata)&&this._handleRegistrationResult(e)}catch(r){}return i}_handleRegistrationResult(e){let t=e.accountId||e.metadata?.accountId;if(!t&&e.state?.createdResources){const i=e.state.createdResources.find(e=>e.startsWith("account:"));i&&(t=i.split(":")[1])}const i=e.inboundTopicId||e.metadata?.inboundTopicId||e.state?.inboundTopicId,n=e.outboundTopicId||e.metadata?.outboundTopicId||e.state?.outboundTopicId,r=e.profileTopicId||e.metadata?.profileTopicId||e.state?.profileTopicId,o=e.privateKey||e.metadata?.privateKey;if(t&&i&&n&&this.specificArgs){const e={name:this.specificArgs.name,accountId:t,inboundTopicId:i,outboundTopicId:n,profileTopicId:r,privateKey:o},s=this.getServiceBuilder().getStateManager();if(s&&(s.setCurrentAgent(e),s.persistAgentData)){const t=this.specificArgs.persistence?.prefix||this.specificArgs.name.toUpperCase().replace(/[^A-Z0-9]/g,"_");s.persistAgentData(e,{type:"env-file",prefix:t}).catch(()=>{})}}}}const f=o.z.object({targetIdentifier:o.z.string().optional().describe("The request key (e.g., 'req-1:0.0.6155171@0.0.6154875'), account ID (e.g., 0.0.12345) of the target agent, OR the connection number (e.g., '1', '2') from the 'list_connections' tool. Request key is most deterministic."),connectionId:o.z.string().optional().describe("The connection number (e.g., '1', '2') from the 'list_connections' tool."),agentId:o.z.string().optional().describe("The account ID (e.g., 0.0.12345) of the target agent."),message:o.z.string().describe("The text message content to send."),disableMonitoring:o.z.boolean().optional().default(!1)});class y extends d{constructor(e){super(e),this.name="send_message_to_connection",this.description="Use this to send a message to an agent you already have an active connection with. Provide the target agent's account ID (e.g., 0.0.12345) and your message. If no active connection exists, this will fail - use initiate_connection instead to create a new connection first.",this.specificInputSchema=f,this.requiresMultipleTransactions=!0,this.neverScheduleThisTool=!0}async callBuilderMethod(e,t){const i=e,n=t.targetIdentifier||t.agentId||t.connectionId;if(!n)throw new Error("Either targetIdentifier, connectionId, or agentId must be provided");const r=i.getStateManager();if(r){const e=r.getConnectionsManager();if(e)try{const t=r.getCurrentAgent();t&&t.accountId&&await e.fetchConnectionData(t.accountId)}catch(o){console.debug("Could not refresh connections:",o)}if(n.match(/^\d+$/)){const e=r.listConnections(),o=parseInt(n)-1,s=e.filter(e=>"established"===e.status&&!e.isPending&&!e.needsConfirmation);if(o>=0&&o<s.length){const e=s[o];if(e&&e.connectionTopicId)return void(await i.sendMessageToConnection({targetIdentifier:e.connectionTopicId,message:t.message,disableMonitoring:t.disableMonitoring}))}}if(n.match(/^\d+\.\d+\.\d+$/)){const e=r.listConnections().find(e=>!(e.targetAccountId!==n&&e.targetAccountId!==`0.0.${n}`||"established"!==e.status||e.isPending||e.needsConfirmation));if(e&&e.connectionTopicId)return void(await i.sendMessageToConnection({targetIdentifier:e.connectionTopicId,message:t.message,disableMonitoring:t.disableMonitoring}))}}await i.sendMessageToConnection({targetIdentifier:n,message:t.message,disableMonitoring:t.disableMonitoring})}}const I=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."),disableMonitor:o.z.boolean().optional().describe("If true, does not wait for connection confirmation. Returns immediately after sending the request."),memo:o.z.string().optional().describe('Optional memo to include with the connection request (e.g., "Hello from Alice"). If not provided, defaults to "true" or "false" based on monitoring preference.')});class b extends d{constructor(e){super(e),this.name="initiate_connection",this.description="ONLY use this to START a BRAND NEW connection to an agent you have NEVER connected to before. If you already have an active connection to this agent, use send_message_to_connection instead. This creates a new connection request and waits for acceptance.",this.specificInputSchema=I,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const i=e,n={targetAccountId:t.targetAccountId};void 0!==t.disableMonitor&&(n.disableMonitor=t.disableMonitor),void 0!==t.memo&&(n.memo=t.memo),await i.initiateConnection(n)}}const w=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")});class T extends u{constructor(e){super(e),this.name="list_connections",this.description="Lists all active HCS-10 connections. Use this FIRST before sending messages to check if you already have an active connection to a target agent. Shows connection details and agent information for each active connection.",this.specificInputSchema=w}async executeQuery(e){const t=this.hcs10Builder,i={};void 0!==e.includeDetails&&(i.includeDetails=e.includeDetails),void 0!==e.showPending&&(i.showPending=e.showPending),await t.listConnections(i);const n=await t.execute();if(n.success&&"rawResult"in n&&n.rawResult){const e=n.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Connections listed"}}return n}}const A=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.")});class C extends u{constructor(e){super(e),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.specificInputSchema=A}async executeQuery({targetIdentifier:e,fetchLatest:t,lastMessagesCount:i}){const n=this.hcs10Builder;await n.checkMessages({targetIdentifier:e,fetchLatest:t,lastMessagesCount:i||1});const r=await n.execute();if(r.success&&"rawResult"in r&&r.rawResult){const e=r.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Messages checked"}}return r}}const E=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.union([o.z.array(o.z.nativeEnum(t.AIAgentCapability)),o.z.array(o.z.string()),o.z.string()]).optional().transform(e=>{if(e)return"string"==typeof e?p.parseCapabilities(e):Array.isArray(e)&&e.length>0&&"string"==typeof e[0]?p.parseTagsOrCapabilities(e):e}).describe('Optional: Filter by capabilities/tags like "ai", "data", "analytics". Can be natural language terms or capability numbers.')});class v extends u{constructor(e){super(e),this.name="find_registrations",this.description='Searches the configured agent registry for HCS-10 agents. You can filter by account ID or tags/capabilities using natural language like "ai", "data processing", "analytics". Returns basic registration info.',this.specificInputSchema=E}async executeQuery({accountId:e,tags:t}){const i=this.hcs10Builder,n={};e&&(n.accountId=e),t&&(n.tags=t),await i.findRegistrations(n);const r=await i.execute();if(r.success&&"rawResult"in r&&r.rawResult){const e=r.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Registrations searched"}}return r}}const R=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 120."),defaultCollectorAccount:o.z.string().optional().describe("Default account to collect fees if not specified at the fee level. Defaults to the agent account.")});class S extends d{constructor(e){super(e),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. Note: When acceptAll=true, this tool requires multiple transactions and cannot be used in returnBytes mode.",this.specificInputSchema=R,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const i=e;await i.monitorConnections({...void 0!==t.acceptAll&&{acceptAll:t.acceptAll},...void 0!==t.targetAccountId&&{targetAccountId:t.targetAccountId},...void 0!==t.monitorDurationSeconds&&{monitorDurationSeconds:t.monitorDurationSeconds},hbarFees:t.hbarFees||[],tokenFees:t.tokenFees||[],...void 0!==t.exemptAccountIds&&{exemptAccountIds:t.exemptAccountIds},...void 0!==t.defaultCollectorAccount&&{defaultCollectorAccount:t.defaultCollectorAccount}})}}const N=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)")});class $ extends u{constructor(e){super(e),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.specificInputSchema=N}async executeQuery({action:e,requestKey:t}){const i=this.hcs10Builder,n={action:e};void 0!==t&&(n.requestKey=t),await i.manageConnectionRequests(n);const r=await i.execute();return"rawResult"in r?r.rawResult:r}}const O=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.")});class M extends d{constructor(e){super(e),this.name="accept_connection_request",this.description="Accepts a pending HCS-10 connection request from another agent. Use list_unapproved_connection_requests to see pending requests.",this.specificInputSchema=O,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const i=e;await i.acceptConnection({requestKey:t.requestKey,hbarFee:t.hbarFee,exemptAccountIds:t.exemptAccountIds})}}const x=o.z.object({accountId:o.z.string().describe("The Hedera account ID of the agent whose profile you want to retrieve (e.g., 0.0.12345)."),disableCache:o.z.boolean().optional().describe("Optional: Force refresh from the network instead of using cache.")});class z extends u{constructor(e){super(e),this.name="retrieve_profile",this.description="Gets the detailed profile information for a specific HCS-10 agent by their account ID. Returns name, bio, capabilities, topics, and other metadata.",this.specificInputSchema=x}async executeQuery({accountId:e,disableCache:t}){const i=this.hcs10Builder,n={accountId:e};void 0!==t&&(n.disableCache=t),await i.retrieveProfile(n);const r=await i.execute();if(r.success&&"rawResult"in r&&r.rawResult){const e=r.rawResult;return{success:!0,data:e.profileDetails||"Profile retrieved",rawProfile:e.rawProfile}}return r}}const q=o.z.object({});class k extends u{constructor(e){super(e),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.specificInputSchema=q}async executeQuery(){const e=this.hcs10Builder;await e.listUnapprovedConnectionRequests();const t=await e.execute();return"rawResult"in t?t.rawResult:t}}class P extends e.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs2",this.hcs2Builder=e.hcs2Builder}getServiceBuilder(){return this.hcs2Builder}}class B extends e.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs2",this.hcs2Builder=e.hcs2Builder}getServiceBuilder(){return this.hcs2Builder}}const D=o.z.object({registryType:o.z.nativeEnum(t.HCS2RegistryType).optional().describe("Registry type: 0 for indexed, 1 for non-indexed (default: 0)"),ttl:o.z.number().int().positive().optional().describe("Time to live in seconds (default: 86400)"),adminKey:o.z.union([o.z.string(),o.z.boolean()]).optional().describe("Admin key: public key string or true to use operator key"),submitKey:o.z.union([o.z.string(),o.z.boolean()]).optional().describe("Submit key: public key string or true to use operator key")});const F=o.z.object({registryTopicId:o.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID (e.g., 0.0.123456)"),targetTopicId:o.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The target topic ID to register (e.g., 0.0.123456)"),metadata:o.z.string().optional().describe("Optional metadata URI (HIP-412 format)"),memo:o.z.string().max(500).optional().describe("Optional memo (max 500 characters)")});const _=o.z.object({registryTopicId:o.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID (must be indexed)"),targetTopicId:o.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The new topic ID to point to"),uid:o.z.string().describe("The unique ID of the entry to update"),metadata:o.z.string().optional().describe("Optional metadata URI (HIP-412 format)"),memo:o.z.string().max(500).optional().describe("Optional memo (max 500 characters)")});const L=o.z.object({registryTopicId:o.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID (must be indexed)"),uid:o.z.string().describe("The unique ID of the entry to delete"),memo:o.z.string().max(500).optional().describe("Optional memo (max 500 characters)")});const H=o.z.object({registryTopicId:o.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The current HCS-2 registry topic ID"),targetTopicId:o.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The new topic ID to migrate to"),metadata:o.z.string().optional().describe("Optional metadata URI for migration details"),memo:o.z.string().max(500).optional().describe("Optional memo (max 500 characters)")});const K=o.z.object({topicId:o.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID to query"),limit:o.z.number().int().positive().optional().describe("Maximum number of entries to return"),order:o.z.enum(["asc","desc"]).optional().describe("Order of results (ascending or descending)"),skip:o.z.number().int().min(0).optional().describe("Number of entries to skip")});class U extends e.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs6",this.hcs6Builder=e.hcs6Builder}getServiceBuilder(){return this.hcs6Builder}}class G extends e.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs6",this.hcs6Builder=e.hcs6Builder}getServiceBuilder(){return this.hcs6Builder}}const j=o.z.object({ttl:o.z.number().min(3600).default(86400).describe("Time-to-live in seconds (minimum 3600 seconds/1 hour)"),submitKey:o.z.union([o.z.boolean(),o.z.string()]).optional().describe("Submit key for the registry topic. Can be boolean (use operator key) or a public key string")});const Q=o.z.object({metadata:o.z.record(o.z.unknown()).describe("Metadata object for the hashinal (e.g., name, description, attributes)"),data:o.z.object({base64:o.z.string().optional().describe("Base64 encoded data for the hashinal"),url:o.z.string().optional().describe("URL to fetch data from"),mimeType:o.z.string().optional().describe("MIME type of the data")}).optional().describe("Data to inscribe with the hashinal"),memo:o.z.string().optional().describe("Optional memo for the registration"),ttl:o.z.number().min(3600).default(86400).describe("Time-to-live in seconds for the inscription"),registryTopicId:o.z.string().optional().describe("Registry topic ID to use. If not provided, a new registry will be created"),submitKey:o.z.string().optional().describe("Submit key for the registry (required if registry has a submit key)")});const W=o.z.object({registryTopicId:o.z.string().describe("The registry topic ID that tracks this dynamic hashinal"),metadata:o.z.record(o.z.unknown()).describe("Updated metadata object for the hashinal"),data:o.z.object({base64:o.z.string().optional().describe("Base64 encoded data for the updated hashinal"),url:o.z.string().optional().describe("URL to fetch updated data from"),mimeType:o.z.string().optional().describe("MIME type of the data")}).optional().describe("Updated data to inscribe"),memo:o.z.string().optional().describe('Optional memo for the update (e.g., "Level up", "Version 2.0")'),submitKey:o.z.string().describe("Submit key for the registry (required to update)")});const V=o.z.object({topicId:o.z.string().describe("The registry topic ID to query"),limit:o.z.number().optional().default(100).describe("Maximum number of entries to retrieve"),order:o.z.enum(["asc","desc"]).optional().default("desc").describe("Order of entries (desc shows latest first)"),skip:o.z.number().optional().describe("Number of entries to skip")});class Y extends e.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="inscriber",this.inscriberBuilder=e.inscriberBuilder,this.contentResolver=e.contentResolver||null}getServiceBuilder(){return this.inscriberBuilder}getContentResolver(){return this.contentResolver}async generateInscriptionQuote(e,t){this.inscriberBuilder.hederaKit.signer.getAccountId().toString(),this.inscriberBuilder.hederaKit.signer?.getOperatorPrivateKey()&&this.inscriberBuilder.hederaKit.signer.getOperatorPrivateKey().toStringRaw();const i={...t,quoteOnly:!0,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet"},n=await this.inscriberBuilder.inscribe(e,i);if(!n.quote||n.confirmed)throw new Error("Failed to generate quote - unexpected response type");return n.result}}class X extends e.BaseHederaQueryTool{constructor(e){super(e),this.namespace="inscriber",this.inscriberBuilder=e.inscriberBuilder,this.contentResolver=e.contentResolver||null}getServiceBuilder(){return this.inscriberBuilder}getContentResolver(){return this.contentResolver}async generateInscriptionQuote(e,t){this.inscriberBuilder.hederaKit.signer.getAccountId().toString(),this.inscriberBuilder.hederaKit.signer?.getOperatorPrivateKey()&&this.inscriberBuilder.hederaKit.signer.getOperatorPrivateKey().toStringRaw();const i={...t,quoteOnly:!0,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet"},n=await this.inscriberBuilder.inscribe(e,i);if(!n.quote||n.confirmed)throw new Error("Failed to generate quote - unexpected response type");return n.result}}const J=o.z.object({url:o.z.string().url().describe("ONLY direct file download URLs with file extensions (.pdf, .jpg, .png, .json, .zip). NEVER use for web pages, articles, or when you already have content to inscribe."),mode:o.z.enum(["file","hashinal"]).optional().describe("Inscription mode: file or hashinal NFT"),metadata:o.z.record(o.z.unknown()).optional().describe("Metadata to attach to the inscription"),tags:o.z.array(o.z.string()).optional().describe("Tags to categorize the inscription"),chunkSize:o.z.number().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:o.z.boolean().optional().describe("Whether to wait for inscription confirmation"),timeoutMs:o.z.number().int().positive().optional().describe("Timeout in milliseconds for inscription (default: no timeout - waits until completion)"),apiKey:o.z.string().optional().describe("API key for inscription service"),quoteOnly:o.z.boolean().optional().default(!1).describe("If true, returns a cost quote instead of executing the inscription")});const Z=o.z.object({filePath:o.z.string().min(1,"File path cannot be empty").describe("The file path of the content to inscribe. Must point to a valid, non-empty file."),mode:o.z.enum(["file","hashinal"]).optional().describe("Inscription mode: file or hashinal NFT"),metadata:o.z.record(o.z.unknown()).optional().describe("Metadata to attach to the inscription"),tags:o.z.array(o.z.string()).optional().describe("Tags to categorize the inscription"),chunkSize:o.z.number().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:o.z.boolean().optional().describe("Whether to wait for inscription confirmation"),timeoutMs:o.z.number().int().positive().optional().describe("Timeout in milliseconds for inscription (default: no timeout)"),apiKey:o.z.string().optional().describe("API key for inscription service"),quoteOnly:o.z.boolean().optional().default(!1).describe("If true, returns a cost quote instead of executing the inscription")});const ee={maxInscriptionSize:51200,minContentSize:10,logLevel:"warn"};function te(){return{maxInscriptionSize:parseInt(process.env.REF_MAX_SIZE||ee.maxInscriptionSize.toString(),10),minContentSize:parseInt(process.env.REF_MIN_SIZE||ee.minContentSize.toString(),10),logLevel:process.env.REF_LOG_LEVEL||ee.logLevel,enableContentValidation:"false"!==process.env.REF_ENABLE_VALIDATION}}const ie=o.z.object({base64Data:o.z.string().min(1,"Data cannot be empty").describe('The content to inscribe. Accept BOTH plain text AND base64. Also accepts content reference IDs in format "content-ref:[id]". When user says "inscribe it" or "inscribe the content", use the EXACT content from your previous message or from MCP tool results. DO NOT generate new content. DO NOT create repetitive text. Pass the actual search results or other retrieved content EXACTLY as you received it.'),fileName:o.z.string().min(1,"File name cannot be empty").describe("Name for the inscribed content. Required for all inscriptions."),mimeType:o.z.string().optional().describe("MIME type of the content"),mode:o.z.enum(["file","hashinal"]).optional().describe("Inscription mode: file or hashinal NFT"),metadata:o.z.record(o.z.unknown()).optional().describe("Metadata to attach to the inscription"),tags:o.z.array(o.z.string()).optional().describe("Tags to categorize the inscription"),chunkSize:o.z.number().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:o.z.boolean().optional().describe("Whether to wait for inscription confirmation"),timeoutMs:o.z.number().int().positive().optional().describe("Timeout in milliseconds for inscription (default: no timeout - waits until completion)"),apiKey:o.z.string().optional().describe("API key for inscription service"),quoteOnly:o.z.boolean().optional().default(!1).describe("If true, returns a cost quote instead of executing the inscription")});const ne=o.z.object({url:o.z.string().url().describe("The URL of the content to inscribe as Hashinal NFT"),name:o.z.string().describe("Name of the Hashinal NFT"),creator:o.z.string().describe("Creator account ID or name"),description:o.z.string().describe("Description of the Hashinal NFT"),type:o.z.string().describe('Type of NFT (e.g., "image", "video", "audio")'),attributes:o.z.array(o.z.object({trait_type:o.z.string(),value:o.z.union([o.z.string(),o.z.number()])})).optional().describe("NFT attributes"),properties:o.z.record(o.z.unknown()).optional().describe("Additional properties"),jsonFileURL:o.z.string().url().optional().describe("URL to JSON metadata file"),tags:o.z.array(o.z.string()).optional().describe("Tags to categorize the NFT"),chunkSize:o.z.number().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:o.z.boolean().optional().describe("Whether to wait for inscription confirmation"),timeoutMs:o.z.number().int().positive().optional().describe("Timeout in milliseconds for inscription (default: no timeout - waits until completion)"),apiKey:o.z.string().optional().describe("API key for inscription service"),quoteOnly:o.z.boolean().optional().default(!1).describe("If true, returns a cost quote instead of executing the inscription")});const re=o.z.object({transactionId:o.z.string().describe("The transaction ID of the inscription to retrieve"),apiKey:o.z.string().optional().describe("API key for inscription service")});const oe=n.join(process.cwd(),".env");class se{constructor(e){this.currentAgent=null,this.connectionMessageTimestamps={},this.connectionsManager=null,this.defaultEnvFilePath=e?.defaultEnvFilePath,this.defaultPrefix=e?.defaultPrefix??"TODD";const i=e?.disableLogging||"true"===process.env.DISABLE_LOGGING;this.logger=new t.Logger({module:"OpenConvaiState",silent:i}),e?.baseClient&&this.initializeConnectionsManager(e.baseClient)}initializeConnectionsManager(e){return this.connectionsManager?this.logger.debug("ConnectionsManager already initialized"):(this.logger.debug("Initializing ConnectionsManager"),this.connectionsManager=new t.ConnectionsManager({baseClient:e,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(),i=parseInt(e)-1;if(!isNaN(i)&&i>=0&&i<t.length)return t[i];const n=this.connectionsManager.getConnectionByTopicId(e);if(n)return this.convertToActiveConnection(n);const r=this.connectionsManager.getConnectionByAccountId(e);return r?this.convertToActiveConnection(r):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",r=t?.prefix||this.defaultPrefix;if(!e.accountId||!e.inboundTopicId||!e.outboundTopicId)throw new Error("Agent data incomplete, cannot persist to environment");const o={[`${r}_ACCOUNT_ID`]:e.accountId,[`${r}_INBOUND_TOPIC_ID`]:e.inboundTopicId,[`${r}_OUTBOUND_TOPIC_ID`]:e.outboundTopicId};e.privateKey&&(o[`${r}_PRIVATE_KEY`]=e.privateKey),e.profileTopicId&&(o[`${r}_PROFILE_TOPIC_ID`]=e.profileTopicId),await async function(e,t){let n="";i.existsSync(e)&&(n=i.readFileSync(e,"utf8"));const r=[...n.split("\n")];for(const[i,o]of Object.entries(t)){const e=r.findIndex(e=>e.startsWith(`${i}=`));-1!==e?r[e]=`${i}=${o}`:r.push(`${i}=${o}`)}i.writeFileSync(e,r.join("\n"))}(n,o)}}const ae="ConnectionsManager not initialized";class ce extends e.BaseServiceBuilder{constructor(e,i,n){super(e),this.useEncryption=!1,this.guardedRegistryBaseUrl="",this.stateManager=i,this.useEncryption=n?.useEncryption||!1,this.guardedRegistryBaseUrl=n?.registryUrl||"";const r=this.hederaKit.client.network;this.network=r.toString().includes("mainnet")?"mainnet":"testnet";const o=this.hederaKit.signer.getAccountId().toString(),s=this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"";this.sdkLogger=new t.Logger({module:"HCS10Builder",level:n?.logLevel||"info"}),this.standardClient=new t.HCS10Client({network:this.network,operatorId:o,operatorPrivateKey:s,logLevel:n?.logLevel||"info"}),this.stateManager&&this.stateManager.initializeConnectionsManager(this.standardClient)}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.network}getStateManager(){return this.stateManager}getAccountAndSigner(){const e=this.standardClient.getAccountAndSigner();return{accountId:e.accountId,signer:e.signer}}async getInboundTopicId(){try{const e=this.getOperatorId();this.logger.info(`[HCS10Builder] 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(`[HCS10Builder] 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(`[HCS10Builder] Error fetching operator's inbound topic ID (${this.getOperatorId()}):`,e);const t=this.getOperatorId();let i=`Failed to get inbound topic ID for operator ${t}.`;throw e instanceof Error&&e.message.includes("does not have a valid HCS-11 memo")?i+=` 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?i+=` Reason: ${e.message}`:i+=` Unexpected error: ${String(e)}`,new Error(i)}}async getAgentProfile(e){try{return await this.standardClient.retrieveProfile(e)}catch(t){throw this.logger.error(`[HCS10Builder] Error retrieving agent profile for account ${e}:`,t),t}}async submitConnectionRequest(e,t){return this.standardClient.submitConnectionRequest(e,t)}async handleConnectionRequest(e,t,i,n){try{const r=await this.standardClient.handleConnectionRequest(e,t,i,n);return r&&r.connectionTopicId&&"object"==typeof r.connectionTopicId&&"toString"in r.connectionTopicId&&(r.connectionTopicId=r.connectionTopicId.toString()),r}catch(r){throw this.logger.error(`Error handling connection request #${i} for topic ${e}:`,r),new Error(`Failed to handle connection request: ${r instanceof Error?r.message:String(r)}`)}}async sendMessage(e,t,i){if(e&&"object"==typeof e&&"toString"in e&&(e=e?.toString()),!e||"string"!=typeof e)throw new Error(`Invalid topic ID provided to sendMessage: ${JSON.stringify(e)}`);try{const n=await this.standardClient.sendMessage(e,t,i,void 0);return{sequenceNumber:n.topicSequenceNumber?.toNumber(),receipt:n,transactionId:"transactionId"in n?n.transactionId?.toString():void 0}}catch(n){throw this.logger.error(`Error sending message to topic ${e}:`,n),new Error(`Failed to send message: ${n instanceof Error?n.message:String(n)}`)}}async getMessages(e){if(e&&"object"==typeof e&&"toString"in e&&(e=e?.toString()),!e||"string"!=typeof e)throw new Error(`Invalid topic ID provided to getMessages: ${JSON.stringify(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,p:"hcs-10"}});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){if(e&&"object"==typeof e&&"toString"in e&&(e=e?.toString()),!e||"string"!=typeof e)throw new Error(`Invalid topic ID provided to getMessageStream: ${JSON.stringify(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)}`)}}getStandardClient(){return this.standardClient}async loadProfilePicture(e){try{if(!e)return null;if("string"==typeof e){if(e.startsWith("http://")||e.startsWith("https://")){this.logger.info(`Loading profile picture from URL: ${e}`);const t=await r.get(e,{responseType:"arraybuffer"}),i=globalThis.Buffer.from(t.data),o=new URL(e).pathname;return{buffer:i,filename:n.basename(o)||"profile.png"}}{if(!i.existsSync(e))return this.logger.warn(`Profile picture file not found: ${e}`),null;this.logger.info(`Loading profile picture from file: ${e}`);const t=i.readFileSync(e);return{buffer:t,filename:n.basename(e)}}}if(e.url){this.logger.info(`Loading profile picture from URL: ${e.url}`);const t=await r.get(e.url,{responseType:"arraybuffer"}),i=globalThis.Buffer.from(t.data);return{buffer:i,filename:e.filename||"profile.png"}}if(e.path){if(!i.existsSync(e.path))return this.logger.warn(`Profile picture file not found: ${e.path}`),null;this.logger.info(`Loading profile picture from file: ${e.path}`);const t=i.readFileSync(e.path);return{buffer:t,filename:e.filename||n.basename(e.path)}}return null}catch(t){return this.logger.error("Failed to load profile picture:",t),null}}async createAndRegisterAgent(e){const i=(new t.AgentBuilder).setName(e.name).setBio(e.bio||"").setCapabilities(e.capabilities||[t.AIAgentCapability.TEXT_GENERATION]).setType(e.type||"autonomous").setModel(e.model||"agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(t.InboundTopicType.PUBLIC);e.alias&&i.setAlias(e.alias),e.creator&&i.setCreator(e.creator),e?.feeConfig&&(i.setInboundTopicType(t.InboundTopicType.FEE_BASED),i.setFeeConfig(e.feeConfig)),e.existingProfilePictureTopicId?i.setExistingProfilePicture(e.existingProfilePictureTopicId):e.pfpBuffer&&e.pfpFileName?0===e.pfpBuffer.byteLength?this.logger.warn("Provided PFP buffer is empty. Skipping profile picture."):(this.logger.info(`Setting profile picture: ${e.pfpFileName} (${e.pfpBuffer.byteLength} bytes)`),i.setProfilePicture(e.pfpBuffer,e.pfpFileName)):this.logger.warn("Profile picture not provided. Agent creation might fail if required by the underlying SDK builder."),e.socials&&Object.entries(e.socials).forEach(([e,t])=>{i.addSocial(e,t)}),e.properties&&Object.entries(e.properties).forEach(([e,t])=>{i.addProperty(e,t)});try{const t=Boolean(e?.feeConfig);return await this.standardClient.createAndRegisterAgent(i,{initialBalance:t?50:10})}catch(n){throw this.logger.error("Error during agent creation/registration:",n),new Error(`Failed to create/register agent: ${n instanceof Error?n.message:String(n)}`)}}async registerAgent(e){if(this.clearNotes(),"returnBytes"===this.hederaKit.operationalMode)throw new Error("Agent registration requires multiple transactions and cannot be performed in returnBytes mode. Please use autonomous mode.");try{let i=null;e.profilePicture&&(i=await this.loadProfilePicture(e.profilePicture));const n={name:e.name,...void 0!==e.bio&&{bio:e.bio},...void 0!==e.alias&&{alias:e.alias},...void 0!==e.type&&{type:e.type},...void 0!==e.model&&{model:e.model},...void 0!==e.capabilities&&{capabilities:e.capabilities},...void 0!==e.creator&&{creator:e.creator},...void 0!==e.socials&&{socials:e.socials},...void 0!==e.properties&&{properties:e.properties},...void 0!==e.existingProfilePictureTopicId&&{existingProfilePictureTopicId:e.existingProfilePictureTopicId},...void 0!==i?.buffer&&{pfpBuffer:i.buffer},...void 0!==i?.filename&&{pfpFileName:i.filename}};if(e.hbarFee&&e.hbarFee>0){const i=new t.FeeConfigBuilder({network:this.network,logger:this.sdkLogger}),{accountId:r}=this.getAccountAndSigner();if(!r)throw new Error("Could not determine account ID for fee collection.");this.addNote(`Setting the operator account (${r}) as the fee collector since no specific collector was provided.`);const o=e.exemptAccountIds?.filter(e=>e!==r&&e.startsWith("0.0"))||[];n.feeConfig=i.addHbarFee(e.hbarFee,r,o)}const r=await this.createAndRegisterAgent(n);this.executeResult={success:!0,transactionId:r.transactionId,receipt:void 0,scheduleId:void 0,rawResult:{...r,name:e.name,accountId:r?.metadata?.accountId||r.state?.agentMetadata?.accountId}}}catch(i){throw this.logger.error("Failed to register agent:",i),i}return this}async initiateConnection(e){this.clearNotes();try{const t=await this.getAgentProfile(e.targetAccountId);if(!t.success||!t.topicInfo?.inboundTopic)throw new Error(`Could not retrieve inbound topic for target account ${e.targetAccountId}`);const i=t.topicInfo.inboundTopic;let n;void 0!==e.memo?n=e.memo:(n=e.disableMonitor?"false":"true",this.addNote(`No custom memo was provided. Using default memo '${n}' based on monitoring preference.`)),e.disableMonitor||this.addNote("Monitoring will be enabled for this connection request as disableMonitor was not specified.");const r=await this.submitConnectionRequest(i,n);this.executeResult={success:!0,transactionId:"transactionId"in r?r.transactionId?.toString():void 0,receipt:r,scheduleId:void 0,rawResult:{targetAccountId:e.targetAccountId,targetInboundTopicId:i,connectionRequestSent:!0,monitoringEnabled:!e.disableMonitor,...r}}}catch(t){throw this.logger.error("Failed to initiate connection:",t),t}return this}async acceptConnection(e){if(this.clearNotes(),"returnBytes"===this.hederaKit.operationalMode)throw new Error("Accepting connections requires multiple transactions and cannot be performed in returnBytes mode. Please use autonomous mode.");try{const n=this.stateManager?.getCurrentAgent();if(!n)throw new Error("Cannot accept connection request. No agent is currently active. Please register or select an agent first.");const r=this.stateManager?.getConnectionsManager();if(!r)throw new Error(ae);await r.fetchConnectionData(n.accountId);const o=[...r.getPendingRequests(),...r.getConnectionsNeedingConfirmation()].find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!o)throw new Error(`Request with key ${e.requestKey} not found or no longer pending.`);if(!o.needsConfirmation||!o.inboundRequestId)throw new Error(`Request with key ${e.requestKey} is not an inbound request that can be accepted.`);const s=o.targetAccountId,a=o.inboundRequestId;let c;if(e.hbarFee&&e.hbarFee>0){const i=new t.FeeConfigBuilder({network:this.network,logger:this.sdkLogger}),{accountId:n}=this.getAccountAndSigner();if(!n)throw new Error("Could not determine account ID for fee collection.");this.addNote(`Setting the operator account (${n}) as the fee collector since no specific collector was provided.`);const r=e.exemptAccountIds?.filter(e=>e!==n&&e.startsWith("0.0"))||[];c=i.addHbarFee(e.hbarFee,n,r)}const l=await this.getInboundTopicId(),d=await this.handleConnectionRequest(l,s,a,c);let u=d?.connectionTopicId;if(u&&"object"==typeof u&&"toString"in u&&(u=u?.toString()),!u||"string"!=typeof u)throw new Error(`Failed to create connection topic. Got: ${JSON.stringify(u)}`);if(this.stateManager){const e=o.targetAgentName||`Agent ${s}`;o.targetAgentName||this.addNote(`No agent name was provided in the connection request, using default name 'Agent ${s}'.`);let t=o.targetInboundTopicId||"";if(!t)try{const e=await this.getAgentProfile(s);e.success&&e.topicInfo?.inboundTopic&&(t=e.topicInfo.inboundTopic)}catch(i){this.logger.warn(`Could not fetch profile for ${s}:`,i)}const n={connectionId:`conn-${Date.now()}`,targetAccountId:s,targetAgentName:e,targetInboundTopicId:t,connectionTopicId:u,status:"established",created:new Date};this.stateManager.addActiveConnection(n),r.markConnectionRequestProcessed(o.targetInboundTopicId||"",a)}this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{targetAccountId:s,connectionTopicId:u,feeConfigured:!!e.hbarFee,hbarFee:e.hbarFee||0,confirmationResult:d}}}catch(n){throw this.logger.error("Failed to accept connection:",n),n}return this}async sendHCS10Message(e){this.clearNotes();try{const t=await this.sendMessage(e.topicId,e.message);this.executeResult={success:!0,transactionId:t.transactionId,receipt:t.receipt,scheduleId:void 0,rawResult:t},this.addNote(`Message sent to topic ${e.topicId}.`)}catch(t){throw this.logger.error("Failed to send message:",t),t}return this}async sendMessageToConnection(e){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required to send messages to connections");try{const t=this.stateManager.getCurrentAgent();if(!t)throw new Error("Cannot send message. No agent is currently active. Please register or select an agent first.");let i;const n=e.targetIdentifier;if(n.includes("@")){const e=n.split("@");if(2===e.length){const t=e[1];i=this.stateManager.getConnectionByIdentifier(t),i||this.addNote(`Could not find connection using request key '${n}', extracted account ID '${t}'.`)}}if(i||(i=this.stateManager.getConnectionByIdentifier(n)),!i&&!n.startsWith("0.0.")&&/^\d+$/.test(n)){const e=`0.0.${n}`;i=this.stateManager.getConnectionByIdentifier(e),i&&this.addNote(`Found connection using account ID with prefix: ${e}`)}if(!i&&/^[1-9]\d*$/.test(n)){const e=this.stateManager.listConnections(),t=parseInt(n)-1;t>=0&&t<e.length&&(i=e[t],i&&this.addNote(`Found connection by index ${n}: ${i.targetAccountId}`))}if(!i){const e=this.stateManager.listConnections().map((e,t)=>`${t+1}. ${e.targetAccountId} (Topic: ${e.connectionTopicId})`);let t=`Connection not found for identifier: "${n}"\n`;throw t+=`Available connections:\n${e.join("\n")||"No active connections"}`,t+="\n\nYou can use:\n",t+='- Connection number (e.g., "1", "2")\n',t+='- Account ID (e.g., "0.0.6412936")\n',t+="- Connection topic ID\n",t+="Use 'list_connections' to see all active connections.",new Error(t)}let r=i.connectionTopicId;if(r&&"object"==typeof r&&"toString"in r&&(r=r?.toString()),!r||"string"!=typeof r)throw new Error(`Invalid connection topic ID for ${i.targetAccountId}: ${JSON.stringify(r)} (type: ${typeof r})`);const o=i.targetAgentName,s=`${t.inboundTopicId}@${t.accountId}`,a=await this.sendMessage(r,e.message,`Agent message from ${t.name}`);if(!a.sequenceNumber)throw new Error("Failed to send message");let c=null;e.disableMonitoring?this.addNote("Message sent successfully. Response monitoring was disabled."):c=await this.monitorResponses(r,s,a.sequenceNumber),this.executeResult={success:!0,transactionId:a.transactionId,receipt:a.receipt,scheduleId:void 0,rawResult:{targetAgentName:o,targetAccountId:i.targetAccountId,connectionTopicId:r,sequenceNumber:a.sequenceNumber,reply:c,monitoringEnabled:!e.disableMonitoring,message:e.message,messageResult:a}}}catch(t){throw this.logger.error("Failed to send message to connection:",t),t}return this}async monitorResponses(e,t,i){let n=0;for(;n<30;){try{const n=await this.getMessageStream(e);for(const e of n.messages){if(e.sequence_number<i||e.operator_id===t)continue;return await this.getMessageContent(e.data||"")}}catch(r){this.logger.error(`Error monitoring responses: ${r}`)}await new Promise(e=>setTimeout(e,4e3)),n++}return null}async startPassiveConnectionMonitoring(){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required for passive monitoring");const e=await this.getInboundTopicId();return this.logger.info(`Starting passive connection monitoring on topic ${e}...`),this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{inboundTopicId:e,message:`Started monitoring inbound topic ${e} for connection requests in the background.`}},this}async monitorConnections(e){this.clearNotes();const{acceptAll:i=!1,targetAccountId:n,monitorDurationSeconds:r=120,hbarFees:o=[],tokenFees:s=[],exemptAccountIds:a=[],defaultCollectorAccount:c}=e;if(!this.stateManager)throw new Error("StateManager is required for connection monitoring");if(!this.stateManager.getCurrentAgent())throw new Error("Cannot monitor for connections. No agent is currently active.");const l=await this.getInboundTopicId(),d=Date.now()+1e3*r;let u=0,g=0;const p=new Set;for(;Date.now()<d;){try{const e=(await this.getMessages(l)).messages.filter(e=>"connection_request"===e.op&&"number"==typeof e.sequence_number);for(const r of e){const e=r.sequence_number;if(!e||p.has(e))continue;const d=r.operator_id?.split("@")[1];if(d)if(u++,n&&d!==n)this.logger.info(`Skipping request from ${d} (not target account)`);else if(i||n===d){let i;if(this.logger.info(`Accepting connection request from ${d}`),o.length>0||s.length>0){const e=new t.FeeConfigBuilder({network:this.network,logger:this.sdkLogger});for(const t of o){const i=t.collectorAccount||c||this.getOperatorId();e.addHbarFee(t.amount,i,a)}for(const t of s){const i=t.collectorAccount||c||this.getOperatorId();e.addTokenFee(t.amount,t.tokenId,i,void 0,a)}i=e}await this.handleConnectionRequest(l,d,e,i),p.add(e),g++}}}catch(h){this.logger.error("Error during connection monitoring:",h)}await new Promise(e=>setTimeout(e,3e3))}return this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{connectionRequestsFound:u,acceptedConnections:g,monitorDurationSeconds:r,processedRequestIds:Array.from(p)}},this.addNote(`Monitoring completed. Found ${u} requests, accepted ${g}.`),this}async manageConnectionRequests(e){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required for managing connection requests");if(!this.stateManager.getCurrentAgent())throw new Error("Cannot manage connection requests. No agent is currently active.");const t=this.stateManager.getConnectionsManager();if(!t)throw new Error(ae);try{const{accountId:i}=this.getAccountAndSigner();await t.fetchConnectionData(i);const n=t.getPendingRequests(),r=t.getConnectionsNeedingConfirmation(),o=[...n,...r];switch(e.action){case"list":this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{requests:o.map((e,t)=>({index:t+1,type:e.needsConfirmation?"incoming":"outgoing",requestKey:e.uniqueRequestKey||`${e.connectionRequestId||e.inboundRequestId||"unknown"}`,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName||`Agent ${e.targetAccountId}`,created:e.created.toISOString(),memo:e.memo,bio:e.profileInfo?.bio}))}};break;case"view":{if(!e.requestKey)throw new Error("Request key is required for viewing a request");const t=o.find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!t)throw new Error(`Request with key ${e.requestKey} not found`);this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{request:{type:t.needsConfirmation?"incoming":"outgoing",requestKey:t.uniqueRequestKey||`${t.connectionRequestId||t.inboundRequestId||"unknown"}`,targetAccountId:t.targetAccountId,targetAgentName:t.targetAgentName||`Agent ${t.targetAccountId}`,created:t.created.toISOString(),memo:t.memo,profileInfo:t.profileInfo}}};break}case"reject":{if(!e.requestKey)throw new Error("Request key is required for rejecting a request");const i=o.find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!i)throw new Error(`Request with key ${e.requestKey} not found`);i.inboundRequestId?t.markConnectionRequestProcessed(i.targetInboundTopicId||"",i.inboundRequestId):i.connectionRequestId&&t.markConnectionRequestProcessed(i.originTopicId||"",i.connectionRequestId),this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{rejectedRequest:{requestKey:e.requestKey,targetAccountId:i.targetAccountId,targetAgentName:i.targetAgentName||`Agent ${i.targetAccountId}`}}};break}}}catch(i){throw this.logger.error("Failed to manage connection requests:",i),i}return this}async listUnapprovedConnectionRequests(){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required for listing connection requests");if(!this.stateManager.getCurrentAgent())throw new Error("Cannot list connection requests. No agent is currently active.");try{const e=await this.getInboundTopicId(),t=(await this.getMessages(e)).messages.filter(e=>"connection_request"===e.op).map(e=>({requestId:e.sequence_number,fromAccountId:e.operator_id?.split("@")[1]||"unknown",timestamp:e.timestamp||new Date(e?.created||"").getTime(),memo:e.m||"",data:e.data})).filter(e=>"unknown"!==e.fromAccountId);this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{requests:t,count:t.length}},0===t.length?this.addNote("No unapproved connection requests found."):this.addNote(`Found ${t.length} unapproved connection request(s).`)}catch(e){throw this.logger.error("Failed to list unapproved connection requests:",e),e}return this}async listConnections(e={}){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required to list connections");const t=e.includeDetails??!0,i=e.showPending??!0;try{const e=await this.getEnhancedConnections();if(0===e.length)return this.executeResult={success:!0,rawResult:{connections:[],message:"There are currently no active connections."}},this;const n=e.filter(e=>"established"===e.status),r=e.filter(e=>e.isPending),o=e.filter(e=>e.needsConfirmation);let s="";n.length>0&&(s+=`🟢 Active Connections (${n.length}):\n`,n.forEach((e,i)=>{s+=this.formatConnection(e,i,t)}),s+="\n"),i&&o.length>0&&(s+=`🟠 Connections Needing Confirmation (${o.length}):\n`,o.forEach((e,i)=>{s+=this.formatConnection(e,i,t)}),s+="\n"),i&&r.length>0&&(s+=`⚪ Pending Connection Requests (${r.length}):\n`,r.forEach((e,i)=>{s+=this.formatConnection(e,i,t)})),this.executeResult={success:!0,rawResult:{connections:e,formattedOutput:s.trim(),activeCount:n.length,pendingCount:r.length,needsConfirmationCount:o.length}}}catch(n){this.logger.error("Failed to list connections:",n),this.executeResult={success:!1,error:`Failed to list connections: ${n instanceof Error?n.message:String(n)}`}}return this}formatConnection(e,t,i){const n=e;let r=`${t+1}. ${n.profileInfo?.display_name||n.targetAgentName||"Unknown Agent"} (${n.targetAccountId})\n`;r+=` Topic: ${n.isPending?"(Pending Request)":n.connectionTopicId}\n`;if(r+=` Status: ${n.status||"unknown"}\n`,i){if(n.profileInfo?.bio&&(r+=` Bio: ${n.profileInfo.bio.substring(0,100)}${n.profileInfo.bio.length>100?"...":""}\n`),n.created){r+=` ${n.isPending?"Request sent":"Connection established"}: ${n.created.toLocaleString()}\n`}n.lastActivity&&(r+=` Last activity: ${n.lastActivity.toLocaleString()}\n`)}return r}async getEnhancedConnections(){try{const{accountId:e}=this.getAccountAndSigner();if(!e)return this.stateManager.listConnections();const t=this.stateManager.getConnectionsManager();if(!t)return this.logger.error(ae),this.stateManager.listConnections();const i=await t.fetchConnectionData(e);for(const n of i)this.stateManager.addActiveConnection(n);return i}catch(e){return this.logger.error("Failed to get enhanced connections:",e),this.stateManager.listConnections()}}async checkMessages(e){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required to check messages");const t=this.stateManager.getConnectionByIdentifier(e.targetIdentifier);if(!t)return this.executeResult={success:!1,error:`Could not find an active connection matching identifier "${e.targetIdentifier}". Use 'list_connections' to see active connections.`},this;const i=t.connectionTopicId||"";if(!i||!i.match(/^\d+\.\d+\.\d+$/))return this.logger.error(`Invalid connection topic ID format: ${i}`),this.executeResult={success:!1,error:`Invalid connection topic ID format: ${i}. Expected format: 0.0.XXXXX`},this;const n=t.targetAgentName,r=this.stateManager.getLastTimestamp(i);this.logger.info(`Checking messages for connection with ${n} (${t.targetAccountId}) on topic ${i} (fetchLatest: ${e.fetchLatest}, lastCount: ${e.lastMessagesCount}, since: ${r})`);try{const t=(await this.getMessages(i)).messages;if(!t||0===t.length)return this.executeResult={success:!0,rawResult:{messages:[],message:`No messages found on connection topic ${i}.`}},this;let s=[],a=r;const c=!0===e.fetchLatest;if(c){this.logger.info("Fetching latest messages regardless of timestamp.");const i=e.lastMessagesCount??1;s=t.slice(-i)}else this.logger.info(`Filtering for messages newer than ${r}`),s=t.filter(e=>1e6*e.timestamp>r),s.length>0&&(a=s.reduce((e,t)=>Math.max(e,1e6*t.timestamp),r));if(0===s.length){const e=c?`Could not retrieve the latest message(s). No messages found on topic ${i}.`:`No new messages found for connection with ${n} since last check.`;return this.executeResult={success:!0,rawResult:{messages:[],message:e}},this}this.logger.info(`Processing ${s.length} message(s).`);let l=c?`Latest message(s) from ${n}:\n`:`New messages from ${n}:\n`;const d=[];for(const e of s){let t=e.data;try{"string"==typeof t&&t.startsWith("hcs://")&&(this.logger.debug(`Resolving inscribed message: ${t}`),t=await this.getMessageContent(t),this.logger.debug(`Resolved content length: ${t?.length}`));let i=t;try{const e=JSON.parse(t||"{}");if("hcs-10"===e.p&&"message"===e.op&&e.data){i=`[${e.operator_id||"unknown_sender"}]: ${e.data}`}else i=t}catch{i=t}l+=`\n[${new Date(e.timestamp).toLocaleString()}] (Seq: ${e.sequence_number})\n${i}\n`,d.push({timestamp:e.timestamp,sequenceNumber:e.sequence_number,content:i,raw:e})}catch(o){const t=`Error processing message (Seq: ${e.sequence_number}): ${o instanceof Error?o.message:String(o)}`;this.logger.error(t),l+=`\n[Error processing message Seq: ${e.sequence_number}]\n`}}!c&&a>r&&(this.logger.debug(`Updating timestamp for topic ${i} to ${a}`),this.stateManager.updateTimestamp(i,a)),this.executeResult={success:!0,rawResult:{messages:d,formattedOutput:l.trim(),targetAgentName:n,connectionTopicId:i}}}catch(o){this.logger.error(`Failed to check messages for topic ${i}: ${o}`),this.executeResult={success:!1,error:`Error checking messages for ${n}: ${o instanceof Error?o.message:String(o)}`}}return this}async findRegistrations(e){this.clearNotes();try{const t={network:this.network};e.accountId&&(t.accountId=e.accountId),e.tags&&e.tags.length>0&&(t.tags=e.tags);const i=await this.standardClient.findRegistrations(t);if(!i.success||i.error)return this.executeResult={success:!1,error:`Error finding registrations: ${i.error||"Unknown error"}`},this;if(!i.registrations||0===i.registrations.length)return this.executeResult={success:!0,rawResult:{registrations:[],message:"No registrations found matching the criteria."}},this;const n=i.registrations.map(e=>{const t=e;return`Agent: ${t.agent?.name||"Unknown Agent"} (${t.accountId||"Unknown Account"}), Capabilities: ${t.agent?.capabilities?.join(", ")||"None"}`}).join("\\n");this.executeResult={success:!0,rawResult:{registrations:i.registrations,formattedOutput:`Found ${i.registrations.length} registration(s):\\n${n}`}}}catch(t){this.logger.error("Error during FindRegistrations execution:",t),this.executeResult={success:!1,error:`Failed to search registrations: ${t instanceof Error?t.message:String(t)}`}}return this}async retrieveProfile(e){this.clearNotes();try{const t=await this.standardClient.retrieveProfile(e.accountId,e.disableCache||!1);if(!t.success)return this.executeResult={success:!1,error:`Failed to retrieve profile: ${t.error||"Unknown error"}`},this;const i=t.profile,n=t.topicInfo;let r=`Profile for ${e.accountId}:\n`;r+=`Name: ${i.name||"Unknown"}\n`,r+=`Bio: ${i.bio||"No bio provided"}\n`,r+=`Type: ${i.type||"Unknown"}\n`,r+=`Model: ${i.model||"Unknown"}\n`,i.capabilities&&i.capabilities.length>0?r+=`Capabilities: ${i.capabilities.join(", ")}\n`:r+="Capabilities: None listed\n",n&&(r+=`Inbound Topic: ${n.inboundTopic||"Unknown"}\n`,r+=`Outbound Topic: ${n.outboundTopic||"Unknown"}\n`,r+=`Profile Topic: ${n.profileTopicId||"Unknown"}\n`),i.social&&Object.keys(i.social).length>0&&(r+=`Social: ${Object.entries(i.social).map(([e,t])=>`${e}: ${t}`).join(", ")}\n`),i.properties&&Object.keys(i.properties).length>0&&(r+=`Properties: ${JSON.stringify(i.properties)}\n`),this.executeResult={success:!0,rawResult:{profileDetails:r,rawProfile:t}}}catch(t){this.logger.error(`Unexpected error retrieving profile for ${e.accountId}:`,t),this.executeResult={success:!1,error:`Unexpected error retrieving profile for ${e.accountId}: ${t instanceof Error?t.message:String(t)}`}}return this}async execute(){return this.executeResult?{success:this.executeResult.success,transactionId:this.executeResult.transactionId,receipt:this.executeResult.receipt,scheduleId:this.executeResult.scheduleId,error:this.executeResult.error,rawResult:this.executeResult.rawResult,notes:this.notes}:{success:!1,error:"No operation result available. Call a builder method first."}}}class le extends e.BasePlugin{constructor(){super(...arguments),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="Hashgraph Online",this.tools=[]}async initialize(e){await super.initialize(e),this.initializeTools()}initializeTools(){this.tools=[new e.HederaGetHbarPriceTool({hederaKit:this.context.config.hederaKit,logger:this.context.logger})]}getTools(){return this.tools}}class de extends e.BaseServiceBuilder{constructor(e){super(e)}async getHCS2Client(){if(!this.hcs2Client){const e=this.hederaKit.signer.getAccountId().toString(),i=this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"",n={network:this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",operatorId:e,operatorKey:i};this.hcs2Client=new t.HCS2Client(n)}return this.hcs2Client}async createRegistry(e={}){const t=await this.getHCS2Client();return await t.createRegistry(e)}async registerEntry(e,t){const i=await this.getHCS2Client();return await i.registerEntry(e,t)}async updateEntry(e,t){const i=await this.getHCS2Client();return await i.updateEntry(e,t)}async deleteEntry(e,t){const i=await this.getHCS2Client();return await i.deleteEntry(e,t)}async migrateRegistry(e,t){const i=await this.getHCS2Client();return await i.migrateRegistry(e,t)}async getRegistry(e,t={}){const i=await this.getHCS2Client();return await i.getRegistry(e,t)}async submitMessage(e,t){const i=await this.getHCS2Client();return await i.submitMessage(e,t)}async getTopicInfo(e){const t=await this.getHCS2Client();return await t.getTopicInfo(e)}async close(){this.hcs2Client&&(this.hcs2Client.close(),this.hcs2Client=void 0)}}class ue extends e.BaseServiceBuilder{constructor(e){super(e)}async getHCS6Client(){if(!this.hcs6Client){const e=this.hederaKit.signer.getAccountId().toString(),i=this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toString():"",n={network:this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",operatorId:e,operatorKey:i};this.hcs6Client=new t.HCS6Client(n)}return this.hcs6Client}async createRegistry(e={}){const t=await this.getHCS6Client(),i={...e};return"adminKey"in i&&delete i.adminKey,await t.createRegistry(i)}async registerEntry(e,t){const i=await this.getHCS6Client();return await i.registerEntry(e,t)}async getRegistry(e,t={}){const i=await this.getHCS6Client();return await i.getRegistry(e,t)}async createHashinal(e){const t=await this.getHCS6Client(),i={name:e.metadata?.name||"Dynamic Hashinal",creator:e.metadata?.creator||this.hederaKit.signer.getAccountId().toString(),description:e.metadata?.description||"Dynamic hashinal metadata",type:e.metadata?.type||"json",...e.metadata};return await t.createHashinal({...e,metadata:i})}async register(e){const t=await this.getHCS6Client(),i={name:e.metadata?.name||"Dynamic Hashinal",creator:e.metadata?.creator||this.hederaKit.signer.getAccountId().toString(),description:e.metadata?.description||"Dynamic hashinal registration",type:e.metadata?.type||"json",...e.metadata};return await t.register({...e,metadata:i})}async submitMessage(e,t){const i=await this.getHCS6Client();return await i.submitMessage(e,t)}async getTopicInfo(e){const t=await this.getHCS6Client();return await t.getTopicInfo(e)}async close(){this.hcs6Client&&(this.hcs6Client.close(),this.hcs6Client=void 0)}}class ge extends e.BaseServiceBuilder{constructor(e){super(e)}async getInscriptionSDK(e){return null}async inscribe(e,i){const n={accountId:this.hederaKit.signer.getAccountId().toString(),privateKey:this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"",network:this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet"};return await t.inscribe(e,n,i)}async inscribeWithSigner(e,i,n){return await t.inscribeWithSigner(e,i,n)}async retrieveInscription(e,i){const n=this.hederaKit.signer.getAccountId().toString(),r=this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"";return await t.retrieveInscription(e,{...i,accountId:n,privateKey:r})}async close(){this.inscriptionSDK=void 0}}Object.defineProperty(exports,"BasePlugin",{enumerable:!0,get:()=>e.BasePlugin}),Object.defineProperty(exports,"GetHbarPriceTool",{enumerable:!0,get:()=>e.HederaGetHbarPriceTool}),Object.defineProperty(exports,"PluginRegistry",{enumerable:!0,get:()=>e.PluginRegistry}),exports.AcceptConnectionRequestTool=M,exports.BaseHCS10QueryTool=u,exports.BaseHCS10TransactionTool=d,exports.BaseHCS2QueryTool=B,exports.BaseHCS2TransactionTool=P,exports.BaseHCS6QueryTool=G,exports.BaseHCS6TransactionTool=U,exports.BaseInscriberQueryTool=X,exports.BaseInscriberTransactionTool=Y,exports.CheckMessagesTool=C,exports.ConnectionMonitorTool=S,exports.CreateDynamicRegistryTool=class extends G{constructor(e){super(e),this.name="createDynamicRegistry",this.description="Create a new HCS-6 dynamic registry for managing evolving content"}get specificInputSchema(){return j}async executeQuery(e,t){const i=await this.hcs6Builder.createRegistry({ttl:e.ttl,submitKey:e.submitKey});if(!i.success)throw new Error(i.error||"Failed to create dynamic registry");return`Successfully created HCS-6 dynamic registry!\n\nTopic ID: ${i.topicId}\nTTL: ${e.ttl} seconds\n\nYou can now register dynamic hashinals to this registry using the topic ID.`}},exports.CreateRegistryTool=class extends B{constructor(){super(...arguments),this.name="createHCS2Registry",this.description="Create a new HCS-2 registry topic for storing decentralized data"}get specificInputSchema(){return D}async executeQuery(e,t){try{const t=await this.hcs2Builder.createRegistry({registryType:e.registryType,ttl:e.ttl,adminKey:e.adminKey,submitKey:e.submitKey});if(!t.success)throw new Error(t.error||"Failed to create registry");return`Successfully created HCS-2 registry!\n\nTopic ID: ${t.topicId}\nRegistry Type: ${1===e.registryType?"Non-Indexed":"Indexed"}\nTTL: ${e.ttl||86400} seconds\n\nYou can now register entries to this registry using the topic ID.`}catch(i){const e=i instanceof Error?i.message:"Failed to create HCS-2 registry";throw new Error(`Registry creation failed: ${e}`)}}},exports.DeleteEntryTool=class extends B{constructor(){super(...arguments),this.name="deleteHCS2Entry",this.description="Delete an entry from an indexed HCS-2 registry"}get specificInputSchema(){return L}async executeQuery(e,t){try{const t=await this.hcs2Builder.deleteEntry(e.registryTopicId,{uid:e.uid,memo:e.memo});if(!t.success)throw new Error(t.error||"Failed to delete entry");return`Successfully deleted entry from HCS-2 registry!\n\nRegistry Topic: ${e.registryTopicId}\nUID: ${e.uid}${e.memo?`\nMemo: ${e.memo}`:""}\n\nThe entry has been removed from the registry.`}catch(i){const e=i instanceof Error?i.message:"Failed to delete entry";throw new Error(`Entry deletion failed: ${e}`)}}},exports.FindRegistrationsTool=v,exports.HCS10Builder=ce,exports.HCS10Client=class{constructor(e,i,n,r){this.standardClient=new t.HCS10Client({network:n,operatorId:e,operatorPrivateKey:i,guardedRegistryBaseUrl:r?.registryUrl,logLevel:r?.logLevel}),this.guardedRegistryBaseUrl=r?.registryUrl||"",this.useEncryption=r?.useEncryption||!1;const o="true"===process.env.DISABLE_LOGGING;this.logger=new t.Logger({level:r?.logLevel||"info",silent:o})}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,i,n){try{return await this.standardClient.handleConnectionRequest(e,t,i,n)}catch(r){throw this.logger.error(`Error handling connection request #${i} for topic ${e}:`,r),new Error(`Failed to handle connection request: ${r instanceof Error?r.message:String(r)}`)}}async getAgentProfile(e){return this.standardClient.retrieveProfile(e)}async submitConnectionRequest(e,t){return this.standardClient.submitConnectionRequest(e,t)}async waitForConnectionConfirmation(e,t,i=60,n=2e3){return this.standardClient.waitForConnectionConfirmation(e,t,i,n)}async createAndRegisterAgent(e){const i=(new t.AgentBuilder).setName(e.name).setBio(e.description||"").setCapabilities(e.capabilities?e.capabilities:[t.AIAgentCapability.TEXT_GENERATION]).setType(e.type||"autonomous").setModel(e.model||"agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(t.InboundTopicType.PUBLIC);e?.feeConfig&&(i.setInboundTopicType(t.InboundTopicType.FEE_BASED),i.setFeeConfig(e.feeConfig)),e.pfpBuffer&&e.pfpFileName?0===e.pfpBuffer.byteLength?this.logger.warn("Provided PFP buffer is empty. Skipping profile picture."):(this.logger.info(`Setting profile picture: ${e.pfpFileName} (${e.pfpBuffer.byteLength} bytes)`),i.setProfilePicture(e.pfpBuffer,e.pfpFileName)):this.logger.warn("Profile picture not provided in metadata. Agent creation might fail if required by the underlying SDK builder."),e.social&&Object.entries(e.social).forEach(([e,t])=>{i.addSocial(e,t)}),e.properties&&Object.entries(e.properties).forEach(([e,t])=>{i.addProperty(e,t)});try{const t=Boolean(e?.feeConfig),n=await this.standardClient.createAndRegisterAgent(i,{initialBalance:t?50:void 0});return n?.metadata?.inboundTopicId&&n?.metadata?.outboundTopicId&&(this.agentChannels={inboundTopicId:n.metadata.inboundTopicId,outboundTopicId:n.metadata.outboundTopicId}),n}catch(n){throw this.logger.error("Error during agent creation/registration:",n),new Error(`Failed to create/register agent: ${n instanceof Error?n.message:String(n)}`)}}async sendMessage(e,t,i,n){this.useEncryption;try{const r=await this.standardClient.sendMessage(e,t,i,n);return r.topicSequenceNumber?.toNumber()}catch(r){throw this.logger.error(`Error sending message to topic ${e}:`,r),new Error(`Failed to send message: ${r instanceof Error?r.message:String(r)}`)}}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 i=`Failed to get inbound topic ID for operator ${t}.`;throw e instanceof Error&&e.message.includes("does not have a valid HCS-11 memo")?i+=` 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?i+=` Reason: ${e.message}`:i+=` Unexpected error: ${String(e)}`,new Error(i)}}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(e,i){return this.standardClient=new t.HCS10Client({network:this.getNetwork(),operatorId:e,operatorPrivateKey:i,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}},exports.HCS2Builder=de,exports.HCS6Builder=ue,exports.HbarPricePlugin=le,exports.InitiateConnectionTool=b,exports.InscribeFromBufferTool=class extends X{constructor(){super(...arguments),this.name="inscribeFromBuffer",this.description='Inscribe content that you have already retrieved or displayed. When user says "inscribe it" after you showed search results or other content, use THIS tool. The base64Data field accepts PLAIN TEXT (not just base64) and content reference IDs in format "content-ref:[id]". Pass the EXACT content from your previous response or MCP tool output. DO NOT generate new content or create repetitive text. Content references are automatically resolved to the original content for inscription. Set quoteOnly=true to get cost estimates without executing the inscription.',this.config=te()}get specificInputSchema(){return ie}async executeQuery(e,t){this.validateInput(e);const i=await this.resolveContent(e.base64Data,e.mimeType,e.fileName);this.validateContent(i.buffer);const n=i.buffer,r=i.mimeType||e.mimeType,o=i.fileName||e.fileName,s={mode:e.mode,metadata:e.metadata,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:!e.quoteOnly&&(e.waitForConfirmation??!0),waitMaxAttempts:10,waitIntervalMs:3e3,apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",quoteOnly:e.quoteOnly};if(e.quoteOnly)try{const e=await this.generateInscriptionQuote({type:"buffer",buffer:n,fileName:o,mimeType:r},s);return{success:!0,quote:{totalCostHbar:e.totalCostHbar,validUntil:e.validUntil,breakdown:e.breakdown},contentInfo:{fileName:o,mimeType:r,sizeBytes:n.length},message:`Quote generated for buffer content: ${o} (${(n.length/1024).toFixed(2)} KB)\nTotal cost: ${e.totalCostHbar} HBAR`}}catch(c){const e=c instanceof Error?c.message:"Failed to generate inscription quote";throw new Error(`Quote generation failed: ${e}`)}const a=e.timeoutMs||(s.waitForConfirmation?6e4:void 0);try{const e=await this.executeInscription(n,o,r,s,a);return this.formatInscriptionResult(e,s)}catch(c){const e=c instanceof Error?c.message:"Failed to inscribe from buffer";throw new Error(`Inscription failed: ${e}`)}}validateInput(e){if(!e.base64Data||""===e.base64Data.trim())throw new Error("No data provided. Cannot inscribe empty content. Please provide valid content, plain text, base64 encoded data, or a content reference ID.");if(!e.fileName||""===e.fileName.trim())throw new Error("No fileName provided. A valid fileName is required for inscription.")}validateContent(e){if(0===e.length)throw new Error("Buffer is empty after conversion. The provided data appears to be invalid or empty.");if(e.length>this.config.maxInscriptionSize){const t=Math.round(this.config.maxInscriptionSize/1024),i=Math.round(e.length/1024);throw new Error(`Content is too large for inscription (${i}KB, max ${t}KB). Please summarize or extract key information before inscribing.`)}if(e.length<this.config.minContentSize)throw new Error(`Buffer content is too small (${e.length} bytes). This may indicate empty or invalid content. Please verify the source data contains actual content.`);if(""===e.toString("utf8",0,Math.min(e.length,100)).trim())throw new Error("Buffer contains only whitespace or empty content. Cannot inscribe meaningless data.");const t=e.toString("utf8");if(/<a\s+href=["'][^"']+["']\s*>\s*<\/a>/i.test(t)&&t.replace(/<[^>]+>/g,"").trim().length<50)throw new Error("Buffer contains empty HTML with only links and no actual content. When inscribing content from external sources, use the actual article text you retrieved, not empty HTML with links.")}async executeInscription(e,t,i,n,r){const o={type:"buffer",buffer:e,fileName:t,mimeType:i};if(r){const e=new Promise((e,t)=>{setTimeout(()=>t(new Error(`Inscription timed out after ${r}ms`)),r)});return Promise.race([this.inscriberBuilder.inscribe(o,n),e])}return this.inscriberBuilder.inscribe(o,n)}formatInscriptionResult(e,t){if(e.confirmed&&!e.quote){const i=e.inscription?.topic_id||e.result.topicId,n=t.network||"testnet",r=i?`https://kiloscribe.com/api/inscription-cdn/${i}?network=${n}`:null;return`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${e.result.transactionId}\nTopic ID: ${i||"N/A"}${r?`\nView inscription: ${r}`:""}\n\nThe inscription is now available.`}return e.quote||e.confirmed?"Inscription operation completed.":`Successfully submitted inscription to the Hedera network!\n\nTransaction ID: ${e.result.transactionId}\n\nThe inscription is processing and will be confirmed shortly.`}async resolveContent(e,i,n){const r=e.trim(),o=this.getContentResolver()||t.ContentResolverRegistry.getResolver();if(!o)return this.handleDirectContent(r,i,n);const s=o.extractReferenceId(r);if(s)try{const e=await o.resolveReference(s);return{buffer:e.content,mimeType:e.metadata?.mimeType||i,fileName:e.metadata?.fileName||n,wasReference:!0}}catch(a){const e=a instanceof Error?a.message:"Unknown error resolving reference";throw new Error(`Reference resolution failed: ${e}`)}return this.handleDirectContent(r,i,n)}handleDirectContent(e,t,i){if(/^[A-Za-z0-9+/]*={0,2}$/.test(e))try{return{buffer:globalThis.Buffer.from(e,"base64"),mimeType:t,fileName:i,wasReference:!1}}catch(n){throw new Error("Failed to decode base64 data. Please ensure the data is properly encoded.")}return{buffer:globalThis.Buffer.from(e,"utf8"),mimeType:t||"text/plain",fileName:i,wasReference:!1}}},exports.InscribeFromFileTool=class extends X{constructor(){super(...arguments),this.name="inscribeFromFile",this.description="Inscribe content from a local file to the Hedera network using a file path. IMPORTANT: Only use this tool when you have a valid file path to actual content. The file must exist and contain meaningful data (minimum 10 bytes). For files accessed through MCP filesystem tools, consider reading the file content first and using inscribeFromBuffer instead. Set quoteOnly=true to get cost estimates without executing the inscription."}get specificInputSchema(){return Z}async executeQuery(e,t){let i;console.log(`[DEBUG] InscribeFromFileTool.executeQuery called with: ${e.filePath}`);try{console.log(`[DEBUG] Checking file: ${e.filePath}`),console.log(`[DEBUG] Current working directory: ${process.cwd()}`);const t=await l.stat(e.filePath);if(!t.isFile())throw new Error(`Path "${e.filePath}" is not a file`);if(console.log(`[DEBUG] File size: ${t.size} bytes`),0===t.size)throw new Error(`File "${e.filePath}" is empty (0 bytes). Cannot inscribe empty files.`);if(t.size<10)throw new Error(`File "${e.filePath}" is too small (${t.size} bytes). Files must contain at least 10 bytes of meaningful content.`);if(t.size>104857600&&console.log(`[InscribeFromFileTool] WARNING: Large file detected (${(t.size/1048576).toFixed(2)} MB)`),this.logger?.info("Reading file content..."),i=await l.readFile(e.filePath),this.logger?.info(`Read ${i.length} bytes from file`),!i||0===i.length)throw new Error(`File "${e.filePath}" has no content after reading. Cannot inscribe empty files.`);if(i.length<10)throw new Error(`File "${e.filePath}" content is too small (${i.length} bytes). Files must contain at least 10 bytes of meaningful content.`);const n=c.basename(e.filePath),r=this.getMimeType(n);if(r.startsWith("text/")||"application/json"===r){if(""===i.toString("utf8",0,Math.min(i.length,1e3)).trim())throw new Error(`File "${e.filePath}" contains only whitespace or empty content. Cannot inscribe meaningless data.`)}}catch(a){if(a instanceof Error){if(a.message.includes("ENOENT"))throw new Error(`File not found: "${e.filePath}"`);throw a}throw new Error(`Failed to read file: ${a}`)}const n=i.toString("base64");this.logger?.info(`Converted to base64: ${n.length} characters`);const r=c.basename(e.filePath),o=this.getMimeType(r);this.logger?.info(`File: ${r}, MIME type: ${o}`);const s={mode:e.mode,metadata:e.metadata,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:!e.quoteOnly&&(e.waitForConfirmation??!0),waitMaxAttempts:10,waitIntervalMs:3e3,apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",quoteOnly:e.quoteOnly};if(e.quoteOnly)try{const t=await this.generateInscriptionQuote({type:"buffer",buffer:globalThis.Buffer.from(n,"base64"),fileName:r,mimeType:o},s);return{success:!0,quote:{totalCostHbar:t.totalCostHbar,validUntil:t.validUntil,breakdown:t.breakdown},contentInfo:{fileName:r,mimeType:o,sizeBytes:i.length,filePath:e.filePath},message:`Quote generated for file: ${r} (${(i.length/1024).toFixed(2)} KB)\nTotal cost: ${t.totalCostHbar} HBAR`}}catch(a){const e=a instanceof Error?a.message:"Failed to generate inscription quote";throw new Error(`Quote generation failed: ${e}`)}try{let t;if(e.timeoutMs){const i=new Promise((t,i)=>{setTimeout(()=>i(new Error(`Inscription timed out after ${e.timeoutMs}ms`)),e.timeoutMs)});t=await Promise.race([this.inscriberBuilder.inscribe({type:"buffer",buffer:globalThis.Buffer.from(n,"base64"),fileName:r,mimeType:o},s),i])}else t=await this.inscriberBuilder.inscribe({type:"buffer",buffer:globalThis.Buffer.from(n,"base64"),fileName:r,mimeType:o},s);const i=t;if(i.confirmed&&!i.quote){const e=i.inscription?.topic_id||i.result.topicId,t=e?`https://kiloscribe.com/api/inscription-cdn/${e}?network=${s.network||"testnet"}`:null;return`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${i.result.transactionId}\nTopic ID: ${e||"N/A"}${t?`\nView inscription: ${t}`:""}\n\nThe inscription is now available.`}return i.quote||i.confirmed?"Inscription operation completed.":`Successfully submitted inscription to the Hedera network!\n\nTransaction ID: ${i.result.transactionId}\n\nThe inscription is processing and will be confirmed shortly.`}catch(a){const e=a instanceof Error?a.message:"Failed to inscribe from file";throw new Error(`Inscription failed: ${e}`)}}getMimeType(e){return{".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".pdf":"application/pdf",".json":"application/json",".txt":"text/plain",".html":"text/html",".css":"text/css",".js":"application/javascript",".ts":"application/typescript",".mp4":"video/mp4",".mp3":"audio/mpeg",".wav":"audio/wav",".zip":"application/zip"}[c.extname(e).toLowerCase()]||"application/octet-stream"}},exports.InscribeFromUrlTool=class extends X{constructor(){super(...arguments),this.name="inscribeFromUrl",this.description='ONLY for direct FILE DOWNLOAD URLs ending with file extensions (.pdf, .jpg, .png, .json, .zip). NEVER use for web pages, articles, or ANY HTML content - it WILL FAIL. If you have already retrieved content from any source (including MCP tools), you MUST use inscribeFromBuffer instead. This tool downloads files from URLs - it does NOT inscribe content you already have. When asked to "inscribe it" after retrieving content, ALWAYS use inscribeFromBuffer with the actual content. Set quoteOnly=true to get cost estimates without executing the inscription.'}get specificInputSchema(){return J}async executeQuery(e,t){if(console.log(`[DEBUG] InscribeFromUrlTool.executeQuery called with URL: ${e.url}`),!e.url||""===e.url.trim())throw new Error("URL cannot be empty. Please provide a valid URL.");try{const t=new URL(e.url);if(!t.protocol||!t.host)throw new Error("Invalid URL format. Please provide a complete URL with protocol (http/https).");if(!["http:","https:"].includes(t.protocol))throw new Error("Only HTTP and HTTPS URLs are supported for inscription.")}catch(n){if(n instanceof Error&&n.message.includes("Cannot inscribe content from"))throw n;throw new Error(`Invalid URL: ${e.url}. Please provide a valid URL.`)}console.log("[InscribeFromUrlTool] Validating URL content before inscription...");try{const t=new AbortController,i=setTimeout(()=>t.abort(),1e4);try{const n=await fetch(e.url,{method:"HEAD",signal:t.signal});if(clearTimeout(i),!n.ok)throw new Error(`URL returned error status ${n.status}: ${n.statusText}. Cannot inscribe content from inaccessible URLs.`);const o=n.headers.get("content-type")||"",s=n.headers.get("content-length");if(["text/html","application/xhtml+xml","text/xml"].some(e=>o.toLowerCase().includes(e)))throw new Error(`URL returns HTML/web page content (Content-Type: ${o}). This tool only works with direct file URLs (PDFs, images, JSON, etc.). For web page content, first retrieve the content using the appropriate MCP tool or web scraper, then use inscribeFromBuffer to inscribe it.`);if(s&&0===parseInt(s))throw new Error("URL returns empty content (Content-Length: 0). Cannot inscribe empty content.");if(s&&parseInt(s)<10)throw new Error(`URL content is too small (${s} bytes). Content must be at least 10 bytes.`);if(!o||"application/octet-stream"===o){console.log("[InscribeFromUrlTool] Content-Type unclear, fetching first 1KB to verify...");const t=new AbortController,i=setTimeout(()=>t.abort(),5e3);try{const n=await fetch(e.url,{signal:t.signal,headers:{Range:"bytes=0-1023"}});if(clearTimeout(i),n.ok||206===n.status){const e=await n.arrayBuffer(),t=new Uint8Array(e),i=new TextDecoder("utf-8",{fatal:!1}).decode(t.slice(0,512));if(i.toLowerCase().includes("<!doctype html")||i.toLowerCase().includes("<html")||i.match(/<meta\s+[^>]*>/i)||i.match(/<title>/i))throw new Error("URL returns HTML content. This tool only works with direct file URLs. For web page content, first retrieve it using the appropriate tool, then use inscribeFromBuffer.")}}catch(r){if(clearTimeout(i),r instanceof Error&&r.message.includes("HTML content"))throw r;console.log(`[InscribeFromUrlTool] Could not perform partial GET validation: ${r instanceof Error?r.message:"Unknown error"}`)}}console.log(`[InscribeFromUrlTool] URL validation passed. Content-Type: ${o}, Content-Length: ${s||"unknown"}`)}catch(o){throw clearTimeout(i),o}}catch(n){if(n instanceof Error)if("AbortError"===n.name)console.log("[InscribeFromUrlTool] Warning: URL validation timed out after 10 seconds. Proceeding with inscription attempt.");else{if(n.message.includes("URL returned error")||n.message.includes("empty content")||n.message.includes("too small")||n.message.includes("HTML"))throw n;console.log(`[InscribeFromUrlTool] Warning: Could not validate URL with HEAD request: ${n.message}. Proceeding with inscription attempt.`)}}const i={mode:e.mode,metadata:e.metadata,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:!e.quoteOnly&&(e.waitForConfirmation??!0),waitMaxAttempts:10,waitIntervalMs:3e3,apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",quoteOnly:e.quoteOnly};if(e.quoteOnly)try{const t=await this.generateInscriptionQuote({type:"url",url:e.url},i);return{success:!0,quote:{totalCostHbar:t.totalCostHbar,validUntil:t.validUntil,breakdown:t.breakdown},contentInfo:{url:e.url},message:`Quote generated for URL: ${e.url}\nTotal cost: ${t.totalCostHbar} HBAR`}}catch(n){const e=n instanceof Error?n.message:"Failed to generate inscription quote";throw new Error(`Quote generation failed: ${e}`)}try{let t;if(e.timeoutMs){const n=new Promise((t,i)=>{setTimeout(()=>i(new Error(`Inscription timed out after ${e.timeoutMs}ms`)),e.timeoutMs)});t=await Promise.race([this.inscriberBuilder.inscribe({type:"url",url:e.url},i),n])}else t=await this.inscriberBuilder.inscribe({type:"url",url:e.url},i);if(t.confirmed&&!t.quote){const e=t.inscription?.topic_id||t.result.topicId,n=e?`https://kiloscribe.com/api/inscription-cdn/${e}?network=${i.network||"testnet"}`:null;return`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${t.result.transactionId}\nTopic ID: ${e||"N/A"}${n?`\nView inscription: ${n}`:""}\n\nThe inscription is now available.`}return t.quote||t.confirmed?"Inscription operation completed.":`Successfully submitted inscription to the Hedera network!\n\nTransaction ID: ${t.result.transactionId}\n\nThe inscription is processing and will be confirmed shortly.`}catch(n){const e=n instanceof Error?n.message:"Failed to inscribe from URL";throw new Error(`Inscription failed: ${e}`)}}},exports.InscribeHashinalTool=class extends X{constructor(){super(...arguments),this.name="inscribeHashinal",this.description="Inscribe content as a Hashinal NFT on the Hedera network. Set quoteOnly=true to get cost estimates without executing the inscription."}get specificInputSchema(){return ne}async executeQuery(e,t){const i={mode:"hashinal",metadata:{name:e.name,creator:e.creator,description:e.description,type:e.type,attributes:e.attributes,properties:e.properties},jsonFileURL:e.jsonFileURL,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:!e.quoteOnly&&(e.waitForConfirmation??!0),waitMaxAttempts:10,waitIntervalMs:3e3,apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",quoteOnly:e.quoteOnly};if(e.quoteOnly)try{const t=await this.generateInscriptionQuote({type:"url",url:e.url},i);return{success:!0,quote:{totalCostHbar:t.totalCostHbar,validUntil:t.validUntil,breakdown:t.breakdown},contentInfo:{url:e.url,name:e.name,creator:e.creator,type:e.type},message:`Quote generated for Hashinal NFT: ${e.name}\nCreator: ${e.creator}\nTotal cost: ${t.totalCostHbar} HBAR`}}catch(n){const e=n instanceof Error?n.message:"Failed to generate inscription quote";throw new Error(`Quote generation failed: ${e}`)}try{let t;if(e.timeoutMs){const n=new Promise((t,i)=>{setTimeout(()=>i(new Error(`Inscription timed out after ${e.timeoutMs}ms`)),e.timeoutMs)});t=await Promise.race([this.inscriberBuilder.inscribe({type:"url",url:e.url},i),n])}else t=await this.inscriberBuilder.inscribe({type:"url",url:e.url},i);if(t.confirmed&&!t.quote){const e=t.inscription?.topic_id||t.result.topicId,n=e?`https://kiloscribe.com/api/inscription-cdn/${e}?network=${i.network||"testnet"}`:null;return`Successfully inscribed and confirmed Hashinal NFT on the Hedera network!\n\nTransaction ID: ${t.result.transactionId}\nTopic ID: ${e||"N/A"}${n?`\nView inscription: ${n}`:""}\n\nThe Hashinal NFT is now available.`}return t.quote||t.confirmed?"Inscription operation completed.":`Successfully submitted Hashinal NFT inscription to the Hedera network!\n\nTransaction ID: ${t.result.transactionId}\n\nThe inscription is processing and will be confirmed shortly.`}catch(n){const e=n instanceof Error?n.message:"Failed to inscribe Hashinal NFT";throw new Error(`Inscription failed: ${e}`)}}},exports.InscriberBuilder=ge,exports.ListConnectionsTool=T,exports.ListUnapprovedConnectionRequestsTool=k,exports.ManageConnectionRequestsTool=$,exports.MigrateRegistryTool=class extends B{constructor(){super(...arguments),this.name="migrateHCS2Registry",this.description="Migrate an HCS-2 registry to a new topic"}get specificInputSchema(){return H}async executeQuery(e,t){try{const t=await this.hcs2Builder.migrateRegistry(e.registryTopicId,{targetTopicId:e.targetTopicId,metadata:e.metadata,memo:e.memo});if(!t.success)throw new Error(t.error||"Failed to migrate registry");return`Successfully migrated HCS-2 registry!\n\nFrom Registry Topic: ${e.registryTopicId}\nTo Target Topic: ${e.targetTopicId}${e.metadata?`\nMetadata: ${e.metadata}`:""}${e.memo?`\nMemo: ${e.memo}`:""}\n\nThe registry has been migrated to the new topic.`}catch(i){const e=i instanceof Error?i.message:"Failed to migrate registry";throw new Error(`Registry migration failed: ${e}`)}}},exports.NaturalLanguageMapper=p,exports.OpenConvaiState=se,exports.QueryDynamicRegistryTool=class extends G{constructor(e){super(e),this.name="queryDynamicRegistry",this.description="Query a dynamic registry to get the current state of a dynamic hashinal"}get specificInputSchema(){return V}async executeQuery(e,t){const i=await this.hcs6Builder.getRegistry(e.topicId,{limit:e.limit,order:e.order,skip:e.skip}),n=i.latestEntry?{topicId:i.latestEntry.message.t_id,timestamp:i.latestEntry.timestamp,memo:i.latestEntry.message.m,sequence:i.latestEntry.sequence,payer:i.latestEntry.payer}:null;return`Successfully queried dynamic registry!\n\nRegistry Topic: ${i.topicId}\nRegistry Type: NON_INDEXED\nTTL: ${i.ttl} seconds\nTotal Entries: ${i.entries.length}${n?`\n\nLatest Entry:\n- Topic ID: ${n.topicId}\n- Timestamp: ${n.timestamp}\n- Memo: ${n.memo||"N/A"}\n- Sequence: ${n.sequence}`:"\n\nNo entries found in registry."}`}},exports.QueryRegistryTool=class extends B{constructor(){super(...arguments),this.name="queryHCS2Registry",this.description="Query entries from an HCS-2 registry"}get specificInputSchema(){return K}async executeQuery(e,t){const i=await this.hcs2Builder.getRegistry(e.topicId,{limit:e.limit,order:e.order,skip:e.skip});return{topicId:i.topicId,registryType:0===i.registryType?"indexed":"non-indexed",ttl:i.ttl,totalEntries:i.entries.length,entries:i.entries.map(e=>({sequence:e.sequence,timestamp:e.timestamp,payer:e.payer,operation:e.message.op,targetTopicId:e.message.t_id,uid:e.message.uid,metadata:e.message.metadata,memo:e.message.m}))}}},exports.RegisterAgentTool=m,exports.RegisterDynamicHashinalTool=class extends G{constructor(e){super(e),this.name="registerDynamicHashinal",this.description="Create and register a new dynamic hashinal that can be updated over time"}get specificInputSchema(){return Q}async executeQuery(e,t){const i=await this.hcs6Builder.register({metadata:e.metadata,data:e.data,memo:e.memo,ttl:e.ttl,registryTopicId:e.registryTopicId,submitKey:e.submitKey});if(!i.success)throw new Error(i.error||"Failed to register dynamic hashinal");return`Successfully registered dynamic hashinal!\n\nRegistry Topic ID: ${i.registryTopicId}\nInscription Topic ID: ${i.inscriptionTopicId}${e.memo?`\nMemo: ${e.memo}`:""}\n\nThe dynamic hashinal has been created and can be updated using the registry topic ID.`}},exports.RegisterEntryTool=class extends B{constructor(){super(...arguments),this.name="registerHCS2Entry",this.description="Register a new entry in an HCS-2 registry"}get specificInputSchema(){return F}async executeQuery(e,t){try{const t=await this.hcs2Builder.registerEntry(e.registryTopicId,{targetTopicId:e.targetTopicId,metadata:e.metadata,memo:e.memo});if(!t.success)throw new Error(t.error||"Failed to register entry");return`Successfully registered entry in HCS-2 registry!\n\nRegistry Topic: ${e.registryTopicId}\nTarget Topic ID: ${e.targetTopicId}${e.metadata?`\nMetadata: ${e.metadata}`:""}${e.memo?`\nMemo: ${e.memo}`:""}\n\nThe entry has been added to the registry.`}catch(i){const e=i instanceof Error?i.message:"Failed to register entry";throw new Error(`Entry registration failed: ${e}`)}}},exports.RetrieveInscriptionTool=class extends X{constructor(){super(...arguments),this.name="retrieveInscription",this.description="Retrieve details of an existing inscription from the Hedera network"}get specificInputSchema(){return re}async executeQuery(e,t){const i=await this.inscriberBuilder.retrieveInscription(e.transactionId,{apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet"});return{inscriptionId:i.inscriptionId,transactionId:i.transactionId,topicId:i.topic_id,status:i.status,holderId:i.holderId,metadata:i.metadata,tags:i.tags,mode:i.mode,chunks:i.chunks,createdAt:i.createdAt,completedAt:i.completed||i.completedAt,fileUrl:i.fileUrl,mimeType:i.mimeType,fileSize:i.fileSize}}},exports.RetrieveProfileTool=z,exports.SendMessageToConnectionTool=y,exports.UpdateDynamicHashinalTool=class extends G{constructor(e){super(e),this.name="updateDynamicHashinal",this.description="Update an existing dynamic hashinal with new content while maintaining the same registry"}get specificInputSchema(){return W}async executeQuery(e,t){const i=await this.hcs6Builder.register({metadata:e.metadata,data:e.data,memo:e.memo,registryTopicId:e.registryTopicId,submitKey:e.submitKey});if(!i.success)throw new Error(i.error||"Failed to update dynamic hashinal");return`Successfully updated dynamic hashinal!\n\nRegistry Topic ID: ${e.registryTopicId}\nInscription Topic ID: ${i.inscriptionTopicId}${e.memo?`\nUpdate Memo: ${e.memo}`:""}\n\nThe dynamic hashinal has been updated with new content.`}},exports.UpdateEntryTool=class extends B{constructor(){super(...arguments),this.name="updateHCS2Entry",this.description="Update an existing entry in an indexed HCS-2 registry"}get specificInputSchema(){return _}async executeQuery(e,t){try{const t=await this.hcs2Builder.updateEntry(e.registryTopicId,{targetTopicId:e.targetTopicId,uid:e.uid,metadata:e.metadata,memo:e.memo});if(!t.success)throw new Error(t.error||"Failed to update entry");return`Successfully updated entry in HCS-2 registry!\n\nRegistry Topic: ${e.registryTopicId}\nUID: ${e.uid}\nNew Target Topic ID: ${e.targetTopicId}${e.metadata?`\nMetadata: ${e.metadata}`:""}${e.memo?`\nMemo: ${e.memo}`:""}\n\nThe entry has been updated in the registry.`}catch(i){const e=i instanceof Error?i.message:"Failed to update entry";throw new Error(`Entry update failed: ${e}`)}}},exports.initializeStandardsAgentKit=async i=>{const n=i?.clientConfig||{},r=n.operatorId||process.env.HEDERA_OPERATOR_ID,o=n.operatorKey||process.env.HEDERA_OPERATOR_KEY,s=n.network||process.env.HEDERA_NETWORK||"testnet";let a;if("mainnet"===s?a="mainnet":("testnet"===s||console.warn(`Unsupported network specified: '${s}'. Defaulting to 'testnet'.`),a="testnet"),!r||!o)throw new Error("Operator ID and private key must be provided either through options or environment variables.");const c="true"===process.env.DISABLE_LOGGING,l=t.Logger.getInstance({level:n.logLevel||"info",silent:c}),d=i?.stateManager||new se({defaultEnvFilePath:oe,defaultPrefix:"TODD"});l.info("State manager initialized");const u=new e.ServerSigner(r,o,a),g=new e.HederaAgentKit(u);await g.initialize(),l.info(`HederaAgentKit initialized for ${r} on ${a}`);const p=new ce(g,d,{useEncryption:n.useEncryption,registryUrl:n.registryUrl,logLevel:n.logLevel});let h,f;if(i?.monitoringClient){const t=new e.ServerSigner(r,o,a);h=new e.HederaAgentKit(t),await h.initialize(),f=new ce(h,d,{useEncryption:n.useEncryption,registryUrl:n.registryUrl,logLevel:"error"}),l.info("Monitoring client initialized")}const I={};return I.registerAgentTool=new m({hederaKit:g,hcs10Builder:p,logger:void 0}),i?.createAllTools&&(I.findRegistrationsTool=new v({hederaKit:g,hcs10Builder:p,logger:void 0}),I.retrieveProfileTool=new z({hederaKit:g,hcs10Builder:p,logger:void 0}),I.initiateConnectionTool=new b({hederaKit:g,hcs10Builder:p,logger:void 0}),I.listConnectionsTool=new T({hederaKit:g,hcs10Builder:p,logger:void 0}),I.sendMessageToConnectionTool=new y({hederaKit:g,hcs10Builder:p,logger:void 0}),I.checkMessagesTool=new C({hederaKit:g,hcs10Builder:p,logger:void 0}),I.connectionMonitorTool=new S({hederaKit:h||g,hcs10Builder:f||p,logger:void 0}),I.manageConnectionRequestsTool=new $({hederaKit:g,hcs10Builder:p,logger:void 0}),I.acceptConnectionRequestTool=new M({hederaKit:g,hcs10Builder:p,logger:void 0}),I.listUnapprovedConnectionRequestsTool=new k({hederaKit:g,hcs10Builder:p,logger:void 0}),l.info("All tools initialized")),{hederaKit:g,hcs10Builder:p,monitoringHederaKit:h,monitoringHcs10Builder:f,tools:I,stateManager:d}},exports.loadConfig=te;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("hedera-agent-kit"),t=require("@hashgraphonline/standards-sdk"),i=require("fs"),n=require("path"),r=require("axios"),o=require("zod"),s=require("fs/promises");function a(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const i in e)if("default"!==i){const n=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,n.get?n:{enumerable:!0,get:()=>e[i]})}return t.default=e,Object.freeze(t)}const c=a(n),l=a(s);class d extends e.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}class u extends e.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}const g=class{static parseCapabilities(e){if(!e)return[t.AIAgentCapability.TEXT_GENERATION];const i=e.toLowerCase(),n=new Set;for(const[t,r]of Object.entries(this.CAPABILITY_MAPPINGS))i.includes(t)&&r.forEach(e=>n.add(e));return 0===n.size&&n.add(t.AIAgentCapability.TEXT_GENERATION),Array.from(n)}static parseTagsOrCapabilities(e){if(Array.isArray(e)&&e.every(e=>"number"==typeof e))return e;if(Array.isArray(e)&&e.every(e=>"string"==typeof e)){const t=new Set;return e.forEach(e=>{this.parseCapabilities(e).forEach(e=>t.add(e))}),Array.from(t)}return"string"==typeof e?this.parseCapabilities(e):[t.AIAgentCapability.TEXT_GENERATION]}static getCapabilityName(e){return{[t.AIAgentCapability.TEXT_GENERATION]:"Text Generation",[t.AIAgentCapability.IMAGE_GENERATION]:"Image Generation",[t.AIAgentCapability.AUDIO_GENERATION]:"Audio Generation",[t.AIAgentCapability.VIDEO_GENERATION]:"Video Generation",[t.AIAgentCapability.CODE_GENERATION]:"Code Generation",[t.AIAgentCapability.LANGUAGE_TRANSLATION]:"Language Translation",[t.AIAgentCapability.SUMMARIZATION_EXTRACTION]:"Summarization & Extraction",[t.AIAgentCapability.KNOWLEDGE_RETRIEVAL]:"Knowledge Retrieval",[t.AIAgentCapability.DATA_INTEGRATION]:"Data Integration",[t.AIAgentCapability.MARKET_INTELLIGENCE]:"Market Intelligence",[t.AIAgentCapability.TRANSACTION_ANALYTICS]:"Transaction Analytics",[t.AIAgentCapability.SMART_CONTRACT_AUDIT]:"Smart Contract Audit",[t.AIAgentCapability.GOVERNANCE_FACILITATION]:"Governance Facilitation",[t.AIAgentCapability.SECURITY_MONITORING]:"Security Monitoring",[t.AIAgentCapability.COMPLIANCE_ANALYSIS]:"Compliance Analysis",[t.AIAgentCapability.FRAUD_DETECTION]:"Fraud Detection",[t.AIAgentCapability.MULTI_AGENT_COORDINATION]:"Multi-Agent Coordination",[t.AIAgentCapability.API_INTEGRATION]:"API Integration",[t.AIAgentCapability.WORKFLOW_AUTOMATION]:"Workflow Automation"}[e]||"Unknown Capability"}};g.CAPABILITY_MAPPINGS={ai:[t.AIAgentCapability.TEXT_GENERATION],"artificial intelligence":[t.AIAgentCapability.TEXT_GENERATION],chat:[t.AIAgentCapability.TEXT_GENERATION],conversation:[t.AIAgentCapability.TEXT_GENERATION],text:[t.AIAgentCapability.TEXT_GENERATION],"text generation":[t.AIAgentCapability.TEXT_GENERATION],image:[t.AIAgentCapability.IMAGE_GENERATION],picture:[t.AIAgentCapability.IMAGE_GENERATION],visual:[t.AIAgentCapability.IMAGE_GENERATION],photo:[t.AIAgentCapability.IMAGE_GENERATION],audio:[t.AIAgentCapability.AUDIO_GENERATION],sound:[t.AIAgentCapability.AUDIO_GENERATION],voice:[t.AIAgentCapability.AUDIO_GENERATION],speech:[t.AIAgentCapability.AUDIO_GENERATION],video:[t.AIAgentCapability.VIDEO_GENERATION],movie:[t.AIAgentCapability.VIDEO_GENERATION],animation:[t.AIAgentCapability.VIDEO_GENERATION],code:[t.AIAgentCapability.CODE_GENERATION],programming:[t.AIAgentCapability.CODE_GENERATION],development:[t.AIAgentCapability.CODE_GENERATION],coding:[t.AIAgentCapability.CODE_GENERATION],translate:[t.AIAgentCapability.LANGUAGE_TRANSLATION],translation:[t.AIAgentCapability.LANGUAGE_TRANSLATION],language:[t.AIAgentCapability.LANGUAGE_TRANSLATION],summarize:[t.AIAgentCapability.SUMMARIZATION_EXTRACTION],summary:[t.AIAgentCapability.SUMMARIZATION_EXTRACTION],extract:[t.AIAgentCapability.SUMMARIZATION_EXTRACTION],extraction:[t.AIAgentCapability.SUMMARIZATION_EXTRACTION],knowledge:[t.AIAgentCapability.KNOWLEDGE_RETRIEVAL],search:[t.AIAgentCapability.KNOWLEDGE_RETRIEVAL],retrieve:[t.AIAgentCapability.KNOWLEDGE_RETRIEVAL],lookup:[t.AIAgentCapability.KNOWLEDGE_RETRIEVAL],data:[t.AIAgentCapability.DATA_INTEGRATION],"data processing":[t.AIAgentCapability.DATA_INTEGRATION],"data integration":[t.AIAgentCapability.DATA_INTEGRATION],etl:[t.AIAgentCapability.DATA_INTEGRATION],market:[t.AIAgentCapability.MARKET_INTELLIGENCE],trading:[t.AIAgentCapability.MARKET_INTELLIGENCE],finance:[t.AIAgentCapability.MARKET_INTELLIGENCE],financial:[t.AIAgentCapability.MARKET_INTELLIGENCE],analytics:[t.AIAgentCapability.TRANSACTION_ANALYTICS],analysis:[t.AIAgentCapability.TRANSACTION_ANALYTICS],analyze:[t.AIAgentCapability.TRANSACTION_ANALYTICS],transactions:[t.AIAgentCapability.TRANSACTION_ANALYTICS],audit:[t.AIAgentCapability.SMART_CONTRACT_AUDIT],contract:[t.AIAgentCapability.SMART_CONTRACT_AUDIT],"smart contract":[t.AIAgentCapability.SMART_CONTRACT_AUDIT],governance:[t.AIAgentCapability.GOVERNANCE_FACILITATION],voting:[t.AIAgentCapability.GOVERNANCE_FACILITATION],dao:[t.AIAgentCapability.GOVERNANCE_FACILITATION],security:[t.AIAgentCapability.SECURITY_MONITORING],monitoring:[t.AIAgentCapability.SECURITY_MONITORING],threat:[t.AIAgentCapability.SECURITY_MONITORING],compliance:[t.AIAgentCapability.COMPLIANCE_ANALYSIS],regulatory:[t.AIAgentCapability.COMPLIANCE_ANALYSIS],regulation:[t.AIAgentCapability.COMPLIANCE_ANALYSIS],fraud:[t.AIAgentCapability.FRAUD_DETECTION],detection:[t.AIAgentCapability.FRAUD_DETECTION],anomaly:[t.AIAgentCapability.FRAUD_DETECTION],coordination:[t.AIAgentCapability.MULTI_AGENT_COORDINATION],"multi-agent":[t.AIAgentCapability.MULTI_AGENT_COORDINATION],orchestration:[t.AIAgentCapability.MULTI_AGENT_COORDINATION],api:[t.AIAgentCapability.API_INTEGRATION],integration:[t.AIAgentCapability.API_INTEGRATION],webhook:[t.AIAgentCapability.API_INTEGRATION],workflow:[t.AIAgentCapability.WORKFLOW_AUTOMATION],automation:[t.AIAgentCapability.WORKFLOW_AUTOMATION],process:[t.AIAgentCapability.WORKFLOW_AUTOMATION]};let p=g;const h=o.z.object({name:o.z.string().min(1).max(50).describe("A unique name for the agent (1-50 characters)"),description:o.z.string().max(500).optional().describe("Optional bio description for the agent (max 500 characters)"),alias:o.z.string().optional().transform(e=>{if(!e||e.toLowerCase().includes("random")){return`bot${Date.now().toString(36)}${Math.random().toString(36)}`}return e}).describe('Optional custom username/alias for the agent. Use "random" to generate a unique alias'),type:o.z.enum(["autonomous","manual"]).optional().describe("Agent type (default: autonomous)"),model:o.z.string().optional().describe("AI model identifier (default: agent-model-2024)"),capabilities:o.z.union([o.z.array(o.z.nativeEnum(t.AIAgentCapability)),o.z.array(o.z.string()),o.z.string()]).optional().transform(e=>{if(e)return"string"==typeof e?p.parseCapabilities(e):Array.isArray(e)&&e.length>0&&"string"==typeof e[0]?p.parseTagsOrCapabilities(e):e}).describe('Agent capabilities - can be capability names (e.g. "ai", "data processing"), capability enum values, or array of either. Common values: "ai"/"text" (TEXT_GENERATION), "data" (DATA_INTEGRATION), "analytics" (TRANSACTION_ANALYTICS)'),tags:o.z.union([o.z.array(o.z.string()),o.z.string()]).optional().transform(e=>{if(e)return"string"==typeof e?p.parseCapabilities(e):p.parseTagsOrCapabilities(e)}).describe('Tags for the agent (alternative to capabilities) - e.g. "ai", "data", "analytics". Will be converted to appropriate capabilities.'),creator:o.z.string().optional().describe("Creator attribution for the agent"),socials:o.z.record(o.z.enum(["twitter","github","discord","telegram","linkedin","youtube","website","x"]),o.z.string()).optional().describe('Social media links (e.g., {"twitter": "@handle", "discord": "username"})'),properties:o.z.record(o.z.unknown()).optional().describe("Custom metadata properties for the agent"),profilePicture:o.z.union([o.z.string().describe("URL or local file path to profile picture"),o.z.object({url:o.z.string().optional(),path:o.z.string().optional(),filename:o.z.string().optional()})]).optional().describe("Optional profile picture as URL, file path, or object with url/path/filename"),existingProfilePictureTopicId:o.z.string().optional().describe("Topic ID of an existing profile picture to reuse (e.g., 0.0.12345)"),initialBalance:o.z.number().positive().optional().describe("Optional initial HBAR balance for the new agent account (will create new account if provided)"),userAccountId:o.z.string().optional().describe("Optional account ID (e.g., 0.0.12345) to use as the agent account instead of creating a new one"),hbarFee:o.z.number().positive().optional().describe("Optional HBAR fee amount to charge per message on the inbound topic"),tokenFees:o.z.array(o.z.object({amount:o.z.number().positive(),tokenId:o.z.string()})).optional().describe("Optional token fees to charge per message"),exemptAccountIds:o.z.array(o.z.string()).optional().describe("Optional account IDs to exempt from fees"),setAsCurrent:o.z.boolean().optional().describe("Whether to set as current agent (default: true)"),persistence:o.z.object({prefix:o.z.string().optional()}).optional().describe("Optional persistence configuration")});class m extends d{constructor(e){super(e),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. Supports natural language for capabilities/tags like "ai", "data processing", "analytics". Note: This tool requires multiple transactions and cannot be used in returnBytes mode. If alias is set to "random" or contains "random", a unique alias will be generated.',this.specificInputSchema=h,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const i=e;this.specificArgs=t;const n={name:t.name};if(void 0!==t.description&&(n.bio=t.description),void 0!==t.alias)n.alias=t.alias;else{const e=Date.now().toString(36);n.alias=`${t.name}${e}`}if(void 0!==t.type&&(n.type=t.type),void 0!==t.model&&(n.model=t.model),void 0!==t.tags?n.capabilities=t.tags:void 0!==t.capabilities&&(n.capabilities=t.capabilities),void 0!==t.creator&&(n.creator=t.creator),void 0!==t.socials&&(n.socials=t.socials),void 0!==t.properties&&(n.properties=t.properties),void 0!==t.profilePicture)if("string"==typeof t.profilePicture)n.profilePicture=t.profilePicture;else{const e={};void 0!==t.profilePicture.url&&(e.url=t.profilePicture.url),void 0!==t.profilePicture.path&&(e.path=t.profilePicture.path),void 0!==t.profilePicture.filename&&(e.filename=t.profilePicture.filename),n.profilePicture=e}void 0!==t.existingProfilePictureTopicId&&(n.existingProfilePictureTopicId=t.existingProfilePictureTopicId),void 0!==t.userAccountId&&(n.userAccountId=t.userAccountId),void 0!==t.hbarFee&&(n.hbarFee=t.hbarFee),void 0!==t.tokenFees&&(n.tokenFees=t.tokenFees),void 0!==t.exemptAccountIds&&(n.exemptAccountIds=t.exemptAccountIds),void 0!==t.initialBalance&&(n.initialBalance=t.initialBalance),await i.registerAgent(n)}async _call(e,t){const i=await super._call(e,t),n=!1!==this.specificArgs?.setAsCurrent;if(this.specificArgs&&n)try{const e=JSON.parse(i);e.rawResult?this._handleRegistrationResult(e.rawResult):(e.state||e.accountId||e.metadata)&&this._handleRegistrationResult(e)}catch(r){}return i}_handleRegistrationResult(e){let t=e.accountId||e.metadata?.accountId;if(!t&&e.state?.createdResources){const i=e.state.createdResources.find(e=>e.startsWith("account:"));i&&(t=i.split(":")[1])}const i=e.inboundTopicId||e.metadata?.inboundTopicId||e.state?.inboundTopicId,n=e.outboundTopicId||e.metadata?.outboundTopicId||e.state?.outboundTopicId,r=e.profileTopicId||e.metadata?.profileTopicId||e.state?.profileTopicId,o=e.privateKey||e.metadata?.privateKey;if(t&&i&&n&&this.specificArgs){const e={name:this.specificArgs.name,accountId:t,inboundTopicId:i,outboundTopicId:n,profileTopicId:r,privateKey:o},s=this.getServiceBuilder().getStateManager();if(s&&(s.setCurrentAgent(e),s.persistAgentData)){const t=this.specificArgs.persistence?.prefix||this.specificArgs.name.toUpperCase().replace(/[^A-Z0-9]/g,"_");s.persistAgentData(e,{type:"env-file",prefix:t}).catch(()=>{})}}}}const f=o.z.object({targetIdentifier:o.z.string().optional().describe("The request key (e.g., 'req-1:0.0.6155171@0.0.6154875'), account ID (e.g., 0.0.12345) of the target agent, OR the connection number (e.g., '1', '2') from the 'list_connections' tool. Request key is most deterministic."),connectionId:o.z.string().optional().describe("The connection number (e.g., '1', '2') from the 'list_connections' tool."),agentId:o.z.string().optional().describe("The account ID (e.g., 0.0.12345) of the target agent."),message:o.z.string().describe("The text message content to send."),disableMonitoring:o.z.boolean().optional().default(!1)});class y extends d{constructor(e){super(e),this.name="send_message_to_connection",this.description="Use this to send a message to an agent you already have an active connection with. Provide the target agent's account ID (e.g., 0.0.12345) and your message. If no active connection exists, this will fail - use initiate_connection instead to create a new connection first.",this.specificInputSchema=f,this.requiresMultipleTransactions=!0,this.neverScheduleThisTool=!0}async callBuilderMethod(e,t){const i=e,n=t.targetIdentifier||t.agentId||t.connectionId;if(!n)throw new Error("Either targetIdentifier, connectionId, or agentId must be provided");const r=i.getStateManager();if(r){const e=r.getConnectionsManager();if(e)try{const t=r.getCurrentAgent();t&&t.accountId&&await e.fetchConnectionData(t.accountId)}catch(o){console.debug("Could not refresh connections:",o)}if(n.match(/^\d+$/)){const e=r.listConnections(),o=parseInt(n)-1,s=e.filter(e=>"established"===e.status&&!e.isPending&&!e.needsConfirmation);if(o>=0&&o<s.length){const e=s[o];if(e&&e.connectionTopicId)return void(await i.sendMessageToConnection({targetIdentifier:e.connectionTopicId,message:t.message,disableMonitoring:t.disableMonitoring}))}}if(n.match(/^\d+\.\d+\.\d+$/)){const e=r.listConnections().find(e=>!(e.targetAccountId!==n&&e.targetAccountId!==`0.0.${n}`||"established"!==e.status||e.isPending||e.needsConfirmation));if(e&&e.connectionTopicId)return void(await i.sendMessageToConnection({targetIdentifier:e.connectionTopicId,message:t.message,disableMonitoring:t.disableMonitoring}))}}await i.sendMessageToConnection({targetIdentifier:n,message:t.message,disableMonitoring:t.disableMonitoring})}}const I=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."),disableMonitor:o.z.boolean().optional().describe("If true, does not wait for connection confirmation. Returns immediately after sending the request."),memo:o.z.string().optional().describe('Optional memo to include with the connection request (e.g., "Hello from Alice"). If not provided, defaults to "true" or "false" based on monitoring preference.')});class b extends d{constructor(e){super(e),this.name="initiate_connection",this.description="ONLY use this to START a BRAND NEW connection to an agent you have NEVER connected to before. If you already have an active connection to this agent, use send_message_to_connection instead. This creates a new connection request and waits for acceptance.",this.specificInputSchema=I,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const i=e,n={targetAccountId:t.targetAccountId};void 0!==t.disableMonitor&&(n.disableMonitor=t.disableMonitor),void 0!==t.memo&&(n.memo=t.memo),await i.initiateConnection(n)}}const w=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")});class T extends u{constructor(e){super(e),this.name="list_connections",this.description="Lists all active HCS-10 connections. Use this FIRST before sending messages to check if you already have an active connection to a target agent. Shows connection details and agent information for each active connection.",this.specificInputSchema=w}async executeQuery(e){const t=this.hcs10Builder,i={};void 0!==e.includeDetails&&(i.includeDetails=e.includeDetails),void 0!==e.showPending&&(i.showPending=e.showPending),await t.listConnections(i);const n=await t.execute();if(n.success&&"rawResult"in n&&n.rawResult){const e=n.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Connections listed"}}return n}}const A=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.")});class C extends u{constructor(e){super(e),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.specificInputSchema=A}async executeQuery({targetIdentifier:e,fetchLatest:t,lastMessagesCount:i}){const n=this.hcs10Builder;await n.checkMessages({targetIdentifier:e,fetchLatest:t,lastMessagesCount:i||1});const r=await n.execute();if(r.success&&"rawResult"in r&&r.rawResult){const e=r.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Messages checked"}}return r}}const E=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.union([o.z.array(o.z.nativeEnum(t.AIAgentCapability)),o.z.array(o.z.string()),o.z.string()]).optional().transform(e=>{if(e)return"string"==typeof e?p.parseCapabilities(e):Array.isArray(e)&&e.length>0&&"string"==typeof e[0]?p.parseTagsOrCapabilities(e):e}).describe('Optional: Filter by capabilities/tags like "ai", "data", "analytics". Can be natural language terms or capability numbers.')});class v extends u{constructor(e){super(e),this.name="find_registrations",this.description='Searches the configured agent registry for HCS-10 agents. You can filter by account ID or tags/capabilities using natural language like "ai", "data processing", "analytics". Returns basic registration info.',this.specificInputSchema=E}async executeQuery({accountId:e,tags:t}){const i=this.hcs10Builder,n={};e&&(n.accountId=e),t&&(n.tags=t),await i.findRegistrations(n);const r=await i.execute();if(r.success&&"rawResult"in r&&r.rawResult){const e=r.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Registrations searched"}}return r}}const R=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 120."),defaultCollectorAccount:o.z.string().optional().describe("Default account to collect fees if not specified at the fee level. Defaults to the agent account.")});class S extends d{constructor(e){super(e),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. Note: When acceptAll=true, this tool requires multiple transactions and cannot be used in returnBytes mode.",this.specificInputSchema=R,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const i=e;await i.monitorConnections({...void 0!==t.acceptAll&&{acceptAll:t.acceptAll},...void 0!==t.targetAccountId&&{targetAccountId:t.targetAccountId},...void 0!==t.monitorDurationSeconds&&{monitorDurationSeconds:t.monitorDurationSeconds},hbarFees:t.hbarFees||[],tokenFees:t.tokenFees||[],...void 0!==t.exemptAccountIds&&{exemptAccountIds:t.exemptAccountIds},...void 0!==t.defaultCollectorAccount&&{defaultCollectorAccount:t.defaultCollectorAccount}})}}const N=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)")});class $ extends u{constructor(e){super(e),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.specificInputSchema=N}async executeQuery({action:e,requestKey:t}){const i=this.hcs10Builder,n={action:e};void 0!==t&&(n.requestKey=t),await i.manageConnectionRequests(n);const r=await i.execute();return"rawResult"in r?r.rawResult:r}}const O=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.")});class M extends d{constructor(e){super(e),this.name="accept_connection_request",this.description="Accepts a pending HCS-10 connection request from another agent. Use list_unapproved_connection_requests to see pending requests.",this.specificInputSchema=O,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const i=e;await i.acceptConnection({requestKey:t.requestKey,hbarFee:t.hbarFee,exemptAccountIds:t.exemptAccountIds})}}const x=o.z.object({accountId:o.z.string().describe("The Hedera account ID of the agent whose profile you want to retrieve (e.g., 0.0.12345)."),disableCache:o.z.boolean().optional().describe("Optional: Force refresh from the network instead of using cache.")});class z extends u{constructor(e){super(e),this.name="retrieve_profile",this.description="Gets the detailed profile information for a specific HCS-10 agent by their account ID. Returns name, bio, capabilities, topics, and other metadata.",this.specificInputSchema=x}async executeQuery({accountId:e,disableCache:t}){const i=this.hcs10Builder,n={accountId:e};void 0!==t&&(n.disableCache=t),await i.retrieveProfile(n);const r=await i.execute();if(r.success&&"rawResult"in r&&r.rawResult){const e=r.rawResult;return{success:!0,data:e.profileDetails||"Profile retrieved",rawProfile:e.rawProfile}}return r}}const q=o.z.object({});class k extends u{constructor(e){super(e),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.specificInputSchema=q}async executeQuery(){const e=this.hcs10Builder;await e.listUnapprovedConnectionRequests();const t=await e.execute();return"rawResult"in t?t.rawResult:t}}class P extends e.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs2",this.hcs2Builder=e.hcs2Builder}getServiceBuilder(){return this.hcs2Builder}}class B extends e.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs2",this.hcs2Builder=e.hcs2Builder}getServiceBuilder(){return this.hcs2Builder}}const D=o.z.object({registryType:o.z.nativeEnum(t.HCS2RegistryType).optional().describe("Registry type: 0 for indexed, 1 for non-indexed (default: 0)"),ttl:o.z.number().int().positive().optional().describe("Time to live in seconds (default: 86400)"),adminKey:o.z.union([o.z.string(),o.z.boolean()]).optional().describe("Admin key: public key string or true to use operator key"),submitKey:o.z.union([o.z.string(),o.z.boolean()]).optional().describe("Submit key: public key string or true to use operator key")});const F=o.z.object({registryTopicId:o.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID (e.g., 0.0.123456)"),targetTopicId:o.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The target topic ID to register (e.g., 0.0.123456)"),metadata:o.z.string().optional().describe("Optional metadata URI (HIP-412 format)"),memo:o.z.string().max(500).optional().describe("Optional memo (max 500 characters)")});const _=o.z.object({registryTopicId:o.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID (must be indexed)"),targetTopicId:o.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The new topic ID to point to"),uid:o.z.string().describe("The unique ID of the entry to update"),metadata:o.z.string().optional().describe("Optional metadata URI (HIP-412 format)"),memo:o.z.string().max(500).optional().describe("Optional memo (max 500 characters)")});const L=o.z.object({registryTopicId:o.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID (must be indexed)"),uid:o.z.string().describe("The unique ID of the entry to delete"),memo:o.z.string().max(500).optional().describe("Optional memo (max 500 characters)")});const H=o.z.object({registryTopicId:o.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The current HCS-2 registry topic ID"),targetTopicId:o.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The new topic ID to migrate to"),metadata:o.z.string().optional().describe("Optional metadata URI for migration details"),memo:o.z.string().max(500).optional().describe("Optional memo (max 500 characters)")});const K=o.z.object({topicId:o.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID to query"),limit:o.z.number().int().positive().optional().describe("Maximum number of entries to return"),order:o.z.enum(["asc","desc"]).optional().describe("Order of results (ascending or descending)"),skip:o.z.number().int().min(0).optional().describe("Number of entries to skip")});class U extends e.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs6",this.hcs6Builder=e.hcs6Builder}getServiceBuilder(){return this.hcs6Builder}}class G extends e.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs6",this.hcs6Builder=e.hcs6Builder}getServiceBuilder(){return this.hcs6Builder}}const j=o.z.object({ttl:o.z.number().min(3600).default(86400).describe("Time-to-live in seconds (minimum 3600 seconds/1 hour)"),submitKey:o.z.union([o.z.boolean(),o.z.string()]).optional().describe("Submit key for the registry topic. Can be boolean (use operator key) or a public key string")});const Q=o.z.object({metadata:o.z.record(o.z.unknown()).describe("Metadata object for the hashinal (e.g., name, description, attributes)"),data:o.z.object({base64:o.z.string().optional().describe("Base64 encoded data for the hashinal"),url:o.z.string().optional().describe("URL to fetch data from"),mimeType:o.z.string().optional().describe("MIME type of the data")}).optional().describe("Data to inscribe with the hashinal"),memo:o.z.string().optional().describe("Optional memo for the registration"),ttl:o.z.number().min(3600).default(86400).describe("Time-to-live in seconds for the inscription"),registryTopicId:o.z.string().optional().describe("Registry topic ID to use. If not provided, a new registry will be created"),submitKey:o.z.string().optional().describe("Submit key for the registry (required if registry has a submit key)")});const W=o.z.object({registryTopicId:o.z.string().describe("The registry topic ID that tracks this dynamic hashinal"),metadata:o.z.record(o.z.unknown()).describe("Updated metadata object for the hashinal"),data:o.z.object({base64:o.z.string().optional().describe("Base64 encoded data for the updated hashinal"),url:o.z.string().optional().describe("URL to fetch updated data from"),mimeType:o.z.string().optional().describe("MIME type of the data")}).optional().describe("Updated data to inscribe"),memo:o.z.string().optional().describe('Optional memo for the update (e.g., "Level up", "Version 2.0")'),submitKey:o.z.string().describe("Submit key for the registry (required to update)")});const V=o.z.object({topicId:o.z.string().describe("The registry topic ID to query"),limit:o.z.number().optional().default(100).describe("Maximum number of entries to retrieve"),order:o.z.enum(["asc","desc"]).optional().default("desc").describe("Order of entries (desc shows latest first)"),skip:o.z.number().optional().describe("Number of entries to skip")});class Y extends e.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="inscriber",this.inscriberBuilder=e.inscriberBuilder,this.contentResolver=e.contentResolver||null}getServiceBuilder(){return this.inscriberBuilder}getContentResolver(){return this.contentResolver}async generateInscriptionQuote(e,t){this.inscriberBuilder.hederaKit.signer.getAccountId().toString(),this.inscriberBuilder.hederaKit.signer?.getOperatorPrivateKey()&&this.inscriberBuilder.hederaKit.signer.getOperatorPrivateKey().toStringRaw();const i={...t,quoteOnly:!0,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet"},n=await this.inscriberBuilder.inscribe(e,i);if(!n.quote||n.confirmed)throw new Error("Failed to generate quote - unexpected response type");return n.result}}class X extends e.BaseHederaQueryTool{constructor(e){super(e),this.namespace="inscriber",this.inscriberBuilder=e.inscriberBuilder,this.contentResolver=e.contentResolver||null}getServiceBuilder(){return this.inscriberBuilder}getContentResolver(){return this.contentResolver}async generateInscriptionQuote(e,t){this.inscriberBuilder.hederaKit.signer.getAccountId().toString(),this.inscriberBuilder.hederaKit.signer?.getOperatorPrivateKey()&&this.inscriberBuilder.hederaKit.signer.getOperatorPrivateKey().toStringRaw();const i={...t,quoteOnly:!0,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet"},n=await this.inscriberBuilder.inscribe(e,i);if(!n.quote||n.confirmed)throw new Error("Failed to generate quote - unexpected response type");return n.result}}const J=o.z.object({url:o.z.string().url().describe("ONLY direct file download URLs with file extensions (.pdf, .jpg, .png, .json, .zip). NEVER use for web pages, articles, or when you already have content to inscribe."),mode:o.z.enum(["file","hashinal"]).optional().describe("Inscription mode: file or hashinal NFT"),metadata:o.z.record(o.z.unknown()).optional().describe("Metadata to attach to the inscription"),tags:o.z.array(o.z.string()).optional().describe("Tags to categorize the inscription"),chunkSize:o.z.number().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:o.z.boolean().optional().describe("Whether to wait for inscription confirmation"),timeoutMs:o.z.number().int().positive().optional().describe("Timeout in milliseconds for inscription (default: no timeout - waits until completion)"),apiKey:o.z.string().optional().describe("API key for inscription service"),quoteOnly:o.z.boolean().optional().default(!1).describe("If true, returns a cost quote instead of executing the inscription")});const Z=o.z.object({filePath:o.z.string().min(1,"File path cannot be empty").describe("The file path of the content to inscribe. Must point to a valid, non-empty file."),mode:o.z.enum(["file","hashinal"]).optional().describe("Inscription mode: file or hashinal NFT"),metadata:o.z.record(o.z.unknown()).optional().describe("Metadata to attach to the inscription"),tags:o.z.array(o.z.string()).optional().describe("Tags to categorize the inscription"),chunkSize:o.z.number().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:o.z.boolean().optional().describe("Whether to wait for inscription confirmation"),timeoutMs:o.z.number().int().positive().optional().describe("Timeout in milliseconds for inscription (default: no timeout)"),apiKey:o.z.string().optional().describe("API key for inscription service"),quoteOnly:o.z.boolean().optional().default(!1).describe("If true, returns a cost quote instead of executing the inscription")});const ee={maxInscriptionSize:51200,minContentSize:10,logLevel:"warn"};function te(){return{maxInscriptionSize:parseInt(process.env.REF_MAX_SIZE||ee.maxInscriptionSize.toString(),10),minContentSize:parseInt(process.env.REF_MIN_SIZE||ee.minContentSize.toString(),10),logLevel:process.env.REF_LOG_LEVEL||ee.logLevel,enableContentValidation:"false"!==process.env.REF_ENABLE_VALIDATION}}const ie=o.z.object({base64Data:o.z.string().min(1,"Data cannot be empty").describe('The content to inscribe. Accept BOTH plain text AND base64. Also accepts content reference IDs in format "content-ref:[id]". When user says "inscribe it" or "inscribe the content", use the EXACT content from your previous message or from MCP tool results. DO NOT generate new content. DO NOT create repetitive text. Pass the actual search results or other retrieved content EXACTLY as you received it.'),fileName:o.z.string().min(1,"File name cannot be empty").describe("Name for the inscribed content. Required for all inscriptions."),mimeType:o.z.string().optional().describe("MIME type of the content"),mode:o.z.enum(["file","hashinal"]).optional().describe("Inscription mode: file or hashinal NFT"),metadata:o.z.record(o.z.unknown()).optional().describe("Metadata to attach to the inscription"),tags:o.z.array(o.z.string()).optional().describe("Tags to categorize the inscription"),chunkSize:o.z.number().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:o.z.boolean().optional().describe("Whether to wait for inscription confirmation"),timeoutMs:o.z.number().int().positive().optional().describe("Timeout in milliseconds for inscription (default: no timeout - waits until completion)"),apiKey:o.z.string().optional().describe("API key for inscription service"),quoteOnly:o.z.boolean().optional().default(!1).describe("If true, returns a cost quote instead of executing the inscription")});const ne=o.z.object({url:o.z.string().url().describe("The URL of the content to inscribe as Hashinal NFT"),name:o.z.string().describe("Name of the Hashinal NFT"),creator:o.z.string().describe("Creator account ID or name"),description:o.z.string().describe("Description of the Hashinal NFT"),type:o.z.string().describe('Type of NFT (e.g., "image", "video", "audio")'),attributes:o.z.array(o.z.object({trait_type:o.z.string(),value:o.z.union([o.z.string(),o.z.number()])})).optional().describe("NFT attributes"),properties:o.z.record(o.z.unknown()).optional().describe("Additional properties"),jsonFileURL:o.z.string().url().optional().describe("URL to JSON metadata file"),tags:o.z.array(o.z.string()).optional().describe("Tags to categorize the NFT"),chunkSize:o.z.number().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:o.z.boolean().optional().describe("Whether to wait for inscription confirmation"),timeoutMs:o.z.number().int().positive().optional().describe("Timeout in milliseconds for inscription (default: no timeout - waits until completion)"),apiKey:o.z.string().optional().describe("API key for inscription service"),quoteOnly:o.z.boolean().optional().default(!1).describe("If true, returns a cost quote instead of executing the inscription")});const re=o.z.object({transactionId:o.z.string().describe("The transaction ID of the inscription to retrieve"),apiKey:o.z.string().optional().describe("API key for inscription service")});const oe=n.join(process.cwd(),".env");class se{constructor(e){this.currentAgent=null,this.connectionMessageTimestamps={},this.connectionsManager=null,this.defaultEnvFilePath=e?.defaultEnvFilePath,this.defaultPrefix=e?.defaultPrefix??"TODD";const i=e?.disableLogging||"true"===process.env.DISABLE_LOGGING;this.logger=new t.Logger({module:"OpenConvaiState",silent:i}),e?.baseClient&&this.initializeConnectionsManager(e.baseClient)}initializeConnectionsManager(e){return this.connectionsManager?this.logger.debug("ConnectionsManager already initialized"):(this.logger.debug("Initializing ConnectionsManager"),this.connectionsManager=new t.ConnectionsManager({baseClient:e,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(),i=parseInt(e)-1;if(!isNaN(i)&&i>=0&&i<t.length)return t[i];const n=this.connectionsManager.getConnectionByTopicId(e);if(n)return this.convertToActiveConnection(n);const r=this.connectionsManager.getConnectionByAccountId(e);return r?this.convertToActiveConnection(r):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",r=t?.prefix||this.defaultPrefix;if(!e.accountId||!e.inboundTopicId||!e.outboundTopicId)throw new Error("Agent data incomplete, cannot persist to environment");const o={[`${r}_ACCOUNT_ID`]:e.accountId,[`${r}_INBOUND_TOPIC_ID`]:e.inboundTopicId,[`${r}_OUTBOUND_TOPIC_ID`]:e.outboundTopicId};e.privateKey&&(o[`${r}_PRIVATE_KEY`]=e.privateKey),e.profileTopicId&&(o[`${r}_PROFILE_TOPIC_ID`]=e.profileTopicId),await async function(e,t){let n="";i.existsSync(e)&&(n=i.readFileSync(e,"utf8"));const r=[...n.split("\n")];for(const[i,o]of Object.entries(t)){const e=r.findIndex(e=>e.startsWith(`${i}=`));-1!==e?r[e]=`${i}=${o}`:r.push(`${i}=${o}`)}i.writeFileSync(e,r.join("\n"))}(n,o)}}const ae="ConnectionsManager not initialized";class ce extends e.BaseServiceBuilder{constructor(e,i,n){super(e),this.useEncryption=!1,this.guardedRegistryBaseUrl="",this.stateManager=i,this.useEncryption=n?.useEncryption||!1,this.guardedRegistryBaseUrl=n?.registryUrl||"";const r=this.hederaKit.client.network;this.network=r.toString().includes("mainnet")?"mainnet":"testnet";const o=this.hederaKit.signer.getAccountId().toString(),s=this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"";this.sdkLogger=new t.Logger({module:"HCS10Builder",level:n?.logLevel||"info"}),this.standardClient=new t.HCS10Client({network:this.network,operatorId:o,operatorPrivateKey:s,logLevel:n?.logLevel||"info"}),this.stateManager&&this.stateManager.initializeConnectionsManager(this.standardClient)}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.network}getStateManager(){return this.stateManager}getAccountAndSigner(){const e=this.standardClient.getAccountAndSigner();return{accountId:e.accountId,signer:e.signer}}async getInboundTopicId(){try{const e=this.getOperatorId();this.logger.info(`[HCS10Builder] 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(`[HCS10Builder] 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(`[HCS10Builder] Error fetching operator's inbound topic ID (${this.getOperatorId()}):`,e);const t=this.getOperatorId();let i=`Failed to get inbound topic ID for operator ${t}.`;throw e instanceof Error&&e.message.includes("does not have a valid HCS-11 memo")?i+=` 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?i+=` Reason: ${e.message}`:i+=` Unexpected error: ${String(e)}`,new Error(i)}}async getAgentProfile(e){try{return await this.standardClient.retrieveProfile(e)}catch(t){throw this.logger.error(`[HCS10Builder] Error retrieving agent profile for account ${e}:`,t),t}}async submitConnectionRequest(e,t){return this.standardClient.submitConnectionRequest(e,t)}async handleConnectionRequest(e,t,i,n){try{const r=await this.standardClient.handleConnectionRequest(e,t,i,n);return r&&r.connectionTopicId&&"object"==typeof r.connectionTopicId&&"toString"in r.connectionTopicId&&(r.connectionTopicId=r.connectionTopicId.toString()),r}catch(r){throw this.logger.error(`Error handling connection request #${i} for topic ${e}:`,r),new Error(`Failed to handle connection request: ${r instanceof Error?r.message:String(r)}`)}}async sendMessage(e,t,i){if(e&&"object"==typeof e&&"toString"in e&&(e=e?.toString()),!e||"string"!=typeof e)throw new Error(`Invalid topic ID provided to sendMessage: ${JSON.stringify(e)}`);try{const n=await this.standardClient.sendMessage(e,t,i,void 0);return{sequenceNumber:n.topicSequenceNumber?.toNumber(),receipt:n,transactionId:"transactionId"in n?n.transactionId?.toString():void 0}}catch(n){throw this.logger.error(`Error sending message to topic ${e}:`,n),new Error(`Failed to send message: ${n instanceof Error?n.message:String(n)}`)}}async getMessages(e){if(e&&"object"==typeof e&&"toString"in e&&(e=e?.toString()),!e||"string"!=typeof e)throw new Error(`Invalid topic ID provided to getMessages: ${JSON.stringify(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,p:"hcs-10"}});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){if(e&&"object"==typeof e&&"toString"in e&&(e=e?.toString()),!e||"string"!=typeof e)throw new Error(`Invalid topic ID provided to getMessageStream: ${JSON.stringify(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)}`)}}getStandardClient(){return this.standardClient}async loadProfilePicture(e){try{if(!e)return null;if("string"==typeof e){if(e.startsWith("http://")||e.startsWith("https://")){this.logger.info(`Loading profile picture from URL: ${e}`);const t=await r.get(e,{responseType:"arraybuffer"}),i=globalThis.Buffer.from(t.data),o=new URL(e).pathname;return{buffer:i,filename:n.basename(o)||"profile.png"}}{if(!i.existsSync(e))return this.logger.warn(`Profile picture file not found: ${e}`),null;this.logger.info(`Loading profile picture from file: ${e}`);const t=i.readFileSync(e);return{buffer:t,filename:n.basename(e)}}}if(e.url){this.logger.info(`Loading profile picture from URL: ${e.url}`);const t=await r.get(e.url,{responseType:"arraybuffer"}),i=globalThis.Buffer.from(t.data);return{buffer:i,filename:e.filename||"profile.png"}}if(e.path){if(!i.existsSync(e.path))return this.logger.warn(`Profile picture file not found: ${e.path}`),null;this.logger.info(`Loading profile picture from file: ${e.path}`);const t=i.readFileSync(e.path);return{buffer:t,filename:e.filename||n.basename(e.path)}}return null}catch(t){return this.logger.error("Failed to load profile picture:",t),null}}async createAndRegisterAgent(e){const i=(new t.AgentBuilder).setName(e.name).setBio(e.bio||"").setCapabilities(e.capabilities||[t.AIAgentCapability.TEXT_GENERATION]).setType(e.type||"autonomous").setModel(e.model||"agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(t.InboundTopicType.PUBLIC);e.alias&&i.setAlias(e.alias),e.creator&&i.setCreator(e.creator),e?.feeConfig&&(i.setInboundTopicType(t.InboundTopicType.FEE_BASED),i.setFeeConfig(e.feeConfig)),e.existingProfilePictureTopicId?i.setExistingProfilePicture(e.existingProfilePictureTopicId):e.pfpBuffer&&e.pfpFileName?0===e.pfpBuffer.byteLength?this.logger.warn("Provided PFP buffer is empty. Skipping profile picture."):(this.logger.info(`Setting profile picture: ${e.pfpFileName} (${e.pfpBuffer.byteLength} bytes)`),i.setProfilePicture(e.pfpBuffer,e.pfpFileName)):this.logger.warn("Profile picture not provided. Agent creation might fail if required by the underlying SDK builder."),e.socials&&Object.entries(e.socials).forEach(([e,t])=>{i.addSocial(e,t)}),e.properties&&Object.entries(e.properties).forEach(([e,t])=>{i.addProperty(e,t)});try{const t=Boolean(e?.feeConfig);return await this.standardClient.createAndRegisterAgent(i,{initialBalance:t?50:10})}catch(n){throw this.logger.error("Error during agent creation/registration:",n),new Error(`Failed to create/register agent: ${n instanceof Error?n.message:String(n)}`)}}async registerAgent(e){if(this.clearNotes(),"returnBytes"===this.hederaKit.operationalMode)throw new Error("Agent registration requires multiple transactions and cannot be performed in returnBytes mode. Please use autonomous mode.");try{let i=null;e.profilePicture&&(i=await this.loadProfilePicture(e.profilePicture));const n={name:e.name,...void 0!==e.bio&&{bio:e.bio},...void 0!==e.alias&&{alias:e.alias},...void 0!==e.type&&{type:e.type},...void 0!==e.model&&{model:e.model},...void 0!==e.capabilities&&{capabilities:e.capabilities},...void 0!==e.creator&&{creator:e.creator},...void 0!==e.socials&&{socials:e.socials},...void 0!==e.properties&&{properties:e.properties},...void 0!==e.existingProfilePictureTopicId&&{existingProfilePictureTopicId:e.existingProfilePictureTopicId},...void 0!==i?.buffer&&{pfpBuffer:i.buffer},...void 0!==i?.filename&&{pfpFileName:i.filename}};if(e.hbarFee&&e.hbarFee>0){const i=new t.FeeConfigBuilder({network:this.network,logger:this.sdkLogger}),{accountId:r}=this.getAccountAndSigner();if(!r)throw new Error("Could not determine account ID for fee collection.");this.addNote(`Setting the operator account (${r}) as the fee collector since no specific collector was provided.`);const o=e.exemptAccountIds?.filter(e=>e!==r&&e.startsWith("0.0"))||[];n.feeConfig=i.addHbarFee(e.hbarFee,r,o)}const r=await this.createAndRegisterAgent(n);this.executeResult={success:!0,transactionId:r.transactionId,receipt:void 0,scheduleId:void 0,rawResult:{...r,name:e.name,accountId:r?.metadata?.accountId||r.state?.agentMetadata?.accountId}}}catch(i){throw this.logger.error("Failed to register agent:",i),i}return this}async initiateConnection(e){this.clearNotes();try{const t=await this.getAgentProfile(e.targetAccountId);if(!t.success||!t.topicInfo?.inboundTopic)throw new Error(`Could not retrieve inbound topic for target account ${e.targetAccountId}`);const i=t.topicInfo.inboundTopic;let n;void 0!==e.memo?n=e.memo:(n=e.disableMonitor?"false":"true",this.addNote(`No custom memo was provided. Using default memo '${n}' based on monitoring preference.`)),e.disableMonitor||this.addNote("Monitoring will be enabled for this connection request as disableMonitor was not specified.");const r=await this.submitConnectionRequest(i,n);this.executeResult={success:!0,transactionId:"transactionId"in r?r.transactionId?.toString():void 0,receipt:r,scheduleId:void 0,rawResult:{targetAccountId:e.targetAccountId,targetInboundTopicId:i,connectionRequestSent:!0,monitoringEnabled:!e.disableMonitor,...r}}}catch(t){throw this.logger.error("Failed to initiate connection:",t),t}return this}async acceptConnection(e){if(this.clearNotes(),"returnBytes"===this.hederaKit.operationalMode)throw new Error("Accepting connections requires multiple transactions and cannot be performed in returnBytes mode. Please use autonomous mode.");try{const n=this.stateManager?.getCurrentAgent();if(!n)throw new Error("Cannot accept connection request. No agent is currently active. Please register or select an agent first.");const r=this.stateManager?.getConnectionsManager();if(!r)throw new Error(ae);await r.fetchConnectionData(n.accountId);const o=[...r.getPendingRequests(),...r.getConnectionsNeedingConfirmation()].find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!o)throw new Error(`Request with key ${e.requestKey} not found or no longer pending.`);if(!o.needsConfirmation||!o.inboundRequestId)throw new Error(`Request with key ${e.requestKey} is not an inbound request that can be accepted.`);const s=o.targetAccountId,a=o.inboundRequestId;let c;if(e.hbarFee&&e.hbarFee>0){const i=new t.FeeConfigBuilder({network:this.network,logger:this.sdkLogger}),{accountId:n}=this.getAccountAndSigner();if(!n)throw new Error("Could not determine account ID for fee collection.");this.addNote(`Setting the operator account (${n}) as the fee collector since no specific collector was provided.`);const r=e.exemptAccountIds?.filter(e=>e!==n&&e.startsWith("0.0"))||[];c=i.addHbarFee(e.hbarFee,n,r)}const l=await this.getInboundTopicId(),d=await this.handleConnectionRequest(l,s,a,c);let u=d?.connectionTopicId;if(u&&"object"==typeof u&&"toString"in u&&(u=u?.toString()),!u||"string"!=typeof u)throw new Error(`Failed to create connection topic. Got: ${JSON.stringify(u)}`);if(this.stateManager){const e=o.targetAgentName||`Agent ${s}`;o.targetAgentName||this.addNote(`No agent name was provided in the connection request, using default name 'Agent ${s}'.`);let t=o.targetInboundTopicId||"";if(!t)try{const e=await this.getAgentProfile(s);e.success&&e.topicInfo?.inboundTopic&&(t=e.topicInfo.inboundTopic)}catch(i){this.logger.warn(`Could not fetch profile for ${s}:`,i)}const n={connectionId:`conn-${Date.now()}`,targetAccountId:s,targetAgentName:e,targetInboundTopicId:t,connectionTopicId:u,status:"established",created:new Date};this.stateManager.addActiveConnection(n),r.markConnectionRequestProcessed(o.targetInboundTopicId||"",a)}this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{targetAccountId:s,connectionTopicId:u,feeConfigured:!!e.hbarFee,hbarFee:e.hbarFee||0,confirmationResult:d}}}catch(n){throw this.logger.error("Failed to accept connection:",n),n}return this}async sendHCS10Message(e){this.clearNotes();try{const t=await this.sendMessage(e.topicId,e.message);this.executeResult={success:!0,transactionId:t.transactionId,receipt:t.receipt,scheduleId:void 0,rawResult:t},this.addNote(`Message sent to topic ${e.topicId}.`)}catch(t){throw this.logger.error("Failed to send message:",t),t}return this}async sendMessageToConnection(e){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required to send messages to connections");try{const t=this.stateManager.getCurrentAgent();if(!t)throw new Error("Cannot send message. No agent is currently active. Please register or select an agent first.");let i;const n=e.targetIdentifier;if(n.includes("@")){const e=n.split("@");if(2===e.length){const t=e[1];i=this.stateManager.getConnectionByIdentifier(t),i||this.addNote(`Could not find connection using request key '${n}', extracted account ID '${t}'.`)}}if(i||(i=this.stateManager.getConnectionByIdentifier(n)),!i&&!n.startsWith("0.0.")&&/^\d+$/.test(n)){const e=`0.0.${n}`;i=this.stateManager.getConnectionByIdentifier(e),i&&this.addNote(`Found connection using account ID with prefix: ${e}`)}if(!i&&/^[1-9]\d*$/.test(n)){const e=this.stateManager.listConnections(),t=parseInt(n)-1;t>=0&&t<e.length&&(i=e[t],i&&this.addNote(`Found connection by index ${n}: ${i.targetAccountId}`))}if(!i){const e=this.stateManager.listConnections().map((e,t)=>`${t+1}. ${e.targetAccountId} (Topic: ${e.connectionTopicId})`);let t=`Connection not found for identifier: "${n}"\n`;throw t+=`Available connections:\n${e.join("\n")||"No active connections"}`,t+="\n\nYou can use:\n",t+='- Connection number (e.g., "1", "2")\n',t+='- Account ID (e.g., "0.0.6412936")\n',t+="- Connection topic ID\n",t+="Use 'list_connections' to see all active connections.",new Error(t)}let r=i.connectionTopicId;if(r&&"object"==typeof r&&"toString"in r&&(r=r?.toString()),!r||"string"!=typeof r)throw new Error(`Invalid connection topic ID for ${i.targetAccountId}: ${JSON.stringify(r)} (type: ${typeof r})`);const o=i.targetAgentName,s=`${t.inboundTopicId}@${t.accountId}`,a=await this.sendMessage(r,e.message,`Agent message from ${t.name}`);if(!a.sequenceNumber)throw new Error("Failed to send message");let c=null;e.disableMonitoring?this.addNote("Message sent successfully. Response monitoring was disabled."):c=await this.monitorResponses(r,s,a.sequenceNumber),this.executeResult={success:!0,transactionId:a.transactionId,receipt:a.receipt,scheduleId:void 0,rawResult:{targetAgentName:o,targetAccountId:i.targetAccountId,connectionTopicId:r,sequenceNumber:a.sequenceNumber,reply:c,monitoringEnabled:!e.disableMonitoring,message:e.message,messageResult:a}}}catch(t){throw this.logger.error("Failed to send message to connection:",t),t}return this}async monitorResponses(e,t,i){let n=0;for(;n<30;){try{const n=await this.getMessageStream(e);for(const e of n.messages){if(e.sequence_number<i||e.operator_id===t)continue;return await this.getMessageContent(e.data||"")}}catch(r){this.logger.error(`Error monitoring responses: ${r}`)}await new Promise(e=>setTimeout(e,4e3)),n++}return null}async startPassiveConnectionMonitoring(){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required for passive monitoring");const e=await this.getInboundTopicId();return this.logger.info(`Starting passive connection monitoring on topic ${e}...`),this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{inboundTopicId:e,message:`Started monitoring inbound topic ${e} for connection requests in the background.`}},this}async monitorConnections(e){this.clearNotes();const{acceptAll:i=!1,targetAccountId:n,monitorDurationSeconds:r=120,hbarFees:o=[],tokenFees:s=[],exemptAccountIds:a=[],defaultCollectorAccount:c}=e;if(!this.stateManager)throw new Error("StateManager is required for connection monitoring");if(!this.stateManager.getCurrentAgent())throw new Error("Cannot monitor for connections. No agent is currently active.");const l=await this.getInboundTopicId(),d=Date.now()+1e3*r;let u=0,g=0;const p=new Set;for(;Date.now()<d;){try{const e=(await this.getMessages(l)).messages.filter(e=>"connection_request"===e.op&&"number"==typeof e.sequence_number);for(const r of e){const e=r.sequence_number;if(!e||p.has(e))continue;const d=r.operator_id?.split("@")[1];if(d)if(u++,n&&d!==n)this.logger.info(`Skipping request from ${d} (not target account)`);else if(i||n===d){let i;if(this.logger.info(`Accepting connection request from ${d}`),o.length>0||s.length>0){const e=new t.FeeConfigBuilder({network:this.network,logger:this.sdkLogger});for(const t of o){const i=t.collectorAccount||c||this.getOperatorId();e.addHbarFee(t.amount,i,a)}for(const t of s){const i=t.collectorAccount||c||this.getOperatorId();e.addTokenFee(t.amount,t.tokenId,i,void 0,a)}i=e}await this.handleConnectionRequest(l,d,e,i),p.add(e),g++}}}catch(h){this.logger.error("Error during connection monitoring:",h)}await new Promise(e=>setTimeout(e,3e3))}return this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{connectionRequestsFound:u,acceptedConnections:g,monitorDurationSeconds:r,processedRequestIds:Array.from(p)}},this.addNote(`Monitoring completed. Found ${u} requests, accepted ${g}.`),this}async manageConnectionRequests(e){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required for managing connection requests");if(!this.stateManager.getCurrentAgent())throw new Error("Cannot manage connection requests. No agent is currently active.");const t=this.stateManager.getConnectionsManager();if(!t)throw new Error(ae);try{const{accountId:i}=this.getAccountAndSigner();await t.fetchConnectionData(i);const n=t.getPendingRequests(),r=t.getConnectionsNeedingConfirmation(),o=[...n,...r];switch(e.action){case"list":this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{requests:o.map((e,t)=>({index:t+1,type:e.needsConfirmation?"incoming":"outgoing",requestKey:e.uniqueRequestKey||`${e.connectionRequestId||e.inboundRequestId||"unknown"}`,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName||`Agent ${e.targetAccountId}`,created:e.created.toISOString(),memo:e.memo,bio:e.profileInfo?.bio}))}};break;case"view":{if(!e.requestKey)throw new Error("Request key is required for viewing a request");const t=o.find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!t)throw new Error(`Request with key ${e.requestKey} not found`);this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{request:{type:t.needsConfirmation?"incoming":"outgoing",requestKey:t.uniqueRequestKey||`${t.connectionRequestId||t.inboundRequestId||"unknown"}`,targetAccountId:t.targetAccountId,targetAgentName:t.targetAgentName||`Agent ${t.targetAccountId}`,created:t.created.toISOString(),memo:t.memo,profileInfo:t.profileInfo}}};break}case"reject":{if(!e.requestKey)throw new Error("Request key is required for rejecting a request");const i=o.find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!i)throw new Error(`Request with key ${e.requestKey} not found`);i.inboundRequestId?t.markConnectionRequestProcessed(i.targetInboundTopicId||"",i.inboundRequestId):i.connectionRequestId&&t.markConnectionRequestProcessed(i.originTopicId||"",i.connectionRequestId),this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{rejectedRequest:{requestKey:e.requestKey,targetAccountId:i.targetAccountId,targetAgentName:i.targetAgentName||`Agent ${i.targetAccountId}`}}};break}}}catch(i){throw this.logger.error("Failed to manage connection requests:",i),i}return this}async listUnapprovedConnectionRequests(){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required for listing connection requests");if(!this.stateManager.getCurrentAgent())throw new Error("Cannot list connection requests. No agent is currently active.");try{const e=await this.getInboundTopicId(),t=(await this.getMessages(e)).messages.filter(e=>"connection_request"===e.op).map(e=>({requestId:e.sequence_number,fromAccountId:e.operator_id?.split("@")[1]||"unknown",timestamp:e.timestamp||new Date(e?.created||"").getTime(),memo:e.m||"",data:e.data})).filter(e=>"unknown"!==e.fromAccountId);this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{requests:t,count:t.length}},0===t.length?this.addNote("No unapproved connection requests found."):this.addNote(`Found ${t.length} unapproved connection request(s).`)}catch(e){throw this.logger.error("Failed to list unapproved connection requests:",e),e}return this}async listConnections(e={}){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required to list connections");const t=e.includeDetails??!0,i=e.showPending??!0;try{const e=await this.getEnhancedConnections();if(0===e.length)return this.executeResult={success:!0,rawResult:{connections:[],message:"There are currently no active connections."}},this;const n=e.filter(e=>"established"===e.status),r=e.filter(e=>e.isPending),o=e.filter(e=>e.needsConfirmation);let s="";n.length>0&&(s+=`🟢 Active Connections (${n.length}):\n`,n.forEach((e,i)=>{s+=this.formatConnection(e,i,t)}),s+="\n"),i&&o.length>0&&(s+=`🟠 Connections Needing Confirmation (${o.length}):\n`,o.forEach((e,i)=>{s+=this.formatConnection(e,i,t)}),s+="\n"),i&&r.length>0&&(s+=`⚪ Pending Connection Requests (${r.length}):\n`,r.forEach((e,i)=>{s+=this.formatConnection(e,i,t)})),this.executeResult={success:!0,rawResult:{connections:e,formattedOutput:s.trim(),activeCount:n.length,pendingCount:r.length,needsConfirmationCount:o.length}}}catch(n){this.logger.error("Failed to list connections:",n),this.executeResult={success:!1,error:`Failed to list connections: ${n instanceof Error?n.message:String(n)}`}}return this}formatConnection(e,t,i){const n=e;let r=`${t+1}. ${n.profileInfo?.display_name||n.targetAgentName||"Unknown Agent"} (${n.targetAccountId})\n`;r+=` Topic: ${n.isPending?"(Pending Request)":n.connectionTopicId}\n`;if(r+=` Status: ${n.status||"unknown"}\n`,i){if(n.profileInfo?.bio&&(r+=` Bio: ${n.profileInfo.bio.substring(0,100)}${n.profileInfo.bio.length>100?"...":""}\n`),n.created){r+=` ${n.isPending?"Request sent":"Connection established"}: ${n.created.toLocaleString()}\n`}n.lastActivity&&(r+=` Last activity: ${n.lastActivity.toLocaleString()}\n`)}return r}async getEnhancedConnections(){try{const{accountId:e}=this.getAccountAndSigner();if(!e)return this.stateManager.listConnections();const t=this.stateManager.getConnectionsManager();if(!t)return this.logger.error(ae),this.stateManager.listConnections();const i=await t.fetchConnectionData(e);for(const n of i)this.stateManager.addActiveConnection(n);return i}catch(e){return this.logger.error("Failed to get enhanced connections:",e),this.stateManager.listConnections()}}async checkMessages(e){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required to check messages");const t=this.stateManager.getConnectionByIdentifier(e.targetIdentifier);if(!t)return this.executeResult={success:!1,error:`Could not find an active connection matching identifier "${e.targetIdentifier}". Use 'list_connections' to see active connections.`},this;const i=t.connectionTopicId||"";if(!i||!i.match(/^\d+\.\d+\.\d+$/))return this.logger.error(`Invalid connection topic ID format: ${i}`),this.executeResult={success:!1,error:`Invalid connection topic ID format: ${i}. Expected format: 0.0.XXXXX`},this;const n=t.targetAgentName,r=this.stateManager.getLastTimestamp(i);this.logger.info(`Checking messages for connection with ${n} (${t.targetAccountId}) on topic ${i} (fetchLatest: ${e.fetchLatest}, lastCount: ${e.lastMessagesCount}, since: ${r})`);try{const t=(await this.getMessages(i)).messages;if(!t||0===t.length)return this.executeResult={success:!0,rawResult:{messages:[],message:`No messages found on connection topic ${i}.`}},this;let s=[],a=r;const c=!0===e.fetchLatest;if(c){this.logger.info("Fetching latest messages regardless of timestamp.");const i=e.lastMessagesCount??1;s=t.slice(-i)}else this.logger.info(`Filtering for messages newer than ${r}`),s=t.filter(e=>1e6*e.timestamp>r),s.length>0&&(a=s.reduce((e,t)=>Math.max(e,1e6*t.timestamp),r));if(0===s.length){const e=c?`Could not retrieve the latest message(s). No messages found on topic ${i}.`:`No new messages found for connection with ${n} since last check.`;return this.executeResult={success:!0,rawResult:{messages:[],message:e}},this}this.logger.info(`Processing ${s.length} message(s).`);let l=c?`Latest message(s) from ${n}:\n`:`New messages from ${n}:\n`;const d=[];for(const e of s){let t=e.data;try{"string"==typeof t&&t.startsWith("hcs://")&&(this.logger.debug(`Resolving inscribed message: ${t}`),t=await this.getMessageContent(t),this.logger.debug(`Resolved content length: ${t?.length}`));let i=t;try{const e=JSON.parse(t||"{}");if("hcs-10"===e.p&&"message"===e.op&&e.data){i=`[${e.operator_id||"unknown_sender"}]: ${e.data}`}else i=t}catch{i=t}l+=`\n[${new Date(e.timestamp).toLocaleString()}] (Seq: ${e.sequence_number})\n${i}\n`,d.push({timestamp:e.timestamp,sequenceNumber:e.sequence_number,content:i,raw:e})}catch(o){const t=`Error processing message (Seq: ${e.sequence_number}): ${o instanceof Error?o.message:String(o)}`;this.logger.error(t),l+=`\n[Error processing message Seq: ${e.sequence_number}]\n`}}!c&&a>r&&(this.logger.debug(`Updating timestamp for topic ${i} to ${a}`),this.stateManager.updateTimestamp(i,a)),this.executeResult={success:!0,rawResult:{messages:d,formattedOutput:l.trim(),targetAgentName:n,connectionTopicId:i}}}catch(o){this.logger.error(`Failed to check messages for topic ${i}: ${o}`),this.executeResult={success:!1,error:`Error checking messages for ${n}: ${o instanceof Error?o.message:String(o)}`}}return this}async findRegistrations(e){this.clearNotes();try{const t={network:this.network};e.accountId&&(t.accountId=e.accountId),e.tags&&e.tags.length>0&&(t.tags=e.tags);const i=await this.standardClient.findRegistrations(t);if(!i.success||i.error)return this.executeResult={success:!1,error:`Error finding registrations: ${i.error||"Unknown error"}`},this;if(!i.registrations||0===i.registrations.length)return this.executeResult={success:!0,rawResult:{registrations:[],message:"No registrations found matching the criteria."}},this;const n=i.registrations.map(e=>{const t=e;return`Agent: ${t.agent?.name||"Unknown Agent"} (${t.accountId||"Unknown Account"}), Capabilities: ${t.agent?.capabilities?.join(", ")||"None"}`}).join("\\n");this.executeResult={success:!0,rawResult:{registrations:i.registrations,formattedOutput:`Found ${i.registrations.length} registration(s):\\n${n}`}}}catch(t){this.logger.error("Error during FindRegistrations execution:",t),this.executeResult={success:!1,error:`Failed to search registrations: ${t instanceof Error?t.message:String(t)}`}}return this}async retrieveProfile(e){this.clearNotes();try{const t=await this.standardClient.retrieveProfile(e.accountId,e.disableCache||!1);if(!t.success)return this.executeResult={success:!1,error:`Failed to retrieve profile: ${t.error||"Unknown error"}`},this;const i=t.profile,n=t.topicInfo;let r=`Profile for ${e.accountId}:\n`;r+=`Name: ${i.name||"Unknown"}\n`,r+=`Bio: ${i.bio||"No bio provided"}\n`,r+=`Type: ${i.type||"Unknown"}\n`,r+=`Model: ${i.model||"Unknown"}\n`,i.capabilities&&i.capabilities.length>0?r+=`Capabilities: ${i.capabilities.join(", ")}\n`:r+="Capabilities: None listed\n",n&&(r+=`Inbound Topic: ${n.inboundTopic||"Unknown"}\n`,r+=`Outbound Topic: ${n.outboundTopic||"Unknown"}\n`,r+=`Profile Topic: ${n.profileTopicId||"Unknown"}\n`),i.social&&Object.keys(i.social).length>0&&(r+=`Social: ${Object.entries(i.social).map(([e,t])=>`${e}: ${t}`).join(", ")}\n`),i.properties&&Object.keys(i.properties).length>0&&(r+=`Properties: ${JSON.stringify(i.properties)}\n`),this.executeResult={success:!0,rawResult:{profileDetails:r,rawProfile:t}}}catch(t){this.logger.error(`Unexpected error retrieving profile for ${e.accountId}:`,t),this.executeResult={success:!1,error:`Unexpected error retrieving profile for ${e.accountId}: ${t instanceof Error?t.message:String(t)}`}}return this}async execute(){return this.executeResult?{success:this.executeResult.success,transactionId:this.executeResult.transactionId,receipt:this.executeResult.receipt,scheduleId:this.executeResult.scheduleId,error:this.executeResult.error,rawResult:this.executeResult.rawResult,notes:this.notes}:{success:!1,error:"No operation result available. Call a builder method first."}}}class le extends e.BasePlugin{constructor(){super(...arguments),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="Hashgraph Online",this.tools=[]}async initialize(e){await super.initialize(e),this.initializeTools()}initializeTools(){this.tools=[new e.HederaGetHbarPriceTool({hederaKit:this.context.config.hederaKit,logger:this.context.logger})]}getTools(){return this.tools}}class de extends e.BaseServiceBuilder{constructor(e){super(e)}async getHCS2Client(){if(!this.hcs2Client){const e=this.hederaKit.signer.getAccountId().toString(),i=this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"",n={network:this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",operatorId:e,operatorKey:i};this.hcs2Client=new t.HCS2Client(n)}return this.hcs2Client}async createRegistry(e={}){const t=await this.getHCS2Client();return await t.createRegistry(e)}async registerEntry(e,t){const i=await this.getHCS2Client();return await i.registerEntry(e,t)}async updateEntry(e,t){const i=await this.getHCS2Client();return await i.updateEntry(e,t)}async deleteEntry(e,t){const i=await this.getHCS2Client();return await i.deleteEntry(e,t)}async migrateRegistry(e,t){const i=await this.getHCS2Client();return await i.migrateRegistry(e,t)}async getRegistry(e,t={}){const i=await this.getHCS2Client();return await i.getRegistry(e,t)}async submitMessage(e,t){const i=await this.getHCS2Client();return await i.submitMessage(e,t)}async getTopicInfo(e){const t=await this.getHCS2Client();return await t.getTopicInfo(e)}async close(){this.hcs2Client&&(this.hcs2Client.close(),this.hcs2Client=void 0)}}class ue extends e.BaseServiceBuilder{constructor(e){super(e)}async getHCS6Client(){if(!this.hcs6Client){const e=this.hederaKit.signer.getAccountId().toString(),i=this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toString():"",n={network:this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",operatorId:e,operatorKey:i};this.hcs6Client=new t.HCS6Client(n)}return this.hcs6Client}async createRegistry(e={}){const t=await this.getHCS6Client(),i={...e};return"adminKey"in i&&delete i.adminKey,await t.createRegistry(i)}async registerEntry(e,t){const i=await this.getHCS6Client();return await i.registerEntry(e,t)}async getRegistry(e,t={}){const i=await this.getHCS6Client();return await i.getRegistry(e,t)}async createHashinal(e){const t=await this.getHCS6Client(),i={name:e.metadata?.name||"Dynamic Hashinal",creator:e.metadata?.creator||this.hederaKit.signer.getAccountId().toString(),description:e.metadata?.description||"Dynamic hashinal metadata",type:e.metadata?.type||"json",...e.metadata};return await t.createHashinal({...e,metadata:i})}async register(e){const t=await this.getHCS6Client(),i={name:e.metadata?.name||"Dynamic Hashinal",creator:e.metadata?.creator||this.hederaKit.signer.getAccountId().toString(),description:e.metadata?.description||"Dynamic hashinal registration",type:e.metadata?.type||"json",...e.metadata};return await t.register({...e,metadata:i})}async submitMessage(e,t){const i=await this.getHCS6Client();return await i.submitMessage(e,t)}async getTopicInfo(e){const t=await this.getHCS6Client();return await t.getTopicInfo(e)}async close(){this.hcs6Client&&(this.hcs6Client.close(),this.hcs6Client=void 0)}}class ge extends e.BaseServiceBuilder{constructor(e){super(e)}async getInscriptionSDK(e){return null}async inscribe(e,i){const n={accountId:this.hederaKit.signer.getAccountId().toString(),privateKey:this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"",network:this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet"};return await t.inscribe(e,n,i)}async inscribeWithSigner(e,i,n){return await t.inscribeWithSigner(e,i,n)}async retrieveInscription(e,i){const n=this.hederaKit.signer.getAccountId().toString(),r=this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"";return await t.retrieveInscription(e,{...i,accountId:n,privateKey:r})}async close(){this.inscriptionSDK=void 0}}Object.defineProperty(exports,"BasePlugin",{enumerable:!0,get:()=>e.BasePlugin}),Object.defineProperty(exports,"GetHbarPriceTool",{enumerable:!0,get:()=>e.HederaGetHbarPriceTool}),Object.defineProperty(exports,"PluginRegistry",{enumerable:!0,get:()=>e.PluginRegistry}),exports.AcceptConnectionRequestTool=M,exports.BaseHCS10QueryTool=u,exports.BaseHCS10TransactionTool=d,exports.BaseHCS2QueryTool=B,exports.BaseHCS2TransactionTool=P,exports.BaseHCS6QueryTool=G,exports.BaseHCS6TransactionTool=U,exports.BaseInscriberQueryTool=X,exports.BaseInscriberTransactionTool=Y,exports.CheckMessagesTool=C,exports.ConnectionMonitorTool=S,exports.CreateDynamicRegistryTool=class extends G{constructor(e){super(e),this.name="createDynamicRegistry",this.description="Create a new HCS-6 dynamic registry for managing evolving content"}get specificInputSchema(){return j}async executeQuery(e,t){const i=await this.hcs6Builder.createRegistry({ttl:e.ttl,submitKey:e.submitKey});if(!i.success)throw new Error(i.error||"Failed to create dynamic registry");return`Successfully created HCS-6 dynamic registry!\n\nTopic ID: ${i.topicId}\nTTL: ${e.ttl} seconds\n\nYou can now register dynamic hashinals to this registry using the topic ID.`}},exports.CreateRegistryTool=class extends B{constructor(){super(...arguments),this.name="createHCS2Registry",this.description="Create a new HCS-2 registry topic for storing decentralized data"}get specificInputSchema(){return D}async executeQuery(e,t){try{const t=await this.hcs2Builder.createRegistry({registryType:e.registryType,ttl:e.ttl,adminKey:e.adminKey,submitKey:e.submitKey});if(!t.success)throw new Error(t.error||"Failed to create registry");return`Successfully created HCS-2 registry!\n\nTopic ID: ${t.topicId}\nRegistry Type: ${1===e.registryType?"Non-Indexed":"Indexed"}\nTTL: ${e.ttl||86400} seconds\n\nYou can now register entries to this registry using the topic ID.`}catch(i){const e=i instanceof Error?i.message:"Failed to create HCS-2 registry";throw new Error(`Registry creation failed: ${e}`)}}},exports.DeleteEntryTool=class extends B{constructor(){super(...arguments),this.name="deleteHCS2Entry",this.description="Delete an entry from an indexed HCS-2 registry"}get specificInputSchema(){return L}async executeQuery(e,t){try{const t=await this.hcs2Builder.deleteEntry(e.registryTopicId,{uid:e.uid,memo:e.memo});if(!t.success)throw new Error(t.error||"Failed to delete entry");return`Successfully deleted entry from HCS-2 registry!\n\nRegistry Topic: ${e.registryTopicId}\nUID: ${e.uid}${e.memo?`\nMemo: ${e.memo}`:""}\n\nThe entry has been removed from the registry.`}catch(i){const e=i instanceof Error?i.message:"Failed to delete entry";throw new Error(`Entry deletion failed: ${e}`)}}},exports.FindRegistrationsTool=v,exports.HCS10Builder=ce,exports.HCS10Client=class{constructor(e,i,n,r){this.standardClient=new t.HCS10Client({network:n,operatorId:e,operatorPrivateKey:i,guardedRegistryBaseUrl:r?.registryUrl,logLevel:r?.logLevel}),this.guardedRegistryBaseUrl=r?.registryUrl||"",this.useEncryption=r?.useEncryption||!1;const o="true"===process.env.DISABLE_LOGGING;this.logger=new t.Logger({level:r?.logLevel||"info",silent:o})}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,i,n){try{return await this.standardClient.handleConnectionRequest(e,t,i,n)}catch(r){throw this.logger.error(`Error handling connection request #${i} for topic ${e}:`,r),new Error(`Failed to handle connection request: ${r instanceof Error?r.message:String(r)}`)}}async getAgentProfile(e){return this.standardClient.retrieveProfile(e)}async submitConnectionRequest(e,t){return this.standardClient.submitConnectionRequest(e,t)}async waitForConnectionConfirmation(e,t,i=60,n=2e3){return this.standardClient.waitForConnectionConfirmation(e,t,i,n)}async createAndRegisterAgent(e){const i=(new t.AgentBuilder).setName(e.name).setBio(e.description||"").setCapabilities(e.capabilities?e.capabilities:[t.AIAgentCapability.TEXT_GENERATION]).setType(e.type||"autonomous").setModel(e.model||"agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(t.InboundTopicType.PUBLIC);e?.feeConfig&&(i.setInboundTopicType(t.InboundTopicType.FEE_BASED),i.setFeeConfig(e.feeConfig)),e.pfpBuffer&&e.pfpFileName?0===e.pfpBuffer.byteLength?this.logger.warn("Provided PFP buffer is empty. Skipping profile picture."):(this.logger.info(`Setting profile picture: ${e.pfpFileName} (${e.pfpBuffer.byteLength} bytes)`),i.setProfilePicture(e.pfpBuffer,e.pfpFileName)):this.logger.warn("Profile picture not provided in metadata. Agent creation might fail if required by the underlying SDK builder."),e.social&&Object.entries(e.social).forEach(([e,t])=>{i.addSocial(e,t)}),e.properties&&Object.entries(e.properties).forEach(([e,t])=>{i.addProperty(e,t)});try{const t=Boolean(e?.feeConfig),n=await this.standardClient.createAndRegisterAgent(i,{initialBalance:t?50:void 0});return n?.metadata?.inboundTopicId&&n?.metadata?.outboundTopicId&&(this.agentChannels={inboundTopicId:n.metadata.inboundTopicId,outboundTopicId:n.metadata.outboundTopicId}),n}catch(n){throw this.logger.error("Error during agent creation/registration:",n),new Error(`Failed to create/register agent: ${n instanceof Error?n.message:String(n)}`)}}async sendMessage(e,t,i,n){this.useEncryption;try{const r=await this.standardClient.sendMessage(e,t,i,n);return r.topicSequenceNumber?.toNumber()}catch(r){throw this.logger.error(`Error sending message to topic ${e}:`,r),new Error(`Failed to send message: ${r instanceof Error?r.message:String(r)}`)}}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 i=`Failed to get inbound topic ID for operator ${t}.`;throw e instanceof Error&&e.message.includes("does not have a valid HCS-11 memo")?i+=` 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?i+=` Reason: ${e.message}`:i+=` Unexpected error: ${String(e)}`,new Error(i)}}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(e,i){return this.standardClient=new t.HCS10Client({network:this.getNetwork(),operatorId:e,operatorPrivateKey:i,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}},exports.HCS2Builder=de,exports.HCS6Builder=ue,exports.HbarPricePlugin=le,exports.InitiateConnectionTool=b,exports.InscribeFromBufferTool=class extends X{constructor(){super(...arguments),this.name="inscribeFromBuffer",this.description='Inscribe content that you have already retrieved or displayed. When user says "inscribe it" after you showed search results or other content, use THIS tool. The base64Data field accepts PLAIN TEXT (not just base64) and content reference IDs in format "content-ref:[id]". Pass the EXACT content from your previous response or MCP tool output. DO NOT generate new content or create repetitive text. Content references are automatically resolved to the original content for inscription. Set quoteOnly=true to get cost estimates without executing the inscription.',this.config=te()}get specificInputSchema(){return ie}async executeQuery(e,t){this.validateInput(e);const i=await this.resolveContent(e.base64Data,e.mimeType,e.fileName);this.validateContent(i.buffer);const n=i.buffer,r=i.mimeType||e.mimeType,o=i.fileName||e.fileName,s={mode:e.mode,metadata:e.metadata,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:!e.quoteOnly&&(e.waitForConfirmation??!0),waitMaxAttempts:10,waitIntervalMs:3e3,apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",quoteOnly:e.quoteOnly};if(e.quoteOnly)try{const e=await this.generateInscriptionQuote({type:"buffer",buffer:n,fileName:o,mimeType:r},s);return{success:!0,quote:{totalCostHbar:e.totalCostHbar,validUntil:e.validUntil,breakdown:e.breakdown},contentInfo:{fileName:o,mimeType:r,sizeBytes:n.length},message:`Estimated Quote for buffer content: ${o} (${(n.length/1024).toFixed(2)} KB)\nTotal cost: ${e.totalCostHbar} HBAR`}}catch(a){const e=a instanceof Error?a.message:"Failed to generate inscription quote";throw new Error(`Quote generation failed: ${e}`)}try{const t=await this.executeInscription(n,o,r,s,e.timeoutMs);return this.formatInscriptionResult(t,s)}catch(a){const e=a instanceof Error?a.message:"Failed to inscribe from buffer";throw new Error(`Inscription failed: ${e}`)}}validateInput(e){if(!e.base64Data||""===e.base64Data.trim())throw new Error("No data provided. Cannot inscribe empty content. Please provide valid content, plain text, base64 encoded data, or a content reference ID.");if(!e.fileName||""===e.fileName.trim())throw new Error("No fileName provided. A valid fileName is required for inscription.")}validateContent(e){if(0===e.length)throw new Error("Buffer is empty after conversion. The provided data appears to be invalid or empty.");if(e.length>this.config.maxInscriptionSize){const t=Math.round(this.config.maxInscriptionSize/1024),i=Math.round(e.length/1024);throw new Error(`Content is too large for inscription (${i}KB, max ${t}KB). Please summarize or extract key information before inscribing.`)}if(e.length<this.config.minContentSize)throw new Error(`Buffer content is too small (${e.length} bytes). This may indicate empty or invalid content. Please verify the source data contains actual content.`);if(""===e.toString("utf8",0,Math.min(e.length,100)).trim())throw new Error("Buffer contains only whitespace or empty content. Cannot inscribe meaningless data.");const t=e.toString("utf8");if(/<a\s+href=["'][^"']+["']\s*>\s*<\/a>/i.test(t)&&t.replace(/<[^>]+>/g,"").trim().length<50)throw new Error("Buffer contains empty HTML with only links and no actual content. When inscribing content from external sources, use the actual article text you retrieved, not empty HTML with links.")}async executeInscription(e,t,i,n,r){const o={type:"buffer",buffer:e,fileName:t,mimeType:i};if(r){const e=new Promise((e,t)=>{setTimeout(()=>t(new Error(`Inscription timed out after ${r}ms`)),r)});return Promise.race([this.inscriberBuilder.inscribe(o,n),e])}return this.inscriberBuilder.inscribe(o,n)}formatInscriptionResult(e,t){if(e.confirmed&&!e.quote){const i=e.inscription?.topic_id||e.result.topicId,n=t.network||"testnet",r=i?`https://kiloscribe.com/api/inscription-cdn/${i}?network=${n}`:null;return`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${e.result.transactionId}\nTopic ID: ${i||"N/A"}${r?`\nView inscription: ${r}`:""}\n\nThe inscription is now available.`}return e.quote||e.confirmed?"Inscription operation completed.":`Successfully submitted inscription to the Hedera network!\n\nTransaction ID: ${e.result.transactionId}\n\nThe inscription is processing and will be confirmed shortly.`}async resolveContent(e,i,n){const r=e.trim(),o=this.getContentResolver()||t.ContentResolverRegistry.getResolver();if(!o)return this.handleDirectContent(r,i,n);const s=o.extractReferenceId(r);if(s)try{const e=await o.resolveReference(s);return{buffer:e.content,mimeType:e.metadata?.mimeType||i,fileName:e.metadata?.fileName||n,wasReference:!0}}catch(a){const e=a instanceof Error?a.message:"Unknown error resolving reference";throw new Error(`Reference resolution failed: ${e}`)}return this.handleDirectContent(r,i,n)}handleDirectContent(e,t,i){if(/^[A-Za-z0-9+/]*={0,2}$/.test(e))try{return{buffer:globalThis.Buffer.from(e,"base64"),mimeType:t,fileName:i,wasReference:!1}}catch(n){throw new Error("Failed to decode base64 data. Please ensure the data is properly encoded.")}return{buffer:globalThis.Buffer.from(e,"utf8"),mimeType:t||"text/plain",fileName:i,wasReference:!1}}},exports.InscribeFromFileTool=class extends X{constructor(){super(...arguments),this.name="inscribeFromFile",this.description="Inscribe content from a local file to the Hedera network using a file path. IMPORTANT: Only use this tool when you have a valid file path to actual content. The file must exist and contain meaningful data (minimum 10 bytes). For files accessed through MCP filesystem tools, consider reading the file content first and using inscribeFromBuffer instead. Set quoteOnly=true to get cost estimates without executing the inscription."}get specificInputSchema(){return Z}async executeQuery(e,t){let i;console.log(`[DEBUG] InscribeFromFileTool.executeQuery called with: ${e.filePath}`);try{console.log(`[DEBUG] Checking file: ${e.filePath}`),console.log(`[DEBUG] Current working directory: ${process.cwd()}`);const t=await l.stat(e.filePath);if(!t.isFile())throw new Error(`Path "${e.filePath}" is not a file`);if(console.log(`[DEBUG] File size: ${t.size} bytes`),0===t.size)throw new Error(`File "${e.filePath}" is empty (0 bytes). Cannot inscribe empty files.`);if(t.size<10)throw new Error(`File "${e.filePath}" is too small (${t.size} bytes). Files must contain at least 10 bytes of meaningful content.`);if(t.size>104857600&&console.log(`[InscribeFromFileTool] WARNING: Large file detected (${(t.size/1048576).toFixed(2)} MB)`),this.logger?.info("Reading file content..."),i=await l.readFile(e.filePath),this.logger?.info(`Read ${i.length} bytes from file`),!i||0===i.length)throw new Error(`File "${e.filePath}" has no content after reading. Cannot inscribe empty files.`);if(i.length<10)throw new Error(`File "${e.filePath}" content is too small (${i.length} bytes). Files must contain at least 10 bytes of meaningful content.`);const n=c.basename(e.filePath),r=this.getMimeType(n);if(r.startsWith("text/")||"application/json"===r){if(""===i.toString("utf8",0,Math.min(i.length,1e3)).trim())throw new Error(`File "${e.filePath}" contains only whitespace or empty content. Cannot inscribe meaningless data.`)}}catch(a){if(a instanceof Error){if(a.message.includes("ENOENT"))throw new Error(`File not found: "${e.filePath}"`);throw a}throw new Error(`Failed to read file: ${a}`)}const n=i.toString("base64");this.logger?.info(`Converted to base64: ${n.length} characters`);const r=c.basename(e.filePath),o=this.getMimeType(r);this.logger?.info(`File: ${r}, MIME type: ${o}`);const s={mode:e.mode,metadata:e.metadata,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:!e.quoteOnly&&(e.waitForConfirmation??!0),waitMaxAttempts:10,waitIntervalMs:3e3,apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",quoteOnly:e.quoteOnly};if(e.quoteOnly)try{const t=await this.generateInscriptionQuote({type:"buffer",buffer:globalThis.Buffer.from(n,"base64"),fileName:r,mimeType:o},s);return{success:!0,quote:{totalCostHbar:t.totalCostHbar,validUntil:t.validUntil,breakdown:t.breakdown},contentInfo:{fileName:r,mimeType:o,sizeBytes:i.length,filePath:e.filePath},message:`Estimated Quote for file: ${r} (${(i.length/1024).toFixed(2)} KB)\nTotal cost: ${t.totalCostHbar} HBAR`}}catch(a){const e=a instanceof Error?a.message:"Failed to generate inscription quote";throw new Error(`Quote generation failed: ${e}`)}try{let t;if(e.timeoutMs){const i=new Promise((t,i)=>{setTimeout(()=>i(new Error(`Inscription timed out after ${e.timeoutMs}ms`)),e.timeoutMs)});t=await Promise.race([this.inscriberBuilder.inscribe({type:"buffer",buffer:globalThis.Buffer.from(n,"base64"),fileName:r,mimeType:o},s),i])}else t=await this.inscriberBuilder.inscribe({type:"buffer",buffer:globalThis.Buffer.from(n,"base64"),fileName:r,mimeType:o},s);const i=t;if(i.confirmed&&!i.quote){const e=i.inscription?.topic_id||i.result.topicId,t=e?`https://kiloscribe.com/api/inscription-cdn/${e}?network=${s.network||"testnet"}`:null;return`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${i.result.transactionId}\nTopic ID: ${e||"N/A"}${t?`\nView inscription: ${t}`:""}\n\nThe inscription is now available.`}return i.quote||i.confirmed?"Inscription operation completed.":`Successfully submitted inscription to the Hedera network!\n\nTransaction ID: ${i.result.transactionId}\n\nThe inscription is processing and will be confirmed shortly.`}catch(a){const e=a instanceof Error?a.message:"Failed to inscribe from file";throw new Error(`Inscription failed: ${e}`)}}getMimeType(e){return{".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".pdf":"application/pdf",".json":"application/json",".txt":"text/plain",".html":"text/html",".css":"text/css",".js":"application/javascript",".ts":"application/typescript",".mp4":"video/mp4",".mp3":"audio/mpeg",".wav":"audio/wav",".zip":"application/zip"}[c.extname(e).toLowerCase()]||"application/octet-stream"}},exports.InscribeFromUrlTool=class extends X{constructor(){super(...arguments),this.name="inscribeFromUrl",this.description='ONLY for direct FILE DOWNLOAD URLs ending with file extensions (.pdf, .jpg, .png, .json, .zip). NEVER use for web pages, articles, or ANY HTML content - it WILL FAIL. If you have already retrieved content from any source (including MCP tools), you MUST use inscribeFromBuffer instead. This tool downloads files from URLs - it does NOT inscribe content you already have. When asked to "inscribe it" after retrieving content, ALWAYS use inscribeFromBuffer with the actual content. Set quoteOnly=true to get cost estimates without executing the inscription.'}get specificInputSchema(){return J}async executeQuery(e,t){if(console.log(`[DEBUG] InscribeFromUrlTool.executeQuery called with URL: ${e.url}`),!e.url||""===e.url.trim())throw new Error("URL cannot be empty. Please provide a valid URL.");try{const t=new URL(e.url);if(!t.protocol||!t.host)throw new Error("Invalid URL format. Please provide a complete URL with protocol (http/https).");if(!["http:","https:"].includes(t.protocol))throw new Error("Only HTTP and HTTPS URLs are supported for inscription.")}catch(n){if(n instanceof Error&&n.message.includes("Cannot inscribe content from"))throw n;throw new Error(`Invalid URL: ${e.url}. Please provide a valid URL.`)}console.log("[InscribeFromUrlTool] Validating URL content before inscription...");try{const t=new AbortController,i=setTimeout(()=>t.abort(),1e4);try{const n=await fetch(e.url,{method:"HEAD",signal:t.signal});if(clearTimeout(i),!n.ok)throw new Error(`URL returned error status ${n.status}: ${n.statusText}. Cannot inscribe content from inaccessible URLs.`);const o=n.headers.get("content-type")||"",s=n.headers.get("content-length");if(["text/html","application/xhtml+xml","text/xml"].some(e=>o.toLowerCase().includes(e)))throw new Error(`URL returns HTML/web page content (Content-Type: ${o}). This tool only works with direct file URLs (PDFs, images, JSON, etc.). For web page content, first retrieve the content using the appropriate MCP tool or web scraper, then use inscribeFromBuffer to inscribe it.`);if(s&&0===parseInt(s))throw new Error("URL returns empty content (Content-Length: 0). Cannot inscribe empty content.");if(s&&parseInt(s)<10)throw new Error(`URL content is too small (${s} bytes). Content must be at least 10 bytes.`);if(!o||"application/octet-stream"===o){console.log("[InscribeFromUrlTool] Content-Type unclear, fetching first 1KB to verify...");const t=new AbortController,i=setTimeout(()=>t.abort(),5e3);try{const n=await fetch(e.url,{signal:t.signal,headers:{Range:"bytes=0-1023"}});if(clearTimeout(i),n.ok||206===n.status){const e=await n.arrayBuffer(),t=new Uint8Array(e),i=new TextDecoder("utf-8",{fatal:!1}).decode(t.slice(0,512));if(i.toLowerCase().includes("<!doctype html")||i.toLowerCase().includes("<html")||i.match(/<meta\s+[^>]*>/i)||i.match(/<title>/i))throw new Error("URL returns HTML content. This tool only works with direct file URLs. For web page content, first retrieve it using the appropriate tool, then use inscribeFromBuffer.")}}catch(r){if(clearTimeout(i),r instanceof Error&&r.message.includes("HTML content"))throw r;console.log(`[InscribeFromUrlTool] Could not perform partial GET validation: ${r instanceof Error?r.message:"Unknown error"}`)}}console.log(`[InscribeFromUrlTool] URL validation passed. Content-Type: ${o}, Content-Length: ${s||"unknown"}`)}catch(o){throw clearTimeout(i),o}}catch(n){if(n instanceof Error)if("AbortError"===n.name)console.log("[InscribeFromUrlTool] Warning: URL validation timed out after 10 seconds. Proceeding with inscription attempt.");else{if(n.message.includes("URL returned error")||n.message.includes("empty content")||n.message.includes("too small")||n.message.includes("HTML"))throw n;console.log(`[InscribeFromUrlTool] Warning: Could not validate URL with HEAD request: ${n.message}. Proceeding with inscription attempt.`)}}const i={mode:e.mode,metadata:e.metadata,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:!e.quoteOnly&&(e.waitForConfirmation??!0),waitMaxAttempts:10,waitIntervalMs:3e3,apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",quoteOnly:e.quoteOnly};if(e.quoteOnly)try{const t=await this.generateInscriptionQuote({type:"url",url:e.url},i);return{success:!0,quote:{totalCostHbar:t.totalCostHbar,validUntil:t.validUntil,breakdown:t.breakdown},contentInfo:{url:e.url},message:`Estimated Quote for URL: ${e.url}\nTotal cost: ${t.totalCostHbar} HBAR`}}catch(n){const e=n instanceof Error?n.message:"Failed to generate inscription quote";throw new Error(`Quote generation failed: ${e}`)}try{let t;if(e.timeoutMs){const n=new Promise((t,i)=>{setTimeout(()=>i(new Error(`Inscription timed out after ${e.timeoutMs}ms`)),e.timeoutMs)});t=await Promise.race([this.inscriberBuilder.inscribe({type:"url",url:e.url},i),n])}else t=await this.inscriberBuilder.inscribe({type:"url",url:e.url},i);if(t.confirmed&&!t.quote){const e=t.inscription?.topic_id||t.result.topicId,n=e?`https://kiloscribe.com/api/inscription-cdn/${e}?network=${i.network||"testnet"}`:null;return`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${t.result.transactionId}\nTopic ID: ${e||"N/A"}${n?`\nView inscription: ${n}`:""}\n\nThe inscription is now available.`}return t.quote||t.confirmed?"Inscription operation completed.":`Successfully submitted inscription to the Hedera network!\n\nTransaction ID: ${t.result.transactionId}\n\nThe inscription is processing and will be confirmed shortly.`}catch(n){const e=n instanceof Error?n.message:"Failed to inscribe from URL";throw new Error(`Inscription failed: ${e}`)}}},exports.InscribeHashinalTool=class extends X{constructor(){super(...arguments),this.name="inscribeHashinal",this.description="Inscribe content as a Hashinal NFT on the Hedera network. Set quoteOnly=true to get cost estimates without executing the inscription."}get specificInputSchema(){return ne}async executeQuery(e,t){const i={mode:"hashinal",metadata:{name:e.name,creator:e.creator,description:e.description,type:e.type,attributes:e.attributes,properties:e.properties},jsonFileURL:e.jsonFileURL,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:!e.quoteOnly&&(e.waitForConfirmation??!0),waitMaxAttempts:10,waitIntervalMs:3e3,apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",quoteOnly:e.quoteOnly};if(e.quoteOnly)try{const t=await this.generateInscriptionQuote({type:"url",url:e.url},i);return{success:!0,quote:{totalCostHbar:t.totalCostHbar,validUntil:t.validUntil,breakdown:t.breakdown},contentInfo:{url:e.url,name:e.name,creator:e.creator,type:e.type},message:`Estimated Quote for Hashinal NFT: ${e.name}\nCreator: ${e.creator}\nTotal cost: ${t.totalCostHbar} HBAR`}}catch(n){const e=n instanceof Error?n.message:"Failed to generate inscription quote";throw new Error(`Quote generation failed: ${e}`)}try{let t;if(e.timeoutMs){const n=new Promise((t,i)=>{setTimeout(()=>i(new Error(`Inscription timed out after ${e.timeoutMs}ms`)),e.timeoutMs)});t=await Promise.race([this.inscriberBuilder.inscribe({type:"url",url:e.url},i),n])}else t=await this.inscriberBuilder.inscribe({type:"url",url:e.url},i);if(t.confirmed&&!t.quote){const e=t.inscription?.topic_id||t.result.topicId,n=e?`https://kiloscribe.com/api/inscription-cdn/${e}?network=${i.network||"testnet"}`:null;return`Successfully inscribed and confirmed Hashinal NFT on the Hedera network!\n\nTransaction ID: ${t.result.transactionId}\nTopic ID: ${e||"N/A"}${n?`\nView inscription: ${n}`:""}\n\nThe Hashinal NFT is now available.`}return t.quote||t.confirmed?"Inscription operation completed.":`Successfully submitted Hashinal NFT inscription to the Hedera network!\n\nTransaction ID: ${t.result.transactionId}\n\nThe inscription is processing and will be confirmed shortly.`}catch(n){const e=n instanceof Error?n.message:"Failed to inscribe Hashinal NFT";throw new Error(`Inscription failed: ${e}`)}}},exports.InscriberBuilder=ge,exports.ListConnectionsTool=T,exports.ListUnapprovedConnectionRequestsTool=k,exports.ManageConnectionRequestsTool=$,exports.MigrateRegistryTool=class extends B{constructor(){super(...arguments),this.name="migrateHCS2Registry",this.description="Migrate an HCS-2 registry to a new topic"}get specificInputSchema(){return H}async executeQuery(e,t){try{const t=await this.hcs2Builder.migrateRegistry(e.registryTopicId,{targetTopicId:e.targetTopicId,metadata:e.metadata,memo:e.memo});if(!t.success)throw new Error(t.error||"Failed to migrate registry");return`Successfully migrated HCS-2 registry!\n\nFrom Registry Topic: ${e.registryTopicId}\nTo Target Topic: ${e.targetTopicId}${e.metadata?`\nMetadata: ${e.metadata}`:""}${e.memo?`\nMemo: ${e.memo}`:""}\n\nThe registry has been migrated to the new topic.`}catch(i){const e=i instanceof Error?i.message:"Failed to migrate registry";throw new Error(`Registry migration failed: ${e}`)}}},exports.NaturalLanguageMapper=p,exports.OpenConvaiState=se,exports.QueryDynamicRegistryTool=class extends G{constructor(e){super(e),this.name="queryDynamicRegistry",this.description="Query a dynamic registry to get the current state of a dynamic hashinal"}get specificInputSchema(){return V}async executeQuery(e,t){const i=await this.hcs6Builder.getRegistry(e.topicId,{limit:e.limit,order:e.order,skip:e.skip}),n=i.latestEntry?{topicId:i.latestEntry.message.t_id,timestamp:i.latestEntry.timestamp,memo:i.latestEntry.message.m,sequence:i.latestEntry.sequence,payer:i.latestEntry.payer}:null;return`Successfully queried dynamic registry!\n\nRegistry Topic: ${i.topicId}\nRegistry Type: NON_INDEXED\nTTL: ${i.ttl} seconds\nTotal Entries: ${i.entries.length}${n?`\n\nLatest Entry:\n- Topic ID: ${n.topicId}\n- Timestamp: ${n.timestamp}\n- Memo: ${n.memo||"N/A"}\n- Sequence: ${n.sequence}`:"\n\nNo entries found in registry."}`}},exports.QueryRegistryTool=class extends B{constructor(){super(...arguments),this.name="queryHCS2Registry",this.description="Query entries from an HCS-2 registry"}get specificInputSchema(){return K}async executeQuery(e,t){const i=await this.hcs2Builder.getRegistry(e.topicId,{limit:e.limit,order:e.order,skip:e.skip});return{topicId:i.topicId,registryType:0===i.registryType?"indexed":"non-indexed",ttl:i.ttl,totalEntries:i.entries.length,entries:i.entries.map(e=>({sequence:e.sequence,timestamp:e.timestamp,payer:e.payer,operation:e.message.op,targetTopicId:e.message.t_id,uid:e.message.uid,metadata:e.message.metadata,memo:e.message.m}))}}},exports.RegisterAgentTool=m,exports.RegisterDynamicHashinalTool=class extends G{constructor(e){super(e),this.name="registerDynamicHashinal",this.description="Create and register a new dynamic hashinal that can be updated over time"}get specificInputSchema(){return Q}async executeQuery(e,t){const i=await this.hcs6Builder.register({metadata:e.metadata,data:e.data,memo:e.memo,ttl:e.ttl,registryTopicId:e.registryTopicId,submitKey:e.submitKey});if(!i.success)throw new Error(i.error||"Failed to register dynamic hashinal");return`Successfully registered dynamic hashinal!\n\nRegistry Topic ID: ${i.registryTopicId}\nInscription Topic ID: ${i.inscriptionTopicId}${e.memo?`\nMemo: ${e.memo}`:""}\n\nThe dynamic hashinal has been created and can be updated using the registry topic ID.`}},exports.RegisterEntryTool=class extends B{constructor(){super(...arguments),this.name="registerHCS2Entry",this.description="Register a new entry in an HCS-2 registry"}get specificInputSchema(){return F}async executeQuery(e,t){try{const t=await this.hcs2Builder.registerEntry(e.registryTopicId,{targetTopicId:e.targetTopicId,metadata:e.metadata,memo:e.memo});if(!t.success)throw new Error(t.error||"Failed to register entry");return`Successfully registered entry in HCS-2 registry!\n\nRegistry Topic: ${e.registryTopicId}\nTarget Topic ID: ${e.targetTopicId}${e.metadata?`\nMetadata: ${e.metadata}`:""}${e.memo?`\nMemo: ${e.memo}`:""}\n\nThe entry has been added to the registry.`}catch(i){const e=i instanceof Error?i.message:"Failed to register entry";throw new Error(`Entry registration failed: ${e}`)}}},exports.RetrieveInscriptionTool=class extends X{constructor(){super(...arguments),this.name="retrieveInscription",this.description="Retrieve details of an existing inscription from the Hedera network"}get specificInputSchema(){return re}async executeQuery(e,t){const i=await this.inscriberBuilder.retrieveInscription(e.transactionId,{apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet"});return{inscriptionId:i.inscriptionId,transactionId:i.transactionId,topicId:i.topic_id,status:i.status,holderId:i.holderId,metadata:i.metadata,tags:i.tags,mode:i.mode,chunks:i.chunks,createdAt:i.createdAt,completedAt:i.completed||i.completedAt,fileUrl:i.fileUrl,mimeType:i.mimeType,fileSize:i.fileSize}}},exports.RetrieveProfileTool=z,exports.SendMessageToConnectionTool=y,exports.UpdateDynamicHashinalTool=class extends G{constructor(e){super(e),this.name="updateDynamicHashinal",this.description="Update an existing dynamic hashinal with new content while maintaining the same registry"}get specificInputSchema(){return W}async executeQuery(e,t){const i=await this.hcs6Builder.register({metadata:e.metadata,data:e.data,memo:e.memo,registryTopicId:e.registryTopicId,submitKey:e.submitKey});if(!i.success)throw new Error(i.error||"Failed to update dynamic hashinal");return`Successfully updated dynamic hashinal!\n\nRegistry Topic ID: ${e.registryTopicId}\nInscription Topic ID: ${i.inscriptionTopicId}${e.memo?`\nUpdate Memo: ${e.memo}`:""}\n\nThe dynamic hashinal has been updated with new content.`}},exports.UpdateEntryTool=class extends B{constructor(){super(...arguments),this.name="updateHCS2Entry",this.description="Update an existing entry in an indexed HCS-2 registry"}get specificInputSchema(){return _}async executeQuery(e,t){try{const t=await this.hcs2Builder.updateEntry(e.registryTopicId,{targetTopicId:e.targetTopicId,uid:e.uid,metadata:e.metadata,memo:e.memo});if(!t.success)throw new Error(t.error||"Failed to update entry");return`Successfully updated entry in HCS-2 registry!\n\nRegistry Topic: ${e.registryTopicId}\nUID: ${e.uid}\nNew Target Topic ID: ${e.targetTopicId}${e.metadata?`\nMetadata: ${e.metadata}`:""}${e.memo?`\nMemo: ${e.memo}`:""}\n\nThe entry has been updated in the registry.`}catch(i){const e=i instanceof Error?i.message:"Failed to update entry";throw new Error(`Entry update failed: ${e}`)}}},exports.initializeStandardsAgentKit=async i=>{const n=i?.clientConfig||{},r=n.operatorId||process.env.HEDERA_OPERATOR_ID,o=n.operatorKey||process.env.HEDERA_OPERATOR_KEY,s=n.network||process.env.HEDERA_NETWORK||"testnet";let a;if("mainnet"===s?a="mainnet":("testnet"===s||console.warn(`Unsupported network specified: '${s}'. Defaulting to 'testnet'.`),a="testnet"),!r||!o)throw new Error("Operator ID and private key must be provided either through options or environment variables.");const c="true"===process.env.DISABLE_LOGGING,l=t.Logger.getInstance({level:n.logLevel||"info",silent:c}),d=i?.stateManager||new se({defaultEnvFilePath:oe,defaultPrefix:"TODD"});l.info("State manager initialized");const u=new e.ServerSigner(r,o,a),g=new e.HederaAgentKit(u);await g.initialize(),l.info(`HederaAgentKit initialized for ${r} on ${a}`);const p=new ce(g,d,{useEncryption:n.useEncryption,registryUrl:n.registryUrl,logLevel:n.logLevel});let h,f;if(i?.monitoringClient){const t=new e.ServerSigner(r,o,a);h=new e.HederaAgentKit(t),await h.initialize(),f=new ce(h,d,{useEncryption:n.useEncryption,registryUrl:n.registryUrl,logLevel:"error"}),l.info("Monitoring client initialized")}const I={};return I.registerAgentTool=new m({hederaKit:g,hcs10Builder:p,logger:void 0}),i?.createAllTools&&(I.findRegistrationsTool=new v({hederaKit:g,hcs10Builder:p,logger:void 0}),I.retrieveProfileTool=new z({hederaKit:g,hcs10Builder:p,logger:void 0}),I.initiateConnectionTool=new b({hederaKit:g,hcs10Builder:p,logger:void 0}),I.listConnectionsTool=new T({hederaKit:g,hcs10Builder:p,logger:void 0}),I.sendMessageToConnectionTool=new y({hederaKit:g,hcs10Builder:p,logger:void 0}),I.checkMessagesTool=new C({hederaKit:g,hcs10Builder:p,logger:void 0}),I.connectionMonitorTool=new S({hederaKit:h||g,hcs10Builder:f||p,logger:void 0}),I.manageConnectionRequestsTool=new $({hederaKit:g,hcs10Builder:p,logger:void 0}),I.acceptConnectionRequestTool=new M({hederaKit:g,hcs10Builder:p,logger:void 0}),I.listUnapprovedConnectionRequestsTool=new k({hederaKit:g,hcs10Builder:p,logger:void 0}),l.info("All tools initialized")),{hederaKit:g,hcs10Builder:p,monitoringHederaKit:h,monitoringHcs10Builder:f,tools:I,stateManager:d}},exports.loadConfig=te;
2
2
  //# sourceMappingURL=standards-agent-kit.cjs.map