@hashgraphonline/standards-agent-kit
Version:
A modular SDK for building on-chain autonomous agents using Hashgraph Online Standards, including HCS-10 for agent discovery and communication.
1 lines • 105 kB
JavaScript
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("hedera-agent-kit"),t=require("@hashgraphonline/standards-sdk"),i=require("fs"),n=require("path"),r=require("axios"),o=require("zod"),s=require("fs/promises");function a(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const i in e)if("default"!==i){const n=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,n.get?n:{enumerable:!0,get:()=>e[i]})}return t.default=e,Object.freeze(t)}const c=a(n),l=a(s);class d extends e.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}class u extends e.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}const g=class{static parseCapabilities(e){if(!e)return[t.AIAgentCapability.TEXT_GENERATION];const i=e.toLowerCase(),n=new Set;for(const[t,r]of Object.entries(this.CAPABILITY_MAPPINGS))i.includes(t)&&r.forEach(e=>n.add(e));return 0===n.size&&n.add(t.AIAgentCapability.TEXT_GENERATION),Array.from(n)}static parseTagsOrCapabilities(e){if(Array.isArray(e)&&e.every(e=>"number"==typeof e))return e;if(Array.isArray(e)&&e.every(e=>"string"==typeof e)){const t=new Set;return e.forEach(e=>{this.parseCapabilities(e).forEach(e=>t.add(e))}),Array.from(t)}return"string"==typeof e?this.parseCapabilities(e):[t.AIAgentCapability.TEXT_GENERATION]}static getCapabilityName(e){return{[t.AIAgentCapability.TEXT_GENERATION]:"Text Generation",[t.AIAgentCapability.IMAGE_GENERATION]:"Image Generation",[t.AIAgentCapability.AUDIO_GENERATION]:"Audio Generation",[t.AIAgentCapability.VIDEO_GENERATION]:"Video Generation",[t.AIAgentCapability.CODE_GENERATION]:"Code Generation",[t.AIAgentCapability.LANGUAGE_TRANSLATION]:"Language Translation",[t.AIAgentCapability.SUMMARIZATION_EXTRACTION]:"Summarization & Extraction",[t.AIAgentCapability.KNOWLEDGE_RETRIEVAL]:"Knowledge Retrieval",[t.AIAgentCapability.DATA_INTEGRATION]:"Data Integration",[t.AIAgentCapability.MARKET_INTELLIGENCE]:"Market Intelligence",[t.AIAgentCapability.TRANSACTION_ANALYTICS]:"Transaction Analytics",[t.AIAgentCapability.SMART_CONTRACT_AUDIT]:"Smart Contract Audit",[t.AIAgentCapability.GOVERNANCE_FACILITATION]:"Governance Facilitation",[t.AIAgentCapability.SECURITY_MONITORING]:"Security Monitoring",[t.AIAgentCapability.COMPLIANCE_ANALYSIS]:"Compliance Analysis",[t.AIAgentCapability.FRAUD_DETECTION]:"Fraud Detection",[t.AIAgentCapability.MULTI_AGENT_COORDINATION]:"Multi-Agent Coordination",[t.AIAgentCapability.API_INTEGRATION]:"API Integration",[t.AIAgentCapability.WORKFLOW_AUTOMATION]:"Workflow Automation"}[e]||"Unknown Capability"}};g.CAPABILITY_MAPPINGS={ai:[t.AIAgentCapability.TEXT_GENERATION],"artificial intelligence":[t.AIAgentCapability.TEXT_GENERATION],chat:[t.AIAgentCapability.TEXT_GENERATION],conversation:[t.AIAgentCapability.TEXT_GENERATION],text:[t.AIAgentCapability.TEXT_GENERATION],"text generation":[t.AIAgentCapability.TEXT_GENERATION],image:[t.AIAgentCapability.IMAGE_GENERATION],picture:[t.AIAgentCapability.IMAGE_GENERATION],visual:[t.AIAgentCapability.IMAGE_GENERATION],photo:[t.AIAgentCapability.IMAGE_GENERATION],audio:[t.AIAgentCapability.AUDIO_GENERATION],sound:[t.AIAgentCapability.AUDIO_GENERATION],voice:[t.AIAgentCapability.AUDIO_GENERATION],speech:[t.AIAgentCapability.AUDIO_GENERATION],video:[t.AIAgentCapability.VIDEO_GENERATION],movie:[t.AIAgentCapability.VIDEO_GENERATION],animation:[t.AIAgentCapability.VIDEO_GENERATION],code:[t.AIAgentCapability.CODE_GENERATION],programming:[t.AIAgentCapability.CODE_GENERATION],development:[t.AIAgentCapability.CODE_GENERATION],coding:[t.AIAgentCapability.CODE_GENERATION],translate:[t.AIAgentCapability.LANGUAGE_TRANSLATION],translation:[t.AIAgentCapability.LANGUAGE_TRANSLATION],language:[t.AIAgentCapability.LANGUAGE_TRANSLATION],summarize:[t.AIAgentCapability.SUMMARIZATION_EXTRACTION],summary:[t.AIAgentCapability.SUMMARIZATION_EXTRACTION],extract:[t.AIAgentCapability.SUMMARIZATION_EXTRACTION],extraction:[t.AIAgentCapability.SUMMARIZATION_EXTRACTION],knowledge:[t.AIAgentCapability.KNOWLEDGE_RETRIEVAL],search:[t.AIAgentCapability.KNOWLEDGE_RETRIEVAL],retrieve:[t.AIAgentCapability.KNOWLEDGE_RETRIEVAL],lookup:[t.AIAgentCapability.KNOWLEDGE_RETRIEVAL],data:[t.AIAgentCapability.DATA_INTEGRATION],"data processing":[t.AIAgentCapability.DATA_INTEGRATION],"data integration":[t.AIAgentCapability.DATA_INTEGRATION],etl:[t.AIAgentCapability.DATA_INTEGRATION],market:[t.AIAgentCapability.MARKET_INTELLIGENCE],trading:[t.AIAgentCapability.MARKET_INTELLIGENCE],finance:[t.AIAgentCapability.MARKET_INTELLIGENCE],financial:[t.AIAgentCapability.MARKET_INTELLIGENCE],analytics:[t.AIAgentCapability.TRANSACTION_ANALYTICS],analysis:[t.AIAgentCapability.TRANSACTION_ANALYTICS],analyze:[t.AIAgentCapability.TRANSACTION_ANALYTICS],transactions:[t.AIAgentCapability.TRANSACTION_ANALYTICS],audit:[t.AIAgentCapability.SMART_CONTRACT_AUDIT],contract:[t.AIAgentCapability.SMART_CONTRACT_AUDIT],"smart contract":[t.AIAgentCapability.SMART_CONTRACT_AUDIT],governance:[t.AIAgentCapability.GOVERNANCE_FACILITATION],voting:[t.AIAgentCapability.GOVERNANCE_FACILITATION],dao:[t.AIAgentCapability.GOVERNANCE_FACILITATION],security:[t.AIAgentCapability.SECURITY_MONITORING],monitoring:[t.AIAgentCapability.SECURITY_MONITORING],threat:[t.AIAgentCapability.SECURITY_MONITORING],compliance:[t.AIAgentCapability.COMPLIANCE_ANALYSIS],regulatory:[t.AIAgentCapability.COMPLIANCE_ANALYSIS],regulation:[t.AIAgentCapability.COMPLIANCE_ANALYSIS],fraud:[t.AIAgentCapability.FRAUD_DETECTION],detection:[t.AIAgentCapability.FRAUD_DETECTION],anomaly:[t.AIAgentCapability.FRAUD_DETECTION],coordination:[t.AIAgentCapability.MULTI_AGENT_COORDINATION],"multi-agent":[t.AIAgentCapability.MULTI_AGENT_COORDINATION],orchestration:[t.AIAgentCapability.MULTI_AGENT_COORDINATION],api:[t.AIAgentCapability.API_INTEGRATION],integration:[t.AIAgentCapability.API_INTEGRATION],webhook:[t.AIAgentCapability.API_INTEGRATION],workflow:[t.AIAgentCapability.WORKFLOW_AUTOMATION],automation:[t.AIAgentCapability.WORKFLOW_AUTOMATION],process:[t.AIAgentCapability.WORKFLOW_AUTOMATION]};let p=g;const h=o.z.object({name:o.z.string().min(1).max(50).describe("A unique name for the agent (1-50 characters)"),description:o.z.string().max(500).optional().describe("Optional bio description for the agent (max 500 characters)"),alias:o.z.string().optional().transform(e=>{if(!e||e.toLowerCase().includes("random")){return`bot${Date.now().toString(36)}${Math.random().toString(36)}`}return e}).describe('Optional custom username/alias for the agent. Use "random" to generate a unique alias'),type:o.z.enum(["autonomous","manual"]).optional().describe("Agent type (default: autonomous)"),model:o.z.string().optional().describe("AI model identifier (default: agent-model-2024)"),capabilities:o.z.union([o.z.array(o.z.nativeEnum(t.AIAgentCapability)),o.z.array(o.z.string()),o.z.string()]).optional().transform(e=>{if(e)return"string"==typeof e?p.parseCapabilities(e):Array.isArray(e)&&e.length>0&&"string"==typeof e[0]?p.parseTagsOrCapabilities(e):e}).describe('Agent capabilities - can be capability names (e.g. "ai", "data processing"), capability enum values, or array of either. Common values: "ai"/"text" (TEXT_GENERATION), "data" (DATA_INTEGRATION), "analytics" (TRANSACTION_ANALYTICS)'),tags:o.z.union([o.z.array(o.z.string()),o.z.string()]).optional().transform(e=>{if(e)return"string"==typeof e?p.parseCapabilities(e):p.parseTagsOrCapabilities(e)}).describe('Tags for the agent (alternative to capabilities) - e.g. "ai", "data", "analytics". Will be converted to appropriate capabilities.'),creator:o.z.string().optional().describe("Creator attribution for the agent"),socials:o.z.record(o.z.enum(["twitter","github","discord","telegram","linkedin","youtube","website","x"]),o.z.string()).optional().describe('Social media links (e.g., {"twitter": "@handle", "discord": "username"})'),properties:o.z.record(o.z.unknown()).optional().describe("Custom metadata properties for the agent"),profilePicture:o.z.union([o.z.string().describe("URL or local file path to profile picture"),o.z.object({url:o.z.string().optional(),path:o.z.string().optional(),filename:o.z.string().optional()})]).optional().describe("Optional profile picture as URL, file path, or object with url/path/filename"),existingProfilePictureTopicId:o.z.string().optional().describe("Topic ID of an existing profile picture to reuse (e.g., 0.0.12345)"),initialBalance:o.z.number().positive().optional().describe("Optional initial HBAR balance for the new agent account (will create new account if provided)"),userAccountId:o.z.string().optional().describe("Optional account ID (e.g., 0.0.12345) to use as the agent account instead of creating a new one"),hbarFee:o.z.number().positive().optional().describe("Optional HBAR fee amount to charge per message on the inbound topic"),tokenFees:o.z.array(o.z.object({amount:o.z.number().positive(),tokenId:o.z.string()})).optional().describe("Optional token fees to charge per message"),exemptAccountIds:o.z.array(o.z.string()).optional().describe("Optional account IDs to exempt from fees"),setAsCurrent:o.z.boolean().optional().describe("Whether to set as current agent (default: true)"),persistence:o.z.object({prefix:o.z.string().optional()}).optional().describe("Optional persistence configuration")});class m extends d{constructor(e){super(e),this.name="register_agent",this.description='Creates and registers the AI agent on the Hedera network. Returns JSON string with agent details (accountId, privateKey, topics) on success. Supports natural language for capabilities/tags like "ai", "data processing", "analytics". Note: This tool requires multiple transactions and cannot be used in returnBytes mode. If alias is set to "random" or contains "random", a unique alias will be generated.',this.specificInputSchema=h,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const i=e;this.specificArgs=t;const n={name:t.name};if(void 0!==t.description&&(n.bio=t.description),void 0!==t.alias)n.alias=t.alias;else{const e=Date.now().toString(36);n.alias=`${t.name}${e}`}if(void 0!==t.type&&(n.type=t.type),void 0!==t.model&&(n.model=t.model),void 0!==t.tags?n.capabilities=t.tags:void 0!==t.capabilities&&(n.capabilities=t.capabilities),void 0!==t.creator&&(n.creator=t.creator),void 0!==t.socials&&(n.socials=t.socials),void 0!==t.properties&&(n.properties=t.properties),void 0!==t.profilePicture)if("string"==typeof t.profilePicture)n.profilePicture=t.profilePicture;else{const e={};void 0!==t.profilePicture.url&&(e.url=t.profilePicture.url),void 0!==t.profilePicture.path&&(e.path=t.profilePicture.path),void 0!==t.profilePicture.filename&&(e.filename=t.profilePicture.filename),n.profilePicture=e}void 0!==t.existingProfilePictureTopicId&&(n.existingProfilePictureTopicId=t.existingProfilePictureTopicId),void 0!==t.userAccountId&&(n.userAccountId=t.userAccountId),void 0!==t.hbarFee&&(n.hbarFee=t.hbarFee),void 0!==t.tokenFees&&(n.tokenFees=t.tokenFees),void 0!==t.exemptAccountIds&&(n.exemptAccountIds=t.exemptAccountIds),void 0!==t.initialBalance&&(n.initialBalance=t.initialBalance),await i.registerAgent(n)}async _call(e,t){const i=await super._call(e,t),n=!1!==this.specificArgs?.setAsCurrent;if(this.specificArgs&&n)try{const e=JSON.parse(i);e.rawResult?this._handleRegistrationResult(e.rawResult):(e.state||e.accountId||e.metadata)&&this._handleRegistrationResult(e)}catch(r){}return i}_handleRegistrationResult(e){let t=e.accountId||e.metadata?.accountId;if(!t&&e.state?.createdResources){const i=e.state.createdResources.find(e=>e.startsWith("account:"));i&&(t=i.split(":")[1])}const i=e.inboundTopicId||e.metadata?.inboundTopicId||e.state?.inboundTopicId,n=e.outboundTopicId||e.metadata?.outboundTopicId||e.state?.outboundTopicId,r=e.profileTopicId||e.metadata?.profileTopicId||e.state?.profileTopicId,o=e.privateKey||e.metadata?.privateKey;if(t&&i&&n&&this.specificArgs){const e={name:this.specificArgs.name,accountId:t,inboundTopicId:i,outboundTopicId:n,profileTopicId:r,privateKey:o},s=this.getServiceBuilder().getStateManager();if(s&&(s.setCurrentAgent(e),s.persistAgentData)){const t=this.specificArgs.persistence?.prefix||this.specificArgs.name.toUpperCase().replace(/[^A-Z0-9]/g,"_");s.persistAgentData(e,{type:"env-file",prefix:t}).catch(()=>{})}}}}const f=o.z.object({targetIdentifier:o.z.string().optional().describe("The request key (e.g., 'req-1:0.0.6155171@0.0.6154875'), account ID (e.g., 0.0.12345) of the target agent, OR the connection number (e.g., '1', '2') from the 'list_connections' tool. Request key is most deterministic."),connectionId:o.z.string().optional().describe("The connection number (e.g., '1', '2') from the 'list_connections' tool."),agentId:o.z.string().optional().describe("The account ID (e.g., 0.0.12345) of the target agent."),message:o.z.string().describe("The text message content to send."),disableMonitoring:o.z.boolean().optional().default(!1)});class y extends d{constructor(e){super(e),this.name="send_message_to_connection",this.description="Use this to send a message to an agent you already have an active connection with. Provide the target agent's account ID (e.g., 0.0.12345) and your message. If no active connection exists, this will fail - use initiate_connection instead to create a new connection first.",this.specificInputSchema=f,this.requiresMultipleTransactions=!0,this.neverScheduleThisTool=!0}async callBuilderMethod(e,t){const i=e,n=t.targetIdentifier||t.agentId||t.connectionId;if(!n)throw new Error("Either targetIdentifier, connectionId, or agentId must be provided");const r=i.getStateManager();if(r){const e=r.getConnectionsManager();if(e)try{const t=r.getCurrentAgent();t&&t.accountId&&await e.fetchConnectionData(t.accountId)}catch(o){console.debug("Could not refresh connections:",o)}if(n.match(/^\d+$/)){const e=r.listConnections(),o=parseInt(n)-1,s=e.filter(e=>"established"===e.status&&!e.isPending&&!e.needsConfirmation);if(o>=0&&o<s.length){const e=s[o];if(e&&e.connectionTopicId)return void(await i.sendMessageToConnection({targetIdentifier:e.connectionTopicId,message:t.message,disableMonitoring:t.disableMonitoring}))}}if(n.match(/^\d+\.\d+\.\d+$/)){const e=r.listConnections().find(e=>!(e.targetAccountId!==n&&e.targetAccountId!==`0.0.${n}`||"established"!==e.status||e.isPending||e.needsConfirmation));if(e&&e.connectionTopicId)return void(await i.sendMessageToConnection({targetIdentifier:e.connectionTopicId,message:t.message,disableMonitoring:t.disableMonitoring}))}}await i.sendMessageToConnection({targetIdentifier:n,message:t.message,disableMonitoring:t.disableMonitoring})}}const I=o.z.object({targetAccountId:o.z.string().describe("The Hedera account ID (e.g., 0.0.12345) of the agent you want to connect with."),disableMonitor:o.z.boolean().optional().describe("If true, does not wait for connection confirmation. Returns immediately after sending the request."),memo:o.z.string().optional().describe('Optional memo to include with the connection request (e.g., "Hello from Alice"). If not provided, defaults to "true" or "false" based on monitoring preference.')});class b extends d{constructor(e){super(e),this.name="initiate_connection",this.description="ONLY use this to START a BRAND NEW connection to an agent you have NEVER connected to before. If you already have an active connection to this agent, use send_message_to_connection instead. This creates a new connection request and waits for acceptance.",this.specificInputSchema=I,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const i=e,n={targetAccountId:t.targetAccountId};void 0!==t.disableMonitor&&(n.disableMonitor=t.disableMonitor),void 0!==t.memo&&(n.memo=t.memo),await i.initiateConnection(n)}}const w=o.z.object({includeDetails:o.z.boolean().optional().describe("Whether to include detailed information about each connection"),showPending:o.z.boolean().optional().describe("Whether to include pending connection requests")});class T extends u{constructor(e){super(e),this.name="list_connections",this.description="Lists all active HCS-10 connections. Use this FIRST before sending messages to check if you already have an active connection to a target agent. Shows connection details and agent information for each active connection.",this.specificInputSchema=w}async executeQuery(e){const t=this.hcs10Builder,i={};void 0!==e.includeDetails&&(i.includeDetails=e.includeDetails),void 0!==e.showPending&&(i.showPending=e.showPending),await t.listConnections(i);const n=await t.execute();if(n.success&&"rawResult"in n&&n.rawResult){const e=n.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Connections listed"}}return n}}const A=o.z.object({targetIdentifier:o.z.string().describe("The account ID (e.g., 0.0.12345) of the target agent OR the connection number (e.g., '1', '2') from the 'list_connections' tool to check messages for."),fetchLatest:o.z.boolean().optional().default(!1).describe("Set to true to fetch the latest messages even if they have been seen before, ignoring the last checked timestamp. Defaults to false (fetching only new messages)."),lastMessagesCount:o.z.number().int().positive().optional().describe("When fetchLatest is true, specifies how many of the most recent messages to retrieve. Defaults to 1.")});class C extends u{constructor(e){super(e),this.name="check_messages",this.description="Checks for and retrieves messages from an active connection.\nIdentify the target agent using their account ID (e.g., 0.0.12345) or the connection number shown in 'list_connections'.\nBy default, it only retrieves messages newer than the last check.\nUse 'fetchLatest: true' to get the most recent messages regardless of when they arrived.\nUse 'lastMessagesCount' to specify how many latest messages to retrieve (default 1 when fetchLatest is true).",this.specificInputSchema=A}async executeQuery({targetIdentifier:e,fetchLatest:t,lastMessagesCount:i}){const n=this.hcs10Builder;await n.checkMessages({targetIdentifier:e,fetchLatest:t,lastMessagesCount:i||1});const r=await n.execute();if(r.success&&"rawResult"in r&&r.rawResult){const e=r.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Messages checked"}}return r}}const E=o.z.object({accountId:o.z.string().optional().describe("Optional: Filter registrations by a specific Hedera account ID (e.g., 0.0.12345)."),tags:o.z.union([o.z.array(o.z.nativeEnum(t.AIAgentCapability)),o.z.array(o.z.string()),o.z.string()]).optional().transform(e=>{if(e)return"string"==typeof e?p.parseCapabilities(e):Array.isArray(e)&&e.length>0&&"string"==typeof e[0]?p.parseTagsOrCapabilities(e):e}).describe('Optional: Filter by capabilities/tags like "ai", "data", "analytics". Can be natural language terms or capability numbers.')});class R extends u{constructor(e){super(e),this.name="find_registrations",this.description='Searches the configured agent registry for HCS-10 agents. You can filter by account ID or tags/capabilities using natural language like "ai", "data processing", "analytics". Returns basic registration info.',this.specificInputSchema=E}async executeQuery({accountId:e,tags:t}){const i=this.hcs10Builder,n={};e&&(n.accountId=e),t&&(n.tags=t),await i.findRegistrations(n);const r=await i.execute();if(r.success&&"rawResult"in r&&r.rawResult){const e=r.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Registrations searched"}}return r}}const v=o.z.object({acceptAll:o.z.boolean().optional().describe("Whether to automatically accept all incoming connection requests. Default is false."),targetAccountId:o.z.string().optional().describe("If provided, only accept connection requests from this specific account ID."),hbarFees:o.z.array(o.z.object({amount:o.z.number(),collectorAccount:o.z.string().optional()})).optional().describe("Array of HBAR fee amounts to charge per message (with optional collector accounts)."),tokenFees:o.z.array(o.z.object({amount:o.z.number(),tokenId:o.z.string(),collectorAccount:o.z.string().optional()})).optional().describe("Array of token fee amounts and IDs to charge per message (with optional collector accounts)."),exemptAccountIds:o.z.array(o.z.string()).optional().describe("Array of account IDs to exempt from ALL fees set in this request."),monitorDurationSeconds:o.z.number().optional().describe("How long to monitor for incoming requests in seconds. Default is 120."),defaultCollectorAccount:o.z.string().optional().describe("Default account to collect fees if not specified at the fee level. Defaults to the agent account.")});class N extends d{constructor(e){super(e),this.name="monitor_connections",this.description="Monitors for incoming connection requests and accepts them with optional fee settings. Use this to watch for connection requests and accept them, optionally setting HBAR or token fees on the connection. Note: When acceptAll=true, this tool requires multiple transactions and cannot be used in returnBytes mode.",this.specificInputSchema=v,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 S=o.z.object({action:o.z.enum(["list","view","reject"]).describe("The action to perform: list all requests, view details of a specific request, or reject a request"),requestKey:o.z.string().optional().describe("The unique request key to view or reject (required for view and reject actions)")});class $ extends u{constructor(e){super(e),this.name="manage_connection_requests",this.description='Manage incoming connection requests. List pending requests, view details about requesting agents, and reject connection requests. Use the separate "accept_connection_request" tool to accept.',this.specificInputSchema=S}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 M=o.z.object({requestKey:o.z.string().describe('The unique request key of the specific request to accept. Use the "manage_connection_requests" tool with action="list" first to get valid keys.'),hbarFee:o.z.number().optional().describe("Optional HBAR fee amount to charge the connecting agent per message on the new connection topic."),exemptAccountIds:o.z.array(o.z.string()).optional().describe("Optional list of account IDs to exempt from any configured fees on the new connection topic.")});class z extends d{constructor(e){super(e),this.name="accept_connection_request",this.description="Accepts a pending HCS-10 connection request from another agent. Use list_unapproved_connection_requests to see pending requests.",this.specificInputSchema=M,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const i=e;await i.acceptConnection({requestKey:t.requestKey,hbarFee:t.hbarFee,exemptAccountIds:t.exemptAccountIds})}}const x=o.z.object({accountId:o.z.string().describe("The Hedera account ID of the agent whose profile you want to retrieve (e.g., 0.0.12345)."),disableCache:o.z.boolean().optional().describe("Optional: Force refresh from the network instead of using cache.")});class O extends u{constructor(e){super(e),this.name="retrieve_profile",this.description="Gets the detailed profile information for a specific HCS-10 agent by their account ID. Returns name, bio, capabilities, topics, and other metadata.",this.specificInputSchema=x}async executeQuery({accountId:e,disableCache:t}){const i=this.hcs10Builder,n={accountId:e};void 0!==t&&(n.disableCache=t),await i.retrieveProfile(n);const r=await i.execute();if(r.success&&"rawResult"in r&&r.rawResult){const e=r.rawResult;return{success:!0,data:e.profileDetails||"Profile retrieved",rawProfile:e.rawProfile}}return r}}const B=o.z.object({});class k extends u{constructor(e){super(e),this.name="list_unapproved_connection_requests",this.description="Lists all connection requests that are not fully established, including incoming requests needing approval and outgoing requests waiting for confirmation.",this.specificInputSchema=B}async executeQuery(){const e=this.hcs10Builder;await e.listUnapprovedConnectionRequests();const t=await e.execute();return"rawResult"in t?t.rawResult:t}}class q extends e.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs2",this.hcs2Builder=e.hcs2Builder}getServiceBuilder(){return this.hcs2Builder}}class F extends e.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs2",this.hcs2Builder=e.hcs2Builder}getServiceBuilder(){return this.hcs2Builder}}const P=o.z.object({registryType:o.z.nativeEnum(t.HCS2RegistryType).optional().describe("Registry type: 0 for indexed, 1 for non-indexed (default: 0)"),ttl:o.z.number().int().positive().optional().describe("Time to live in seconds (default: 86400)"),adminKey:o.z.union([o.z.string(),o.z.boolean()]).optional().describe("Admin key: public key string or true to use operator key"),submitKey:o.z.union([o.z.string(),o.z.boolean()]).optional().describe("Submit key: public key string or true to use operator key")});const D=o.z.object({registryTopicId:o.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID (e.g., 0.0.123456)"),targetTopicId:o.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The target topic ID to register (e.g., 0.0.123456)"),metadata:o.z.string().optional().describe("Optional metadata URI (HIP-412 format)"),memo:o.z.string().max(500).optional().describe("Optional memo (max 500 characters)")});const _=o.z.object({registryTopicId:o.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID (must be indexed)"),targetTopicId:o.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The new topic ID to point to"),uid:o.z.string().describe("The unique ID of the entry to update"),metadata:o.z.string().optional().describe("Optional metadata URI (HIP-412 format)"),memo:o.z.string().max(500).optional().describe("Optional memo (max 500 characters)")});const L=o.z.object({registryTopicId:o.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID (must be indexed)"),uid:o.z.string().describe("The unique ID of the entry to delete"),memo:o.z.string().max(500).optional().describe("Optional memo (max 500 characters)")});const U=o.z.object({registryTopicId:o.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The current HCS-2 registry topic ID"),targetTopicId:o.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The new topic ID to migrate to"),metadata:o.z.string().optional().describe("Optional metadata URI for migration details"),memo:o.z.string().max(500).optional().describe("Optional memo (max 500 characters)")});const H=o.z.object({topicId:o.z.string().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID to query"),limit:o.z.number().int().positive().optional().describe("Maximum number of entries to return"),order:o.z.enum(["asc","desc"]).optional().describe("Order of results (ascending or descending)"),skip:o.z.number().int().min(0).optional().describe("Number of entries to skip")});class K extends e.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs6",this.hcs6Builder=e.hcs6Builder}getServiceBuilder(){return this.hcs6Builder}}class G extends e.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs6",this.hcs6Builder=e.hcs6Builder}getServiceBuilder(){return this.hcs6Builder}}const j=o.z.object({ttl:o.z.number().min(3600).default(86400).describe("Time-to-live in seconds (minimum 3600 seconds/1 hour)"),adminKey:o.z.union([o.z.boolean(),o.z.string()]).optional().describe("Admin key for the registry topic. Can be boolean (use operator key) or a public key string"),submitKey:o.z.union([o.z.boolean(),o.z.string()]).optional().describe("Submit key for the registry topic. Can be boolean (use operator key) or a public key string")});const W=o.z.object({metadata:o.z.record(o.z.unknown()).describe("Metadata object for the hashinal (e.g., name, description, attributes)"),data:o.z.object({base64:o.z.string().optional().describe("Base64 encoded data for the hashinal"),url:o.z.string().optional().describe("URL to fetch data from"),mimeType:o.z.string().optional().describe("MIME type of the data")}).optional().describe("Data to inscribe with the hashinal"),memo:o.z.string().optional().describe("Optional memo for the registration"),ttl:o.z.number().min(3600).default(86400).describe("Time-to-live in seconds for the inscription"),registryTopicId:o.z.string().optional().describe("Registry topic ID to use. If not provided, a new registry will be created"),submitKey:o.z.string().optional().describe("Submit key for the registry (required if registry has a submit key)")});const Q=o.z.object({registryTopicId:o.z.string().describe("The registry topic ID that tracks this dynamic hashinal"),metadata:o.z.record(o.z.unknown()).describe("Updated metadata object for the hashinal"),data:o.z.object({base64:o.z.string().optional().describe("Base64 encoded data for the updated hashinal"),url:o.z.string().optional().describe("URL to fetch updated data from"),mimeType:o.z.string().optional().describe("MIME type of the data")}).optional().describe("Updated data to inscribe"),memo:o.z.string().optional().describe('Optional memo for the update (e.g., "Level up", "Version 2.0")'),submitKey:o.z.string().describe("Submit key for the registry (required to update)")});const V=o.z.object({topicId:o.z.string().describe("The registry topic ID to query"),limit:o.z.number().optional().default(100).describe("Maximum number of entries to retrieve"),order:o.z.enum(["asc","desc"]).optional().default("desc").describe("Order of entries (desc shows latest first)"),skip:o.z.number().optional().describe("Number of entries to skip")});class Y extends e.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="inscriber",this.inscriberBuilder=e.inscriberBuilder}getServiceBuilder(){return this.inscriberBuilder}}class X extends e.BaseHederaQueryTool{constructor(e){super(e),this.namespace="inscriber",this.inscriberBuilder=e.inscriberBuilder}getServiceBuilder(){return this.inscriberBuilder}}const J=o.z.object({url:o.z.string().url().describe("ONLY direct file download URLs with file extensions (.pdf, .jpg, .png, .json, .zip). NEVER use for web pages, articles, or when you already have content to inscribe."),mode:o.z.enum(["file","hashinal"]).optional().describe("Inscription mode: file or hashinal NFT"),metadata:o.z.record(o.z.unknown()).optional().describe("Metadata to attach to the inscription"),tags:o.z.array(o.z.string()).optional().describe("Tags to categorize the inscription"),chunkSize:o.z.number().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:o.z.boolean().optional().describe("Whether to wait for inscription confirmation"),timeoutMs:o.z.number().int().positive().optional().describe("Timeout in milliseconds for inscription (default: no timeout - waits until completion)"),apiKey:o.z.string().optional().describe("API key for inscription service")});const Z=o.z.object({filePath:o.z.string().min(1,"File path cannot be empty").describe("The file path of the content to inscribe. Must point to a valid, non-empty file."),mode:o.z.enum(["file","hashinal"]).optional().describe("Inscription mode: file or hashinal NFT"),metadata:o.z.record(o.z.unknown()).optional().describe("Metadata to attach to the inscription"),tags:o.z.array(o.z.string()).optional().describe("Tags to categorize the inscription"),chunkSize:o.z.number().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:o.z.boolean().optional().describe("Whether to wait for inscription confirmation"),timeoutMs:o.z.number().int().positive().optional().describe("Timeout in milliseconds for inscription (default: no timeout)"),apiKey:o.z.string().optional().describe("API key for inscription service")});const ee=o.z.object({base64Data:o.z.string().min(1,"Data cannot be empty").describe('The FULL content to inscribe as plain text or base64. When asked to "inscribe it" after retrieving content, pass ALL the content you retrieved here as plain text - NOT a summary, NOT URLs, NOT truncated. Example: if you fetched articles from any source, pass the complete article text you received.'),fileName:o.z.string().min(1,"File name cannot be empty").describe("Name for the inscribed content. Required for all inscriptions."),mimeType:o.z.string().optional().describe("MIME type of the content"),mode:o.z.enum(["file","hashinal"]).optional().describe("Inscription mode: file or hashinal NFT"),metadata:o.z.record(o.z.unknown()).optional().describe("Metadata to attach to the inscription"),tags:o.z.array(o.z.string()).optional().describe("Tags to categorize the inscription"),chunkSize:o.z.number().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:o.z.boolean().optional().describe("Whether to wait for inscription confirmation"),timeoutMs:o.z.number().int().positive().optional().describe("Timeout in milliseconds for inscription (default: no timeout - waits until completion)"),apiKey:o.z.string().optional().describe("API key for inscription service")});const te=o.z.object({url:o.z.string().url().describe("The URL of the content to inscribe as Hashinal NFT"),name:o.z.string().describe("Name of the Hashinal NFT"),creator:o.z.string().describe("Creator account ID or name"),description:o.z.string().describe("Description of the Hashinal NFT"),type:o.z.string().describe('Type of NFT (e.g., "image", "video", "audio")'),attributes:o.z.array(o.z.object({trait_type:o.z.string(),value:o.z.union([o.z.string(),o.z.number()])})).optional().describe("NFT attributes"),properties:o.z.record(o.z.unknown()).optional().describe("Additional properties"),jsonFileURL:o.z.string().url().optional().describe("URL to JSON metadata file"),tags:o.z.array(o.z.string()).optional().describe("Tags to categorize the NFT"),chunkSize:o.z.number().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:o.z.boolean().optional().describe("Whether to wait for inscription confirmation"),timeoutMs:o.z.number().int().positive().optional().describe("Timeout in milliseconds for inscription (default: no timeout - waits until completion)"),apiKey:o.z.string().optional().describe("API key for inscription service")});const ie=o.z.object({transactionId:o.z.string().describe("The transaction ID of the inscription to retrieve"),apiKey:o.z.string().optional().describe("API key for inscription service")});const ne=n.join(process.cwd(),".env");class re{constructor(e){this.currentAgent=null,this.connectionMessageTimestamps={},this.connectionsManager=null,this.defaultEnvFilePath=e?.defaultEnvFilePath,this.defaultPrefix=e?.defaultPrefix??"TODD";const i=e?.disableLogging||"true"===process.env.DISABLE_LOGGING;this.logger=new t.Logger({module:"OpenConvaiState",silent:i}),e?.baseClient&&this.initializeConnectionsManager(e.baseClient)}initializeConnectionsManager(e){return this.connectionsManager?this.logger.debug("ConnectionsManager already initialized"):(this.logger.debug("Initializing ConnectionsManager"),this.connectionsManager=new t.ConnectionsManager({baseClient:e,logLevel:"error"})),this.connectionsManager}getConnectionsManager(){return this.connectionsManager}setCurrentAgent(e){this.currentAgent=e,this.connectionMessageTimestamps={},this.connectionsManager&&this.connectionsManager.clearAll()}getCurrentAgent(){return this.currentAgent}addActiveConnection(e){if(!this.connectionsManager)throw this.logger.error("ConnectionsManager not initialized. Call initializeConnectionsManager before adding connections."),new Error("ConnectionsManager not initialized. Call initializeConnectionsManager before adding connections.");const t={connectionTopicId:e.connectionTopicId,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName,targetInboundTopicId:e.targetInboundTopicId,status:this.convertConnectionStatus(e.status||"established"),isPending:e.isPending||!1,needsConfirmation:e.needsConfirmation||!1,created:e.created||new Date,lastActivity:e.lastActivity,profileInfo:e.profileInfo,connectionRequestId:e.connectionRequestId,processed:!0};this.connectionsManager.updateOrAddConnection(t),this.initializeTimestampIfNeeded(e.connectionTopicId)}updateOrAddConnection(e){this.addActiveConnection(e)}listConnections(){return this.connectionsManager?this.connectionsManager.getAllConnections().map(e=>this.convertToActiveConnection(e)):(this.logger.debug("ConnectionsManager not initialized, returning empty connections list"),[])}getConnectionByIdentifier(e){if(!this.connectionsManager)return;const t=this.listConnections(),i=parseInt(e)-1;if(!isNaN(i)&&i>=0&&i<t.length)return t[i];const n=this.connectionsManager.getConnectionByTopicId(e);if(n)return this.convertToActiveConnection(n);const r=this.connectionsManager.getConnectionByAccountId(e);return r?this.convertToActiveConnection(r):void 0}getLastTimestamp(e){return this.connectionMessageTimestamps[e]||0}updateTimestamp(e,t){if(!(e in this.connectionMessageTimestamps))return void(this.connectionMessageTimestamps[e]=t);t>this.connectionMessageTimestamps[e]&&(this.connectionMessageTimestamps[e]=t)}initializeTimestampIfNeeded(e){e in this.connectionMessageTimestamps||(this.connectionMessageTimestamps[e]=1e6*Date.now())}convertConnectionStatus(e){switch(e){case"pending":return"pending";case"established":default:return"established";case"needs confirmation":return"needs_confirmation"}}convertToActiveConnection(e){return{targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName||`Agent ${e.targetAccountId}`,targetInboundTopicId:e.targetInboundTopicId||"",connectionTopicId:e.connectionTopicId,status:this.convertToStateStatus(e.status),created:e.created,lastActivity:e.lastActivity,isPending:e.isPending,needsConfirmation:e.needsConfirmation,profileInfo:e.profileInfo,connectionRequestId:e.connectionRequestId}}convertToStateStatus(e){switch(e){case"pending":return"pending";case"established":case"closed":return"established";case"needs_confirmation":return"needs confirmation";default:return"unknown"}}async persistAgentData(e,t){if(t?.type&&"env-file"!==t.type)throw new Error(`Unsupported persistence type: ${t.type}. Only 'env-file' is supported.`);const n=t?.envFilePath||this.defaultEnvFilePath||process.env.ENV_FILE_PATH||".env",r=t?.prefix||this.defaultPrefix;if(!e.accountId||!e.inboundTopicId||!e.outboundTopicId)throw new Error("Agent data incomplete, cannot persist to environment");const o={[`${r}_ACCOUNT_ID`]:e.accountId,[`${r}_INBOUND_TOPIC_ID`]:e.inboundTopicId,[`${r}_OUTBOUND_TOPIC_ID`]:e.outboundTopicId};e.privateKey&&(o[`${r}_PRIVATE_KEY`]=e.privateKey),e.profileTopicId&&(o[`${r}_PROFILE_TOPIC_ID`]=e.profileTopicId),await async function(e,t){let n="";i.existsSync(e)&&(n=i.readFileSync(e,"utf8"));const r=[...n.split("\n")];for(const[i,o]of Object.entries(t)){const e=r.findIndex(e=>e.startsWith(`${i}=`));-1!==e?r[e]=`${i}=${o}`:r.push(`${i}=${o}`)}i.writeFileSync(e,r.join("\n"))}(n,o)}}const oe="ConnectionsManager not initialized";class se extends e.BaseServiceBuilder{constructor(e,i,n){super(e),this.stateManager=i,this.useEncryption=n?.useEncryption||!1,this.guardedRegistryBaseUrl=n?.registryUrl||"";const r=this.hederaKit.client.network;this.network=r.toString().includes("mainnet")?"mainnet":"testnet";const o=this.hederaKit.signer.getAccountId().toString(),s=this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"";this.sdkLogger=new t.Logger({module:"HCS10Builder",level:n?.logLevel||"info"}),this.standardClient=new t.HCS10Client({network:this.network,operatorId:o,operatorPrivateKey:s,guardedRegistryBaseUrl:this.guardedRegistryBaseUrl,logLevel:n?.logLevel||"info"}),this.stateManager&&this.stateManager.initializeConnectionsManager(this.standardClient)}getOperatorId(){const e=this.standardClient.getClient().operatorAccountId;if(!e)throw new Error("Operator Account ID not configured in standard client.");return e.toString()}getNetwork(){return this.network}getStateManager(){return this.stateManager}getAccountAndSigner(){const e=this.standardClient.getAccountAndSigner();return{accountId:e.accountId,signer:e.signer}}async getInboundTopicId(){try{const e=this.getOperatorId();this.logger.info(`[HCS10Builder] Retrieving profile for operator ${e} to find inbound topic...`);const t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.inboundTopic)return this.logger.info(`[HCS10Builder] Found inbound topic for operator ${e}: ${t.topicInfo.inboundTopic}`),t.topicInfo.inboundTopic;throw new Error(`Could not retrieve inbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}catch(e){this.logger.error(`[HCS10Builder] Error fetching operator's inbound topic ID (${this.getOperatorId()}):`,e);const t=this.getOperatorId();let i=`Failed to get inbound topic ID for operator ${t}.`;throw e instanceof Error&&e.message.includes("does not have a valid HCS-11 memo")?i+=` The account profile may not exist or is invalid. Please ensure this operator account (${t}) is registered as an HCS-10 agent. You might need to register it first (e.g., using the 'register_agent' tool or SDK function).`:e instanceof Error?i+=` Reason: ${e.message}`:i+=` Unexpected error: ${String(e)}`,new Error(i)}}async getAgentProfile(e){try{return await this.standardClient.retrieveProfile(e)}catch(t){throw this.logger.error(`[HCS10Builder] Error retrieving agent profile for account ${e}:`,t),t}}async submitConnectionRequest(e,t){return this.standardClient.submitConnectionRequest(e,t)}async handleConnectionRequest(e,t,i,n){try{const r=await this.standardClient.handleConnectionRequest(e,t,i,n);return r&&r.connectionTopicId&&"object"==typeof r.connectionTopicId&&"toString"in r.connectionTopicId&&(r.connectionTopicId=r.connectionTopicId.toString()),r}catch(r){throw this.logger.error(`Error handling connection request #${i} for topic ${e}:`,r),new Error(`Failed to handle connection request: ${r instanceof Error?r.message:String(r)}`)}}async sendMessage(e,t,i){if(e&&"object"==typeof e&&"toString"in e&&(e=e?.toString()),!e||"string"!=typeof e)throw new Error(`Invalid topic ID provided to sendMessage: ${JSON.stringify(e)}`);try{const n=await this.standardClient.sendMessage(e,t,i,void 0);return{sequenceNumber:n.topicSequenceNumber?.toNumber(),receipt:n,transactionId:"transactionId"in n?n.transactionId?.toString():void 0}}catch(n){throw this.logger.error(`Error sending message to topic ${e}:`,n),new Error(`Failed to send message: ${n instanceof Error?n.message:String(n)}`)}}async getMessages(e){if(e&&"object"==typeof e&&"toString"in e&&(e=e?.toString()),!e||"string"!=typeof e)throw new Error(`Invalid topic ID provided to getMessages: ${JSON.stringify(e)}`);try{const t=(await this.standardClient.getMessages(e)).messages.map(e=>{const t=e?.created?.getTime()||0;return{...e,timestamp:t,data:e.data||"",sequence_number:e.sequence_number,p:"hcs-10"}});return t.sort((e,t)=>e.timestamp-t.timestamp),{messages:t}}catch(t){return this.logger.error(`Error getting messages from topic ${e}:`,t),{messages:[]}}}async getMessageStream(e){if(e&&"object"==typeof e&&"toString"in e&&(e=e?.toString()),!e||"string"!=typeof e)throw new Error(`Invalid topic ID provided to getMessageStream: ${JSON.stringify(e)}`);return this.standardClient.getMessageStream(e)}async getMessageContent(e){try{return await this.standardClient.getMessageContent(e)}catch(t){throw this.logger.error(`Error retrieving message content for: ${e}`,t),new Error(`Failed to retrieve message content: ${t instanceof Error?t.message:String(t)}`)}}getStandardClient(){return this.standardClient}async loadProfilePicture(e){try{if(!e)return null;if("string"==typeof e){if(e.startsWith("http://")||e.startsWith("https://")){this.logger.info(`Loading profile picture from URL: ${e}`);const t=await r.get(e,{responseType:"arraybuffer"}),i=globalThis.Buffer.from(t.data),o=new URL(e).pathname;return{buffer:i,filename:n.basename(o)||"profile.png"}}{if(!i.existsSync(e))return this.logger.warn(`Profile picture file not found: ${e}`),null;this.logger.info(`Loading profile picture from file: ${e}`);const t=i.readFileSync(e);return{buffer:t,filename:n.basename(e)}}}if(e.url){this.logger.info(`Loading profile picture from URL: ${e.url}`);const t=await r.get(e.url,{responseType:"arraybuffer"}),i=globalThis.Buffer.from(t.data);return{buffer:i,filename:e.filename||"profile.png"}}if(e.path){if(!i.existsSync(e.path))return this.logger.warn(`Profile picture file not found: ${e.path}`),null;this.logger.info(`Loading profile picture from file: ${e.path}`);const t=i.readFileSync(e.path);return{buffer:t,filename:e.filename||n.basename(e.path)}}return null}catch(t){return this.logger.error("Failed to load profile picture:",t),null}}async createAndRegisterAgent(e){const i=(new t.AgentBuilder).setName(e.name).setBio(e.bio||"").setCapabilities(e.capabilities||[t.AIAgentCapability.TEXT_GENERATION]).setType(e.type||"autonomous").setModel(e.model||"agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(t.InboundTopicType.PUBLIC);e.alias&&i.setAlias(e.alias),e.creator&&i.setCreator(e.creator),e?.feeConfig&&(i.setInboundTopicType(t.InboundTopicType.FEE_BASED),i.setFeeConfig(e.feeConfig)),e.existingProfilePictureTopicId?i.setExistingProfilePicture(e.existingProfilePictureTopicId):e.pfpBuffer&&e.pfpFileName?0===e.pfpBuffer.byteLength?this.logger.warn("Provided PFP buffer is empty. Skipping profile picture."):(this.logger.info(`Setting profile picture: ${e.pfpFileName} (${e.pfpBuffer.byteLength} bytes)`),i.setProfilePicture(e.pfpBuffer,e.pfpFileName)):this.logger.warn("Profile picture not provided. Agent creation might fail if required by the underlying SDK builder."),e.socials&&Object.entries(e.socials).forEach(([e,t])=>{i.addSocial(e,t)}),e.properties&&Object.entries(e.properties).forEach(([e,t])=>{i.addProperty(e,t)});try{const t=Boolean(e?.feeConfig);return await this.standardClient.createAndRegisterAgent(i,{initialBalance:t?50:10})}catch(n){throw this.logger.error("Error during agent creation/registration:",n),new Error(`Failed to create/register agent: ${n instanceof Error?n.message:String(n)}`)}}async registerAgent(e){if(this.clearNotes(),"returnBytes"===this.hederaKit.operationalMode)throw new Error("Agent registration requires multiple transactions and cannot be performed in returnBytes mode. Please use autonomous mode.");try{let i=null;e.profilePicture&&(i=await this.loadProfilePicture(e.profilePicture));const n={name:e.name,...void 0!==e.bio&&{bio:e.bio},...void 0!==e.alias&&{alias:e.alias},...void 0!==e.type&&{type:e.type},...void 0!==e.model&&{model:e.model},...void 0!==e.capabilities&&{capabilities:e.capabilities},...void 0!==e.creator&&{creator:e.creator},...void 0!==e.socials&&{socials:e.socials},...void 0!==e.properties&&{properties:e.properties},...void 0!==e.existingProfilePictureTopicId&&{existingProfilePictureTopicId:e.existingProfilePictureTopicId},...void 0!==i?.buffer&&{pfpBuffer:i.buffer},...void 0!==i?.filename&&{pfpFileName:i.filename}};if(e.hbarFee&&e.hbarFee>0){const i=new t.FeeConfigBuilder({network:this.network,logger:this.sdkLogger}),{accountId:r}=this.getAccountAndSigner();if(!r)throw new Error("Could not determine account ID for fee collection.");this.addNote(`Setting the operator account (${r}) as the fee collector since no specific collector was provided.`);const o=e.exemptAccountIds?.filter(e=>e!==r&&e.startsWith("0.0"))||[];n.feeConfig=i.addHbarFee(e.hbarFee,r,o)}const r=await this.createAndRegisterAgent(n);this.executeResult={success:!0,transactionId:r.transactionId,receipt:void 0,scheduleId:void 0,rawResult:{...r,name:e.name,accountId:r?.metadata?.accountId||r.state?.agentMetadata?.accountId}}}catch(i){throw this.logger.error("Failed to register agent:",i),i}return this}async initiateConnection(e){this.clearNotes();try{const t=await this.getAgentProfile(e.targetAccountId);if(!t.success||!t.topicInfo?.inboundTopic)throw new Error(`Could not retrieve inbound topic for target account ${e.targetAccountId}`);const i=t.topicInfo.inboundTopic;let n;void 0!==e.memo?n=e.memo:(n=e.disableMonitor?"false":"true",this.addNote(`No custom memo was provided. Using default memo '${n}' based on monitoring preference.`)),e.disableMonitor||this.addNote("Monitoring will be enabled for this connection request as disableMonitor was not specified.");const r=await this.submitConnectionRequest(i,n);this.executeResult={success:!0,transactionId:"transactionId"in r?r.transactionId?.toString():void 0,receipt:r,scheduleId:void 0,rawResult:{targetAccountId:e.targetAccountId,targetInboundTopicId:i,connectionRequestSent:!0,monitoringEnabled:!e.disableMonitor,...r}}}catch(t){throw this.logger.error("Failed to initiate connection:",t),t}return this}async acceptConnection(e){if(this.clearNotes(),"returnBytes"===this.hederaKit.operationalMode)throw new Error("Accepting connections requires multiple transactions and cannot be performed in returnBytes mode. Please use autonomous mode.");try{const n=this.stateManager?.getCurrentAgent();if(!n)throw new Error("Cannot accept connection request. No agent is currently active. Please register or select an agent first.");const r=this.stateManager?.getConnectionsManager();if(!r)throw new Error(oe);await r.fetchConnectionData(n.accountId);const o=[...r.getPendingRequests(),...r.getConnectionsNeedingConfirmation()].find(t=>t.uniqueRequestKey===e.reque