@hashgraphonline/standards-agent-kit 0.2.159 → 0.2.160
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/builders/inscriber/inscriber-builder.d.ts +6 -6
- package/dist/cjs/standards-agent-kit.cjs +1 -1
- package/dist/cjs/standards-agent-kit.cjs.map +1 -1
- package/dist/es/builders/inscriber/inscriber-builder.d.ts +6 -6
- package/dist/es/standards-agent-kit.es48.js +7 -3
- package/dist/es/standards-agent-kit.es48.js.map +1 -1
- package/dist/es/standards-agent-kit.es49.js +3 -7
- package/dist/es/standards-agent-kit.es49.js.map +1 -1
- package/dist/es/standards-agent-kit.es6.js +1 -1
- package/dist/es/standards-agent-kit.es7.js +1 -1
- package/dist/es/standards-agent-kit.es8.js +27 -4
- package/dist/es/standards-agent-kit.es8.js.map +1 -1
- package/dist/es/standards-agent-kit.es9.js +1 -1
- package/dist/umd/builders/inscriber/inscriber-builder.d.ts +6 -6
- package/dist/umd/standards-agent-kit.umd.js +30 -30
- package/dist/umd/standards-agent-kit.umd.js.map +1 -1
- package/package.json +1 -1
- package/src/builders/inscriber/inscriber-builder.ts +47 -11
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("@hashgraph/sdk"),t=require("@hashgraphonline/standards-sdk"),i=require("hedera-agent-kit"),n=require("fs"),r=require("path"),o=require("axios"),s=require("@kiloscribe/inscription-sdk"),a=require("zod"),c=require("fs/promises");function l(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 d=l(r),u=l(c);class g extends i.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}class p extends i.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}const h=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"}};h.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 f=h;const m=a.z.object({name:a.z.string().min(1).max(50).describe("A unique name for the agent (1-50 characters)"),description:a.z.string().max(500).optional().describe("Optional bio description for the agent (max 500 characters)"),alias:a.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:a.z.enum(["autonomous","manual"]).optional().describe("Agent type (default: autonomous)"),model:a.z.string().optional().describe("AI model identifier (default: agent-model-2024)"),capabilities:a.z.union([a.z.array(a.z.nativeEnum(t.AIAgentCapability)),a.z.array(a.z.string()),a.z.string()]).optional().transform(e=>{if(e)return"string"==typeof e?f.parseCapabilities(e):Array.isArray(e)&&e.length>0&&"string"==typeof e[0]?f.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:a.z.union([a.z.array(a.z.string()),a.z.string()]).optional().transform(e=>{if(e)return"string"==typeof e?f.parseCapabilities(e):f.parseTagsOrCapabilities(e)}).describe('Tags for the agent (alternative to capabilities) - e.g. "ai", "data", "analytics". Will be converted to appropriate capabilities.'),creator:a.z.string().optional().describe("Creator attribution for the agent"),socials:a.z.record(a.z.enum(["twitter","github","discord","telegram","linkedin","youtube","website","x"]),a.z.string()).optional().describe('Social media links (e.g., {"twitter": "@handle", "discord": "username"})'),properties:a.z.record(a.z.unknown()).optional().describe("Custom metadata properties for the agent"),profilePicture:a.z.union([a.z.string().describe("URL or local file path to profile picture"),a.z.object({url:a.z.string().optional(),path:a.z.string().optional(),filename:a.z.string().optional()})]).optional().describe("Optional profile picture as URL, file path, or object with url/path/filename"),existingProfilePictureTopicId:a.z.string().optional().describe("Topic ID of an existing profile picture to reuse (e.g., 0.0.12345)"),initialBalance:a.z.number().positive().optional().describe("Optional initial HBAR balance for the new agent account (will create new account if provided)"),userAccountId:a.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:a.z.number().positive().optional().describe("Optional HBAR fee amount to charge per message on the inbound topic"),tokenFees:a.z.array(a.z.object({amount:a.z.number().positive(),tokenId:a.z.string()})).optional().describe("Optional token fees to charge per message"),exemptAccountIds:a.z.array(a.z.string()).optional().describe("Optional account IDs to exempt from fees"),setAsCurrent:a.z.boolean().optional().describe("Whether to set as current agent (default: true)"),persistence:a.z.object({prefix:a.z.string().optional()}).optional().describe("Optional persistence configuration")});class y extends g{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=m,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 b=new t.Logger({module:"SendMessageToConnectionTool"}),w=a.z.object({targetIdentifier:a.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:a.z.string().optional().describe("The connection number (e.g., '1', '2') from the 'list_connections' tool."),agentId:a.z.string().optional().describe("The account ID (e.g., 0.0.12345) of the target agent."),message:a.z.string().describe("The text message content to send."),disableMonitoring:a.z.boolean().optional().default(!1)});class I extends g{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=w,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){b.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 T=a.z.object({targetAccountId:a.z.string().describe("The Hedera account ID (e.g., 0.0.12345) of the agent you want to connect with."),disableMonitor:a.z.boolean().optional().describe("If true, does not wait for connection confirmation. Returns immediately after sending the request."),memo:a.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 A extends g{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=T,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 C=a.z.object({includeDetails:a.z.boolean().optional().describe("Whether to include detailed information about each connection"),showPending:a.z.boolean().optional().describe("Whether to include pending connection requests")});class v extends p{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=C}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 E=a.z.object({targetIdentifier:a.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:a.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:a.z.number().int().positive().optional().describe("When fetchLatest is true, specifies how many of the most recent messages to retrieve. Defaults to 1.")});class S extends p{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=E}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 R=a.z.object({accountId:a.z.string().optional().describe("Optional: Filter registrations by a specific Hedera account ID (e.g., 0.0.12345)."),tags:a.z.union([a.z.array(a.z.nativeEnum(t.AIAgentCapability)),a.z.array(a.z.string()),a.z.string()]).optional().transform(e=>{if(e)return"string"==typeof e?f.parseCapabilities(e):Array.isArray(e)&&e.length>0&&"string"==typeof e[0]?f.parseTagsOrCapabilities(e):e}).describe('Optional: Filter by capabilities/tags like "ai", "data", "analytics". Can be natural language terms or capability numbers.')});class N extends p{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=R}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 x=a.z.object({acceptAll:a.z.boolean().optional().describe("Whether to automatically accept all incoming connection requests. Default is false."),targetAccountId:a.z.string().optional().describe("If provided, only accept connection requests from this specific account ID."),hbarFees:a.z.array(a.z.object({amount:a.z.number(),collectorAccount:a.z.string().optional()})).optional().describe("Array of HBAR fee amounts to charge per message (with optional collector accounts)."),tokenFees:a.z.array(a.z.object({amount:a.z.number(),tokenId:a.z.string(),collectorAccount:a.z.string().optional()})).optional().describe("Array of token fee amounts and IDs to charge per message (with optional collector accounts)."),exemptAccountIds:a.z.array(a.z.string()).optional().describe("Array of account IDs to exempt from ALL fees set in this request."),monitorDurationSeconds:a.z.number().optional().describe("How long to monitor for incoming requests in seconds. Default is 120."),defaultCollectorAccount:a.z.string().optional().describe("Default account to collect fees if not specified at the fee level. Defaults to the agent account.")});class O extends g{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=x,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 q=a.z.object({action:a.z.enum(["list","view","reject"]).describe("The action to perform: list all requests, view details of a specific request, or reject a request"),requestKey:a.z.string().optional().describe("The unique request key to view or reject (required for view and reject actions)")});class $ extends p{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=q}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 B=a.z.object({requestKey:a.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:a.z.number().optional().describe("Optional HBAR fee amount to charge the connecting agent per message on the new connection topic."),exemptAccountIds:a.z.array(a.z.string()).optional().describe("Optional list of account IDs to exempt from any configured fees on the new connection topic.")});class M extends g{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=B,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 k=a.z.object({accountId:a.z.string().describe("The Hedera account ID of the agent whose profile you want to retrieve (e.g., 0.0.12345)."),disableCache:a.z.boolean().optional().describe("Optional: Force refresh from the network instead of using cache.")});class _ extends p{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=k}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 z=a.z.object({});class P extends p{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=z}async executeQuery(){const e=this.hcs10Builder;await e.listUnapprovedConnectionRequests();const t=await e.execute();return"rawResult"in t?t.rawResult:t}}class D extends i.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs2",this.hcs2Builder=e.hcs2Builder}getServiceBuilder(){return this.hcs2Builder}}class H extends i.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs2",this.hcs2Builder=e.hcs2Builder}getServiceBuilder(){return this.hcs2Builder}}function F(e){return!!e&&"string"==typeof e.transactionBytes}const K=a.z.object({registryType:a.z.nativeEnum(t.HCS2RegistryType).optional().describe("Registry type: 0 for indexed, 1 for non-indexed (default: 0)"),ttl:a.z.number().int().positive().optional().describe("Time to live in seconds (default: 86400)"),adminKey:a.z.union([a.z.string(),a.z.boolean()]).optional().describe("Admin key: public key string or true to use operator key"),submitKey:a.z.union([a.z.string(),a.z.boolean()]).optional().describe("Submit key: public key string or true to use operator key")});const L=a.z.object({registryTopicId:a.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID (e.g., 0.0.123456)"),targetTopicId:a.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The target topic ID to register (e.g., 0.0.123456)"),metadata:a.z.string().optional().describe("Optional metadata URI (HIP-412 format)"),memo:a.z.string().max(500).optional().describe("Optional memo (max 500 characters)")});const U=a.z.object({registryTopicId:a.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID (must be indexed)"),targetTopicId:a.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The new topic ID to point to"),uid:a.z.string().describe("The unique ID of the entry to update"),metadata:a.z.string().optional().describe("Optional metadata URI (HIP-412 format)"),memo:a.z.string().max(500).optional().describe("Optional memo (max 500 characters)")});const j=a.z.object({registryTopicId:a.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID (must be indexed)"),uid:a.z.string().describe("The unique ID of the entry to delete"),memo:a.z.string().max(500).optional().describe("Optional memo (max 500 characters)")});const G=a.z.object({registryTopicId:a.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The current HCS-2 registry topic ID"),targetTopicId:a.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The new topic ID to migrate to"),metadata:a.z.string().optional().describe("Optional metadata URI for migration details"),memo:a.z.string().max(500).optional().describe("Optional memo (max 500 characters)")});const W=a.z.object({topicId:a.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID to query"),limit:a.z.number().int().positive().optional().describe("Maximum number of entries to return"),order:a.z.enum(["asc","desc"]).optional().describe("Order of results (ascending or descending)"),skip:a.z.number().int().min(0).optional().describe("Number of entries to skip")});class Z extends i.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs6",this.hcs6Builder=e.hcs6Builder}getServiceBuilder(){return this.hcs6Builder}}class Q extends i.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs6",this.hcs6Builder=e.hcs6Builder}getServiceBuilder(){return this.hcs6Builder}}const V=a.z.object({ttl:a.z.number().min(3600).default(86400).describe("Time-to-live in seconds (minimum 3600 seconds/1 hour)"),submitKey:a.z.union([a.z.boolean(),a.z.string()]).optional().describe("Submit key for the registry topic. Can be boolean (use operator key) or a public key string")});const Y=a.z.object({metadata:a.z.record(a.z.unknown()).describe("Metadata object for the hashinal (e.g., name, description, attributes)"),data:a.z.object({base64:a.z.string().optional().describe("Base64 encoded data for the hashinal"),url:a.z.string().optional().describe("URL to fetch data from"),mimeType:a.z.string().optional().describe("MIME type of the data")}).optional().describe("Data to inscribe with the hashinal"),memo:a.z.string().optional().describe("Optional memo for the registration"),ttl:a.z.number().min(3600).default(86400).describe("Time-to-live in seconds for the inscription"),registryTopicId:a.z.string().optional().describe("Registry topic ID to use. If not provided, a new registry will be created"),submitKey:a.z.string().optional().describe("Submit key for the registry (required if registry has a submit key)")});const X=a.z.object({registryTopicId:a.z.string().describe("The registry topic ID that tracks this dynamic hashinal"),metadata:a.z.record(a.z.unknown()).describe("Updated metadata object for the hashinal"),data:a.z.object({base64:a.z.string().optional().describe("Base64 encoded data for the updated hashinal"),url:a.z.string().optional().describe("URL to fetch updated data from"),mimeType:a.z.string().optional().describe("MIME type of the data")}).optional().describe("Updated data to inscribe"),memo:a.z.string().optional().describe('Optional memo for the update (e.g., "Level up", "Version 2.0")'),submitKey:a.z.string().describe("Submit key for the registry (required to update)")});const J=a.z.object({topicId:a.z.string().describe("The registry topic ID to query"),limit:a.z.number().optional().default(100).describe("Maximum number of entries to retrieve"),order:a.z.enum(["asc","desc"]).optional().default("desc").describe("Order of entries (desc shows latest first)"),skip:a.z.number().optional().describe("Number of entries to skip")});class ee extends i.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}setEntityCreationHandler(e){this.onEntityCreated=e}async generateInscriptionQuote(e,t){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 te extends i.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}setEntityCreationHandler(e){this.onEntityCreated=e}async generateInscriptionQuote(e,t){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}}function ie(e,t){if(!e||"object"!=typeof e)return;const i=e[t];return"string"==typeof i&&i.trim()?i:void 0}function ne(e,t){return{jsonTopicId:e.jsonTopicId||ie(e,"json_topic_id"),topicId:ie(e,"topic_id")||ie(e,"topicId")||ie(t,"topicId")||ie(t,"topic_id")}}function re(e,t,i="1"){const n=e.jsonTopicId||e.topicId;return{hrl:n?`hcs://${i}/${n}`:void 0,cdnUrl:e.jsonTopicId?`https://kiloscribe.com/api/inscription-cdn/${e.jsonTopicId}?network=${t}`:void 0,topicId:n}}const oe=new t.Logger({module:"InscribeFromUrlTool"}),se=a.z.object({url:a.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:a.z.enum(["file","hashinal"]).optional().describe("Inscription mode: file or hashinal NFT"),metadata:a.z.record(a.z.unknown()).optional().describe("Metadata to attach to the inscription"),tags:a.z.array(a.z.string()).optional().describe("Tags to categorize the inscription"),chunkSize:a.z.number().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:a.z.boolean().optional().describe("Whether to wait for inscription confirmation"),timeoutMs:a.z.number().int().positive().optional().describe("Timeout in milliseconds for inscription (default: no timeout - waits until completion)"),apiKey:a.z.string().optional().describe("API key for inscription service"),quoteOnly:a.z.boolean().optional().default(!1).describe("If true, returns a cost quote instead of executing the inscription")});const ae=a.z.object({filePath:a.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:a.z.enum(["file","hashinal"]).optional().describe("Inscription mode: file or hashinal NFT"),metadata:a.z.record(a.z.unknown()).optional().describe("Metadata to attach to the inscription"),tags:a.z.array(a.z.string()).optional().describe("Tags to categorize the inscription"),chunkSize:a.z.number().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:a.z.boolean().optional().describe("Whether to wait for inscription confirmation"),timeoutMs:a.z.number().int().positive().optional().describe("Timeout in milliseconds for inscription (default: no timeout)"),apiKey:a.z.string().optional().describe("API key for inscription service"),quoteOnly:a.z.boolean().optional().default(!1).describe("If true, returns a cost quote instead of executing the inscription")});function ce(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}}const le=a.z.string().regex(/^content-ref:[a-zA-Z0-9_-]+$/,'Content reference must be in format "content-ref:[alphanumeric-id]"').describe('Content reference in format "content-ref:[id]"'),de={maxInscriptionSize:51200,minContentSize:10,logLevel:"warn"};function ue(){return{maxInscriptionSize:parseInt(process.env.REF_MAX_SIZE||de.maxInscriptionSize.toString(),10),minContentSize:parseInt(process.env.REF_MIN_SIZE||de.minContentSize.toString(),10),logLevel:process.env.REF_LOG_LEVEL||de.logLevel,enableContentValidation:"false"!==process.env.REF_ENABLE_VALIDATION}}const ge=a.z.object({base64Data:a.z.union([a.z.string(),le]).describe("Content to inscribe as base64 data, plain text, or content reference"),fileName:a.z.string().min(1).describe("Name for the inscribed content"),mimeType:a.z.string().optional().describe("MIME type of the content"),metadata:a.z.record(a.z.unknown()).optional().describe("Metadata to attach"),tags:a.z.array(a.z.string()).optional().describe("Tags to categorize the inscription"),chunkSize:a.z.number().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:a.z.boolean().optional().describe("Wait for inscription confirmation"),timeoutMs:a.z.number().int().positive().optional().describe("Timeout in milliseconds"),apiKey:a.z.string().optional().describe("API key for inscription service"),quoteOnly:a.z.boolean().optional().default(!1).describe("Return cost quote only")});const pe=a.z.object({uri:a.z.string().describe("URI of the file"),checksum:a.z.string().optional().describe("SHA-256 checksum of the file"),is_default_file:a.z.boolean().optional().describe("Whether this is the default file"),type:a.z.string().describe("MIME type of the file")}),he=a.z.object({trait_type:a.z.string().describe("The trait type"),value:a.z.union([a.z.string(),a.z.number()]).describe("The trait value"),display_type:a.z.string().optional().describe("Display type for the attribute")}),fe=a.z.object({name:a.z.string().describe("Token name (required by HIP-412)"),description:a.z.string().describe("Human readable description (required by HIP-412)"),image:a.z.string().describe("Preview image URI (required by HIP-412)"),type:a.z.string().describe("MIME type (required by HIP-412)"),creator:a.z.string().optional().describe("Creator name or comma-separated names"),creatorDID:a.z.string().optional().describe("Decentralized identifier for creator"),checksum:a.z.string().optional().describe("SHA-256 checksum of the image"),format:a.z.string().optional().default("HIP412@2.0.0").describe("Metadata format version"),files:a.z.array(pe).optional().describe("Array of files for multi-file NFTs"),attributes:a.z.array(he).optional().describe("NFT attributes/traits"),properties:a.z.record(a.z.unknown()).optional().describe("Additional properties")});function me(e){const t=e.fileName?.replace(/\.[^/.]+$/,"")||"Hashinal NFT";let i="media";return e.mimeType?.startsWith("image/")?i="image":e.mimeType?.startsWith("video/")?i="video":e.mimeType?.startsWith("audio/")&&(i="audio"),{name:e.name||t,creator:e.creator||e.operatorAccount,description:e.description||`${i.charAt(0).toUpperCase()+i.slice(1)} NFT inscribed as Hashinal`,type:e.type||i,image:""}}function ye(e){const t=e;return t.withRender=function(e){const i=Object.create(this),n=this._renderConfig||{},r={...n,...e,ui:{...n.ui||{},...e.ui||{}}};return(n.progressive||e.progressive)&&(r.progressive={...n.progressive||{},...e.progressive||{}}),(n.block||e.block)&&(r.block={...n.block||{},...e.block||{}}),i._renderConfig=r,i.withRender=t.withRender,i.withProgressive=t.withProgressive,i.withBlock=t.withBlock,i},t.withProgressive=function(t,i){const n=this._renderConfig||{fieldType:Ie(e)};return this.withRender({...n,progressive:{priority:t,group:i}})},t.withBlock=function(t){const i=this._renderConfig||{fieldType:Ie(e)};return this.withRender({...i,block:{id:t,type:"field",reusable:!0}})},t}function be(e){return Boolean(e&&"function"==typeof e.withRender)}function we(e){if(be(e))return e._renderConfig}function Ie(e){const t=e._def?.typeName;switch(t){case"ZodString":{const t=e._def?.checks||[];for(const e of t){if("email"===e.kind)return"text";if("url"===e.kind)return"text"}return"text"}case"ZodNumber":case"ZodBigInt":return"number";case"ZodBoolean":return"checkbox";case"ZodEnum":case"ZodNativeEnum":case"ZodUnion":case"ZodDiscriminatedUnion":return"select";case"ZodArray":return"array";case"ZodDate":default:return"text";case"ZodObject":return"object";case"ZodOptional":case"ZodDefault":{const t=e._def?.innerType;return t?Ie(t):"text"}}}function Te(e){const t=e._def?.typeName;if("ZodEnum"===t){const t=e._def?.values;if(Array.isArray(t))return t.map(e=>({value:e,label:e.charAt(0).toUpperCase()+e.slice(1).replace(/[_-]/g," ")}))}if("ZodNativeEnum"===t){const t=e._def?.values;if(t)return Object.entries(t).map(([e,t])=>({value:t,label:e.replace(/[_-]/g," ")}))}if("ZodUnion"===t){const t=[],i=e._def?.options;if(Array.isArray(i))for(const e of i)if("ZodLiteral"===e._def?.typeName){const i=e._def?.value;void 0!==i&&t.push({value:i,label:"string"==typeof i?i.charAt(0).toUpperCase()+i.slice(1):String(i)})}return t.length>0?t:void 0}}function Ae(e){const t=e._def?.typeName;return"ZodOptional"===t||"ZodDefault"===t}function Ce(e){const t=e._def?.typeName;if("ZodOptional"===t||"ZodDefault"===t){const t=e._def?.innerType;return t||e}return e}function ve(e){const t=Ce(e),i=t._def?.typeName,n={};if("ZodString"===i){const e=t._def.checks;if(e&&Array.isArray(e))for(const t of e)switch(t.kind){case"min":n.minLength=t.value;break;case"max":n.maxLength=t.value;break;case"email":n.type="email";break;case"url":n.type="url";break;case"regex":n.pattern=t.regex}}if("ZodNumber"===i){const e=t._def.checks;if(e&&Array.isArray(e))for(const t of e)switch(t.kind){case"min":n.min=t.value;break;case"max":n.max=t.value;break;case"int":n.step=1;break;case"multipleOf":n.step=t.value}}if("ZodArray"===i){const e=t._def,i=e.minLength,r=e.maxLength;void 0!==i&&(n.minItems=i.value),void 0!==r&&(n.maxItems=r.value)}return n}function Ee(e){const t=e._def?.typeName;if("ZodDefault"===t){const t=e._def?.defaultValue;return"function"==typeof t?t():t}const i=Ce(e),n=i._def?.typeName;switch(n){case"ZodString":return"";case"ZodNumber":case"ZodBigInt":return 0;case"ZodBoolean":return!1;case"ZodArray":return[];case"ZodObject":{const e=i._def?.shape;if(e){const t={};for(const[i,n]of Object.entries(e))t[i]=Ee(n);return t}return{}}case"ZodDate":return new Date;case"ZodEnum":{const e=i._def?.values;return Array.isArray(e)&&e.length>0?e[0]:void 0}default:return}}function Se(e){const t=Ce(e),i=Ie(e),n=!Ae(e),r=Ae(e),o=Ee(e),s=Te(t),a=ve(e),c=e?.description;return{type:i,required:n,optional:r,default:o,options:s,constraints:a,description:c,validation:{minLength:a.minLength,maxLength:a.maxLength,min:a.min,max:a.max,pattern:a.pattern?new RegExp(a.pattern):void 0}}}const Re={text:(e,t,i="common")=>({fieldType:"text",ui:{label:e,placeholder:t,priority:i},progressive:{priority:i}}),number:(e,t,i,n="common")=>({fieldType:"number",ui:{label:e,priority:n},constraints:{min:t,max:i},progressive:{priority:n}}),select:(e,t,i="common")=>({fieldType:"select",ui:{label:e,priority:i},options:t,progressive:{priority:i}}),textarea:(e,t=3,i="common")=>({fieldType:"textarea",ui:{label:e,priority:i},props:{rows:t},progressive:{priority:i}}),currency:(e,t="HBAR",i="common")=>({fieldType:"currency",ui:{label:e,priority:i},props:{symbol:t},progressive:{priority:i}}),array:(e,t,i="advanced")=>({fieldType:"array",ui:{label:e,priority:i},props:{itemLabel:t},progressive:{priority:i}}),essential:{text:(e,t)=>Re.text(e,t,"essential"),number:(e,t,i)=>Re.number(e,t,i,"essential"),select:(e,t)=>Re.select(e,t,"essential"),textarea:(e,t)=>Re.textarea(e,t,"essential")},advanced:{text:(e,t)=>Re.text(e,t,"advanced"),number:(e,t,i)=>Re.number(e,t,i,"advanced"),select:(e,t)=>Re.select(e,t,"advanced"),textarea:(e,t)=>Re.textarea(e,t,"advanced"),array:(e,t)=>Re.array(e,t,"advanced")},expert:{text:(e,t)=>Re.text(e,t,"expert"),number:(e,t,i)=>Re.number(e,t,i,"expert"),select:(e,t)=>Re.select(e,t,"expert"),textarea:(e,t)=>Re.textarea(e,t,"expert")}};function Ne(e){const{code:t,details:i,suggestions:n}=e;return{success:!1,type:"error",title:"Inscription Failed",message:`Unable to complete inscription: ${i}`,error:{code:t,details:i,suggestions:n}}}const xe={testnet:{blockId:"0.0.6617393",hashLink:"hcs://12/0.0.6617393",template:"0.0.6617393"},mainnet:{blockId:"0.0.TBD",hashLink:"hcs://12/0.0.TBD",template:"0.0.TBD"}};const Oe=ye(a.z.object({url:a.z.string().optional().describe("The URL of the content to inscribe as Hashinal NFT (use this OR contentRef)"),contentRef:le.optional().describe('Content reference ID in format "content-ref:[id]" for already stored content (use this OR url)'),base64Data:a.z.string().optional().describe("Base64 encoded content data (use this if neither url nor contentRef provided)"),fileName:a.z.string().optional().describe("File name for the content (required when using base64Data or contentRef)"),mimeType:a.z.string().optional().describe('MIME type of the content (e.g., "image/png", "image/jpeg")'),name:a.z.string().optional().describe('Display name for the NFT (e.g., "Sunset Landscape #42", "Digital Abstract Art")'),creator:a.z.string().optional().describe('Creator account ID, artist name, or brand (e.g., "0.0.123456", "ArtistName", "StudioBrand")'),description:a.z.string().optional().describe("Meaningful description of the artwork, story, or concept behind this NFT"),type:a.z.string().optional().describe('Category or genre of the NFT (e.g., "Digital Art", "Photography", "Collectible Card")'),attributes:ye(a.z.array(a.z.object({trait_type:a.z.string(),value:a.z.union([a.z.string(),a.z.number()])}))).withRender(Re.array("NFT Attributes","Attribute")).optional().describe('Collectible traits and characteristics (e.g., "Rarity": "Epic", "Color": "Blue", "Style": "Abstract")'),properties:a.z.record(a.z.unknown()).optional().describe("Additional properties"),jsonFileURL:a.z.string().url().optional().describe("URL to JSON metadata file"),fileStandard:a.z.enum(["1","6"]).optional().default("1").describe("HCS file standard: 1 for static Hashinals (HCS-5), 6 for dynamic Hashinals (HCS-6)"),tags:a.z.array(a.z.string()).optional().describe("Tags to categorize the NFT"),chunkSize:a.z.number().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:a.z.boolean().optional().describe("Whether to wait for inscription confirmation").default(!0),timeoutMs:a.z.number().int().positive().optional().describe("Timeout in milliseconds for inscription (default: no timeout - waits until completion)"),quoteOnly:a.z.boolean().optional().default(!1).describe("If true, returns a cost quote instead of executing the inscription"),withHashLinkBlocks:a.z.boolean().optional().default(!0).describe("If true, creates interactive HashLink blocks for the inscribed content and returns block data alongside the inscription response"),renderForm:a.z.boolean().optional().default(!0).describe("Whether to show a form to collect metadata. Set to false only if user provided complete metadata including name, description, creator, and attributes.")})).withRender({fieldType:"object",ui:{label:"Inscribe Hashinal NFT",description:"Create a Hashinal inscription for NFT minting"}});const qe=a.z.object({transactionId:a.z.string().describe("The transaction ID of the inscription to retrieve"),apiKey:a.z.string().optional().describe("API key for inscription service")});const $e=r.join(process.cwd(),".env");class Be{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 i=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 i="";n.existsSync(e)&&(i=n.readFileSync(e,"utf8"));const r=[...i.split("\n")];for(const[n,o]of Object.entries(t)){const e=r.findIndex(e=>e.startsWith(`${n}=`));-1!==e?r[e]=`${n}=${o}`:r.push(`${n}=${o}`)}n.writeFileSync(e,r.join("\n"))}(i,o)}}const Me=class{static setSignerProvider(e){this._signerProvider=e}static async getSigner(){const e=this._signerProvider;if(!e)return null;try{if("function"==typeof e){const t=e();return t&&"function"==typeof t.then?await t:t}return e}catch{return null}}static setWalletInfoResolver(e){this._walletInfoResolver=e||null}static async getWalletInfo(){const e=this._walletInfoResolver;if(!e)return null;try{const t=e();return t&&"function"==typeof t.then?await t:t}catch{return null}}static setWalletExecutor(e){this._walletExecutor=e||null}static get walletExecutor(){return this._walletExecutor||null}static setStartHCSDelegate(e){this._startHCSDelegate=e||null}static get startHCSDelegate(){return this._startHCSDelegate||null}static setPreferWalletOnly(e){this._preferWalletOnly=!!e}static setBrowserHCSClientFactory(e){this._browserHCSClientFactory=e||null}static getBrowserHCSClient(e){return this._browserHCSClientFactory?this._browserHCSClientFactory(e):null}static get preferWalletOnly(){return this._preferWalletOnly}};Me._preferWalletOnly=!1;let ke=Me;const _e="ConnectionsManager not initialized";class ze extends i.BaseServiceBuilder{constructor(e,i,n){super(e),this.stateManager=i;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=(()=>{try{if("function"==typeof t.Logger)return new t.Logger({module:"HCS10Builder",level:n?.logLevel||"info"})}catch{}return{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{},trace:()=>{},setLogLevel:()=>{},getLevel:()=>"info",setSilent:()=>{},setModule:()=>{}}})(),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){const i=ke.startHCSDelegate,n=ke.walletExecutor,r=ke.preferWalletOnly,o=this.network;try{const{ByteBuildRegistry:i}=await Promise.resolve().then(()=>nt);if(n&&i.has("submitConnectionRequest")){const r=await i.build("submitConnectionRequest",this.hederaKit,{inboundTopicId:e,memo:t});if(r&&r.transactionBytes){const{transactionId:e}=await n(r.transactionBytes,o);return{transactionId:e}}}}catch{}if(i&&n)try{const r={inboundTopicId:e,memo:t},{transactionBytes:s}=await i("submitConnectionRequest",r,o),{transactionId:a}=await n(s,o);return{transactionId:a}}catch(s){if(r){const e=new Error(`wallet_submit_failed: ${s instanceof Error?s.message:String(s)}`);throw e.code="wallet_submit_failed",e}}else if(r){const e=new Error("wallet_unavailable: connect a wallet or configure StartHCSDelegate and WalletExecutor");throw e.code="wallet_unavailable",e}return this.standardClient.submitConnectionRequest(e,t)}async handleConnectionRequest(e,t,i,n){try{const o=ke.startHCSDelegate,s=ke.walletExecutor,a=ke.preferWalletOnly,c=this.network;if(o&&s)try{const r={inboundTopicId:e,requestingAccountId:t,connectionRequestId:i,feeConfig:n?"configured":void 0},{transactionBytes:a}=await o("handleConnectionRequest",r,c),{transactionId:l}=await s(a,c);return{success:!0,transactionId:l}}catch(r){if(a){const e=new Error(`wallet_submit_failed: ${r instanceof Error?r.message:String(r)}`);throw e.code="wallet_submit_failed",e}}else if(a){const e=new Error("wallet_unavailable: connect a wallet or configure StartHCSDelegate and WalletExecutor");throw e.code="wallet_unavailable",e}const l=await this.standardClient.handleConnectionRequest(e,t,i,n);return l&&l.connectionTopicId&&"object"==typeof l.connectionTopicId&&"toString"in l.connectionTopicId&&(l.connectionTopicId=l.connectionTopicId.toString()),l}catch(o){throw this.logger.error(`Error handling connection request #${i} for topic ${e}:`,o),new Error(`Failed to handle connection request: ${o instanceof Error?o.message:String(o)}`)}}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{let r=0;try{r=(await this.getMessages(e)).messages.reduce((e,t)=>Math.max(e,t.sequence_number||0),0)}catch{}const o=ke.startHCSDelegate,s=ke.walletExecutor,a=ke.preferWalletOnly,c=this.network;try{const{ByteBuildRegistry:n}=await Promise.resolve().then(()=>nt);if(s&&n.has("sendMessage")){const o=await n.build("sendMessage",this.hederaKit,{topicId:e,data:t,memo:i});if(o&&o.transactionBytes){const{transactionId:t}=await s(o.transactionBytes,c);return{sequenceNumber:await this.pollForNewSequence(e,r),receipt:{transactionId:t},transactionId:t}}}}catch{}if(o&&s)try{const n={topicId:e,data:t,memo:i},{transactionBytes:a}=await o("sendMessage",n,c),{transactionId:l}=await s(a,c);return{sequenceNumber:await this.pollForNewSequence(e,r),receipt:{transactionId:l},transactionId:l}}catch(n){if(a){const e=new Error(`wallet_submit_failed: ${n instanceof Error?n.message:String(n)}`);throw e.code="wallet_submit_failed",e}}else if(a){const e=new Error("wallet_unavailable: connect a wallet or configure StartHCSDelegate and WalletExecutor");throw e.code="wallet_unavailable",e}const l=await this.standardClient.sendMessage(e,t,i,void 0);return{sequenceNumber:l.topicSequenceNumber?.toNumber(),receipt:l,transactionId:"transactionId"in l?l.transactionId?.toString():void 0}}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){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 o.get(e,{responseType:"arraybuffer"}),i=globalThis.Buffer.from(t.data),n=new URL(e).pathname;return{buffer:i,filename:r.basename(n)||"profile.png"}}{if(!n.existsSync(e))return this.logger.warn(`Profile picture file not found: ${e}`),null;this.logger.info(`Loading profile picture from file: ${e}`);const t=n.readFileSync(e);return{buffer:t,filename:r.basename(e)}}}if(e.url){this.logger.info(`Loading profile picture from URL: ${e.url}`);const t=await o.get(e.url,{responseType:"arraybuffer"}),i=globalThis.Buffer.from(t.data);return{buffer:i,filename:e.filename||"profile.png"}}if(e.path){if(!n.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=n.readFileSync(e.path);return{buffer:t,filename:e.filename||r.basename(e.path)}}return null}catch(t){return this.logger.error("Failed to load profile picture:",t),null}}async pollForNewSequence(e,t){for(let i=0;i<10;i++){try{const i=(await this.getMessages(e)).messages.reduce((e,t)=>Math.max(e,t.sequence_number||0),t);if(i>t)return i}catch{}await new Promise(e=>setTimeout(e,1e3))}}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 n=null;e.profilePicture&&(n=await this.loadProfilePicture(e.profilePicture));const r={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!==n?.buffer&&{pfpBuffer:n.buffer},...void 0!==n?.filename&&{pfpFileName:n.filename}};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 o=e.exemptAccountIds?.filter(e=>e!==n&&e.startsWith("0.0"))||[];r.feeConfig=i.addHbarFee(e.hbarFee,n,o)}const o=ke.preferWalletOnly,s=ke.getBrowserHCSClient(this.network);if(s)try{const e=(new t.AgentBuilder).setNetwork(this.network).setName(r.name).setAlias(r.alias||`${r.name}-${Date.now()}`).setBio(r.bio||"").setType(r.type||"autonomous").setModel(r.model||"agent-model-2024");r.capabilities?.length&&e.setCapabilities(r.capabilities),r.creator&&e.setCreator(r.creator),r.existingProfilePictureTopicId&&e.setExistingProfilePicture(r.existingProfilePictureTopicId),r.socials&&Object.entries(r.socials).forEach(([t,i])=>{i&&"string"==typeof i&&e.addSocial(t,i)}),r.properties&&Object.entries(r.properties).forEach(([t,i])=>{null!=i&&e.addProperty(t,i)});const i=await s.create(e,{progressCallback:e=>{},updateAccountMemo:!0});return this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{result:i,name:r.name}},this}catch(i){if(o)throw new Error(`wallet_registration_failed: ${i instanceof Error?i.message:String(i)}`)}else if(o)throw new Error("wallet_unavailable: BrowserHCSClient factory not provided");const a=await this.createAndRegisterAgent(r);this.executeResult={success:!0,transactionId:a.transactionId,receipt:void 0,scheduleId:void 0,rawResult:{...a,name:e.name,accountId:a?.metadata?.accountId||a.state?.agentMetadata?.accountId}}}catch(n){throw this.logger.error("Failed to register agent:",n),n}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 r=this.stateManager?.getCurrentAgent();if(!r)throw new Error("Cannot accept connection request. No agent is currently active. Please register or select an agent first.");const o=this.stateManager?.getConnectionsManager();if(!o)throw new Error(_e);await o.fetchConnectionData(r.accountId);const s=[...o.getPendingRequests(),...o.getConnectionsNeedingConfirmation()].find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!s)throw new Error(`Request with key ${e.requestKey} not found or no longer pending.`);if(!s.needsConfirmation||!s.inboundRequestId)throw new Error(`Request with key ${e.requestKey} is not an inbound request that can be accepted.`);const a=s.targetAccountId,c=s.inboundRequestId;let l;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"))||[];l=i.addHbarFee(e.hbarFee,n,r)}const d=await this.getInboundTopicId(),u=await this.handleConnectionRequest(d,a,c,l);let g=u?.connectionTopicId;if(g&&"object"==typeof g&&"toString"in g&&(g=g?.toString()),!g||"string"!=typeof g)try{const e=(await(this.stateManager?.getConnectionsManager()?.fetchConnectionData(r.accountId))||[]).find(e=>e.targetAccountId===a&&"established"===e.status);e?.connectionTopicId&&(g=e.connectionTopicId)}catch(i){this.logger.debug("Could not refresh connections after acceptance to derive topic id:",i)}if(!g||"string"!=typeof g)throw new Error(`Failed to create connection topic. Got: ${JSON.stringify(g)}`);if(this.stateManager){const e=s.targetAgentName||`Agent ${a}`;s.targetAgentName||this.addNote(`No agent name was provided in the connection request, using default name 'Agent ${a}'.`);let t=s.targetInboundTopicId||"";if(!t)try{const e=await this.getAgentProfile(a);e.success&&e.topicInfo?.inboundTopic&&(t=e.topicInfo.inboundTopic)}catch(n){this.logger.warn(`Could not fetch profile for ${a}:`,n)}const i={connectionId:`conn-${Date.now()}`,targetAccountId:a,targetAgentName:e,targetInboundTopicId:t,connectionTopicId:g,status:"established",created:new Date};this.stateManager.addActiveConnection(i),o.markConnectionRequestProcessed(s.targetInboundTopicId||"",c)}this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{targetAccountId:a,connectionTopicId:g,feeConfigured:!!e.hbarFee,hbarFee:e.hbarFee||0,confirmationResult:u}}}catch(r){throw this.logger.error("Failed to accept connection:",r),r}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}`;let a=0;try{a=(await this.getMessages(r)).messages.reduce((e,t)=>Math.max(e,t.sequence_number||0),0)}catch{}const c=await this.sendMessage(r,e.message,`Agent message from ${t.name}`),l=c.sequenceNumber??a;if(0===l)throw new Error("Failed to send message");let d=null;e.disableMonitoring?this.addNote("Message sent successfully. Response monitoring was disabled."):d=await this.monitorResponses(r,s,l),this.executeResult={success:!0,transactionId:c.transactionId,receipt:c.receipt,scheduleId:void 0,rawResult:{targetAgentName:o,targetAccountId:i.targetAccountId,connectionTopicId:r,sequenceNumber:c.sequenceNumber,reply:d,monitoringEnabled:!e.disableMonitoring,message:e.message,messageResult:c}}}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(_e);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(_e),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 Pe extends i.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 i.HederaGetHbarPriceTool({hederaKit:this.context.config.hederaKit,logger:this.context.logger})]}getTools(){return this.tools}}function De(e){const t={},i={},n=[],r={};return He(e,"",t,i,n,r),{fields:t,groups:Le(i),order:Ue(n,t),metadata:r}}function He(e,t,i,n,r,o){const s=Ce(e),a=s._def?.typeName;"ZodObject"===a?function(e,t,i,n,r,o){const s=e.shape;if(be(e)){const o=we(e);o&&t&&(i[t]=o,Fe(n,o.ui?.group||"default",t),Ke(r,t,o.ui?.order))}for(const[a,c]of Object.entries(s)){He(c,t?`${t}.${a}`:a,i,n,r,o)}}(s,t,i,n,r,o):"ZodArray"===a?function(e,t,i,n,r,o){if(be(e)){const s=we(e);s&&(i[t]=s,Fe(n,s.ui?.group||"default",t),Ke(r,t,s.ui?.order),o[t]=Se(e))}const s=e._def.type;if(s){He(s,`${t}[]`,i,n,r,o)}}(s,t,i,n,r,o):function(e,t,i,n,r,o){if(be(e)){const o=we(e);o&&(i[t]=o,Fe(n,o.ui?.group||"default",t),Ke(r,t,o.ui?.order))}o[t]=Se(e)}(e,t,i,n,r,o)}function Fe(e,t,i){e[t]||(e[t]=[]),e[t].push(i)}function Ke(e,t,i){void 0!==i?e.splice(i,0,t):e.push(t)}function Le(e){const t={},i=["default","Keys & Security","Token Settings","Custom Fees"];for(const n of i)e[n]&&(t[n]=e[n]);for(const[n,r]of Object.entries(e))i.includes(n)||(t[n]=r);return t}function Ue(e,t){const i={tokenName:1,tokenSymbol:2,maxSupply:3,supplyType:4,treasuryAccountId:5,memo:6};return e.sort((e,n)=>{const r=t[e],o=t[n];if(void 0!==r?.ui?.order&&void 0!==o?.ui?.order)return r.ui.order-o.ui.order;if(void 0!==r?.ui?.order)return-1;if(void 0!==o?.ui?.order)return 1;const s=i[e]||1e3,a=i[n]||1e3;return s!==a?s-a:e.localeCompare(n)})}class je extends Error{constructor(e,t){super(t),this.code=e,Object.setPrototypeOf(this,je.prototype)}}class Ge extends i.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().toString():"",n=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet";let r;try{const i=new t.HederaMirrorNode(n),o=await i.requestAccount(e),s=o?.key?._type;if(s){const e=s.toUpperCase();e.includes("ED25519")?r="ed25519":e.includes("ECDSA")&&(r="ecdsa")}}catch{}const o={network:n,operatorId:e,operatorKey:i,...r?{keyType:r}:{}};this.hcs2Client=new t.HCS2Client(o)}return this.hcs2Client}async createRegistry(e={}){const t=ke.walletExecutor,i=ke.preferWalletOnly,n=!(!this.hederaKit?.signer?.getOperatorPrivateKey||!this.hederaKit.signer.getOperatorPrivateKey());if(t){const t=ke.startHCSDelegate;if(t)try{const i={options:e},n=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",{transactionBytes:r}=await t("hcs2.createRegistry",i,n);if(r)return{success:!0,transactionBytes:r}}catch(o){if(i)throw new je("wallet_submit_failed",`wallet_submit_failed: ${o instanceof Error?o.message:String(o)}`)}if(i)throw new je("wallet_unavailable","WalletExecutor not configured for hcs2.createRegistry")}if(!n)throw new je("wallet_unavailable","No wallet executor and no operator private key available for server execution");const r=await this.getHCS2Client();return await r.createRegistry(e)}async registerEntry(e,t){const i=ke.walletExecutor,n=ke.preferWalletOnly,r=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",o=!(!this.hederaKit?.signer?.getOperatorPrivateKey||!this.hederaKit.signer.getOperatorPrivateKey());try{const{ByteBuildRegistry:n}=await Promise.resolve().then(()=>nt);if(n.has("hcs2.registerEntry")){const r=await n.build("hcs2.registerEntry",this.hederaKit,{registryTopicId:e,options:t});if(r&&r.transactionBytes){if(i)return{success:!0,transactionBytes:r.transactionBytes};if(!o)return{success:!0,transactionBytes:r.transactionBytes}}}}catch{}const s=ke.startHCSDelegate;if(s)try{const n={registryTopicId:e,options:t},{transactionBytes:a}=await s("hcs2.registerEntry",n,r);if(a){if(i)return{success:!0,transactionBytes:a};if(!o)return{success:!0,transactionBytes:a}}}catch(c){if(n){const e=`wallet_submit_failed: ${c instanceof Error?c.message:String(c)}`;throw new je("wallet_submit_failed",e)}}if(n)throw new je("wallet_unavailable","WalletExecutor not configured for hcs2.registerEntry");if(!o)throw new je("wallet_unavailable","No wallet executor and no operator private key available for server execution");const a=await this.getHCS2Client();return await a.registerEntry(e,t)}async updateEntry(e,t){const i=ke.walletExecutor,n=ke.preferWalletOnly,r=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",o=!(!this.hederaKit?.signer?.getOperatorPrivateKey||!this.hederaKit.signer.getOperatorPrivateKey());try{const{ByteBuildRegistry:n}=await Promise.resolve().then(()=>nt);if(n.has("hcs2.updateEntry")){const r=await n.build("hcs2.updateEntry",this.hederaKit,{registryTopicId:e,options:t});if(r&&r.transactionBytes){if(i)return{success:!0,transactionBytes:r.transactionBytes};if(!o)return{success:!0,transactionBytes:r.transactionBytes}}}}catch{}const s=ke.startHCSDelegate;if(s)try{const n={registryTopicId:e,options:t},{transactionBytes:a}=await s("hcs2.updateEntry",n,r);if(a){if(i)return{success:!0,transactionBytes:a};if(!o)return{success:!0,transactionBytes:a}}}catch(c){if(n){const e=`wallet_submit_failed: ${c instanceof Error?c.message:String(c)}`;throw new je("wallet_submit_failed",e)}}if(n)throw new je("wallet_unavailable","WalletExecutor not configured for hcs2.updateEntry");if(!o)throw new je("wallet_unavailable","No wallet executor and no operator private key available for server execution");const a=await this.getHCS2Client();return await a.updateEntry(e,t)}async deleteEntry(e,t){const i=ke.walletExecutor,n=ke.preferWalletOnly,r=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",o=!(!this.hederaKit?.signer?.getOperatorPrivateKey||!this.hederaKit.signer.getOperatorPrivateKey());try{const{ByteBuildRegistry:n}=await Promise.resolve().then(()=>nt);if(n.has("hcs2.deleteEntry")){const r=await n.build("hcs2.deleteEntry",this.hederaKit,{registryTopicId:e,options:t});if(r&&r.transactionBytes){if(i)return{success:!0,transactionBytes:r.transactionBytes};if(!o)return{success:!0,transactionBytes:r.transactionBytes}}}}catch{}const s=ke.startHCSDelegate;if(s)try{const n={registryTopicId:e,options:t},{transactionBytes:a}=await s("hcs2.deleteEntry",n,r);if(a){if(i)return{success:!0,transactionBytes:a};if(!o)return{success:!0,transactionBytes:a}}}catch(c){if(n){const e=`wallet_submit_failed: ${c instanceof Error?c.message:String(c)}`;throw new je("wallet_submit_failed",e)}}if(n)throw new je("wallet_unavailable","WalletExecutor not configured for hcs2.deleteEntry");if(!o)throw new je("wallet_unavailable","No wallet executor and no operator private key available for server execution");const a=await this.getHCS2Client();return await a.deleteEntry(e,t)}async migrateRegistry(e,t){const i=ke.walletExecutor,n=ke.preferWalletOnly,r=!(!this.hederaKit?.signer?.getOperatorPrivateKey||!this.hederaKit.signer.getOperatorPrivateKey());try{const{ByteBuildRegistry:n}=await Promise.resolve().then(()=>nt);if(n.has("hcs2.migrateRegistry")){const o=await n.build("hcs2.migrateRegistry",this.hederaKit,{registryTopicId:e,options:t});if(o&&o.transactionBytes){if(i)return{success:!0,transactionBytes:o.transactionBytes};if(!r)return{success:!0,transactionBytes:o.transactionBytes}}}}catch{}const o=ke.startHCSDelegate;if(o)try{const n={registryTopicId:e,options:t},s=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",{transactionBytes:a}=await o("hcs2.migrateRegistry",n,s);if(a){if(i)return{success:!0,transactionBytes:a};if(!r)return{success:!0,transactionBytes:a}}}catch(a){if(n){const e=`wallet_submit_failed: ${a instanceof Error?a.message:String(a)}`;throw new je("wallet_submit_failed",e)}}if(n)throw new je("wallet_unavailable","WalletExecutor not configured for hcs2.migrateRegistry");if(!r)throw new je("wallet_unavailable","No wallet executor and no operator private key available for server execution");const s=await this.getHCS2Client();return await s.migrateRegistry(e,t)}async getRegistry(e,t={}){const i=await this.getHCS2Client();return await i.getRegistry(e,t)}async submitMessage(e,t){const i=ke.walletExecutor,n=ke.preferWalletOnly,r=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",o=!(!this.hederaKit?.signer?.getOperatorPrivateKey||!this.hederaKit.signer.getOperatorPrivateKey());try{const{ByteBuildRegistry:n}=await Promise.resolve().then(()=>nt);if(n.has("hcs2.submitMessage")){const r=await n.build("hcs2.submitMessage",this.hederaKit,{topicId:e,payload:t});if(r&&r.transactionBytes){if(i)return{success:!0,transactionBytes:r.transactionBytes};if(!o)return{success:!0,transactionBytes:r.transactionBytes}}}}catch{}const s=ke.startHCSDelegate;if(s)try{const n={topicId:e,payload:t},{transactionBytes:a}=await s("hcs2.submitMessage",n,r);if(a){if(i)return{success:!0,transactionBytes:a};if(!o)return{success:!0,transactionBytes:a}}}catch(c){if(n){const e=`wallet_submit_failed: ${c instanceof Error?c.message:String(c)}`;throw new je("wallet_submit_failed",e)}}if(n)throw new je("wallet_unavailable","WalletExecutor not configured for hcs2.submitMessage");if(!o)throw new je("wallet_unavailable","No wallet executor and no operator private key available for server execution");const a=await this.getHCS2Client();return await a.submitMessage(e,t),{success:!0}}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 We extends i.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=ke.walletExecutor,i=ke.preferWalletOnly,n=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet";if(t){const t=ke.startHCSDelegate;if(t)try{const i={options:e},{transactionBytes:r}=await t("hcs6.createRegistry",i,n);if(r)return{success:!0,transactionBytes:r}}catch(s){if(i)throw new je("wallet_submit_failed",`wallet_submit_failed: ${s instanceof Error?s.message:String(s)}`)}if(i)throw new je("wallet_unavailable","WalletExecutor not configured for hcs6.createRegistry")}const r=await this.getHCS6Client(),o={...e};return"adminKey"in o&&delete o.adminKey,await r.createRegistry(o)}async registerEntry(e,t){const i=ke.walletExecutor,n=ke.preferWalletOnly,r=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet";if(i){const i=ke.startHCSDelegate;if(i)try{const n={registryTopicId:e,options:t},{transactionBytes:o}=await i("hcs6.registerEntry",n,r);if(o)return{success:!0,transactionBytes:o}}catch(s){if(n)throw new je("wallet_submit_failed",`wallet_submit_failed: ${s instanceof Error?s.message:String(s)}`)}if(n)throw new je("wallet_unavailable","WalletExecutor not configured for hcs6.registerEntry")}const o=await this.getHCS6Client();return await o.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=ke.walletExecutor,n=ke.preferWalletOnly,r=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet";if(i){const i=ke.startHCSDelegate;if(i)try{const n={topicId:e,payload:t},{transactionBytes:o}=await i("hcs6.submitMessage",n,r);if(o)return{success:!0,transactionBytes:o}}catch(s){if(n)throw new je("wallet_submit_failed",`wallet_submit_failed: ${s instanceof Error?s.message:String(s)}`)}if(n)throw new je("wallet_unavailable","WalletExecutor not configured for hcs6.submitMessage")}const o=await this.getHCS6Client();return await o.submitMessage(e,t)}async getTopicInfo(e){const i=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",n=new t.HederaMirrorNode(i);return await n.getTopicInfo(e)}async close(){this.hcs6Client&&(this.hcs6Client.close(),this.hcs6Client=void 0)}}const Ze=class e extends i.BaseServiceBuilder{constructor(e){super(e)}getOperationalMode(){return this.hederaKit.operationalMode}static setSignerProvider(t){e.signerProvider=t}static setWalletInfoResolver(t){e.walletInfoResolver=t}static setStartInscriptionDelegate(t){e.startInscriptionDelegate=t}static setWalletExecutor(t){e.walletExecutor=t}static setPreferWalletOnly(t){e.preferWalletOnly=!!t}async getSigner(){const t=e.signerProvider;if(!t)return null;try{const e=t();return e&&"function"==typeof e.then?await e:e}catch{return null}}async getInscriptionSDK(e){if(this.inscriptionSDK)return this.inscriptionSDK;try{const e=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",t=await this.getSigner(),i=this.hederaKit.signer.getAccountId().toString();if(t)this.inscriptionSDK=await s.InscriptionSDK.createWithAuth({type:"client",accountId:i,signer:t,network:e});else{const t=this.hederaKit.signer?.getOperatorPrivateKey();t&&(this.inscriptionSDK=await s.InscriptionSDK.createWithAuth({type:"server",accountId:i,privateKey:t.toStringRaw(),network:e}))}}catch(t){this.logger.warn("Failed to create InscriptionSDK with auth",t)}return this.inscriptionSDK||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 inscribeAuto(i,n){const r=await this.getSigner();if(r)return this.inscribeWithSigner(i,r,n);const o=e.walletInfoResolver?await e.walletInfoResolver():null;if(e.preferWalletOnly&&!o){const e=new Error("Wallet unavailable: connect a wallet or switch to autonomous mode");throw e.code="wallet_unavailable",e}if(o&&e.startInscriptionDelegate&&e.walletExecutor){const r=o.accountId,s=o.network,a=n,c={holderId:r,metadata:a.metadata||{},tags:n.tags||[],mode:n.mode||"file"};void 0!==a.fileStandard&&(c.fileStandard=a.fileStandard),void 0!==a.chunkSize&&(c.chunkSize=a.chunkSize);let l={...c};switch(i.type){case"url":l={...c,file:{type:"url",url:i.url}};break;case"file":l={...c,file:{type:"path",path:i.path}};break;case"buffer":l={...c,file:{type:"base64",base64:globalThis.Buffer.from(i.buffer).toString("base64"),fileName:i.fileName,mimeType:i.mimeType}}}"hashinal"===n.mode&&(l.metadataObject=a.metadata,l.creator=a.metadata?.creator||r,l.description=a.metadata?.description,"string"==typeof a.jsonFileURL&&a.jsonFileURL.length>0&&(l.jsonFileURL=a.jsonFileURL));const d=await e.startInscriptionDelegate(l,s),u=d;if(Boolean(u?.inscription)&&u?.confirmed){const e=d;return this.logger.info("inscription already completed, short circuiting",d),{quote:!1,confirmed:!0===e.confirmed,result:e.result,inscription:e.inscription}}const g=d;if(!g||!g.transactionBytes)throw new Error("Failed to start inscription (no transaction bytes)");const p=await e.walletExecutor(g.transactionBytes,s),h=p?.transactionId||"";if(!n.quoteOnly&&(n.waitForConfirmation??!0)){this.logger.debug("Will be retrieving inscription");const e=n.waitMaxAttempts??60,i=n.waitIntervalMs??5e3,r=await this.getInscriptionSDK(n);if(r){const n=await r.waitForInscription(h,e,i,!0),o=t.getTopicId(n)??g.topic_id,s={quote:!1,confirmed:!0,result:{jobId:g.tx_id||"",transactionId:h,topicId:o},inscription:n};return this.logger.debug("retrieved inscription",s,n),s}}return{quote:!1,confirmed:!1,result:{jobId:g.tx_id||"",transactionId:h,status:g.status,completed:g.completed},inscription:g.topic_id?{topic_id:g.topic_id}:void 0}}if(e.preferWalletOnly){const e=new Error("Wallet unavailable: connect a wallet or switch to autonomous mode");throw e.code="wallet_unavailable",e}return this.inscribe(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}};Ze.preferWalletOnly=!1;let Qe=Ze;const Ve=new class{constructor(){this.handlers=new Map}register(e,t){this.handlers.set(e,t)}has(e){return this.handlers.has(e)}async build(e,t,i){const n=this.handlers.get(e);return n?await n({hederaKit:t,request:i}):null}};async function Ye(t,i){const n="mainnet"===(t.client.network.toString().includes("mainnet")?"mainnet":"testnet")?e.Client.forMainnet():e.Client.forTestnet(),r=t.signer.getAccountId().toString(),o=e.AccountId.fromString(r);if("function"==typeof i.setTransactionId&&i.setTransactionId(e.TransactionId.generate(o)),"function"==typeof i.setAutoRenewAccountId)try{i.setAutoRenewAccountId(r)}catch{}const s=await i.freezeWith(n);return{transactionBytes:globalThis.Buffer.from(s.toBytes()).toString("base64")}}async function Xe(t,i,n,r){const o="mainnet"===(t.client.network.toString().includes("mainnet")?"mainnet":"testnet")?e.Client.forMainnet():e.Client.forTestnet(),s=t.signer.getAccountId().toString(),a=e.AccountId.fromString(s),c=(new e.TopicMessageSubmitTransaction).setTopicId(e.TopicId.fromString(i)).setTransactionId(e.TransactionId.generate(a)).setMessage(n),l=await c.freezeWith(o);return{transactionBytes:globalThis.Buffer.from(l.toBytes()).toString("base64")}}function Je(e){return"object"==typeof e&&null!==e}function et(e,t){const i=e[t];return"string"==typeof i?i:void 0}function tt(e,t){const i=e[t];return"number"==typeof i&&Number.isFinite(i)?i:void 0}function it(e,t){const i=e[t];return Je(i)?i:void 0}Ve.register("hcs2.createRegistry",async({hederaKit:e,request:i})=>{const n=i?.options||{};let r;try{const t=e?.signer?.getOperatorPrivateKey?.();r=t?.publicKey}catch{}const o=t.buildHcs2CreateRegistryTx({registryType:n.registryType??t.HCS2RegistryType.INDEXED,ttl:n.ttl??86400,adminKey:n.adminKey,submitKey:n.submitKey,operatorPublicKey:r});return await Ye(e,o)}),Ve.register("hcs2.migrateRegistry",async({hederaKit:e,request:i})=>{if(!Je(i))throw new Error("hcs2.migrateRegistry: invalid request payload");const n=et(i,"registryTopicId")||"";if(!n)throw new Error("hcs2.migrateRegistry: registryTopicId is required");const r=it(i,"options")||{},o=et(r,"targetTopicId")||"",s=et(r,"metadata"),a=et(r,"memo"),c=t.buildHcs2MigrateTx({registryTopicId:n,targetTopicId:o,metadata:s,memo:a});return await Ye(e,c)}),Ve.register("hcs2.submitMessage",async({hederaKit:e,request:t})=>{if(!Je(t))throw new Error("hcs2.submitMessage: invalid request payload");const i=et(t,"topicId")||et(t,"registryTopicId")||"";if(!i)throw new Error("hcs2.submitMessage: topicId is required");const n=t.payload,r="string"==typeof n?n:JSON.stringify(n??{});return await Xe(e,i,r)}),Ve.register("hcs2.registerEntry",async({hederaKit:e,request:i})=>{if(!Je(i))throw new Error("hcs2.registerEntry: invalid request payload");const n=et(i,"registryTopicId")||"";if(!n)throw new Error("hcs2.registerEntry: registryTopicId is required");const r=it(i,"options")||{},o=et(r,"targetTopicId")||"",s=et(r,"metadata"),a=et(r,"memo"),c=t.buildHcs2RegisterTx({registryTopicId:n,targetTopicId:o,metadata:s,memo:a});return await Ye(e,c)}),Ve.register("hcs2.updateEntry",async({hederaKit:e,request:i})=>{if(!Je(i))throw new Error("hcs2.updateEntry: invalid request payload");const n=et(i,"registryTopicId")||"";if(!n)throw new Error("hcs2.updateEntry: registryTopicId is required");const r=it(i,"options")||{},o=et(r,"targetTopicId")||"",s=et(r,"uid")||"",a=et(r,"metadata"),c=et(r,"memo"),l=t.buildHcs2UpdateTx({registryTopicId:n,uid:s,targetTopicId:o,metadata:a,memo:c});return await Ye(e,l)}),Ve.register("hcs2.deleteEntry",async({hederaKit:e,request:i})=>{if(!Je(i))throw new Error("hcs2.deleteEntry: invalid request payload");const n=et(i,"registryTopicId")||"";if(!n)throw new Error("hcs2.deleteEntry: registryTopicId is required");const r=it(i,"options")||{},o=et(r,"uid")||"",s=et(r,"memo"),a=t.buildHcs2DeleteTx({registryTopicId:n,uid:o,memo:s});return await Ye(e,a)}),Ve.register("hcs6.createRegistry",async({hederaKit:e,request:i})=>{const n=Je(i)?it(i,"options"):void 0,r=n?tt(n,"ttl"):void 0;let o;try{const t=e?.signer?.getOperatorPrivateKey?.();o=t?.publicKey}catch{}const s=t.buildHcs6CreateRegistryTx({ttl:r??86400,operatorPublicKey:o});return await Ye(e,s)}),Ve.register("hcs6.registerEntry",async({hederaKit:e,request:i})=>{if(!Je(i))throw new Error("hcs6.registerEntry: invalid request payload");const n=et(i,"registryTopicId")||"";if(!n)throw new Error("hcs6.registerEntry: registryTopicId is required");const r=it(i,"options")||{},o=et(r,"targetTopicId")||"",s=et(r,"memo"),a=t.buildHcs6RegisterEntryTx({registryTopicId:n,targetTopicId:o,memo:s});return await Ye(e,a)}),Ve.register("hcs6.submitMessage",async({hederaKit:e,request:t})=>{if(!Je(t))throw new Error("hcs6.submitMessage: invalid request payload");const i=et(t,"topicId")||"";if(!i)throw new Error("hcs6.submitMessage: topicId is required");const n=t.payload,r="string"==typeof n?n:JSON.stringify(n??{});return await Xe(e,i,r)}),Ve.register("sendMessage",async({hederaKit:e,request:i})=>{if(!Je(i))throw new Error("sendMessage: invalid request payload");const n=et(i,"topicId")||"";if(!n)throw new Error("sendMessage: topicId is required");const r=i.data,o=et(i,"memo")||"",s=e.signer.getAccountId().toString(),a="string"==typeof r?r:JSON.stringify(r??{}),c=t.buildHcs10SendMessageTx({connectionTopicId:n,operatorId:s,data:a,memo:o});return await Ye(e,c)}),Ve.register("submitConnectionRequest",async({hederaKit:e,request:i})=>{if(!Je(i))throw new Error("submitConnectionRequest: invalid request payload");const n=et(i,"inboundTopicId")||"";if(!n)throw new Error("submitConnectionRequest: inboundTopicId is required");const r=et(i,"memo")||"",o=e.signer.getAccountId().toString(),s=t.buildHcs10SubmitConnectionRequestTx({inboundTopicId:n,operatorId:o,memo:r});return await Ye(e,s)}),Ve.register("hcs20.deploy",async({hederaKit:e,request:i})=>{if(!Je(i))throw new Error("hcs20.deploy: invalid request payload");const n=et(i,"topicId")||"";if(!n)throw new Error("hcs20.deploy: topicId is required");const r=et(i,"name")||"",o=et(i,"tick")||"",s=et(i,"max")||"",a=et(i,"lim"),c=et(i,"metadata"),l=et(i,"memo"),d=t.buildHcs20DeployTx({topicId:n,name:r,tick:o,max:s,lim:a,metadata:c,memo:l});return await Ye(e,d)}),Ve.register("hcs20.mint",async({hederaKit:e,request:i})=>{if(!Je(i))throw new Error("hcs20.mint: invalid request payload");const n=et(i,"topicId")||"";if(!n)throw new Error("hcs20.mint: topicId is required");const r=et(i,"tick")||"",o=et(i,"amt")||"",s=et(i,"to")||"",a=et(i,"memo"),c=t.buildHcs20MintTx({topicId:n,tick:r,amt:o,to:s,memo:a});return await Ye(e,c)}),Ve.register("hcs20.transfer",async({hederaKit:e,request:i})=>{if(!Je(i))throw new Error("hcs20.transfer: invalid request payload");const n=et(i,"topicId")||"";if(!n)throw new Error("hcs20.transfer: topicId is required");const r=et(i,"tick")||"",o=et(i,"amt")||"",s=et(i,"from")||"",a=et(i,"to")||"",c=et(i,"memo"),l=t.buildHcs20TransferTx({topicId:n,tick:r,amt:o,from:s,to:a,memo:c});return await Ye(e,l)}),Ve.register("hcs20.burn",async({hederaKit:e,request:i})=>{if(!Je(i))throw new Error("hcs20.burn: invalid request payload");const n=et(i,"topicId")||"";if(!n)throw new Error("hcs20.burn: topicId is required");const r=et(i,"tick")||"",o=et(i,"amt")||"",s=et(i,"from")||"",a=et(i,"memo"),c=t.buildHcs20BurnTx({topicId:n,tick:r,amt:o,from:s,memo:a});return await Ye(e,c)}),Ve.register("hcs20.register",async({hederaKit:e,request:i})=>{if(!Je(i))throw new Error("hcs20.register: invalid request payload");const n=et(i,"registryTopicId")||"";if(!n)throw new Error("hcs20.register: registryTopicId is required");const r=et(i,"topicId")||"",o=et(i,"name")||"",s=i.isPrivate,a="boolean"==typeof s&&s,c=et(i,"metadata"),l=et(i,"memo"),d=t.buildHcs20RegisterTx({registryTopicId:n,name:o,topicId:r,isPrivate:a,metadata:c,memo:l});return await Ye(e,d)}),Ve.register("hcs12.createRegistry",async({hederaKit:e,request:i})=>{const n=Je(i)?it(i,"options"):void 0,r=(n?tt(n,"ttl"):void 0)??60,o=n&&et(n,"registry")||"hashlinks";let s;try{const t=e?.signer?.getOperatorPrivateKey?.();s=t?.publicKey}catch{}const a=t.buildHcs12CreateRegistryTopicTx({registry:o,ttl:r,operatorPublicKey:s});return await Ye(e,a)}),Ve.register("hcs12.submitMessage",async({hederaKit:e,request:i})=>{if(!Je(i))throw new Error("hcs12.submitMessage: invalid request payload");const n=et(i,"topicId")||"";if(!n)throw new Error("hcs12.submitMessage: topicId is required");const r=i.payload,o=t.buildHcs12SubmitMessageTx({topicId:n,payload:r});return await Ye(e,o)}),Ve.register("hcs12.registerAssembly",async({hederaKit:e,request:i})=>{if(!Je(i))throw new Error("hcs12.registerAssembly: invalid request payload");const n=et(i,"assemblyTopicId")||"";if(!n)throw new Error("hcs12.registerAssembly: assemblyTopicId is required");const r=it(i,"registration")||{},o=t.buildHcs12RegisterAssemblyTx({assemblyTopicId:n,registration:r});return await Ye(e,o)}),Ve.register("hcs12.addBlock",async({hederaKit:e,request:i})=>{if(!Je(i))throw new Error("hcs12.addBlock: invalid request payload");const n=et(i,"assemblyTopicId")||"";if(!n)throw new Error("hcs12.addBlock: assemblyTopicId is required");const r=it(i,"operation")||{},o=t.buildHcs12AddBlockToAssemblyTx({assemblyTopicId:n,operation:r});return await Ye(e,o)}),Ve.register("hcs12.addAction",async({hederaKit:e,request:i})=>{if(!Je(i))throw new Error("hcs12.addAction: invalid request payload");const n=et(i,"assemblyTopicId")||"";if(!n)throw new Error("hcs12.addAction: assemblyTopicId is required");const r=it(i,"operation")||{},o=t.buildHcs12AddActionToAssemblyTx({assemblyTopicId:n,operation:r});return await Ye(e,o)}),Ve.register("hcs12.updateAssembly",async({hederaKit:e,request:i})=>{if(!Je(i))throw new Error("hcs12.updateAssembly: invalid request payload");const n=et(i,"assemblyTopicId")||"";if(!n)throw new Error("hcs12.updateAssembly: assemblyTopicId is required");const r=it(i,"operation")||{},o=t.buildHcs12UpdateAssemblyTx({assemblyTopicId:n,operation:r});return await Ye(e,o)}),Ve.register("hcs7.submitMessage",async({hederaKit:e,request:i})=>{if(!Je(i))throw new Error("hcs7.submitMessage: invalid request payload");const n=et(i,"topicId")||"";if(!n)throw new Error("hcs7.submitMessage: topicId is required");const r=it(i,"message")||{},o=t.buildHcs7SubmitMessageTx({topicId:n,message:r});return await Ye(e,o)}),Ve.register("hcs7.evm",async({hederaKit:e,request:i})=>{if(!Je(i))throw new Error("hcs7.evm: invalid request payload");const n=et(i,"topicId")||"";if(!n)throw new Error("hcs7.evm: topicId is required");const r=it(i,"config")||{},o=t.buildHcs7EvmMessageTx({topicId:n,config:r});return await Ye(e,o)}),Ve.register("hcs7.wasm",async({hederaKit:e,request:i})=>{if(!Je(i))throw new Error("hcs7.wasm: invalid request payload");const n=et(i,"topicId")||"";if(!n)throw new Error("hcs7.wasm: topicId is required");const r=it(i,"config")||{},o=t.buildHcs7WasmMessageTx({topicId:n,config:r});return await Ye(e,o)});const nt=Object.freeze(Object.defineProperty({__proto__:null,ByteBuildRegistry:Ve},Symbol.toStringTag,{value:"Module"}));Object.defineProperty(exports,"BasePlugin",{enumerable:!0,get:()=>i.BasePlugin}),Object.defineProperty(exports,"GetHbarPriceTool",{enumerable:!0,get:()=>i.HederaGetHbarPriceTool}),Object.defineProperty(exports,"PluginRegistry",{enumerable:!0,get:()=>i.PluginRegistry}),exports.AcceptConnectionRequestTool=M,exports.BaseHCS10QueryTool=p,exports.BaseHCS10TransactionTool=g,exports.BaseHCS2QueryTool=H,exports.BaseHCS2TransactionTool=D,exports.BaseHCS6QueryTool=Q,exports.BaseHCS6TransactionTool=Z,exports.BaseInscriberQueryTool=te,exports.BaseInscriberTransactionTool=ee,exports.ByteBuildRegistry=Ve,exports.CheckMessagesTool=S,exports.ConnectionMonitorTool=O,exports.CreateDynamicRegistryTool=class extends Q{constructor(e){super(e),this.name="createDynamicRegistry",this.description="Create a new HCS-6 dynamic registry for managing evolving content"}get specificInputSchema(){return V}async executeQuery(e,t){const i=await this.hcs6Builder.createRegistry({ttl:e.ttl,submitKey:e.submitKey});if(!("success"in i)||!i.success)throw new Error(i.error||"Failed to create dynamic registry");if(F(i)){const t=i.transactionBytes;return{message:"I prepared an unsigned transaction to create your HCS-6 dynamic registry. Please review and approve to submit.",transactionBytes:t,metadata:{transactionBytes:t,pendingApproval:!0,description:`Create HCS-6 dynamic registry (TTL: ${e.ttl}s)`}}}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 H{constructor(){super(...arguments),this.name="createHCS2Registry",this.description="Create an HCS-2 registry (standard HCS-2). Use when the user asks to create an HCS-2 registry, not a generic HCS topic. Builds a standards-compliant registry topic and returns the result or transaction bytes."}get specificInputSchema(){return K}async executeQuery(e,t){const i=e=>{if("string"==typeof e){const t=e.trim().toLowerCase();return"true"===t||"false"!==t&&e}return e};try{const t=await this.hcs2Builder.createRegistry({registryType:e.registryType,ttl:e.ttl,adminKey:i(e.adminKey),submitKey:i(e.submitKey)});if(!t.success)throw new Error(t.error||"Failed to create registry");if(F(t)){const i=t.transactionBytes;return{message:"I prepared an unsigned transaction to create your HCS-2 registry. Please review and approve to submit.",transactionBytes:i,metadata:{transactionBytes:i,pendingApproval:!0,description:`Create HCS-2 registry (${1===e.registryType?"Non-Indexed":"Indexed"}; TTL: ${e.ttl||86400}s)`}}}return`Successfully created HCS-2 registry!\n\nTopic ID: ${t?.topicId||"unknown"}\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(n){const e=n instanceof Error?n.message:"Failed to create HCS-2 registry";throw new Error(`Registry creation failed: ${e}`)}}},exports.DeleteEntryTool=class extends H{constructor(){super(...arguments),this.name="deleteHCS2Entry",this.description="Delete an entry from an indexed HCS-2 registry"}get specificInputSchema(){return j}async executeQuery(e,t){try{const t=await this.hcs2Builder.deleteEntry(e.registryTopicId,{uid:e.uid,memo:e.memo});if(!("success"in t)||!t.success)throw new Error(t.error||"Failed to delete entry");if(F(t)){const i=t.transactionBytes;return{message:"I prepared an unsigned transaction to delete the HCS-2 registry entry. Please review and approve to submit.",transactionBytes:i,metadata:{transactionBytes:i,pendingApproval:!0,description:`Delete HCS-2 entry (registry ${e.registryTopicId}, uid ${e.uid})`}}}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=N,exports.HCS10Builder=ze,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=Ge,exports.HCS6Builder=We,exports.HbarPricePlugin=Pe,exports.InitiateConnectionTool=A,exports.InscribeFromBufferTool=class extends te{constructor(){super(...arguments),this.name="inscribeFromBuffer",this.description='Use ONLY for inscribing regular files or content (NOT for NFT/Hashinal inscriptions). When user says "inscribe it" after you showed search results or other content WITHOUT mentioning NFT/hashinal, 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. NEVER use this for Hashinal NFTs - always use InscribeHashinalTool instead when user mentions hashinal, NFT, dynamic, or minting.',this.config=ue()}get specificInputSchema(){return ge}async _call(e,t){try{const t="string"==typeof e.base64Data?e.base64Data:"",i=/^[A-Za-z0-9+/]*={0,2}$/.test(t)?globalThis.Buffer.from(t,"base64"):globalThis.Buffer.from(t,"utf8"),n=e.fileName,r=e.mimeType,o=this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",s={mode:"file",metadata:e.metadata,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:!e.quoteOnly&&(e.waitForConfirmation??!0),waitMaxAttempts:60,waitIntervalMs:5e3,apiKey:e.apiKey,network:o,quoteOnly:e.quoteOnly},a=await this.inscriberBuilder.inscribe({type:"buffer",buffer:i,fileName:n,mimeType:r},s);if(a.confirmed&&!a.quote){const e=ne(a.inscription,a.result),{topicId:t,cdnUrl:i}=re(e,o,"1");return JSON.stringify({success:!0,data:`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${a.result?.transactionId??"unknown"}\nTopic ID: ${t||"N/A"}${i?`\nView inscription: ${i}`:""}\n\nThe inscription is now available.`})}return JSON.stringify({success:!0,data:`Successfully submitted inscription to the Hedera network!\n\nTransaction ID: ${a.result?.transactionId??"unknown"}\n\nThe inscription is processing and will be confirmed shortly.`})}catch(i){const e=i instanceof Error?i.message:String(i);return JSON.stringify({success:!1,error:`Inscription failed: ${e}`})}}async executeQuery(e,i){const n=await async function(e,i,n){const r=e.trim(),o=t.ContentResolverRegistry.getResolver();if(!o)return ce(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 ce(r,i,n)}(e.base64Data,e.mimeType,e.fileName);this.logger?.debug(`[InscribeFromBufferTool] Resolved content bytes: ${n.buffer?.length??-1}`);try{this.validateContent(n.buffer)}catch(c){this.logger?.warn(`Content validation warning: ${c instanceof Error?c.message:String(c)}`)}const r=n.buffer,o=n.mimeType||e.mimeType,s=n.fileName||e.fileName,a={mode:"file",metadata:e.metadata,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:!e.quoteOnly&&(e.waitForConfirmation??!0),waitMaxAttempts:60,waitIntervalMs:5e3,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:r,fileName:s,mimeType:o},a);return{success:!0,quote:{totalCostHbar:e.totalCostHbar,validUntil:e.validUntil,breakdown:e.breakdown},contentInfo:{fileName:s,mimeType:o,sizeBytes:r.length},message:`Estimated Quote for buffer content: ${s} (${(r.length/1024).toFixed(2)} KB)\nTotal cost: ${e.totalCostHbar} HBAR`}}catch(l){const e=l instanceof Error?l.message:"Failed to generate inscription quote";throw new Error(`Quote generation failed: ${e}`)}try{this.logger?.debug(`[InscribeFromBufferTool] Calling inscribe with fileName: ${s}, mime: ${o}`);const t=await this.executeInscription(r,s,o,a,e.timeoutMs);return this.logger?.debug(`[InscribeFromBufferTool] Inscribe result (confirmed): ${Boolean(t?.confirmed)}`),this.formatInscriptionResult(t,a)}catch(l){this.logger?.warn(`[InscribeFromBufferTool] Error during inscription: ${l instanceof Error?l.message:String(l)}`);const e=l instanceof Error?l.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){const i=e;if(i.confirmed&&!i.quote){const e=ne(i.inscription,i.result),n=t.network||"testnet",{topicId:r,cdnUrl:o}=re(e,n,"1");return`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${i.result?.transactionId??"unknown"}\nTopic ID: ${r||"N/A"}${o?`\nView inscription: ${o}`:""}\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??"unknown"}\n\nThe inscription is processing and will be confirmed shortly.`}},exports.InscribeFromFileTool=class extends te{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 ae}async executeQuery(e,t){let i;try{const t=await u.stat(e.filePath);if(!t.isFile())throw new Error(`Path "${e.filePath}" is not a file`);if(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&&this.logger?.warn(`Large file detected (${(t.size/1048576).toFixed(2)} MB)`),this.logger?.info("Reading file content..."),i=await u.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=d.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=d.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=ne(i.inscription,i.result),t=s.network||"testnet",{topicId:n,cdnUrl:r}=re(e,t,"1");return`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${i.result?.transactionId??"unknown"}\nTopic ID: ${n||"N/A"}${r?`\nView inscription: ${r}`:""}\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??"unknown"}\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"}[d.extname(e).toLowerCase()]||"application/octet-stream"}},exports.InscribeFromUrlTool=class extends te{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 se}async executeQuery(e,t){if(oe.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.`)}oe.info("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){oe.info("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;oe.warn(`Could not perform partial GET validation: ${r instanceof Error?r.message:"Unknown error"}`)}}oe.info(`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)oe.warn("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;oe.warn(`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:60,waitIntervalMs:5e3,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);const n=t;if(n.confirmed&&!n.quote){const e=ne(n.inscription,n.result),t=i.network||"testnet",{topicId:r,cdnUrl:o}=re(e,t,"1");return`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${n.result?.transactionId??"unknown"}\nTopic ID: ${r||"N/A"}${o?`\nView inscription: ${o}`:""}\n\nThe inscription is now available.`}return n.quote||n.confirmed?"Inscription operation completed.":`Successfully submitted inscription to the Hedera network!\n\nTransaction ID: ${n.result?.transactionId??"unknown"}\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 te{constructor(){super(...arguments),this.name="inscribeHashinal",this.description="Tool for inscribing Hashinal NFTs. CRITICAL: When user provides content (url/contentRef/base64Data), call with ONLY the content parameters - DO NOT auto-generate name, description, creator, or attributes. A form will be automatically shown to collect metadata from the user. Only include metadata parameters if the user explicitly provided them in their message."}getEntityResolutionPreferences(){return{name:"literal",description:"literal",creator:"literal",attributes:"literal",properties:"literal"}}get specificInputSchema(){return Oe._def?.schema||Oe}get schema(){if(!this._schemaWithRenderConfig){const e=this.specificInputSchema,t=e;t._renderConfig||(t._renderConfig={fieldType:"object",ui:{label:"Inscribe Hashinal NFT",description:"Create a Hashinal inscription for NFT minting"}}),this._schemaWithRenderConfig=e}return this._schemaWithRenderConfig}shouldGenerateForm(e){const i=new t.Logger({module:"InscribeHashinalTool"}),n=e;i.info("InscribeHashinalTool: Checking if form should be generated",{inputKeys:Object.keys(n||{}),hasContent:!!(n.url||n.contentRef||n.base64Data),renderFormProvided:"renderForm"in n,renderFormValue:n.renderForm});if(!!!(n.url||n.contentRef||n.base64Data))return i.info("InscribeHashinalTool: No content source provided"),!1;if("renderForm"in n&&!1===n.renderForm)return i.info("InscribeHashinalTool: renderForm=false, skipping form generation"),!1;const r=e=>"string"==typeof e&&0!==e.trim().length;return r(n.name)&&r(n.description)&&r(n.creator)?(i.info("InscribeHashinalTool: Required metadata present, skipping form generation"),!1):(i.info("InscribeHashinalTool: Content provided, showing form for metadata collection"),!0)}getFormSchema(){return ye(a.z.object({name:a.z.string().min(1,"Name is required").describe('Display name for the NFT (e.g., "Sunset Landscape #42", "Digital Abstract Art")'),description:a.z.string().min(1,"Description is required").describe("Meaningful description of the artwork, story, or concept behind this NFT"),creator:a.z.string().min(1,"Creator is required").describe('Creator account ID, artist name, or brand (e.g., "0.0.123456", "ArtistName", "StudioBrand")'),attributes:ye(a.z.array(a.z.object({trait_type:a.z.string().describe('Trait name (e.g., "Rarity", "Color", "Style")'),value:a.z.union([a.z.string(),a.z.number()]).describe('Trait value (e.g., "Epic", "Blue", 85)')}))).withRender(Re.array("NFT Attributes","Attribute")).optional().describe("Collectible traits and characteristics."),type:a.z.string().optional().describe('Category or genre of the NFT (e.g., "Digital Art", "Photography", "Collectible Card)')})).withRender({fieldType:"object",ui:{label:"Complete NFT Metadata",description:"Provide meaningful metadata to create a valuable NFT"}})}async executeQuery(e,i){if(!e.url&&!e.contentRef&&!e.base64Data)return Ne({code:"MISSING_CONTENT",details:"No content source provided",suggestions:["Provide a URL to content you want to inscribe","Upload a file and use the content reference","Provide base64-encoded content data"]});const n=this.inscriberBuilder.hederaKit?.client?.operatorAccountId?.toString()||"0.0.unknown",r={...me({name:e.name,creator:e.creator,description:e.description,type:e.type,fileName:e.fileName,mimeType:e.mimeType,operatorAccount:n}),attributes:Array.isArray(e.attributes)?e.attributes:[],properties:e.properties||{}};let o;try{o=function(e){try{return fe.parse(e)}catch(t){if(t instanceof a.z.ZodError){const e=t.errors.map(e=>`${e.path.join(".")}: ${e.message}`).join("; ");throw new Error(`HIP-412 metadata validation failed: ${e}`)}throw t}}(r)}catch(l){return Ne({code:"METADATA_VALIDATION_FAILED",details:`Metadata validation error: ${l instanceof Error?l.message:String(l)}`,suggestions:["Ensure all required metadata fields are provided","Check that attribute values are valid","Verify metadata follows HIP-412 standard"]})}const s={mode:"hashinal",metadata:o,jsonFileURL:e.jsonFileURL,fileStandard:e.fileStandard,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:!e.quoteOnly&&(e.waitForConfirmation??!0),waitMaxAttempts:60,waitIntervalMs:5e3,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",quoteOnly:e.quoteOnly};let c;if(e.url)c={type:"url",url:e.url};else{if(!e.contentRef&&!e.base64Data)throw new Error("No valid input data provided for inscription");{const t=e.contentRef||e.base64Data||"",{buffer:i,mimeType:n,fileName:r}=await this.resolveContent(t,e.mimeType,e.fileName);c={type:"buffer",buffer:i,fileName:r||e.fileName||"hashinal-content",mimeType:n||e.mimeType}}}if(e.quoteOnly)try{const t=await this.generateInscriptionQuote(c,s);return function(e){const{totalCostHbar:t,validUntil:i,breakdown:n,content:r}=e;return{success:!0,type:"quote",title:"Inscription Cost Quote",message:`Estimated cost to inscribe "${r.name||"your content"}" is ${t} HBAR.`,quote:{totalCostHbar:t,validUntil:i,breakdown:n},content:r}}({totalCostHbar:t.totalCostHbar,validUntil:t.validUntil,breakdown:t.breakdown,content:{name:e.name,creator:e.creator,type:e.type}})}catch(l){return Ne({code:"QUOTE_GENERATION_FAILED",details:`Quote generation failed: ${l instanceof Error?l.message:"Failed to generate inscription quote"}`,suggestions:["Check network connectivity","Verify content is accessible","Try again in a moment"]})}try{let i;if(e.timeoutMs){const t=new Promise((t,i)=>{setTimeout(()=>i(new Error(`Inscription timed out after ${e.timeoutMs}ms`)),e.timeoutMs)});i=await Promise.race([this.inscriberBuilder.inscribeAuto?this.inscriberBuilder.inscribeAuto(c,s):this.inscriberBuilder.inscribe(c,s),t])}else i=this.inscriberBuilder.inscribeAuto?await this.inscriberBuilder.inscribeAuto(c,s):await this.inscriberBuilder.inscribe(c,s);if(i.confirmed&&!i.quote){const n=ne(i.inscription,i.result),r=s.network||"testnet",o=e.fileStandard||"1",{hrl:a,topicId:c,cdnUrl:l}=re(n,r,o),u=function(e){const{hrl:t,topicId:i,standard:n,cdnUrl:r,transactionId:o,metadata:s}=e;return{success:!0,type:"inscription",title:`${n} Hashinal Inscription Complete`,message:`Successfully inscribed "${s.name||"your content"}" as a ${n} Hashinal. The content is now ready for NFT minting.`,inscription:{hrl:t,topicId:i,standard:n,cdnUrl:r,transactionId:o},metadata:s,nextSteps:{primary:"CRITICAL: When minting NFTs, use ONLY the mintingMetadata value as a single string in the metadata array. Do NOT create JSON objects.",context:'The metadata parameter for minting should be exactly: ["'+t+'"] - just the HRL string in an array, nothing else.',mintingMetadata:t}}}({hrl:a||"hcs://1/unknown",topicId:c||"unknown",standard:"6"===o?"Dynamic":"Static",cdnUrl:l,transactionId:i?.inscription?.tx_id||i?.result?.transactionId||"unknown",metadata:{name:e.name,creator:e.creator,description:e.description,type:e.type,attributes:Array.isArray(e.attributes)?e.attributes:[]}});if(!1!==e.withHashLinkBlocks)try{const e=await this.createHashLinkBlock(u);u.hashLinkBlock=e}catch(d){new t.Logger({module:"InscribeHashinalTool"}).warn("Failed to create HashLink block",d)}return u}if(i.quote||i.confirmed)return Ne({code:"UNEXPECTED_RESULT",details:"Received an unexpected inscription result state",suggestions:["Try again or verify network status"]});return function(e){const{transactionId:t,details:i,suggestions:n}=e,r=i||`Inscription submitted but not yet confirmed. Transaction ID: ${t}`;return{success:!1,type:"error",title:"Inscription Submitted (Pending)",message:r,error:{code:"INSCRIPTION_PENDING",details:r,suggestions:n||["Wait a few moments for confirmation","Check the transaction status on a Hedera explorer","Try the inscription again if it doesn't confirm within 5 minutes"]}}}({transactionId:i.result?.transactionId||i?.inscription?.transactionId||"unknown",details:"Successfully submitted Hashinal inscription. Waiting for network confirmation..."})}catch(l){const e=l instanceof Error?l.message:"Failed to inscribe Hashinal NFT";throw new Error(`Inscription failed: ${e}`)}}async createHashLinkBlock(e,i){const n=this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",r=e.inscription.cdnUrl?.includes("mainnet")?"mainnet":"testnet";if(n!==r){new t.Logger({module:"InscribeHashinalTool"}).warn(`Network mismatch detected: client=${n}, cdn=${r}. Using client network.`)}const o=n,s=function(e){const t="mainnet"===e?xe.mainnet:xe.testnet;return t&&"0.0.TBD"!==t.blockId?t:xe.testnet}(o);return{blockId:s.blockId,hashLink:s.hashLink,template:s.template,attributes:{name:e.metadata.name||"Untitled Content",creator:e.metadata.creator||"",topicId:e.inscription.topicId,hrl:e.inscription.hrl,network:o}}}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}}getEssentialFields(){return["name","description","creator","attributes"]}isFieldEmpty(e,t){return null==t||""===t||(!(!Array.isArray(t)||0!==t.length)||!("attributes"!==e||!Array.isArray(t))&&t.every(e=>!e||"object"==typeof e&&(!e.trait_type||!e.value)))}},exports.InscriberBuilder=Qe,exports.ListConnectionsTool=v,exports.ListUnapprovedConnectionRequestsTool=P,exports.ManageConnectionRequestsTool=$,exports.MigrateRegistryTool=class extends H{constructor(){super(...arguments),this.name="migrateHCS2Registry",this.description="Migrate an HCS-2 registry to a new topic"}get specificInputSchema(){return G}async executeQuery(e,t){try{const t=await this.hcs2Builder.migrateRegistry(e.registryTopicId,{targetTopicId:e.targetTopicId,metadata:e.metadata,memo:e.memo});if(!("success"in t)||!t.success)throw new Error(t.error||"Failed to migrate registry");if(F(t)){const i=t.transactionBytes;return{message:"I prepared an unsigned transaction to migrate the HCS-2 registry. Please review and approve to submit.",transactionBytes:i,metadata:{transactionBytes:i,pendingApproval:!0,description:`Migrate HCS-2 registry (from ${e.registryTopicId} to ${e.targetTopicId})`}}}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=f,exports.OpenConvaiState=Be,exports.QueryDynamicRegistryTool=class extends Q{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 J}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 H{constructor(){super(...arguments),this.name="queryHCS2Registry",this.description="Query entries from an HCS-2 registry (standard HCS-2). Retrieves indexed or latest entries and returns a structured summary."}get specificInputSchema(){return W}async executeQuery(e,t){const i=await this.hcs2Builder.getRegistry(e.topicId,{limit:e.limit,order:e.order,skip:e.skip}),n=i.registryType,r=0===n||"0"===n||"indexed"===String(n).toLowerCase()||"index"===String(n).toLowerCase()||"index_topic"===String(n).toLowerCase()||"indexed_registry"===String(n).toLowerCase();return{topicId:i.topicId,registryType:r?"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=y,exports.RegisterDynamicHashinalTool=class extends Q{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 Y}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(!("success"in i)||!i.success)throw new Error(i.error||"Failed to register dynamic hashinal");if(F(i)){const t=i.transactionBytes;return{message:"I prepared an unsigned transaction to register a dynamic hashinal. Please review and approve to submit.",transactionBytes:t,metadata:{transactionBytes:t,pendingApproval:!0,description:"Register dynamic hashinal"+(e.memo?` (Memo: ${e.memo})`:"")}}}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 H{constructor(){super(...arguments),this.name="registerHCS2Entry",this.description="Register an entry in an HCS-2 registry (standard HCS-2). Use this to add a target topic to an existing HCS-2 registry."}get specificInputSchema(){return L}async executeQuery(e,t){try{const t=await this.hcs2Builder.registerEntry(e.registryTopicId,{targetTopicId:e.targetTopicId,metadata:e.metadata,memo:e.memo});if(!("success"in t)||!t.success)throw new Error(t.error||"Failed to register entry");if(F(t)){const i=t.transactionBytes;return{message:"I prepared an unsigned transaction to register the entry in the HCS-2 registry. Please review and approve to submit.",transactionBytes:i,metadata:{transactionBytes:i,pendingApproval:!0,description:`Register HCS-2 entry (registry ${e.registryTopicId} -> target ${e.targetTopicId})`}}}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 te{constructor(){super(...arguments),this.name="retrieveInscription",this.description="Retrieve details of an existing inscription from the Hedera network"}get specificInputSchema(){return qe}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||"unknown",topicId:i.topic_id||i.topicId,status:i.status||"unknown",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=_,exports.SendMessageToConnectionTool=I,exports.SignerProviderRegistry=ke,exports.UpdateDynamicHashinalTool=class extends Q{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 X}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(!("success"in i)||!i.success)throw new Error(i.error||"Failed to update dynamic hashinal");if(F(i)){const t=i.transactionBytes;return{message:"I prepared an unsigned transaction to update a dynamic hashinal. Please review and approve to submit.",transactionBytes:t,metadata:{transactionBytes:t,pendingApproval:!0,description:`Update dynamic hashinal (registry ${e.registryTopicId})${e.memo?` (Memo: ${e.memo})`:""}`}}}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 H{constructor(){super(...arguments),this.name="updateHCS2Entry",this.description="Update an existing entry in an indexed HCS-2 registry"}get specificInputSchema(){return U}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(!("success"in t)||!t.success)throw new Error(t.error||"Failed to update entry");if(F(t)){const i=t.transactionBytes;return{message:"I prepared an unsigned transaction to update the HCS-2 registry entry. Please review and approve to submit.",transactionBytes:i,metadata:{transactionBytes:i,pendingApproval:!0,description:`Update HCS-2 entry (registry ${e.registryTopicId}, uid ${e.uid} -> ${e.targetTopicId})`}}}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.createFieldConfigMap=function(e){const t=De(e),i={};for(const[n,r]of Object.entries(t.fields)){const e=t.metadata[n],o=n.split(".");i[n]={renderConfig:r,metadata:e,path:o}}return i},exports.createProgressiveSchema=function(e,t){const i=ye(e),n=e._def?.typeName;if("ZodObject"===n){const n=e._def?.shape;if(n){for(const[e,i]of Object.entries(n)){let n,r="common";for(const[i,o]of Object.entries(t))if(o.fields.includes(e)){n=i,r=o.priority;break}ye(i).withProgressive(r,n)}return i}}return i},exports.createSimpleConfig=function(e){const t=De(e),i=[];for(const n of t.order){const e=t.fields[n],r=t.metadata[n];e&&r&&i.push({name:n,type:r.type,label:e.ui?.label||n,required:r.required,placeholder:e.ui?.placeholder,options:e.options||r.options})}return{fields:i}},exports.enhanceRenderConfig=function(e){return{...e,progressive:{priority:e.ui?.priority||"common",group:e.ui?.group}}},exports.extendZodSchema=ye,exports.extractFieldMetadata=Se,exports.extractOptionsFromSchema=Te,exports.extractProgressiveInfo=function(e){const t=we(e);return t?.progressive?{priority:t.progressive.priority,group:t.progressive.group}:t?.ui?.priority?{priority:t.ui.priority,group:t.ui.group}:{priority:"common"}},exports.extractRenderConfigs=De,exports.extractValidationConstraints=ve,exports.generateFieldOrdering=function(e){const t=De(e),i={},n={default:0,"Basic Information":1,"Token Settings":2,"Keys & Security":3,"Custom Fees":4,"Advanced Settings":5};for(const[r,o]of Object.entries(t.groups)){const e="default"===r?"Basic Information":r;i[e]={title:e,fields:o,order:n[e]||10}}return{sections:i,fieldOrder:t.order}},exports.getDefaultValue=Ee,exports.getInnerSchema=Ce,exports.getRenderConfig=we,exports.hasRenderConfig=be,exports.inferFieldTypeFromSchema=Ie,exports.initializeStandardsAgentKit=async e=>{const n=e?.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",a="true"===process.env.DISABLE_LOGGING,c=t.Logger.getInstance({level:n.logLevel||"info",silent:a});let l;if("mainnet"===s?l="mainnet":("testnet"===s||c.warn(`Unsupported network specified: '${s}'. Defaulting to 'testnet'.`),l="testnet"),!r||!o)throw new Error("Operator ID and private key must be provided either through options or environment variables.");const d=e?.stateManager||new Be({defaultEnvFilePath:$e,defaultPrefix:"TODD"});c.info("State manager initialized");const u=new i.ServerSigner(r,o,l),g=new i.HederaAgentKit(u);await g.initialize(),c.info(`HederaAgentKit initialized for ${r} on ${l}`);const p=new ze(g,d,{useEncryption:n.useEncryption,registryUrl:n.registryUrl,logLevel:n.logLevel});let h,f;if(e?.monitoringClient){const e=new i.ServerSigner(r,o,l);h=new i.HederaAgentKit(e),await h.initialize(),f=new ze(h,d,{useEncryption:n.useEncryption,registryUrl:n.registryUrl,logLevel:"error"}),c.info("Monitoring client initialized")}const m={};return m.registerAgentTool=new y({hederaKit:g,hcs10Builder:p,logger:void 0}),e?.createAllTools&&(m.findRegistrationsTool=new N({hederaKit:g,hcs10Builder:p,logger:void 0}),m.retrieveProfileTool=new _({hederaKit:g,hcs10Builder:p,logger:void 0}),m.initiateConnectionTool=new A({hederaKit:g,hcs10Builder:p,logger:void 0}),m.listConnectionsTool=new v({hederaKit:g,hcs10Builder:p,logger:void 0}),m.sendMessageToConnectionTool=new I({hederaKit:g,hcs10Builder:p,logger:void 0}),m.checkMessagesTool=new S({hederaKit:g,hcs10Builder:p,logger:void 0}),m.connectionMonitorTool=new O({hederaKit:h||g,hcs10Builder:f||p,logger:void 0}),m.manageConnectionRequestsTool=new $({hederaKit:g,hcs10Builder:p,logger:void 0}),m.acceptConnectionRequestTool=new M({hederaKit:g,hcs10Builder:p,logger:void 0}),m.listUnapprovedConnectionRequestsTool=new P({hederaKit:g,hcs10Builder:p,logger:void 0}),c.info("All tools initialized")),{hederaKit:g,hcs10Builder:p,monitoringHederaKit:h,monitoringHcs10Builder:f,tools:m,stateManager:d}},exports.installZodRenderExtensions=function(){a.ZodType.prototype.withRender||(a.ZodType.prototype.withRender=function(e){return ye(this).withRender(e)},a.ZodType.prototype.withProgressive=function(e,t){return ye(this).withProgressive(e,t)},a.ZodType.prototype.withBlock=function(e){return ye(this).withBlock(e)})},exports.isFormValidatable=function(e){return null!==e&&"object"==typeof e&&"shouldGenerateForm"in e&&"getFormSchema"in e&&"getEssentialFields"in e&&"isFieldEmpty"in e&&"function"==typeof e.shouldGenerateForm&&"function"==typeof e.getFormSchema&&"function"==typeof e.getEssentialFields&&"function"==typeof e.isFieldEmpty},exports.isOptionalSchema=Ae,exports.loadConfig=ue,exports.renderConfigs=Re;
|
|
1
|
+
"use strict";Object.create,Object.defineProperty,Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("@hashgraph/sdk"),t=require("@hashgraphonline/standards-sdk"),i=require("hedera-agent-kit"),n=require("fs"),r=require("path"),o=require("axios"),s=require("zod"),a=require("fs/promises");function c(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 l=c(r),d=c(a);class u extends i.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}class g extends i.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}const p=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"}};p.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 h=p;const f=s.z.object({name:s.z.string().min(1).max(50).describe("A unique name for the agent (1-50 characters)"),description:s.z.string().max(500).optional().describe("Optional bio description for the agent (max 500 characters)"),alias:s.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:s.z.enum(["autonomous","manual"]).optional().describe("Agent type (default: autonomous)"),model:s.z.string().optional().describe("AI model identifier (default: agent-model-2024)"),capabilities:s.z.union([s.z.array(s.z.nativeEnum(t.AIAgentCapability)),s.z.array(s.z.string()),s.z.string()]).optional().transform(e=>{if(e)return"string"==typeof e?h.parseCapabilities(e):Array.isArray(e)&&e.length>0&&"string"==typeof e[0]?h.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:s.z.union([s.z.array(s.z.string()),s.z.string()]).optional().transform(e=>{if(e)return"string"==typeof e?h.parseCapabilities(e):h.parseTagsOrCapabilities(e)}).describe('Tags for the agent (alternative to capabilities) - e.g. "ai", "data", "analytics". Will be converted to appropriate capabilities.'),creator:s.z.string().optional().describe("Creator attribution for the agent"),socials:s.z.record(s.z.enum(["twitter","github","discord","telegram","linkedin","youtube","website","x"]),s.z.string()).optional().describe('Social media links (e.g., {"twitter": "@handle", "discord": "username"})'),properties:s.z.record(s.z.unknown()).optional().describe("Custom metadata properties for the agent"),profilePicture:s.z.union([s.z.string().describe("URL or local file path to profile picture"),s.z.object({url:s.z.string().optional(),path:s.z.string().optional(),filename:s.z.string().optional()})]).optional().describe("Optional profile picture as URL, file path, or object with url/path/filename"),existingProfilePictureTopicId:s.z.string().optional().describe("Topic ID of an existing profile picture to reuse (e.g., 0.0.12345)"),initialBalance:s.z.number().positive().optional().describe("Optional initial HBAR balance for the new agent account (will create new account if provided)"),userAccountId:s.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:s.z.number().positive().optional().describe("Optional HBAR fee amount to charge per message on the inbound topic"),tokenFees:s.z.array(s.z.object({amount:s.z.number().positive(),tokenId:s.z.string()})).optional().describe("Optional token fees to charge per message"),exemptAccountIds:s.z.array(s.z.string()).optional().describe("Optional account IDs to exempt from fees"),setAsCurrent:s.z.boolean().optional().describe("Whether to set as current agent (default: true)"),persistence:s.z.object({prefix:s.z.string().optional()}).optional().describe("Optional persistence configuration")});class m extends u{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=f,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 y=new t.Logger({module:"SendMessageToConnectionTool"}),b=s.z.object({targetIdentifier:s.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:s.z.string().optional().describe("The connection number (e.g., '1', '2') from the 'list_connections' tool."),agentId:s.z.string().optional().describe("The account ID (e.g., 0.0.12345) of the target agent."),message:s.z.string().describe("The text message content to send."),disableMonitoring:s.z.boolean().optional().default(!1)});class w extends u{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=b,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){y.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=s.z.object({targetAccountId:s.z.string().describe("The Hedera account ID (e.g., 0.0.12345) of the agent you want to connect with."),disableMonitor:s.z.boolean().optional().describe("If true, does not wait for connection confirmation. Returns immediately after sending the request."),memo:s.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 T extends u{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 A=s.z.object({includeDetails:s.z.boolean().optional().describe("Whether to include detailed information about each connection"),showPending:s.z.boolean().optional().describe("Whether to include pending connection requests")});class C extends g{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=A}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 v=s.z.object({targetIdentifier:s.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:s.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:s.z.number().int().positive().optional().describe("When fetchLatest is true, specifies how many of the most recent messages to retrieve. Defaults to 1.")});class E extends g{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=v}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 S=s.z.object({accountId:s.z.string().optional().describe("Optional: Filter registrations by a specific Hedera account ID (e.g., 0.0.12345)."),tags:s.z.union([s.z.array(s.z.nativeEnum(t.AIAgentCapability)),s.z.array(s.z.string()),s.z.string()]).optional().transform(e=>{if(e)return"string"==typeof e?h.parseCapabilities(e):Array.isArray(e)&&e.length>0&&"string"==typeof e[0]?h.parseTagsOrCapabilities(e):e}).describe('Optional: Filter by capabilities/tags like "ai", "data", "analytics". Can be natural language terms or capability numbers.')});class R extends g{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=S}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 N=s.z.object({acceptAll:s.z.boolean().optional().describe("Whether to automatically accept all incoming connection requests. Default is false."),targetAccountId:s.z.string().optional().describe("If provided, only accept connection requests from this specific account ID."),hbarFees:s.z.array(s.z.object({amount:s.z.number(),collectorAccount:s.z.string().optional()})).optional().describe("Array of HBAR fee amounts to charge per message (with optional collector accounts)."),tokenFees:s.z.array(s.z.object({amount:s.z.number(),tokenId:s.z.string(),collectorAccount:s.z.string().optional()})).optional().describe("Array of token fee amounts and IDs to charge per message (with optional collector accounts)."),exemptAccountIds:s.z.array(s.z.string()).optional().describe("Array of account IDs to exempt from ALL fees set in this request."),monitorDurationSeconds:s.z.number().optional().describe("How long to monitor for incoming requests in seconds. Default is 120."),defaultCollectorAccount:s.z.string().optional().describe("Default account to collect fees if not specified at the fee level. Defaults to the agent account.")});class x extends u{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=N,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 O=s.z.object({action:s.z.enum(["list","view","reject"]).describe("The action to perform: list all requests, view details of a specific request, or reject a request"),requestKey:s.z.string().optional().describe("The unique request key to view or reject (required for view and reject actions)")});class q extends g{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=O}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 $=s.z.object({requestKey:s.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:s.z.number().optional().describe("Optional HBAR fee amount to charge the connecting agent per message on the new connection topic."),exemptAccountIds:s.z.array(s.z.string()).optional().describe("Optional list of account IDs to exempt from any configured fees on the new connection topic.")});class B extends u{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=$,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 k=s.z.object({accountId:s.z.string().describe("The Hedera account ID of the agent whose profile you want to retrieve (e.g., 0.0.12345)."),disableCache:s.z.boolean().optional().describe("Optional: Force refresh from the network instead of using cache.")});class M extends g{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=k}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 _=s.z.object({});class z extends g{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=_}async executeQuery(){const e=this.hcs10Builder;await e.listUnapprovedConnectionRequests();const t=await e.execute();return"rawResult"in t?t.rawResult:t}}class P extends i.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs2",this.hcs2Builder=e.hcs2Builder}getServiceBuilder(){return this.hcs2Builder}}class D extends i.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs2",this.hcs2Builder=e.hcs2Builder}getServiceBuilder(){return this.hcs2Builder}}function H(e){return!!e&&"string"==typeof e.transactionBytes}const F=s.z.object({registryType:s.z.nativeEnum(t.HCS2RegistryType).optional().describe("Registry type: 0 for indexed, 1 for non-indexed (default: 0)"),ttl:s.z.number().int().positive().optional().describe("Time to live in seconds (default: 86400)"),adminKey:s.z.union([s.z.string(),s.z.boolean()]).optional().describe("Admin key: public key string or true to use operator key"),submitKey:s.z.union([s.z.string(),s.z.boolean()]).optional().describe("Submit key: public key string or true to use operator key")});const K=s.z.object({registryTopicId:s.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID (e.g., 0.0.123456)"),targetTopicId:s.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The target topic ID to register (e.g., 0.0.123456)"),metadata:s.z.string().optional().describe("Optional metadata URI (HIP-412 format)"),memo:s.z.string().max(500).optional().describe("Optional memo (max 500 characters)")});const L=s.z.object({registryTopicId:s.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID (must be indexed)"),targetTopicId:s.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The new topic ID to point to"),uid:s.z.string().describe("The unique ID of the entry to update"),metadata:s.z.string().optional().describe("Optional metadata URI (HIP-412 format)"),memo:s.z.string().max(500).optional().describe("Optional memo (max 500 characters)")});const U=s.z.object({registryTopicId:s.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID (must be indexed)"),uid:s.z.string().describe("The unique ID of the entry to delete"),memo:s.z.string().max(500).optional().describe("Optional memo (max 500 characters)")});const j=s.z.object({registryTopicId:s.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The current HCS-2 registry topic ID"),targetTopicId:s.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The new topic ID to migrate to"),metadata:s.z.string().optional().describe("Optional metadata URI for migration details"),memo:s.z.string().max(500).optional().describe("Optional memo (max 500 characters)")});const G=s.z.object({topicId:s.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID to query"),limit:s.z.number().int().positive().optional().describe("Maximum number of entries to return"),order:s.z.enum(["asc","desc"]).optional().describe("Order of results (ascending or descending)"),skip:s.z.number().int().min(0).optional().describe("Number of entries to skip")});class W extends i.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs6",this.hcs6Builder=e.hcs6Builder}getServiceBuilder(){return this.hcs6Builder}}class Z extends i.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs6",this.hcs6Builder=e.hcs6Builder}getServiceBuilder(){return this.hcs6Builder}}const Q=s.z.object({ttl:s.z.number().min(3600).default(86400).describe("Time-to-live in seconds (minimum 3600 seconds/1 hour)"),submitKey:s.z.union([s.z.boolean(),s.z.string()]).optional().describe("Submit key for the registry topic. Can be boolean (use operator key) or a public key string")});const V=s.z.object({metadata:s.z.record(s.z.unknown()).describe("Metadata object for the hashinal (e.g., name, description, attributes)"),data:s.z.object({base64:s.z.string().optional().describe("Base64 encoded data for the hashinal"),url:s.z.string().optional().describe("URL to fetch data from"),mimeType:s.z.string().optional().describe("MIME type of the data")}).optional().describe("Data to inscribe with the hashinal"),memo:s.z.string().optional().describe("Optional memo for the registration"),ttl:s.z.number().min(3600).default(86400).describe("Time-to-live in seconds for the inscription"),registryTopicId:s.z.string().optional().describe("Registry topic ID to use. If not provided, a new registry will be created"),submitKey:s.z.string().optional().describe("Submit key for the registry (required if registry has a submit key)")});const Y=s.z.object({registryTopicId:s.z.string().describe("The registry topic ID that tracks this dynamic hashinal"),metadata:s.z.record(s.z.unknown()).describe("Updated metadata object for the hashinal"),data:s.z.object({base64:s.z.string().optional().describe("Base64 encoded data for the updated hashinal"),url:s.z.string().optional().describe("URL to fetch updated data from"),mimeType:s.z.string().optional().describe("MIME type of the data")}).optional().describe("Updated data to inscribe"),memo:s.z.string().optional().describe('Optional memo for the update (e.g., "Level up", "Version 2.0")'),submitKey:s.z.string().describe("Submit key for the registry (required to update)")});const X=s.z.object({topicId:s.z.string().describe("The registry topic ID to query"),limit:s.z.number().optional().default(100).describe("Maximum number of entries to retrieve"),order:s.z.enum(["asc","desc"]).optional().default("desc").describe("Order of entries (desc shows latest first)"),skip:s.z.number().optional().describe("Number of entries to skip")});class J extends i.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}setEntityCreationHandler(e){this.onEntityCreated=e}async generateInscriptionQuote(e,t){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 ee extends i.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}setEntityCreationHandler(e){this.onEntityCreated=e}async generateInscriptionQuote(e,t){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}}function te(e,t){if(!e||"object"!=typeof e)return;const i=e[t];return"string"==typeof i&&i.trim()?i:void 0}function ie(e,t){return{jsonTopicId:e.jsonTopicId||te(e,"json_topic_id"),topicId:te(e,"topic_id")||te(e,"topicId")||te(t,"topicId")||te(t,"topic_id")}}function ne(e,t,i="1"){const n=e.jsonTopicId||e.topicId;return{hrl:n?`hcs://${i}/${n}`:void 0,cdnUrl:e.jsonTopicId?`https://kiloscribe.com/api/inscription-cdn/${e.jsonTopicId}?network=${t}`:void 0,topicId:n}}const re=new t.Logger({module:"InscribeFromUrlTool"}),oe=s.z.object({url:s.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:s.z.enum(["file","hashinal"]).optional().describe("Inscription mode: file or hashinal NFT"),metadata:s.z.record(s.z.unknown()).optional().describe("Metadata to attach to the inscription"),tags:s.z.array(s.z.string()).optional().describe("Tags to categorize the inscription"),chunkSize:s.z.number().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:s.z.boolean().optional().describe("Whether to wait for inscription confirmation"),timeoutMs:s.z.number().int().positive().optional().describe("Timeout in milliseconds for inscription (default: no timeout - waits until completion)"),apiKey:s.z.string().optional().describe("API key for inscription service"),quoteOnly:s.z.boolean().optional().default(!1).describe("If true, returns a cost quote instead of executing the inscription")});const se=s.z.object({filePath:s.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:s.z.enum(["file","hashinal"]).optional().describe("Inscription mode: file or hashinal NFT"),metadata:s.z.record(s.z.unknown()).optional().describe("Metadata to attach to the inscription"),tags:s.z.array(s.z.string()).optional().describe("Tags to categorize the inscription"),chunkSize:s.z.number().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:s.z.boolean().optional().describe("Whether to wait for inscription confirmation"),timeoutMs:s.z.number().int().positive().optional().describe("Timeout in milliseconds for inscription (default: no timeout)"),apiKey:s.z.string().optional().describe("API key for inscription service"),quoteOnly:s.z.boolean().optional().default(!1).describe("If true, returns a cost quote instead of executing the inscription")});function ae(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}}const ce=s.z.string().regex(/^content-ref:[a-zA-Z0-9_-]+$/,'Content reference must be in format "content-ref:[alphanumeric-id]"').describe('Content reference in format "content-ref:[id]"'),le={maxInscriptionSize:51200,minContentSize:10,logLevel:"warn"};function de(){return{maxInscriptionSize:parseInt(process.env.REF_MAX_SIZE||le.maxInscriptionSize.toString(),10),minContentSize:parseInt(process.env.REF_MIN_SIZE||le.minContentSize.toString(),10),logLevel:process.env.REF_LOG_LEVEL||le.logLevel,enableContentValidation:"false"!==process.env.REF_ENABLE_VALIDATION}}const ue=s.z.object({base64Data:s.z.union([s.z.string(),ce]).describe("Content to inscribe as base64 data, plain text, or content reference"),fileName:s.z.string().min(1).describe("Name for the inscribed content"),mimeType:s.z.string().optional().describe("MIME type of the content"),metadata:s.z.record(s.z.unknown()).optional().describe("Metadata to attach"),tags:s.z.array(s.z.string()).optional().describe("Tags to categorize the inscription"),chunkSize:s.z.number().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:s.z.boolean().optional().describe("Wait for inscription confirmation"),timeoutMs:s.z.number().int().positive().optional().describe("Timeout in milliseconds"),apiKey:s.z.string().optional().describe("API key for inscription service"),quoteOnly:s.z.boolean().optional().default(!1).describe("Return cost quote only")});const ge=s.z.object({uri:s.z.string().describe("URI of the file"),checksum:s.z.string().optional().describe("SHA-256 checksum of the file"),is_default_file:s.z.boolean().optional().describe("Whether this is the default file"),type:s.z.string().describe("MIME type of the file")}),pe=s.z.object({trait_type:s.z.string().describe("The trait type"),value:s.z.union([s.z.string(),s.z.number()]).describe("The trait value"),display_type:s.z.string().optional().describe("Display type for the attribute")}),he=s.z.object({name:s.z.string().describe("Token name (required by HIP-412)"),description:s.z.string().describe("Human readable description (required by HIP-412)"),image:s.z.string().describe("Preview image URI (required by HIP-412)"),type:s.z.string().describe("MIME type (required by HIP-412)"),creator:s.z.string().optional().describe("Creator name or comma-separated names"),creatorDID:s.z.string().optional().describe("Decentralized identifier for creator"),checksum:s.z.string().optional().describe("SHA-256 checksum of the image"),format:s.z.string().optional().default("HIP412@2.0.0").describe("Metadata format version"),files:s.z.array(ge).optional().describe("Array of files for multi-file NFTs"),attributes:s.z.array(pe).optional().describe("NFT attributes/traits"),properties:s.z.record(s.z.unknown()).optional().describe("Additional properties")});function fe(e){const t=e.fileName?.replace(/\.[^/.]+$/,"")||"Hashinal NFT";let i="media";return e.mimeType?.startsWith("image/")?i="image":e.mimeType?.startsWith("video/")?i="video":e.mimeType?.startsWith("audio/")&&(i="audio"),{name:e.name||t,creator:e.creator||e.operatorAccount,description:e.description||`${i.charAt(0).toUpperCase()+i.slice(1)} NFT inscribed as Hashinal`,type:e.type||i,image:""}}function me(e){const t=e;return t.withRender=function(e){const i=Object.create(this),n=this._renderConfig||{},r={...n,...e,ui:{...n.ui||{},...e.ui||{}}};return(n.progressive||e.progressive)&&(r.progressive={...n.progressive||{},...e.progressive||{}}),(n.block||e.block)&&(r.block={...n.block||{},...e.block||{}}),i._renderConfig=r,i.withRender=t.withRender,i.withProgressive=t.withProgressive,i.withBlock=t.withBlock,i},t.withProgressive=function(t,i){const n=this._renderConfig||{fieldType:we(e)};return this.withRender({...n,progressive:{priority:t,group:i}})},t.withBlock=function(t){const i=this._renderConfig||{fieldType:we(e)};return this.withRender({...i,block:{id:t,type:"field",reusable:!0}})},t}function ye(e){return Boolean(e&&"function"==typeof e.withRender)}function be(e){if(ye(e))return e._renderConfig}function we(e){const t=e._def?.typeName;switch(t){case"ZodString":{const t=e._def?.checks||[];for(const e of t){if("email"===e.kind)return"text";if("url"===e.kind)return"text"}return"text"}case"ZodNumber":case"ZodBigInt":return"number";case"ZodBoolean":return"checkbox";case"ZodEnum":case"ZodNativeEnum":case"ZodUnion":case"ZodDiscriminatedUnion":return"select";case"ZodArray":return"array";case"ZodDate":default:return"text";case"ZodObject":return"object";case"ZodOptional":case"ZodDefault":{const t=e._def?.innerType;return t?we(t):"text"}}}function Ie(e){const t=e._def?.typeName;if("ZodEnum"===t){const t=e._def?.values;if(Array.isArray(t))return t.map(e=>({value:e,label:e.charAt(0).toUpperCase()+e.slice(1).replace(/[_-]/g," ")}))}if("ZodNativeEnum"===t){const t=e._def?.values;if(t)return Object.entries(t).map(([e,t])=>({value:t,label:e.replace(/[_-]/g," ")}))}if("ZodUnion"===t){const t=[],i=e._def?.options;if(Array.isArray(i))for(const e of i)if("ZodLiteral"===e._def?.typeName){const i=e._def?.value;void 0!==i&&t.push({value:i,label:"string"==typeof i?i.charAt(0).toUpperCase()+i.slice(1):String(i)})}return t.length>0?t:void 0}}function Te(e){const t=e._def?.typeName;return"ZodOptional"===t||"ZodDefault"===t}function Ae(e){const t=e._def?.typeName;if("ZodOptional"===t||"ZodDefault"===t){const t=e._def?.innerType;return t||e}return e}function Ce(e){const t=Ae(e),i=t._def?.typeName,n={};if("ZodString"===i){const e=t._def.checks;if(e&&Array.isArray(e))for(const t of e)switch(t.kind){case"min":n.minLength=t.value;break;case"max":n.maxLength=t.value;break;case"email":n.type="email";break;case"url":n.type="url";break;case"regex":n.pattern=t.regex}}if("ZodNumber"===i){const e=t._def.checks;if(e&&Array.isArray(e))for(const t of e)switch(t.kind){case"min":n.min=t.value;break;case"max":n.max=t.value;break;case"int":n.step=1;break;case"multipleOf":n.step=t.value}}if("ZodArray"===i){const e=t._def,i=e.minLength,r=e.maxLength;void 0!==i&&(n.minItems=i.value),void 0!==r&&(n.maxItems=r.value)}return n}function ve(e){const t=e._def?.typeName;if("ZodDefault"===t){const t=e._def?.defaultValue;return"function"==typeof t?t():t}const i=Ae(e),n=i._def?.typeName;switch(n){case"ZodString":return"";case"ZodNumber":case"ZodBigInt":return 0;case"ZodBoolean":return!1;case"ZodArray":return[];case"ZodObject":{const e=i._def?.shape;if(e){const t={};for(const[i,n]of Object.entries(e))t[i]=ve(n);return t}return{}}case"ZodDate":return new Date;case"ZodEnum":{const e=i._def?.values;return Array.isArray(e)&&e.length>0?e[0]:void 0}default:return}}function Ee(e){const t=Ae(e),i=we(e),n=!Te(e),r=Te(e),o=ve(e),s=Ie(t),a=Ce(e),c=e?.description;return{type:i,required:n,optional:r,default:o,options:s,constraints:a,description:c,validation:{minLength:a.minLength,maxLength:a.maxLength,min:a.min,max:a.max,pattern:a.pattern?new RegExp(a.pattern):void 0}}}const Se={text:(e,t,i="common")=>({fieldType:"text",ui:{label:e,placeholder:t,priority:i},progressive:{priority:i}}),number:(e,t,i,n="common")=>({fieldType:"number",ui:{label:e,priority:n},constraints:{min:t,max:i},progressive:{priority:n}}),select:(e,t,i="common")=>({fieldType:"select",ui:{label:e,priority:i},options:t,progressive:{priority:i}}),textarea:(e,t=3,i="common")=>({fieldType:"textarea",ui:{label:e,priority:i},props:{rows:t},progressive:{priority:i}}),currency:(e,t="HBAR",i="common")=>({fieldType:"currency",ui:{label:e,priority:i},props:{symbol:t},progressive:{priority:i}}),array:(e,t,i="advanced")=>({fieldType:"array",ui:{label:e,priority:i},props:{itemLabel:t},progressive:{priority:i}}),essential:{text:(e,t)=>Se.text(e,t,"essential"),number:(e,t,i)=>Se.number(e,t,i,"essential"),select:(e,t)=>Se.select(e,t,"essential"),textarea:(e,t)=>Se.textarea(e,t,"essential")},advanced:{text:(e,t)=>Se.text(e,t,"advanced"),number:(e,t,i)=>Se.number(e,t,i,"advanced"),select:(e,t)=>Se.select(e,t,"advanced"),textarea:(e,t)=>Se.textarea(e,t,"advanced"),array:(e,t)=>Se.array(e,t,"advanced")},expert:{text:(e,t)=>Se.text(e,t,"expert"),number:(e,t,i)=>Se.number(e,t,i,"expert"),select:(e,t)=>Se.select(e,t,"expert"),textarea:(e,t)=>Se.textarea(e,t,"expert")}};function Re(e){const{code:t,details:i,suggestions:n}=e;return{success:!1,type:"error",title:"Inscription Failed",message:`Unable to complete inscription: ${i}`,error:{code:t,details:i,suggestions:n}}}const Ne={testnet:{blockId:"0.0.6617393",hashLink:"hcs://12/0.0.6617393",template:"0.0.6617393"},mainnet:{blockId:"0.0.TBD",hashLink:"hcs://12/0.0.TBD",template:"0.0.TBD"}};const xe=me(s.z.object({url:s.z.string().optional().describe("The URL of the content to inscribe as Hashinal NFT (use this OR contentRef)"),contentRef:ce.optional().describe('Content reference ID in format "content-ref:[id]" for already stored content (use this OR url)'),base64Data:s.z.string().optional().describe("Base64 encoded content data (use this if neither url nor contentRef provided)"),fileName:s.z.string().optional().describe("File name for the content (required when using base64Data or contentRef)"),mimeType:s.z.string().optional().describe('MIME type of the content (e.g., "image/png", "image/jpeg")'),name:s.z.string().optional().describe('Display name for the NFT (e.g., "Sunset Landscape #42", "Digital Abstract Art")'),creator:s.z.string().optional().describe('Creator account ID, artist name, or brand (e.g., "0.0.123456", "ArtistName", "StudioBrand")'),description:s.z.string().optional().describe("Meaningful description of the artwork, story, or concept behind this NFT"),type:s.z.string().optional().describe('Category or genre of the NFT (e.g., "Digital Art", "Photography", "Collectible Card")'),attributes:me(s.z.array(s.z.object({trait_type:s.z.string(),value:s.z.union([s.z.string(),s.z.number()])}))).withRender(Se.array("NFT Attributes","Attribute")).optional().describe('Collectible traits and characteristics (e.g., "Rarity": "Epic", "Color": "Blue", "Style": "Abstract")'),properties:s.z.record(s.z.unknown()).optional().describe("Additional properties"),jsonFileURL:s.z.string().url().optional().describe("URL to JSON metadata file"),fileStandard:s.z.enum(["1","6"]).optional().default("1").describe("HCS file standard: 1 for static Hashinals (HCS-5), 6 for dynamic Hashinals (HCS-6)"),tags:s.z.array(s.z.string()).optional().describe("Tags to categorize the NFT"),chunkSize:s.z.number().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:s.z.boolean().optional().describe("Whether to wait for inscription confirmation").default(!0),timeoutMs:s.z.number().int().positive().optional().describe("Timeout in milliseconds for inscription (default: no timeout - waits until completion)"),quoteOnly:s.z.boolean().optional().default(!1).describe("If true, returns a cost quote instead of executing the inscription"),withHashLinkBlocks:s.z.boolean().optional().default(!0).describe("If true, creates interactive HashLink blocks for the inscribed content and returns block data alongside the inscription response"),renderForm:s.z.boolean().optional().default(!0).describe("Whether to show a form to collect metadata. Set to false only if user provided complete metadata including name, description, creator, and attributes.")})).withRender({fieldType:"object",ui:{label:"Inscribe Hashinal NFT",description:"Create a Hashinal inscription for NFT minting"}});const Oe=s.z.object({transactionId:s.z.string().describe("The transaction ID of the inscription to retrieve"),apiKey:s.z.string().optional().describe("API key for inscription service")});const qe=r.join(process.cwd(),".env");class $e{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 i=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 i="";n.existsSync(e)&&(i=n.readFileSync(e,"utf8"));const r=[...i.split("\n")];for(const[n,o]of Object.entries(t)){const e=r.findIndex(e=>e.startsWith(`${n}=`));-1!==e?r[e]=`${n}=${o}`:r.push(`${n}=${o}`)}n.writeFileSync(e,r.join("\n"))}(i,o)}}const Be=class{static setSignerProvider(e){this._signerProvider=e}static async getSigner(){const e=this._signerProvider;if(!e)return null;try{if("function"==typeof e){const t=e();return t&&"function"==typeof t.then?await t:t}return e}catch{return null}}static setWalletInfoResolver(e){this._walletInfoResolver=e||null}static async getWalletInfo(){const e=this._walletInfoResolver;if(!e)return null;try{const t=e();return t&&"function"==typeof t.then?await t:t}catch{return null}}static setWalletExecutor(e){this._walletExecutor=e||null}static get walletExecutor(){return this._walletExecutor||null}static setStartHCSDelegate(e){this._startHCSDelegate=e||null}static get startHCSDelegate(){return this._startHCSDelegate||null}static setPreferWalletOnly(e){this._preferWalletOnly=!!e}static setBrowserHCSClientFactory(e){this._browserHCSClientFactory=e||null}static getBrowserHCSClient(e){return this._browserHCSClientFactory?this._browserHCSClientFactory(e):null}static get preferWalletOnly(){return this._preferWalletOnly}};Be._preferWalletOnly=!1;let ke=Be;const Me="ConnectionsManager not initialized";class _e extends i.BaseServiceBuilder{constructor(e,i,n){super(e),this.stateManager=i;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=(()=>{try{if("function"==typeof t.Logger)return new t.Logger({module:"HCS10Builder",level:n?.logLevel||"info"})}catch{}return{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{},trace:()=>{},setLogLevel:()=>{},getLevel:()=>"info",setSilent:()=>{},setModule:()=>{}}})(),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){const i=ke.startHCSDelegate,n=ke.walletExecutor,r=ke.preferWalletOnly,o=this.network;try{const{ByteBuildRegistry:i}=await Promise.resolve().then(()=>rt);if(n&&i.has("submitConnectionRequest")){const r=await i.build("submitConnectionRequest",this.hederaKit,{inboundTopicId:e,memo:t});if(r&&r.transactionBytes){const{transactionId:e}=await n(r.transactionBytes,o);return{transactionId:e}}}}catch{}if(i&&n)try{const r={inboundTopicId:e,memo:t},{transactionBytes:s}=await i("submitConnectionRequest",r,o),{transactionId:a}=await n(s,o);return{transactionId:a}}catch(s){if(r){const e=new Error(`wallet_submit_failed: ${s instanceof Error?s.message:String(s)}`);throw e.code="wallet_submit_failed",e}}else if(r){const e=new Error("wallet_unavailable: connect a wallet or configure StartHCSDelegate and WalletExecutor");throw e.code="wallet_unavailable",e}return this.standardClient.submitConnectionRequest(e,t)}async handleConnectionRequest(e,t,i,n){try{const o=ke.startHCSDelegate,s=ke.walletExecutor,a=ke.preferWalletOnly,c=this.network;if(o&&s)try{const r={inboundTopicId:e,requestingAccountId:t,connectionRequestId:i,feeConfig:n?"configured":void 0},{transactionBytes:a}=await o("handleConnectionRequest",r,c),{transactionId:l}=await s(a,c);return{success:!0,transactionId:l}}catch(r){if(a){const e=new Error(`wallet_submit_failed: ${r instanceof Error?r.message:String(r)}`);throw e.code="wallet_submit_failed",e}}else if(a){const e=new Error("wallet_unavailable: connect a wallet or configure StartHCSDelegate and WalletExecutor");throw e.code="wallet_unavailable",e}const l=await this.standardClient.handleConnectionRequest(e,t,i,n);return l&&l.connectionTopicId&&"object"==typeof l.connectionTopicId&&"toString"in l.connectionTopicId&&(l.connectionTopicId=l.connectionTopicId.toString()),l}catch(o){throw this.logger.error(`Error handling connection request #${i} for topic ${e}:`,o),new Error(`Failed to handle connection request: ${o instanceof Error?o.message:String(o)}`)}}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{let r=0;try{r=(await this.getMessages(e)).messages.reduce((e,t)=>Math.max(e,t.sequence_number||0),0)}catch{}const o=ke.startHCSDelegate,s=ke.walletExecutor,a=ke.preferWalletOnly,c=this.network;try{const{ByteBuildRegistry:n}=await Promise.resolve().then(()=>rt);if(s&&n.has("sendMessage")){const o=await n.build("sendMessage",this.hederaKit,{topicId:e,data:t,memo:i});if(o&&o.transactionBytes){const{transactionId:t}=await s(o.transactionBytes,c);return{sequenceNumber:await this.pollForNewSequence(e,r),receipt:{transactionId:t},transactionId:t}}}}catch{}if(o&&s)try{const n={topicId:e,data:t,memo:i},{transactionBytes:a}=await o("sendMessage",n,c),{transactionId:l}=await s(a,c);return{sequenceNumber:await this.pollForNewSequence(e,r),receipt:{transactionId:l},transactionId:l}}catch(n){if(a){const e=new Error(`wallet_submit_failed: ${n instanceof Error?n.message:String(n)}`);throw e.code="wallet_submit_failed",e}}else if(a){const e=new Error("wallet_unavailable: connect a wallet or configure StartHCSDelegate and WalletExecutor");throw e.code="wallet_unavailable",e}const l=await this.standardClient.sendMessage(e,t,i,void 0);return{sequenceNumber:l.topicSequenceNumber?.toNumber(),receipt:l,transactionId:"transactionId"in l?l.transactionId?.toString():void 0}}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){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 o.get(e,{responseType:"arraybuffer"}),i=globalThis.Buffer.from(t.data),n=new URL(e).pathname;return{buffer:i,filename:r.basename(n)||"profile.png"}}{if(!n.existsSync(e))return this.logger.warn(`Profile picture file not found: ${e}`),null;this.logger.info(`Loading profile picture from file: ${e}`);const t=n.readFileSync(e);return{buffer:t,filename:r.basename(e)}}}if(e.url){this.logger.info(`Loading profile picture from URL: ${e.url}`);const t=await o.get(e.url,{responseType:"arraybuffer"}),i=globalThis.Buffer.from(t.data);return{buffer:i,filename:e.filename||"profile.png"}}if(e.path){if(!n.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=n.readFileSync(e.path);return{buffer:t,filename:e.filename||r.basename(e.path)}}return null}catch(t){return this.logger.error("Failed to load profile picture:",t),null}}async pollForNewSequence(e,t){for(let i=0;i<10;i++){try{const i=(await this.getMessages(e)).messages.reduce((e,t)=>Math.max(e,t.sequence_number||0),t);if(i>t)return i}catch{}await new Promise(e=>setTimeout(e,1e3))}}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 n=null;e.profilePicture&&(n=await this.loadProfilePicture(e.profilePicture));const r={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!==n?.buffer&&{pfpBuffer:n.buffer},...void 0!==n?.filename&&{pfpFileName:n.filename}};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 o=e.exemptAccountIds?.filter(e=>e!==n&&e.startsWith("0.0"))||[];r.feeConfig=i.addHbarFee(e.hbarFee,n,o)}const o=ke.preferWalletOnly,s=ke.getBrowserHCSClient(this.network);if(s)try{const e=(new t.AgentBuilder).setNetwork(this.network).setName(r.name).setAlias(r.alias||`${r.name}-${Date.now()}`).setBio(r.bio||"").setType(r.type||"autonomous").setModel(r.model||"agent-model-2024");r.capabilities?.length&&e.setCapabilities(r.capabilities),r.creator&&e.setCreator(r.creator),r.existingProfilePictureTopicId&&e.setExistingProfilePicture(r.existingProfilePictureTopicId),r.socials&&Object.entries(r.socials).forEach(([t,i])=>{i&&"string"==typeof i&&e.addSocial(t,i)}),r.properties&&Object.entries(r.properties).forEach(([t,i])=>{null!=i&&e.addProperty(t,i)});const i=await s.create(e,{progressCallback:e=>{},updateAccountMemo:!0});return this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{result:i,name:r.name}},this}catch(i){if(o)throw new Error(`wallet_registration_failed: ${i instanceof Error?i.message:String(i)}`)}else if(o)throw new Error("wallet_unavailable: BrowserHCSClient factory not provided");const a=await this.createAndRegisterAgent(r);this.executeResult={success:!0,transactionId:a.transactionId,receipt:void 0,scheduleId:void 0,rawResult:{...a,name:e.name,accountId:a?.metadata?.accountId||a.state?.agentMetadata?.accountId}}}catch(n){throw this.logger.error("Failed to register agent:",n),n}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 r=this.stateManager?.getCurrentAgent();if(!r)throw new Error("Cannot accept connection request. No agent is currently active. Please register or select an agent first.");const o=this.stateManager?.getConnectionsManager();if(!o)throw new Error(Me);await o.fetchConnectionData(r.accountId);const s=[...o.getPendingRequests(),...o.getConnectionsNeedingConfirmation()].find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!s)throw new Error(`Request with key ${e.requestKey} not found or no longer pending.`);if(!s.needsConfirmation||!s.inboundRequestId)throw new Error(`Request with key ${e.requestKey} is not an inbound request that can be accepted.`);const a=s.targetAccountId,c=s.inboundRequestId;let l;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"))||[];l=i.addHbarFee(e.hbarFee,n,r)}const d=await this.getInboundTopicId(),u=await this.handleConnectionRequest(d,a,c,l);let g=u?.connectionTopicId;if(g&&"object"==typeof g&&"toString"in g&&(g=g?.toString()),!g||"string"!=typeof g)try{const e=(await(this.stateManager?.getConnectionsManager()?.fetchConnectionData(r.accountId))||[]).find(e=>e.targetAccountId===a&&"established"===e.status);e?.connectionTopicId&&(g=e.connectionTopicId)}catch(i){this.logger.debug("Could not refresh connections after acceptance to derive topic id:",i)}if(!g||"string"!=typeof g)throw new Error(`Failed to create connection topic. Got: ${JSON.stringify(g)}`);if(this.stateManager){const e=s.targetAgentName||`Agent ${a}`;s.targetAgentName||this.addNote(`No agent name was provided in the connection request, using default name 'Agent ${a}'.`);let t=s.targetInboundTopicId||"";if(!t)try{const e=await this.getAgentProfile(a);e.success&&e.topicInfo?.inboundTopic&&(t=e.topicInfo.inboundTopic)}catch(n){this.logger.warn(`Could not fetch profile for ${a}:`,n)}const i={connectionId:`conn-${Date.now()}`,targetAccountId:a,targetAgentName:e,targetInboundTopicId:t,connectionTopicId:g,status:"established",created:new Date};this.stateManager.addActiveConnection(i),o.markConnectionRequestProcessed(s.targetInboundTopicId||"",c)}this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{targetAccountId:a,connectionTopicId:g,feeConfigured:!!e.hbarFee,hbarFee:e.hbarFee||0,confirmationResult:u}}}catch(r){throw this.logger.error("Failed to accept connection:",r),r}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}`;let a=0;try{a=(await this.getMessages(r)).messages.reduce((e,t)=>Math.max(e,t.sequence_number||0),0)}catch{}const c=await this.sendMessage(r,e.message,`Agent message from ${t.name}`),l=c.sequenceNumber??a;if(0===l)throw new Error("Failed to send message");let d=null;e.disableMonitoring?this.addNote("Message sent successfully. Response monitoring was disabled."):d=await this.monitorResponses(r,s,l),this.executeResult={success:!0,transactionId:c.transactionId,receipt:c.receipt,scheduleId:void 0,rawResult:{targetAgentName:o,targetAccountId:i.targetAccountId,connectionTopicId:r,sequenceNumber:c.sequenceNumber,reply:d,monitoringEnabled:!e.disableMonitoring,message:e.message,messageResult:c}}}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(Me);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(Me),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 ze extends i.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 i.HederaGetHbarPriceTool({hederaKit:this.context.config.hederaKit,logger:this.context.logger})]}getTools(){return this.tools}}function Pe(e){const t={},i={},n=[],r={};return De(e,"",t,i,n,r),{fields:t,groups:Ke(i),order:Le(n,t),metadata:r}}function De(e,t,i,n,r,o){const s=Ae(e),a=s._def?.typeName;"ZodObject"===a?function(e,t,i,n,r,o){const s=e.shape;if(ye(e)){const o=be(e);o&&t&&(i[t]=o,He(n,o.ui?.group||"default",t),Fe(r,t,o.ui?.order))}for(const[a,c]of Object.entries(s)){De(c,t?`${t}.${a}`:a,i,n,r,o)}}(s,t,i,n,r,o):"ZodArray"===a?function(e,t,i,n,r,o){if(ye(e)){const s=be(e);s&&(i[t]=s,He(n,s.ui?.group||"default",t),Fe(r,t,s.ui?.order),o[t]=Ee(e))}const s=e._def.type;if(s){De(s,`${t}[]`,i,n,r,o)}}(s,t,i,n,r,o):function(e,t,i,n,r,o){if(ye(e)){const o=be(e);o&&(i[t]=o,He(n,o.ui?.group||"default",t),Fe(r,t,o.ui?.order))}o[t]=Ee(e)}(e,t,i,n,r,o)}function He(e,t,i){e[t]||(e[t]=[]),e[t].push(i)}function Fe(e,t,i){void 0!==i?e.splice(i,0,t):e.push(t)}function Ke(e){const t={},i=["default","Keys & Security","Token Settings","Custom Fees"];for(const n of i)e[n]&&(t[n]=e[n]);for(const[n,r]of Object.entries(e))i.includes(n)||(t[n]=r);return t}function Le(e,t){const i={tokenName:1,tokenSymbol:2,maxSupply:3,supplyType:4,treasuryAccountId:5,memo:6};return e.sort((e,n)=>{const r=t[e],o=t[n];if(void 0!==r?.ui?.order&&void 0!==o?.ui?.order)return r.ui.order-o.ui.order;if(void 0!==r?.ui?.order)return-1;if(void 0!==o?.ui?.order)return 1;const s=i[e]||1e3,a=i[n]||1e3;return s!==a?s-a:e.localeCompare(n)})}class Ue extends Error{constructor(e,t){super(t),this.code=e,Object.setPrototypeOf(this,Ue.prototype)}}class je extends i.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().toString():"",n=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet";let r;try{const i=new t.HederaMirrorNode(n),o=await i.requestAccount(e),s=o?.key?._type;if(s){const e=s.toUpperCase();e.includes("ED25519")?r="ed25519":e.includes("ECDSA")&&(r="ecdsa")}}catch{}const o={network:n,operatorId:e,operatorKey:i,...r?{keyType:r}:{}};this.hcs2Client=new t.HCS2Client(o)}return this.hcs2Client}async createRegistry(e={}){const t=ke.walletExecutor,i=ke.preferWalletOnly,n=!(!this.hederaKit?.signer?.getOperatorPrivateKey||!this.hederaKit.signer.getOperatorPrivateKey());if(t){const t=ke.startHCSDelegate;if(t)try{const i={options:e},n=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",{transactionBytes:r}=await t("hcs2.createRegistry",i,n);if(r)return{success:!0,transactionBytes:r}}catch(o){if(i)throw new Ue("wallet_submit_failed",`wallet_submit_failed: ${o instanceof Error?o.message:String(o)}`)}if(i)throw new Ue("wallet_unavailable","WalletExecutor not configured for hcs2.createRegistry")}if(!n)throw new Ue("wallet_unavailable","No wallet executor and no operator private key available for server execution");const r=await this.getHCS2Client();return await r.createRegistry(e)}async registerEntry(e,t){const i=ke.walletExecutor,n=ke.preferWalletOnly,r=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",o=!(!this.hederaKit?.signer?.getOperatorPrivateKey||!this.hederaKit.signer.getOperatorPrivateKey());try{const{ByteBuildRegistry:n}=await Promise.resolve().then(()=>rt);if(n.has("hcs2.registerEntry")){const r=await n.build("hcs2.registerEntry",this.hederaKit,{registryTopicId:e,options:t});if(r&&r.transactionBytes){if(i)return{success:!0,transactionBytes:r.transactionBytes};if(!o)return{success:!0,transactionBytes:r.transactionBytes}}}}catch{}const s=ke.startHCSDelegate;if(s)try{const n={registryTopicId:e,options:t},{transactionBytes:a}=await s("hcs2.registerEntry",n,r);if(a){if(i)return{success:!0,transactionBytes:a};if(!o)return{success:!0,transactionBytes:a}}}catch(c){if(n){const e=`wallet_submit_failed: ${c instanceof Error?c.message:String(c)}`;throw new Ue("wallet_submit_failed",e)}}if(n)throw new Ue("wallet_unavailable","WalletExecutor not configured for hcs2.registerEntry");if(!o)throw new Ue("wallet_unavailable","No wallet executor and no operator private key available for server execution");const a=await this.getHCS2Client();return await a.registerEntry(e,t)}async updateEntry(e,t){const i=ke.walletExecutor,n=ke.preferWalletOnly,r=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",o=!(!this.hederaKit?.signer?.getOperatorPrivateKey||!this.hederaKit.signer.getOperatorPrivateKey());try{const{ByteBuildRegistry:n}=await Promise.resolve().then(()=>rt);if(n.has("hcs2.updateEntry")){const r=await n.build("hcs2.updateEntry",this.hederaKit,{registryTopicId:e,options:t});if(r&&r.transactionBytes){if(i)return{success:!0,transactionBytes:r.transactionBytes};if(!o)return{success:!0,transactionBytes:r.transactionBytes}}}}catch{}const s=ke.startHCSDelegate;if(s)try{const n={registryTopicId:e,options:t},{transactionBytes:a}=await s("hcs2.updateEntry",n,r);if(a){if(i)return{success:!0,transactionBytes:a};if(!o)return{success:!0,transactionBytes:a}}}catch(c){if(n){const e=`wallet_submit_failed: ${c instanceof Error?c.message:String(c)}`;throw new Ue("wallet_submit_failed",e)}}if(n)throw new Ue("wallet_unavailable","WalletExecutor not configured for hcs2.updateEntry");if(!o)throw new Ue("wallet_unavailable","No wallet executor and no operator private key available for server execution");const a=await this.getHCS2Client();return await a.updateEntry(e,t)}async deleteEntry(e,t){const i=ke.walletExecutor,n=ke.preferWalletOnly,r=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",o=!(!this.hederaKit?.signer?.getOperatorPrivateKey||!this.hederaKit.signer.getOperatorPrivateKey());try{const{ByteBuildRegistry:n}=await Promise.resolve().then(()=>rt);if(n.has("hcs2.deleteEntry")){const r=await n.build("hcs2.deleteEntry",this.hederaKit,{registryTopicId:e,options:t});if(r&&r.transactionBytes){if(i)return{success:!0,transactionBytes:r.transactionBytes};if(!o)return{success:!0,transactionBytes:r.transactionBytes}}}}catch{}const s=ke.startHCSDelegate;if(s)try{const n={registryTopicId:e,options:t},{transactionBytes:a}=await s("hcs2.deleteEntry",n,r);if(a){if(i)return{success:!0,transactionBytes:a};if(!o)return{success:!0,transactionBytes:a}}}catch(c){if(n){const e=`wallet_submit_failed: ${c instanceof Error?c.message:String(c)}`;throw new Ue("wallet_submit_failed",e)}}if(n)throw new Ue("wallet_unavailable","WalletExecutor not configured for hcs2.deleteEntry");if(!o)throw new Ue("wallet_unavailable","No wallet executor and no operator private key available for server execution");const a=await this.getHCS2Client();return await a.deleteEntry(e,t)}async migrateRegistry(e,t){const i=ke.walletExecutor,n=ke.preferWalletOnly,r=!(!this.hederaKit?.signer?.getOperatorPrivateKey||!this.hederaKit.signer.getOperatorPrivateKey());try{const{ByteBuildRegistry:n}=await Promise.resolve().then(()=>rt);if(n.has("hcs2.migrateRegistry")){const o=await n.build("hcs2.migrateRegistry",this.hederaKit,{registryTopicId:e,options:t});if(o&&o.transactionBytes){if(i)return{success:!0,transactionBytes:o.transactionBytes};if(!r)return{success:!0,transactionBytes:o.transactionBytes}}}}catch{}const o=ke.startHCSDelegate;if(o)try{const n={registryTopicId:e,options:t},s=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",{transactionBytes:a}=await o("hcs2.migrateRegistry",n,s);if(a){if(i)return{success:!0,transactionBytes:a};if(!r)return{success:!0,transactionBytes:a}}}catch(a){if(n){const e=`wallet_submit_failed: ${a instanceof Error?a.message:String(a)}`;throw new Ue("wallet_submit_failed",e)}}if(n)throw new Ue("wallet_unavailable","WalletExecutor not configured for hcs2.migrateRegistry");if(!r)throw new Ue("wallet_unavailable","No wallet executor and no operator private key available for server execution");const s=await this.getHCS2Client();return await s.migrateRegistry(e,t)}async getRegistry(e,t={}){const i=await this.getHCS2Client();return await i.getRegistry(e,t)}async submitMessage(e,t){const i=ke.walletExecutor,n=ke.preferWalletOnly,r=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",o=!(!this.hederaKit?.signer?.getOperatorPrivateKey||!this.hederaKit.signer.getOperatorPrivateKey());try{const{ByteBuildRegistry:n}=await Promise.resolve().then(()=>rt);if(n.has("hcs2.submitMessage")){const r=await n.build("hcs2.submitMessage",this.hederaKit,{topicId:e,payload:t});if(r&&r.transactionBytes){if(i)return{success:!0,transactionBytes:r.transactionBytes};if(!o)return{success:!0,transactionBytes:r.transactionBytes}}}}catch{}const s=ke.startHCSDelegate;if(s)try{const n={topicId:e,payload:t},{transactionBytes:a}=await s("hcs2.submitMessage",n,r);if(a){if(i)return{success:!0,transactionBytes:a};if(!o)return{success:!0,transactionBytes:a}}}catch(c){if(n){const e=`wallet_submit_failed: ${c instanceof Error?c.message:String(c)}`;throw new Ue("wallet_submit_failed",e)}}if(n)throw new Ue("wallet_unavailable","WalletExecutor not configured for hcs2.submitMessage");if(!o)throw new Ue("wallet_unavailable","No wallet executor and no operator private key available for server execution");const a=await this.getHCS2Client();return await a.submitMessage(e,t),{success:!0}}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 Ge extends i.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=ke.walletExecutor,i=ke.preferWalletOnly,n=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet";if(t){const t=ke.startHCSDelegate;if(t)try{const i={options:e},{transactionBytes:r}=await t("hcs6.createRegistry",i,n);if(r)return{success:!0,transactionBytes:r}}catch(s){if(i)throw new Ue("wallet_submit_failed",`wallet_submit_failed: ${s instanceof Error?s.message:String(s)}`)}if(i)throw new Ue("wallet_unavailable","WalletExecutor not configured for hcs6.createRegistry")}const r=await this.getHCS6Client(),o={...e};return"adminKey"in o&&delete o.adminKey,await r.createRegistry(o)}async registerEntry(e,t){const i=ke.walletExecutor,n=ke.preferWalletOnly,r=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet";if(i){const i=ke.startHCSDelegate;if(i)try{const n={registryTopicId:e,options:t},{transactionBytes:o}=await i("hcs6.registerEntry",n,r);if(o)return{success:!0,transactionBytes:o}}catch(s){if(n)throw new Ue("wallet_submit_failed",`wallet_submit_failed: ${s instanceof Error?s.message:String(s)}`)}if(n)throw new Ue("wallet_unavailable","WalletExecutor not configured for hcs6.registerEntry")}const o=await this.getHCS6Client();return await o.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=ke.walletExecutor,n=ke.preferWalletOnly,r=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet";if(i){const i=ke.startHCSDelegate;if(i)try{const n={topicId:e,payload:t},{transactionBytes:o}=await i("hcs6.submitMessage",n,r);if(o)return{success:!0,transactionBytes:o}}catch(s){if(n)throw new Ue("wallet_submit_failed",`wallet_submit_failed: ${s instanceof Error?s.message:String(s)}`)}if(n)throw new Ue("wallet_unavailable","WalletExecutor not configured for hcs6.submitMessage")}const o=await this.getHCS6Client();return await o.submitMessage(e,t)}async getTopicInfo(e){const i=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",n=new t.HederaMirrorNode(i);return await n.getTopicInfo(e)}async close(){this.hcs6Client&&(this.hcs6Client.close(),this.hcs6Client=void 0)}}let We=null;const Ze=async()=>(We||(We=await import("@kiloscribe/inscription-sdk")),We),Qe=class e extends i.BaseServiceBuilder{constructor(e){super(e)}getOperationalMode(){return this.hederaKit.operationalMode}static setSignerProvider(t){e.signerProvider=t}static setWalletInfoResolver(t){e.walletInfoResolver=t}static setStartInscriptionDelegate(t){e.startInscriptionDelegate=t}static setWalletExecutor(t){e.walletExecutor=t}static setPreferWalletOnly(t){e.preferWalletOnly=!!t}async getSigner(){const t=e.signerProvider;if(!t)return null;try{const e=t();return e&&"function"==typeof e.then?await e:e}catch{return null}}async getInscriptionSDK(e){if(this.inscriptionSDK)return this.inscriptionSDK;const t=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",i=this.hederaKit.signer.getAccountId().toString();try{const{InscriptionSDK:e}=await Ze(),n=await this.getSigner();if(n)this.inscriptionSDK=await e.createWithAuth({type:"client",accountId:i,signer:n,network:t});else{const n=this.hederaKit.signer?.getOperatorPrivateKey();n&&(this.inscriptionSDK=await e.createWithAuth({type:"server",accountId:i,privateKey:n.toStringRaw(),network:t}))}}catch(n){this.logger.warn("Failed to create InscriptionSDK with auth",n),this.inscriptionSDK=void 0}if(!this.inscriptionSDK)try{const{InscriptionSDK:e}=await Ze();this.inscriptionSDK=new e({apiKey:"public-access",network:t,connectionMode:"http"})}catch(r){this.logger.warn("Failed to create InscriptionSDK fallback instance",r)}return this.inscriptionSDK||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 inscribeAuto(i,n){const r=await this.getSigner();if(r)return this.inscribeWithSigner(i,r,n);const o=e.walletInfoResolver?await e.walletInfoResolver():null;if(e.preferWalletOnly&&!o){const e=new Error("Wallet unavailable: connect a wallet or switch to autonomous mode");throw e.code="wallet_unavailable",e}if(o&&e.startInscriptionDelegate&&e.walletExecutor){const r=o.accountId,s=o.network,a=n,c={holderId:r,metadata:a.metadata||{},tags:n.tags||[],mode:n.mode||"file"};void 0!==a.fileStandard&&(c.fileStandard=a.fileStandard),void 0!==a.chunkSize&&(c.chunkSize=a.chunkSize);let l={...c};switch(i.type){case"url":l={...c,file:{type:"url",url:i.url}};break;case"file":l={...c,file:{type:"path",path:i.path}};break;case"buffer":l={...c,file:{type:"base64",base64:globalThis.Buffer.from(i.buffer).toString("base64"),fileName:i.fileName,mimeType:i.mimeType}}}"hashinal"===n.mode&&(l.metadataObject=a.metadata,l.creator=a.metadata?.creator||r,l.description=a.metadata?.description,"string"==typeof a.jsonFileURL&&a.jsonFileURL.length>0&&(l.jsonFileURL=a.jsonFileURL));const d=await e.startInscriptionDelegate(l,s),u=d;if(Boolean(u?.inscription)&&u?.confirmed){const e=d;return this.logger.info("inscription already completed, short circuiting",d),{quote:!1,confirmed:!0===e.confirmed,result:e.result,inscription:e.inscription}}const g=d;if(!g||!g.transactionBytes)throw new Error("Failed to start inscription (no transaction bytes)");const p=await e.walletExecutor(g.transactionBytes,s),h=p?.transactionId||"";if(!n.quoteOnly&&(n.waitForConfirmation??!0)){this.logger.debug("Will be retrieving inscription");const e=n.waitMaxAttempts??60,i=n.waitIntervalMs??5e3,r=await this.getInscriptionSDK(n);if(r){const n=await r.waitForInscription(h,e,i,!0),o=t.getTopicId(n)??g.topic_id,s={quote:!1,confirmed:!0,result:{jobId:g.tx_id||"",transactionId:h,topicId:o},inscription:n};return this.logger.debug("retrieved inscription",s,n),s}}return{quote:!1,confirmed:!1,result:{jobId:g.tx_id||"",transactionId:h,status:g.status,completed:g.completed},inscription:g.topic_id?{topic_id:g.topic_id}:void 0}}if(e.preferWalletOnly){const e=new Error("Wallet unavailable: connect a wallet or switch to autonomous mode");throw e.code="wallet_unavailable",e}return this.inscribe(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}};Qe.preferWalletOnly=!1;let Ve=Qe;const Ye=new class{constructor(){this.handlers=new Map}register(e,t){this.handlers.set(e,t)}has(e){return this.handlers.has(e)}async build(e,t,i){const n=this.handlers.get(e);return n?await n({hederaKit:t,request:i}):null}};async function Xe(t,i){const n="mainnet"===(t.client.network.toString().includes("mainnet")?"mainnet":"testnet")?e.Client.forMainnet():e.Client.forTestnet(),r=t.signer.getAccountId().toString(),o=e.AccountId.fromString(r);if("function"==typeof i.setTransactionId&&i.setTransactionId(e.TransactionId.generate(o)),"function"==typeof i.setAutoRenewAccountId)try{i.setAutoRenewAccountId(r)}catch{}const s=await i.freezeWith(n);return{transactionBytes:globalThis.Buffer.from(s.toBytes()).toString("base64")}}async function Je(t,i,n,r){const o="mainnet"===(t.client.network.toString().includes("mainnet")?"mainnet":"testnet")?e.Client.forMainnet():e.Client.forTestnet(),s=t.signer.getAccountId().toString(),a=e.AccountId.fromString(s),c=(new e.TopicMessageSubmitTransaction).setTopicId(e.TopicId.fromString(i)).setTransactionId(e.TransactionId.generate(a)).setMessage(n),l=await c.freezeWith(o);return{transactionBytes:globalThis.Buffer.from(l.toBytes()).toString("base64")}}function et(e){return"object"==typeof e&&null!==e}function tt(e,t){const i=e[t];return"string"==typeof i?i:void 0}function it(e,t){const i=e[t];return"number"==typeof i&&Number.isFinite(i)?i:void 0}function nt(e,t){const i=e[t];return et(i)?i:void 0}Ye.register("hcs2.createRegistry",async({hederaKit:e,request:i})=>{const n=i?.options||{};let r;try{const t=e?.signer?.getOperatorPrivateKey?.();r=t?.publicKey}catch{}const o=t.buildHcs2CreateRegistryTx({registryType:n.registryType??t.HCS2RegistryType.INDEXED,ttl:n.ttl??86400,adminKey:n.adminKey,submitKey:n.submitKey,operatorPublicKey:r});return await Xe(e,o)}),Ye.register("hcs2.migrateRegistry",async({hederaKit:e,request:i})=>{if(!et(i))throw new Error("hcs2.migrateRegistry: invalid request payload");const n=tt(i,"registryTopicId")||"";if(!n)throw new Error("hcs2.migrateRegistry: registryTopicId is required");const r=nt(i,"options")||{},o=tt(r,"targetTopicId")||"",s=tt(r,"metadata"),a=tt(r,"memo"),c=t.buildHcs2MigrateTx({registryTopicId:n,targetTopicId:o,metadata:s,memo:a});return await Xe(e,c)}),Ye.register("hcs2.submitMessage",async({hederaKit:e,request:t})=>{if(!et(t))throw new Error("hcs2.submitMessage: invalid request payload");const i=tt(t,"topicId")||tt(t,"registryTopicId")||"";if(!i)throw new Error("hcs2.submitMessage: topicId is required");const n=t.payload,r="string"==typeof n?n:JSON.stringify(n??{});return await Je(e,i,r)}),Ye.register("hcs2.registerEntry",async({hederaKit:e,request:i})=>{if(!et(i))throw new Error("hcs2.registerEntry: invalid request payload");const n=tt(i,"registryTopicId")||"";if(!n)throw new Error("hcs2.registerEntry: registryTopicId is required");const r=nt(i,"options")||{},o=tt(r,"targetTopicId")||"",s=tt(r,"metadata"),a=tt(r,"memo"),c=t.buildHcs2RegisterTx({registryTopicId:n,targetTopicId:o,metadata:s,memo:a});return await Xe(e,c)}),Ye.register("hcs2.updateEntry",async({hederaKit:e,request:i})=>{if(!et(i))throw new Error("hcs2.updateEntry: invalid request payload");const n=tt(i,"registryTopicId")||"";if(!n)throw new Error("hcs2.updateEntry: registryTopicId is required");const r=nt(i,"options")||{},o=tt(r,"targetTopicId")||"",s=tt(r,"uid")||"",a=tt(r,"metadata"),c=tt(r,"memo"),l=t.buildHcs2UpdateTx({registryTopicId:n,uid:s,targetTopicId:o,metadata:a,memo:c});return await Xe(e,l)}),Ye.register("hcs2.deleteEntry",async({hederaKit:e,request:i})=>{if(!et(i))throw new Error("hcs2.deleteEntry: invalid request payload");const n=tt(i,"registryTopicId")||"";if(!n)throw new Error("hcs2.deleteEntry: registryTopicId is required");const r=nt(i,"options")||{},o=tt(r,"uid")||"",s=tt(r,"memo"),a=t.buildHcs2DeleteTx({registryTopicId:n,uid:o,memo:s});return await Xe(e,a)}),Ye.register("hcs6.createRegistry",async({hederaKit:e,request:i})=>{const n=et(i)?nt(i,"options"):void 0,r=n?it(n,"ttl"):void 0;let o;try{const t=e?.signer?.getOperatorPrivateKey?.();o=t?.publicKey}catch{}const s=t.buildHcs6CreateRegistryTx({ttl:r??86400,operatorPublicKey:o});return await Xe(e,s)}),Ye.register("hcs6.registerEntry",async({hederaKit:e,request:i})=>{if(!et(i))throw new Error("hcs6.registerEntry: invalid request payload");const n=tt(i,"registryTopicId")||"";if(!n)throw new Error("hcs6.registerEntry: registryTopicId is required");const r=nt(i,"options")||{},o=tt(r,"targetTopicId")||"",s=tt(r,"memo"),a=t.buildHcs6RegisterEntryTx({registryTopicId:n,targetTopicId:o,memo:s});return await Xe(e,a)}),Ye.register("hcs6.submitMessage",async({hederaKit:e,request:t})=>{if(!et(t))throw new Error("hcs6.submitMessage: invalid request payload");const i=tt(t,"topicId")||"";if(!i)throw new Error("hcs6.submitMessage: topicId is required");const n=t.payload,r="string"==typeof n?n:JSON.stringify(n??{});return await Je(e,i,r)}),Ye.register("sendMessage",async({hederaKit:e,request:i})=>{if(!et(i))throw new Error("sendMessage: invalid request payload");const n=tt(i,"topicId")||"";if(!n)throw new Error("sendMessage: topicId is required");const r=i.data,o=tt(i,"memo")||"",s=e.signer.getAccountId().toString(),a="string"==typeof r?r:JSON.stringify(r??{}),c=t.buildHcs10SendMessageTx({connectionTopicId:n,operatorId:s,data:a,memo:o});return await Xe(e,c)}),Ye.register("submitConnectionRequest",async({hederaKit:e,request:i})=>{if(!et(i))throw new Error("submitConnectionRequest: invalid request payload");const n=tt(i,"inboundTopicId")||"";if(!n)throw new Error("submitConnectionRequest: inboundTopicId is required");const r=tt(i,"memo")||"",o=e.signer.getAccountId().toString(),s=t.buildHcs10SubmitConnectionRequestTx({inboundTopicId:n,operatorId:o,memo:r});return await Xe(e,s)}),Ye.register("hcs20.deploy",async({hederaKit:e,request:i})=>{if(!et(i))throw new Error("hcs20.deploy: invalid request payload");const n=tt(i,"topicId")||"";if(!n)throw new Error("hcs20.deploy: topicId is required");const r=tt(i,"name")||"",o=tt(i,"tick")||"",s=tt(i,"max")||"",a=tt(i,"lim"),c=tt(i,"metadata"),l=tt(i,"memo"),d=t.buildHcs20DeployTx({topicId:n,name:r,tick:o,max:s,lim:a,metadata:c,memo:l});return await Xe(e,d)}),Ye.register("hcs20.mint",async({hederaKit:e,request:i})=>{if(!et(i))throw new Error("hcs20.mint: invalid request payload");const n=tt(i,"topicId")||"";if(!n)throw new Error("hcs20.mint: topicId is required");const r=tt(i,"tick")||"",o=tt(i,"amt")||"",s=tt(i,"to")||"",a=tt(i,"memo"),c=t.buildHcs20MintTx({topicId:n,tick:r,amt:o,to:s,memo:a});return await Xe(e,c)}),Ye.register("hcs20.transfer",async({hederaKit:e,request:i})=>{if(!et(i))throw new Error("hcs20.transfer: invalid request payload");const n=tt(i,"topicId")||"";if(!n)throw new Error("hcs20.transfer: topicId is required");const r=tt(i,"tick")||"",o=tt(i,"amt")||"",s=tt(i,"from")||"",a=tt(i,"to")||"",c=tt(i,"memo"),l=t.buildHcs20TransferTx({topicId:n,tick:r,amt:o,from:s,to:a,memo:c});return await Xe(e,l)}),Ye.register("hcs20.burn",async({hederaKit:e,request:i})=>{if(!et(i))throw new Error("hcs20.burn: invalid request payload");const n=tt(i,"topicId")||"";if(!n)throw new Error("hcs20.burn: topicId is required");const r=tt(i,"tick")||"",o=tt(i,"amt")||"",s=tt(i,"from")||"",a=tt(i,"memo"),c=t.buildHcs20BurnTx({topicId:n,tick:r,amt:o,from:s,memo:a});return await Xe(e,c)}),Ye.register("hcs20.register",async({hederaKit:e,request:i})=>{if(!et(i))throw new Error("hcs20.register: invalid request payload");const n=tt(i,"registryTopicId")||"";if(!n)throw new Error("hcs20.register: registryTopicId is required");const r=tt(i,"topicId")||"",o=tt(i,"name")||"",s=i.isPrivate,a="boolean"==typeof s&&s,c=tt(i,"metadata"),l=tt(i,"memo"),d=t.buildHcs20RegisterTx({registryTopicId:n,name:o,topicId:r,isPrivate:a,metadata:c,memo:l});return await Xe(e,d)}),Ye.register("hcs12.createRegistry",async({hederaKit:e,request:i})=>{const n=et(i)?nt(i,"options"):void 0,r=(n?it(n,"ttl"):void 0)??60,o=n&&tt(n,"registry")||"hashlinks";let s;try{const t=e?.signer?.getOperatorPrivateKey?.();s=t?.publicKey}catch{}const a=t.buildHcs12CreateRegistryTopicTx({registry:o,ttl:r,operatorPublicKey:s});return await Xe(e,a)}),Ye.register("hcs12.submitMessage",async({hederaKit:e,request:i})=>{if(!et(i))throw new Error("hcs12.submitMessage: invalid request payload");const n=tt(i,"topicId")||"";if(!n)throw new Error("hcs12.submitMessage: topicId is required");const r=i.payload,o=t.buildHcs12SubmitMessageTx({topicId:n,payload:r});return await Xe(e,o)}),Ye.register("hcs12.registerAssembly",async({hederaKit:e,request:i})=>{if(!et(i))throw new Error("hcs12.registerAssembly: invalid request payload");const n=tt(i,"assemblyTopicId")||"";if(!n)throw new Error("hcs12.registerAssembly: assemblyTopicId is required");const r=nt(i,"registration")||{},o=t.buildHcs12RegisterAssemblyTx({assemblyTopicId:n,registration:r});return await Xe(e,o)}),Ye.register("hcs12.addBlock",async({hederaKit:e,request:i})=>{if(!et(i))throw new Error("hcs12.addBlock: invalid request payload");const n=tt(i,"assemblyTopicId")||"";if(!n)throw new Error("hcs12.addBlock: assemblyTopicId is required");const r=nt(i,"operation")||{},o=t.buildHcs12AddBlockToAssemblyTx({assemblyTopicId:n,operation:r});return await Xe(e,o)}),Ye.register("hcs12.addAction",async({hederaKit:e,request:i})=>{if(!et(i))throw new Error("hcs12.addAction: invalid request payload");const n=tt(i,"assemblyTopicId")||"";if(!n)throw new Error("hcs12.addAction: assemblyTopicId is required");const r=nt(i,"operation")||{},o=t.buildHcs12AddActionToAssemblyTx({assemblyTopicId:n,operation:r});return await Xe(e,o)}),Ye.register("hcs12.updateAssembly",async({hederaKit:e,request:i})=>{if(!et(i))throw new Error("hcs12.updateAssembly: invalid request payload");const n=tt(i,"assemblyTopicId")||"";if(!n)throw new Error("hcs12.updateAssembly: assemblyTopicId is required");const r=nt(i,"operation")||{},o=t.buildHcs12UpdateAssemblyTx({assemblyTopicId:n,operation:r});return await Xe(e,o)}),Ye.register("hcs7.submitMessage",async({hederaKit:e,request:i})=>{if(!et(i))throw new Error("hcs7.submitMessage: invalid request payload");const n=tt(i,"topicId")||"";if(!n)throw new Error("hcs7.submitMessage: topicId is required");const r=nt(i,"message")||{},o=t.buildHcs7SubmitMessageTx({topicId:n,message:r});return await Xe(e,o)}),Ye.register("hcs7.evm",async({hederaKit:e,request:i})=>{if(!et(i))throw new Error("hcs7.evm: invalid request payload");const n=tt(i,"topicId")||"";if(!n)throw new Error("hcs7.evm: topicId is required");const r=nt(i,"config")||{},o=t.buildHcs7EvmMessageTx({topicId:n,config:r});return await Xe(e,o)}),Ye.register("hcs7.wasm",async({hederaKit:e,request:i})=>{if(!et(i))throw new Error("hcs7.wasm: invalid request payload");const n=tt(i,"topicId")||"";if(!n)throw new Error("hcs7.wasm: topicId is required");const r=nt(i,"config")||{},o=t.buildHcs7WasmMessageTx({topicId:n,config:r});return await Xe(e,o)});const rt=Object.freeze(Object.defineProperty({__proto__:null,ByteBuildRegistry:Ye},Symbol.toStringTag,{value:"Module"}));Object.defineProperty(exports,"BasePlugin",{enumerable:!0,get:()=>i.BasePlugin}),Object.defineProperty(exports,"GetHbarPriceTool",{enumerable:!0,get:()=>i.HederaGetHbarPriceTool}),Object.defineProperty(exports,"PluginRegistry",{enumerable:!0,get:()=>i.PluginRegistry}),exports.AcceptConnectionRequestTool=B,exports.BaseHCS10QueryTool=g,exports.BaseHCS10TransactionTool=u,exports.BaseHCS2QueryTool=D,exports.BaseHCS2TransactionTool=P,exports.BaseHCS6QueryTool=Z,exports.BaseHCS6TransactionTool=W,exports.BaseInscriberQueryTool=ee,exports.BaseInscriberTransactionTool=J,exports.ByteBuildRegistry=Ye,exports.CheckMessagesTool=E,exports.ConnectionMonitorTool=x,exports.CreateDynamicRegistryTool=class extends Z{constructor(e){super(e),this.name="createDynamicRegistry",this.description="Create a new HCS-6 dynamic registry for managing evolving content"}get specificInputSchema(){return Q}async executeQuery(e,t){const i=await this.hcs6Builder.createRegistry({ttl:e.ttl,submitKey:e.submitKey});if(!("success"in i)||!i.success)throw new Error(i.error||"Failed to create dynamic registry");if(H(i)){const t=i.transactionBytes;return{message:"I prepared an unsigned transaction to create your HCS-6 dynamic registry. Please review and approve to submit.",transactionBytes:t,metadata:{transactionBytes:t,pendingApproval:!0,description:`Create HCS-6 dynamic registry (TTL: ${e.ttl}s)`}}}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 D{constructor(){super(...arguments),this.name="createHCS2Registry",this.description="Create an HCS-2 registry (standard HCS-2). Use when the user asks to create an HCS-2 registry, not a generic HCS topic. Builds a standards-compliant registry topic and returns the result or transaction bytes."}get specificInputSchema(){return F}async executeQuery(e,t){const i=e=>{if("string"==typeof e){const t=e.trim().toLowerCase();return"true"===t||"false"!==t&&e}return e};try{const t=await this.hcs2Builder.createRegistry({registryType:e.registryType,ttl:e.ttl,adminKey:i(e.adminKey),submitKey:i(e.submitKey)});if(!t.success)throw new Error(t.error||"Failed to create registry");if(H(t)){const i=t.transactionBytes;return{message:"I prepared an unsigned transaction to create your HCS-2 registry. Please review and approve to submit.",transactionBytes:i,metadata:{transactionBytes:i,pendingApproval:!0,description:`Create HCS-2 registry (${1===e.registryType?"Non-Indexed":"Indexed"}; TTL: ${e.ttl||86400}s)`}}}return`Successfully created HCS-2 registry!\n\nTopic ID: ${t?.topicId||"unknown"}\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(n){const e=n instanceof Error?n.message:"Failed to create HCS-2 registry";throw new Error(`Registry creation failed: ${e}`)}}},exports.DeleteEntryTool=class extends D{constructor(){super(...arguments),this.name="deleteHCS2Entry",this.description="Delete an entry from an indexed HCS-2 registry"}get specificInputSchema(){return U}async executeQuery(e,t){try{const t=await this.hcs2Builder.deleteEntry(e.registryTopicId,{uid:e.uid,memo:e.memo});if(!("success"in t)||!t.success)throw new Error(t.error||"Failed to delete entry");if(H(t)){const i=t.transactionBytes;return{message:"I prepared an unsigned transaction to delete the HCS-2 registry entry. Please review and approve to submit.",transactionBytes:i,metadata:{transactionBytes:i,pendingApproval:!0,description:`Delete HCS-2 entry (registry ${e.registryTopicId}, uid ${e.uid})`}}}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=R,exports.HCS10Builder=_e,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=je,exports.HCS6Builder=Ge,exports.HbarPricePlugin=ze,exports.InitiateConnectionTool=T,exports.InscribeFromBufferTool=class extends ee{constructor(){super(...arguments),this.name="inscribeFromBuffer",this.description='Use ONLY for inscribing regular files or content (NOT for NFT/Hashinal inscriptions). When user says "inscribe it" after you showed search results or other content WITHOUT mentioning NFT/hashinal, 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. NEVER use this for Hashinal NFTs - always use InscribeHashinalTool instead when user mentions hashinal, NFT, dynamic, or minting.',this.config=de()}get specificInputSchema(){return ue}async _call(e,t){try{const t="string"==typeof e.base64Data?e.base64Data:"",i=/^[A-Za-z0-9+/]*={0,2}$/.test(t)?globalThis.Buffer.from(t,"base64"):globalThis.Buffer.from(t,"utf8"),n=e.fileName,r=e.mimeType,o=this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",s={mode:"file",metadata:e.metadata,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:!e.quoteOnly&&(e.waitForConfirmation??!0),waitMaxAttempts:60,waitIntervalMs:5e3,apiKey:e.apiKey,network:o,quoteOnly:e.quoteOnly},a=await this.inscriberBuilder.inscribe({type:"buffer",buffer:i,fileName:n,mimeType:r},s);if(a.confirmed&&!a.quote){const e=ie(a.inscription,a.result),{topicId:t,cdnUrl:i}=ne(e,o,"1");return JSON.stringify({success:!0,data:`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${a.result?.transactionId??"unknown"}\nTopic ID: ${t||"N/A"}${i?`\nView inscription: ${i}`:""}\n\nThe inscription is now available.`})}return JSON.stringify({success:!0,data:`Successfully submitted inscription to the Hedera network!\n\nTransaction ID: ${a.result?.transactionId??"unknown"}\n\nThe inscription is processing and will be confirmed shortly.`})}catch(i){const e=i instanceof Error?i.message:String(i);return JSON.stringify({success:!1,error:`Inscription failed: ${e}`})}}async executeQuery(e,i){const n=await async function(e,i,n){const r=e.trim(),o=t.ContentResolverRegistry.getResolver();if(!o)return ae(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 ae(r,i,n)}(e.base64Data,e.mimeType,e.fileName);this.logger?.debug(`[InscribeFromBufferTool] Resolved content bytes: ${n.buffer?.length??-1}`);try{this.validateContent(n.buffer)}catch(c){this.logger?.warn(`Content validation warning: ${c instanceof Error?c.message:String(c)}`)}const r=n.buffer,o=n.mimeType||e.mimeType,s=n.fileName||e.fileName,a={mode:"file",metadata:e.metadata,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:!e.quoteOnly&&(e.waitForConfirmation??!0),waitMaxAttempts:60,waitIntervalMs:5e3,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:r,fileName:s,mimeType:o},a);return{success:!0,quote:{totalCostHbar:e.totalCostHbar,validUntil:e.validUntil,breakdown:e.breakdown},contentInfo:{fileName:s,mimeType:o,sizeBytes:r.length},message:`Estimated Quote for buffer content: ${s} (${(r.length/1024).toFixed(2)} KB)\nTotal cost: ${e.totalCostHbar} HBAR`}}catch(l){const e=l instanceof Error?l.message:"Failed to generate inscription quote";throw new Error(`Quote generation failed: ${e}`)}try{this.logger?.debug(`[InscribeFromBufferTool] Calling inscribe with fileName: ${s}, mime: ${o}`);const t=await this.executeInscription(r,s,o,a,e.timeoutMs);return this.logger?.debug(`[InscribeFromBufferTool] Inscribe result (confirmed): ${Boolean(t?.confirmed)}`),this.formatInscriptionResult(t,a)}catch(l){this.logger?.warn(`[InscribeFromBufferTool] Error during inscription: ${l instanceof Error?l.message:String(l)}`);const e=l instanceof Error?l.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){const i=e;if(i.confirmed&&!i.quote){const e=ie(i.inscription,i.result),n=t.network||"testnet",{topicId:r,cdnUrl:o}=ne(e,n,"1");return`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${i.result?.transactionId??"unknown"}\nTopic ID: ${r||"N/A"}${o?`\nView inscription: ${o}`:""}\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??"unknown"}\n\nThe inscription is processing and will be confirmed shortly.`}},exports.InscribeFromFileTool=class extends ee{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 se}async executeQuery(e,t){let i;try{const t=await d.stat(e.filePath);if(!t.isFile())throw new Error(`Path "${e.filePath}" is not a file`);if(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&&this.logger?.warn(`Large file detected (${(t.size/1048576).toFixed(2)} MB)`),this.logger?.info("Reading file content..."),i=await d.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=l.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=l.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=ie(i.inscription,i.result),t=s.network||"testnet",{topicId:n,cdnUrl:r}=ne(e,t,"1");return`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${i.result?.transactionId??"unknown"}\nTopic ID: ${n||"N/A"}${r?`\nView inscription: ${r}`:""}\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??"unknown"}\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"}[l.extname(e).toLowerCase()]||"application/octet-stream"}},exports.InscribeFromUrlTool=class extends ee{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 oe}async executeQuery(e,t){if(re.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.`)}re.info("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){re.info("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;re.warn(`Could not perform partial GET validation: ${r instanceof Error?r.message:"Unknown error"}`)}}re.info(`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)re.warn("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;re.warn(`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:60,waitIntervalMs:5e3,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);const n=t;if(n.confirmed&&!n.quote){const e=ie(n.inscription,n.result),t=i.network||"testnet",{topicId:r,cdnUrl:o}=ne(e,t,"1");return`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${n.result?.transactionId??"unknown"}\nTopic ID: ${r||"N/A"}${o?`\nView inscription: ${o}`:""}\n\nThe inscription is now available.`}return n.quote||n.confirmed?"Inscription operation completed.":`Successfully submitted inscription to the Hedera network!\n\nTransaction ID: ${n.result?.transactionId??"unknown"}\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 ee{constructor(){super(...arguments),this.name="inscribeHashinal",this.description="Tool for inscribing Hashinal NFTs. CRITICAL: When user provides content (url/contentRef/base64Data), call with ONLY the content parameters - DO NOT auto-generate name, description, creator, or attributes. A form will be automatically shown to collect metadata from the user. Only include metadata parameters if the user explicitly provided them in their message."}getEntityResolutionPreferences(){return{name:"literal",description:"literal",creator:"literal",attributes:"literal",properties:"literal"}}get specificInputSchema(){return xe._def?.schema||xe}get schema(){if(!this._schemaWithRenderConfig){const e=this.specificInputSchema,t=e;t._renderConfig||(t._renderConfig={fieldType:"object",ui:{label:"Inscribe Hashinal NFT",description:"Create a Hashinal inscription for NFT minting"}}),this._schemaWithRenderConfig=e}return this._schemaWithRenderConfig}shouldGenerateForm(e){const i=new t.Logger({module:"InscribeHashinalTool"}),n=e;i.info("InscribeHashinalTool: Checking if form should be generated",{inputKeys:Object.keys(n||{}),hasContent:!!(n.url||n.contentRef||n.base64Data),renderFormProvided:"renderForm"in n,renderFormValue:n.renderForm});if(!!!(n.url||n.contentRef||n.base64Data))return i.info("InscribeHashinalTool: No content source provided"),!1;if("renderForm"in n&&!1===n.renderForm)return i.info("InscribeHashinalTool: renderForm=false, skipping form generation"),!1;const r=e=>"string"==typeof e&&0!==e.trim().length;return r(n.name)&&r(n.description)&&r(n.creator)?(i.info("InscribeHashinalTool: Required metadata present, skipping form generation"),!1):(i.info("InscribeHashinalTool: Content provided, showing form for metadata collection"),!0)}getFormSchema(){return me(s.z.object({name:s.z.string().min(1,"Name is required").describe('Display name for the NFT (e.g., "Sunset Landscape #42", "Digital Abstract Art")'),description:s.z.string().min(1,"Description is required").describe("Meaningful description of the artwork, story, or concept behind this NFT"),creator:s.z.string().min(1,"Creator is required").describe('Creator account ID, artist name, or brand (e.g., "0.0.123456", "ArtistName", "StudioBrand")'),attributes:me(s.z.array(s.z.object({trait_type:s.z.string().describe('Trait name (e.g., "Rarity", "Color", "Style")'),value:s.z.union([s.z.string(),s.z.number()]).describe('Trait value (e.g., "Epic", "Blue", 85)')}))).withRender(Se.array("NFT Attributes","Attribute")).optional().describe("Collectible traits and characteristics."),type:s.z.string().optional().describe('Category or genre of the NFT (e.g., "Digital Art", "Photography", "Collectible Card)')})).withRender({fieldType:"object",ui:{label:"Complete NFT Metadata",description:"Provide meaningful metadata to create a valuable NFT"}})}async executeQuery(e,i){if(!e.url&&!e.contentRef&&!e.base64Data)return Re({code:"MISSING_CONTENT",details:"No content source provided",suggestions:["Provide a URL to content you want to inscribe","Upload a file and use the content reference","Provide base64-encoded content data"]});const n=this.inscriberBuilder.hederaKit?.client?.operatorAccountId?.toString()||"0.0.unknown",r={...fe({name:e.name,creator:e.creator,description:e.description,type:e.type,fileName:e.fileName,mimeType:e.mimeType,operatorAccount:n}),attributes:Array.isArray(e.attributes)?e.attributes:[],properties:e.properties||{}};let o;try{o=function(e){try{return he.parse(e)}catch(t){if(t instanceof s.z.ZodError){const e=t.errors.map(e=>`${e.path.join(".")}: ${e.message}`).join("; ");throw new Error(`HIP-412 metadata validation failed: ${e}`)}throw t}}(r)}catch(l){return Re({code:"METADATA_VALIDATION_FAILED",details:`Metadata validation error: ${l instanceof Error?l.message:String(l)}`,suggestions:["Ensure all required metadata fields are provided","Check that attribute values are valid","Verify metadata follows HIP-412 standard"]})}const a={mode:"hashinal",metadata:o,jsonFileURL:e.jsonFileURL,fileStandard:e.fileStandard,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:!e.quoteOnly&&(e.waitForConfirmation??!0),waitMaxAttempts:60,waitIntervalMs:5e3,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",quoteOnly:e.quoteOnly};let c;if(e.url)c={type:"url",url:e.url};else{if(!e.contentRef&&!e.base64Data)throw new Error("No valid input data provided for inscription");{const t=e.contentRef||e.base64Data||"",{buffer:i,mimeType:n,fileName:r}=await this.resolveContent(t,e.mimeType,e.fileName);c={type:"buffer",buffer:i,fileName:r||e.fileName||"hashinal-content",mimeType:n||e.mimeType}}}if(e.quoteOnly)try{const t=await this.generateInscriptionQuote(c,a);return function(e){const{totalCostHbar:t,validUntil:i,breakdown:n,content:r}=e;return{success:!0,type:"quote",title:"Inscription Cost Quote",message:`Estimated cost to inscribe "${r.name||"your content"}" is ${t} HBAR.`,quote:{totalCostHbar:t,validUntil:i,breakdown:n},content:r}}({totalCostHbar:t.totalCostHbar,validUntil:t.validUntil,breakdown:t.breakdown,content:{name:e.name,creator:e.creator,type:e.type}})}catch(l){return Re({code:"QUOTE_GENERATION_FAILED",details:`Quote generation failed: ${l instanceof Error?l.message:"Failed to generate inscription quote"}`,suggestions:["Check network connectivity","Verify content is accessible","Try again in a moment"]})}try{let i;if(e.timeoutMs){const t=new Promise((t,i)=>{setTimeout(()=>i(new Error(`Inscription timed out after ${e.timeoutMs}ms`)),e.timeoutMs)});i=await Promise.race([this.inscriberBuilder.inscribeAuto?this.inscriberBuilder.inscribeAuto(c,a):this.inscriberBuilder.inscribe(c,a),t])}else i=this.inscriberBuilder.inscribeAuto?await this.inscriberBuilder.inscribeAuto(c,a):await this.inscriberBuilder.inscribe(c,a);if(i.confirmed&&!i.quote){const n=ie(i.inscription,i.result),r=a.network||"testnet",o=e.fileStandard||"1",{hrl:s,topicId:c,cdnUrl:l}=ne(n,r,o),u=function(e){const{hrl:t,topicId:i,standard:n,cdnUrl:r,transactionId:o,metadata:s}=e;return{success:!0,type:"inscription",title:`${n} Hashinal Inscription Complete`,message:`Successfully inscribed "${s.name||"your content"}" as a ${n} Hashinal. The content is now ready for NFT minting.`,inscription:{hrl:t,topicId:i,standard:n,cdnUrl:r,transactionId:o},metadata:s,nextSteps:{primary:"CRITICAL: When minting NFTs, use ONLY the mintingMetadata value as a single string in the metadata array. Do NOT create JSON objects.",context:'The metadata parameter for minting should be exactly: ["'+t+'"] - just the HRL string in an array, nothing else.',mintingMetadata:t}}}({hrl:s||"hcs://1/unknown",topicId:c||"unknown",standard:"6"===o?"Dynamic":"Static",cdnUrl:l,transactionId:i?.inscription?.tx_id||i?.result?.transactionId||"unknown",metadata:{name:e.name,creator:e.creator,description:e.description,type:e.type,attributes:Array.isArray(e.attributes)?e.attributes:[]}});if(!1!==e.withHashLinkBlocks)try{const e=await this.createHashLinkBlock(u);u.hashLinkBlock=e}catch(d){new t.Logger({module:"InscribeHashinalTool"}).warn("Failed to create HashLink block",d)}return u}if(i.quote||i.confirmed)return Re({code:"UNEXPECTED_RESULT",details:"Received an unexpected inscription result state",suggestions:["Try again or verify network status"]});return function(e){const{transactionId:t,details:i,suggestions:n}=e,r=i||`Inscription submitted but not yet confirmed. Transaction ID: ${t}`;return{success:!1,type:"error",title:"Inscription Submitted (Pending)",message:r,error:{code:"INSCRIPTION_PENDING",details:r,suggestions:n||["Wait a few moments for confirmation","Check the transaction status on a Hedera explorer","Try the inscription again if it doesn't confirm within 5 minutes"]}}}({transactionId:i.result?.transactionId||i?.inscription?.transactionId||"unknown",details:"Successfully submitted Hashinal inscription. Waiting for network confirmation..."})}catch(l){const e=l instanceof Error?l.message:"Failed to inscribe Hashinal NFT";throw new Error(`Inscription failed: ${e}`)}}async createHashLinkBlock(e,i){const n=this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",r=e.inscription.cdnUrl?.includes("mainnet")?"mainnet":"testnet";if(n!==r){new t.Logger({module:"InscribeHashinalTool"}).warn(`Network mismatch detected: client=${n}, cdn=${r}. Using client network.`)}const o=n,s=function(e){const t="mainnet"===e?Ne.mainnet:Ne.testnet;return t&&"0.0.TBD"!==t.blockId?t:Ne.testnet}(o);return{blockId:s.blockId,hashLink:s.hashLink,template:s.template,attributes:{name:e.metadata.name||"Untitled Content",creator:e.metadata.creator||"",topicId:e.inscription.topicId,hrl:e.inscription.hrl,network:o}}}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}}getEssentialFields(){return["name","description","creator","attributes"]}isFieldEmpty(e,t){return null==t||""===t||(!(!Array.isArray(t)||0!==t.length)||!("attributes"!==e||!Array.isArray(t))&&t.every(e=>!e||"object"==typeof e&&(!e.trait_type||!e.value)))}},exports.InscriberBuilder=Ve,exports.ListConnectionsTool=C,exports.ListUnapprovedConnectionRequestsTool=z,exports.ManageConnectionRequestsTool=q,exports.MigrateRegistryTool=class extends D{constructor(){super(...arguments),this.name="migrateHCS2Registry",this.description="Migrate an HCS-2 registry to a new topic"}get specificInputSchema(){return j}async executeQuery(e,t){try{const t=await this.hcs2Builder.migrateRegistry(e.registryTopicId,{targetTopicId:e.targetTopicId,metadata:e.metadata,memo:e.memo});if(!("success"in t)||!t.success)throw new Error(t.error||"Failed to migrate registry");if(H(t)){const i=t.transactionBytes;return{message:"I prepared an unsigned transaction to migrate the HCS-2 registry. Please review and approve to submit.",transactionBytes:i,metadata:{transactionBytes:i,pendingApproval:!0,description:`Migrate HCS-2 registry (from ${e.registryTopicId} to ${e.targetTopicId})`}}}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=h,exports.OpenConvaiState=$e,exports.QueryDynamicRegistryTool=class extends Z{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 X}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 D{constructor(){super(...arguments),this.name="queryHCS2Registry",this.description="Query entries from an HCS-2 registry (standard HCS-2). Retrieves indexed or latest entries and returns a structured summary."}get specificInputSchema(){return G}async executeQuery(e,t){const i=await this.hcs2Builder.getRegistry(e.topicId,{limit:e.limit,order:e.order,skip:e.skip}),n=i.registryType,r=0===n||"0"===n||"indexed"===String(n).toLowerCase()||"index"===String(n).toLowerCase()||"index_topic"===String(n).toLowerCase()||"indexed_registry"===String(n).toLowerCase();return{topicId:i.topicId,registryType:r?"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 Z{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 V}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(!("success"in i)||!i.success)throw new Error(i.error||"Failed to register dynamic hashinal");if(H(i)){const t=i.transactionBytes;return{message:"I prepared an unsigned transaction to register a dynamic hashinal. Please review and approve to submit.",transactionBytes:t,metadata:{transactionBytes:t,pendingApproval:!0,description:"Register dynamic hashinal"+(e.memo?` (Memo: ${e.memo})`:"")}}}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 D{constructor(){super(...arguments),this.name="registerHCS2Entry",this.description="Register an entry in an HCS-2 registry (standard HCS-2). Use this to add a target topic to an existing HCS-2 registry."}get specificInputSchema(){return K}async executeQuery(e,t){try{const t=await this.hcs2Builder.registerEntry(e.registryTopicId,{targetTopicId:e.targetTopicId,metadata:e.metadata,memo:e.memo});if(!("success"in t)||!t.success)throw new Error(t.error||"Failed to register entry");if(H(t)){const i=t.transactionBytes;return{message:"I prepared an unsigned transaction to register the entry in the HCS-2 registry. Please review and approve to submit.",transactionBytes:i,metadata:{transactionBytes:i,pendingApproval:!0,description:`Register HCS-2 entry (registry ${e.registryTopicId} -> target ${e.targetTopicId})`}}}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 ee{constructor(){super(...arguments),this.name="retrieveInscription",this.description="Retrieve details of an existing inscription from the Hedera network"}get specificInputSchema(){return Oe}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||"unknown",topicId:i.topic_id||i.topicId,status:i.status||"unknown",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=M,exports.SendMessageToConnectionTool=w,exports.SignerProviderRegistry=ke,exports.UpdateDynamicHashinalTool=class extends Z{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 Y}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(!("success"in i)||!i.success)throw new Error(i.error||"Failed to update dynamic hashinal");if(H(i)){const t=i.transactionBytes;return{message:"I prepared an unsigned transaction to update a dynamic hashinal. Please review and approve to submit.",transactionBytes:t,metadata:{transactionBytes:t,pendingApproval:!0,description:`Update dynamic hashinal (registry ${e.registryTopicId})${e.memo?` (Memo: ${e.memo})`:""}`}}}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 D{constructor(){super(...arguments),this.name="updateHCS2Entry",this.description="Update an existing entry in an indexed HCS-2 registry"}get specificInputSchema(){return L}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(!("success"in t)||!t.success)throw new Error(t.error||"Failed to update entry");if(H(t)){const i=t.transactionBytes;return{message:"I prepared an unsigned transaction to update the HCS-2 registry entry. Please review and approve to submit.",transactionBytes:i,metadata:{transactionBytes:i,pendingApproval:!0,description:`Update HCS-2 entry (registry ${e.registryTopicId}, uid ${e.uid} -> ${e.targetTopicId})`}}}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.createFieldConfigMap=function(e){const t=Pe(e),i={};for(const[n,r]of Object.entries(t.fields)){const e=t.metadata[n],o=n.split(".");i[n]={renderConfig:r,metadata:e,path:o}}return i},exports.createProgressiveSchema=function(e,t){const i=me(e),n=e._def?.typeName;if("ZodObject"===n){const n=e._def?.shape;if(n){for(const[e,i]of Object.entries(n)){let n,r="common";for(const[i,o]of Object.entries(t))if(o.fields.includes(e)){n=i,r=o.priority;break}me(i).withProgressive(r,n)}return i}}return i},exports.createSimpleConfig=function(e){const t=Pe(e),i=[];for(const n of t.order){const e=t.fields[n],r=t.metadata[n];e&&r&&i.push({name:n,type:r.type,label:e.ui?.label||n,required:r.required,placeholder:e.ui?.placeholder,options:e.options||r.options})}return{fields:i}},exports.enhanceRenderConfig=function(e){return{...e,progressive:{priority:e.ui?.priority||"common",group:e.ui?.group}}},exports.extendZodSchema=me,exports.extractFieldMetadata=Ee,exports.extractOptionsFromSchema=Ie,exports.extractProgressiveInfo=function(e){const t=be(e);return t?.progressive?{priority:t.progressive.priority,group:t.progressive.group}:t?.ui?.priority?{priority:t.ui.priority,group:t.ui.group}:{priority:"common"}},exports.extractRenderConfigs=Pe,exports.extractValidationConstraints=Ce,exports.generateFieldOrdering=function(e){const t=Pe(e),i={},n={default:0,"Basic Information":1,"Token Settings":2,"Keys & Security":3,"Custom Fees":4,"Advanced Settings":5};for(const[r,o]of Object.entries(t.groups)){const e="default"===r?"Basic Information":r;i[e]={title:e,fields:o,order:n[e]||10}}return{sections:i,fieldOrder:t.order}},exports.getDefaultValue=ve,exports.getInnerSchema=Ae,exports.getRenderConfig=be,exports.hasRenderConfig=ye,exports.inferFieldTypeFromSchema=we,exports.initializeStandardsAgentKit=async e=>{const n=e?.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",a="true"===process.env.DISABLE_LOGGING,c=t.Logger.getInstance({level:n.logLevel||"info",silent:a});let l;if("mainnet"===s?l="mainnet":("testnet"===s||c.warn(`Unsupported network specified: '${s}'. Defaulting to 'testnet'.`),l="testnet"),!r||!o)throw new Error("Operator ID and private key must be provided either through options or environment variables.");const d=e?.stateManager||new $e({defaultEnvFilePath:qe,defaultPrefix:"TODD"});c.info("State manager initialized");const u=new i.ServerSigner(r,o,l),g=new i.HederaAgentKit(u);await g.initialize(),c.info(`HederaAgentKit initialized for ${r} on ${l}`);const p=new _e(g,d,{useEncryption:n.useEncryption,registryUrl:n.registryUrl,logLevel:n.logLevel});let h,f;if(e?.monitoringClient){const e=new i.ServerSigner(r,o,l);h=new i.HederaAgentKit(e),await h.initialize(),f=new _e(h,d,{useEncryption:n.useEncryption,registryUrl:n.registryUrl,logLevel:"error"}),c.info("Monitoring client initialized")}const y={};return y.registerAgentTool=new m({hederaKit:g,hcs10Builder:p,logger:void 0}),e?.createAllTools&&(y.findRegistrationsTool=new R({hederaKit:g,hcs10Builder:p,logger:void 0}),y.retrieveProfileTool=new M({hederaKit:g,hcs10Builder:p,logger:void 0}),y.initiateConnectionTool=new T({hederaKit:g,hcs10Builder:p,logger:void 0}),y.listConnectionsTool=new C({hederaKit:g,hcs10Builder:p,logger:void 0}),y.sendMessageToConnectionTool=new w({hederaKit:g,hcs10Builder:p,logger:void 0}),y.checkMessagesTool=new E({hederaKit:g,hcs10Builder:p,logger:void 0}),y.connectionMonitorTool=new x({hederaKit:h||g,hcs10Builder:f||p,logger:void 0}),y.manageConnectionRequestsTool=new q({hederaKit:g,hcs10Builder:p,logger:void 0}),y.acceptConnectionRequestTool=new B({hederaKit:g,hcs10Builder:p,logger:void 0}),y.listUnapprovedConnectionRequestsTool=new z({hederaKit:g,hcs10Builder:p,logger:void 0}),c.info("All tools initialized")),{hederaKit:g,hcs10Builder:p,monitoringHederaKit:h,monitoringHcs10Builder:f,tools:y,stateManager:d}},exports.installZodRenderExtensions=function(){s.ZodType.prototype.withRender||(s.ZodType.prototype.withRender=function(e){return me(this).withRender(e)},s.ZodType.prototype.withProgressive=function(e,t){return me(this).withProgressive(e,t)},s.ZodType.prototype.withBlock=function(e){return me(this).withBlock(e)})},exports.isFormValidatable=function(e){return null!==e&&"object"==typeof e&&"shouldGenerateForm"in e&&"getFormSchema"in e&&"getEssentialFields"in e&&"isFieldEmpty"in e&&"function"==typeof e.shouldGenerateForm&&"function"==typeof e.getFormSchema&&"function"==typeof e.getEssentialFields&&"function"==typeof e.isFieldEmpty},exports.isOptionalSchema=Te,exports.loadConfig=de,exports.renderConfigs=Se;
|
|
2
2
|
//# sourceMappingURL=standards-agent-kit.cjs.map
|