@hashgraphonline/standards-agent-kit 0.2.1 → 0.2.101
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/hcs10/hcs10-builder.d.ts +4 -0
- package/dist/cjs/standards-agent-kit.cjs +1 -1
- package/dist/cjs/standards-agent-kit.cjs.map +1 -1
- package/dist/cjs/tools/hcs10/RegisterAgentTool.d.ts +14 -4
- package/dist/es/builders/hcs10/hcs10-builder.d.ts +4 -0
- package/dist/es/standards-agent-kit.es2.js +27 -13
- package/dist/es/standards-agent-kit.es2.js.map +1 -1
- package/dist/es/standards-agent-kit.es5.js +75 -2
- package/dist/es/standards-agent-kit.es5.js.map +1 -1
- package/dist/es/tools/hcs10/RegisterAgentTool.d.ts +14 -4
- package/dist/umd/builders/hcs10/hcs10-builder.d.ts +4 -0
- package/dist/umd/standards-agent-kit.umd.js +1 -1
- package/dist/umd/standards-agent-kit.umd.js.map +1 -1
- package/dist/umd/tools/hcs10/RegisterAgentTool.d.ts +14 -4
- package/package.json +4 -4
- package/src/builders/hcs10/hcs10-builder.ts +37 -16
- package/src/tools/hcs10/RegisterAgentTool.ts +111 -5
|
@@ -104,6 +104,10 @@ export declare class HCS10Builder extends BaseServiceBuilder {
|
|
|
104
104
|
* Get the network type
|
|
105
105
|
*/
|
|
106
106
|
getNetwork(): StandardNetworkType;
|
|
107
|
+
/**
|
|
108
|
+
* Get state manager instance
|
|
109
|
+
*/
|
|
110
|
+
getStateManager(): IStateManager | undefined;
|
|
107
111
|
/**
|
|
108
112
|
* Get account and signer information
|
|
109
113
|
*/
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("hedera-agent-kit"),t=require("@hashgraphonline/standards-sdk"),n=require("fs"),o=require("path"),i=require("axios"),r=require("zod");class s extends e.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}class a extends e.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}const c=r.z.object({name:r.z.string().min(1).max(50).describe("A unique name for the agent (1-50 characters)"),description:r.z.string().max(500).optional().describe("Optional bio description for the agent (max 500 characters)"),alias:r.z.string().optional().describe("Optional custom username/alias for the agent"),type:r.z.enum(["autonomous","manual"]).optional().describe("Agent type (default: autonomous)"),model:r.z.string().optional().describe("AI model identifier (default: agent-model-2024)"),capabilities:r.z.array(r.z.nativeEnum(t.AIAgentCapability)).optional().describe("Array of agent capabilities (default: [TEXT_GENERATION])"),creator:r.z.string().optional().describe("Creator attribution for the agent"),socials:r.z.record(r.z.enum(["twitter","github","discord","telegram","linkedin","youtube","website","x"]),r.z.string()).optional().describe('Social media links (e.g., {"twitter": "@handle", "discord": "username"})'),properties:r.z.record(r.z.unknown()).optional().describe("Custom metadata properties for the agent"),profilePicture:r.z.union([r.z.string().describe("URL or local file path to profile picture"),r.z.object({url:r.z.string().optional(),path:r.z.string().optional(),filename:r.z.string().optional()})]).optional().describe("Optional profile picture as URL, file path, or object with url/path/filename"),existingProfilePictureTopicId:r.z.string().optional().describe("Topic ID of an existing profile picture to reuse (e.g., 0.0.12345)"),initialBalance:r.z.number().positive().optional().describe("Optional initial HBAR balance for the new agent account (will create new account if provided)"),userAccountId:r.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:r.z.number().positive().optional().describe("Optional HBAR fee amount to charge per message on the inbound topic"),tokenFees:r.z.array(r.z.object({amount:r.z.number().positive(),tokenId:r.z.string()})).optional().describe("Optional token fees to charge per message"),exemptAccountIds:r.z.array(r.z.string()).optional().describe("Optional account IDs to exempt from fees"),setAsCurrent:r.z.boolean().optional().describe("Whether to set as current agent (default: true)"),persistence:r.z.object({prefix:r.z.string().optional()}).optional().describe("Optional persistence configuration")});class u extends s{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. Note: This tool requires multiple transactions and cannot be used in returnBytes mode.",this.specificInputSchema=c,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const n=e,o={name:t.name};if(void 0!==t.description&&(o.bio=t.description),void 0!==t.alias&&(o.alias=t.alias),void 0!==t.type&&(o.type=t.type),void 0!==t.model&&(o.model=t.model),void 0!==t.capabilities&&(o.capabilities=t.capabilities),void 0!==t.creator&&(o.creator=t.creator),void 0!==t.socials&&(o.socials=t.socials),void 0!==t.properties&&(o.properties=t.properties),void 0!==t.profilePicture)if("string"==typeof t.profilePicture)o.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),o.profilePicture=e}void 0!==t.existingProfilePictureTopicId&&(o.existingProfilePictureTopicId=t.existingProfilePictureTopicId),void 0!==t.userAccountId&&(o.userAccountId=t.userAccountId),void 0!==t.hbarFee&&(o.hbarFee=t.hbarFee),void 0!==t.tokenFees&&(o.tokenFees=t.tokenFees),void 0!==t.exemptAccountIds&&(o.exemptAccountIds=t.exemptAccountIds),void 0!==t.initialBalance&&(o.initialBalance=t.initialBalance),await n.registerAgent(o)}}const d=r.z.object({targetIdentifier:r.z.string().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."),message:r.z.string().describe("The text message content to send."),disableMonitoring:r.z.boolean().optional().default(!1)});class l extends s{constructor(e){super(e),this.name="send_message_to_connection",this.description="Sends a text message to another agent using an existing active connection. Identify the target agent using their account ID (e.g., 0.0.12345) or the connection number shown in 'list_connections'. Return back the reply from the target agent if possible",this.specificInputSchema=d,this.requiresMultipleTransactions=!0,this.neverScheduleThisTool=!0}async callBuilderMethod(e,t){const n=e;await n.sendMessageToConnection({targetIdentifier:t.targetIdentifier,message:t.message,disableMonitoring:t.disableMonitoring})}}const g=r.z.object({targetAccountId:r.z.string().describe("The Hedera account ID (e.g., 0.0.12345) of the agent you want to connect with."),disableMonitor:r.z.boolean().optional().describe("If true, does not wait for connection confirmation. Returns immediately after sending the request."),memo:r.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 h extends s{constructor(e){super(e),this.name="initiate_connection",this.description="Actively STARTS a NEW HCS-10 connection TO a specific target agent identified by their account ID. Requires the targetAccountId parameter. Use this ONLY to INITIATE an OUTGOING connection request.",this.specificInputSchema=g,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const n=e,o={targetAccountId:t.targetAccountId};void 0!==t.disableMonitor&&(o.disableMonitor=t.disableMonitor),void 0!==t.memo&&(o.memo=t.memo),await n.initiateConnection(o)}}const p=r.z.object({includeDetails:r.z.boolean().optional().describe("Whether to include detailed information about each connection"),showPending:r.z.boolean().optional().describe("Whether to include pending connection requests")});class f extends a{constructor(e){super(e),this.name="list_connections",this.description="Lists the currently active HCS-10 connections with detailed information. Shows connection status, agent details, and recent activity. Use this to get a comprehensive view of all active connections.",this.specificInputSchema=p}async executeQuery(e){const t=this.hcs10Builder,n={};void 0!==e.includeDetails&&(n.includeDetails=e.includeDetails),void 0!==e.showPending&&(n.showPending=e.showPending),await t.listConnections(n);const o=await t.execute();if(o.success&&"rawResult"in o&&o.rawResult){const e=o.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Connections listed"}}return o}}const m=r.z.object({targetIdentifier:r.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:r.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:r.z.number().int().positive().optional().describe("When fetchLatest is true, specifies how many of the most recent messages to retrieve. Defaults to 1.")});class I extends a{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=m}async executeQuery({targetIdentifier:e,fetchLatest:t,lastMessagesCount:n}){const o=this.hcs10Builder;await o.checkMessages({targetIdentifier:e,fetchLatest:t,lastMessagesCount:n||1});const i=await o.execute();if(i.success&&"rawResult"in i&&i.rawResult){const e=i.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Messages checked"}}return i}}const w=r.z.object({accountId:r.z.string().optional().describe("Optional: Filter registrations by a specific Hedera account ID (e.g., 0.0.12345)."),tags:r.z.array(r.z.nativeEnum(t.AIAgentCapability)).optional().describe("Optional: Filter registrations by a list of tags (API filter only).")});class b extends a{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. Returns basic registration info.",this.specificInputSchema=w}async executeQuery({accountId:e,tags:t}){const n=this.hcs10Builder,o={};e&&(o.accountId=e),t&&(o.tags=t),await n.findRegistrations(o);const i=await n.execute();if(i.success&&"rawResult"in i&&i.rawResult){const e=i.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Registrations searched"}}return i}}const y=r.z.object({acceptAll:r.z.boolean().optional().describe("Whether to automatically accept all incoming connection requests. Default is false."),targetAccountId:r.z.string().optional().describe("If provided, only accept connection requests from this specific account ID."),hbarFees:r.z.array(r.z.object({amount:r.z.number(),collectorAccount:r.z.string().optional()})).optional().describe("Array of HBAR fee amounts to charge per message (with optional collector accounts)."),tokenFees:r.z.array(r.z.object({amount:r.z.number(),tokenId:r.z.string(),collectorAccount:r.z.string().optional()})).optional().describe("Array of token fee amounts and IDs to charge per message (with optional collector accounts)."),exemptAccountIds:r.z.array(r.z.string()).optional().describe("Array of account IDs to exempt from ALL fees set in this request."),monitorDurationSeconds:r.z.number().optional().describe("How long to monitor for incoming requests in seconds. Default is 120."),defaultCollectorAccount:r.z.string().optional().describe("Default account to collect fees if not specified at the fee level. Defaults to the agent account.")});class C extends s{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=y,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const n=e;await n.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 v=r.z.object({action:r.z.enum(["list","view","reject"]).describe("The action to perform: list all requests, view details of a specific request, or reject a request"),requestKey:r.z.string().optional().describe("The unique request key to view or reject (required for view and reject actions)")});class A extends a{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=v}async executeQuery({action:e,requestKey:t}){const n=this.hcs10Builder,o={action:e};void 0!==t&&(o.requestKey=t),await n.manageConnectionRequests(o);const i=await n.execute();return"rawResult"in i?i.rawResult:i}}const T=r.z.object({requestKey:r.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:r.z.number().optional().describe("Optional HBAR fee amount to charge the connecting agent per message on the new connection topic."),exemptAccountIds:r.z.array(r.z.string()).optional().describe("Optional list of account IDs to exempt from any configured fees on the new connection topic.")});class q extends s{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=T,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const n=e;await n.acceptConnection({requestKey:t.requestKey,hbarFee:t.hbarFee,exemptAccountIds:t.exemptAccountIds})}}const R=r.z.object({accountId:r.z.string().describe("The Hedera account ID of the agent whose profile you want to retrieve (e.g., 0.0.12345)."),disableCache:r.z.boolean().optional().describe("Optional: Force refresh from the network instead of using cache.")});class S extends a{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=R}async executeQuery({accountId:e,disableCache:t}){const n=this.hcs10Builder,o={accountId:e};void 0!==t&&(o.disableCache=t),await n.retrieveProfile(o);const i=await n.execute();if(i.success&&"rawResult"in i&&i.rawResult){const e=i.rawResult;return{success:!0,data:e.profileDetails||"Profile retrieved",rawProfile:e.rawProfile}}return i}}const $=r.z.object({});class M extends a{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}}const E=o.join(process.cwd(),".env");class P{constructor(e){this.currentAgent=null,this.connectionMessageTimestamps={},this.connectionsManager=null,this.defaultEnvFilePath=e?.defaultEnvFilePath,this.defaultPrefix=e?.defaultPrefix??"TODD";const n=e?.disableLogging||"true"===process.env.DISABLE_LOGGING;this.logger=new t.Logger({module:"OpenConvaiState",silent:n}),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(),n=parseInt(e)-1;if(!isNaN(n)&&n>=0&&n<t.length)return t[n];const o=this.connectionsManager.getConnectionByTopicId(e);if(o)return this.convertToActiveConnection(o);const i=this.connectionsManager.getConnectionByAccountId(e);return i?this.convertToActiveConnection(i):void 0}getLastTimestamp(e){return this.connectionMessageTimestamps[e]||0}updateTimestamp(e,t){if(!(e in this.connectionMessageTimestamps))return void(this.connectionMessageTimestamps[e]=t);t>this.connectionMessageTimestamps[e]&&(this.connectionMessageTimestamps[e]=t)}initializeTimestampIfNeeded(e){e in this.connectionMessageTimestamps||(this.connectionMessageTimestamps[e]=1e6*Date.now())}convertConnectionStatus(e){switch(e){case"pending":return"pending";case"established":default:return"established";case"needs confirmation":return"needs_confirmation"}}convertToActiveConnection(e){return{targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName||`Agent ${e.targetAccountId}`,targetInboundTopicId:e.targetInboundTopicId||"",connectionTopicId:e.connectionTopicId,status:this.convertToStateStatus(e.status),created:e.created,lastActivity:e.lastActivity,isPending:e.isPending,needsConfirmation:e.needsConfirmation,profileInfo:e.profileInfo,connectionRequestId:e.connectionRequestId}}convertToStateStatus(e){switch(e){case"pending":return"pending";case"established":case"closed":return"established";case"needs_confirmation":return"needs confirmation";default:return"unknown"}}async persistAgentData(e,t){if(t?.type&&"env-file"!==t.type)throw new Error(`Unsupported persistence type: ${t.type}. Only 'env-file' is supported.`);const o=t?.envFilePath||this.defaultEnvFilePath||process.env.ENV_FILE_PATH||".env",i=t?.prefix||this.defaultPrefix;if(!e.accountId||!e.inboundTopicId||!e.outboundTopicId)throw new Error("Agent data incomplete, cannot persist to environment");const r={[`${i}_ACCOUNT_ID`]:e.accountId,[`${i}_INBOUND_TOPIC_ID`]:e.inboundTopicId,[`${i}_OUTBOUND_TOPIC_ID`]:e.outboundTopicId};e.privateKey&&(r[`${i}_PRIVATE_KEY`]=e.privateKey),e.profileTopicId&&(r[`${i}_PROFILE_TOPIC_ID`]=e.profileTopicId),await async function(e,t){let o="";n.existsSync(e)&&(o=n.readFileSync(e,"utf8"));const i=[...o.split("\n")];for(const[n,r]of Object.entries(t)){const e=i.findIndex(e=>e.startsWith(`${n}=`));-1!==e?i[e]=`${n}=${r}`:i.push(`${n}=${r}`)}n.writeFileSync(e,i.join("\n"))}(o,r)}}const x="ConnectionsManager not initialized";class N extends e.BaseServiceBuilder{constructor(e,n,o){super(e),this.stateManager=n,this.useEncryption=o?.useEncryption||!1,this.guardedRegistryBaseUrl=o?.registryUrl||"";const i=this.hederaKit.client.network;this.network=i.toString().includes("mainnet")?"mainnet":"testnet";const r=this.hederaKit.signer.getAccountId().toString(),s=this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"";this.sdkLogger=new t.Logger({module:"HCS10Builder",level:o?.logLevel||"info"}),this.standardClient=new t.HCS10Client({network:this.network,operatorId:r,operatorPrivateKey:s,guardedRegistryBaseUrl:this.guardedRegistryBaseUrl,logLevel:o?.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}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 n=`Failed to get inbound topic ID for operator ${t}.`;throw e instanceof Error&&e.message.includes("does not have a valid HCS-11 memo")?n+=` The account profile may not exist or is invalid. Please ensure this operator account (${t}) is registered as an HCS-10 agent. You might need to register it first (e.g., using the 'register_agent' tool or SDK function).`:e instanceof Error?n+=` Reason: ${e.message}`:n+=` Unexpected error: ${String(e)}`,new Error(n)}}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,n,o){try{const i=await this.standardClient.handleConnectionRequest(e,t,n,o);return i&&i.connectionTopicId&&"object"==typeof i.connectionTopicId&&"toString"in i.connectionTopicId&&(i.connectionTopicId=i.connectionTopicId.toString()),i}catch(i){throw this.logger.error(`Error handling connection request #${n} for topic ${e}:`,i),new Error(`Failed to handle connection request: ${i instanceof Error?i.message:String(i)}`)}}async sendMessage(e,t,n){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 o=await this.standardClient.sendMessage(e,t,n,void 0);return{sequenceNumber:o.topicSequenceNumber?.toNumber(),receipt:o,transactionId:"transactionId"in o?o.transactionId?.toString():void 0}}catch(o){throw this.logger.error(`Error sending message to topic ${e}:`,o),new Error(`Failed to send message: ${o instanceof Error?o.message:String(o)}`)}}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 i.get(e,{responseType:"arraybuffer"}),n=globalThis.Buffer.from(t.data),r=new URL(e).pathname;return{buffer:n,filename:o.basename(r)||"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:o.basename(e)}}}if(e.url){this.logger.info(`Loading profile picture from URL: ${e.url}`);const t=await i.get(e.url,{responseType:"arraybuffer"}),n=globalThis.Buffer.from(t.data);return{buffer:n,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||o.basename(e.path)}}return null}catch(t){return this.logger.error("Failed to load profile picture:",t),null}}async createAndRegisterAgent(e){const n=(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&&n.setAlias(e.alias),e.creator&&n.setCreator(e.creator),e?.feeConfig&&(n.setInboundTopicType(t.InboundTopicType.FEE_BASED),n.setFeeConfig(e.feeConfig)),e.existingProfilePictureTopicId?n.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)`),n.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])=>{n.addSocial(e,t)}),e.properties&&Object.entries(e.properties).forEach(([e,t])=>{n.addProperty(e,t)});try{const t=Boolean(e?.feeConfig);return await this.standardClient.createAndRegisterAgent(n,{initialBalance:t?50:10})}catch(o){throw this.logger.error("Error during agent creation/registration:",o),new Error(`Failed to create/register agent: ${o instanceof Error?o.message:String(o)}`)}}async 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 o={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 n=new t.FeeConfigBuilder({network:this.network,logger:this.sdkLogger}),{accountId:i}=this.getAccountAndSigner();if(!i)throw new Error("Could not determine account ID for fee collection.");this.addNote(`Setting the operator account (${i}) as the fee collector since no specific collector was provided.`);const r=e.exemptAccountIds?.filter(e=>e!==i&&e.startsWith("0.0"))||[];o.feeConfig=n.addHbarFee(e.hbarFee,i,r)}const i=await this.createAndRegisterAgent(o);this.executeResult={success:!0,transactionId:i.transactionId,receipt:void 0,scheduleId:void 0,rawResult:{...i,name:e.name,accountId:i?.metadata?.accountId||i.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 n=t.topicInfo.inboundTopic;let o;void 0!==e.memo?o=e.memo:(o=e.disableMonitor?"false":"true",this.addNote(`No custom memo was provided. Using default memo '${o}' based on monitoring preference.`)),e.disableMonitor||this.addNote("Monitoring will be enabled for this connection request as disableMonitor was not specified.");const i=await this.submitConnectionRequest(n,o);this.executeResult={success:!0,transactionId:"transactionId"in i?i.transactionId?.toString():void 0,receipt:i,scheduleId:void 0,rawResult:{targetAccountId:e.targetAccountId,targetInboundTopicId:n,connectionRequestSent:!0,monitoringEnabled:!e.disableMonitor,...i}}}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 o=this.stateManager?.getCurrentAgent();if(!o)throw new Error("Cannot accept connection request. No agent is currently active. Please register or select an agent first.");const i=this.stateManager?.getConnectionsManager();if(!i)throw new Error(x);await i.fetchConnectionData(o.accountId);const r=[...i.getPendingRequests(),...i.getConnectionsNeedingConfirmation()].find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!r)throw new Error(`Request with key ${e.requestKey} not found or no longer pending.`);if(!r.needsConfirmation||!r.inboundRequestId)throw new Error(`Request with key ${e.requestKey} is not an inbound request that can be accepted.`);const s=r.targetAccountId,a=r.inboundRequestId;let c;if(e.hbarFee&&e.hbarFee>0){const n=new t.FeeConfigBuilder({network:this.network,logger:this.sdkLogger}),{accountId:o}=this.getAccountAndSigner();if(!o)throw new Error("Could not determine account ID for fee collection.");this.addNote(`Setting the operator account (${o}) as the fee collector since no specific collector was provided.`);const i=e.exemptAccountIds?.filter(e=>e!==o&&e.startsWith("0.0"))||[];c=n.addHbarFee(e.hbarFee,o,i)}const u=await this.getInboundTopicId(),d=await this.handleConnectionRequest(u,s,a,c);let l=d?.connectionTopicId;if(l&&"object"==typeof l&&"toString"in l&&(l=l?.toString()),!l||"string"!=typeof l)throw new Error(`Failed to create connection topic. Got: ${JSON.stringify(l)}`);if(this.stateManager){const e=r.targetAgentName||`Agent ${s}`;r.targetAgentName||this.addNote(`No agent name was provided in the connection request, using default name 'Agent ${s}'.`);let t=r.targetInboundTopicId||"";if(!t)try{const e=await this.getAgentProfile(s);e.success&&e.topicInfo?.inboundTopic&&(t=e.topicInfo.inboundTopic)}catch(n){this.logger.warn(`Could not fetch profile for ${s}:`,n)}const o={connectionId:`conn-${Date.now()}`,targetAccountId:s,targetAgentName:e,targetInboundTopicId:t,connectionTopicId:l,status:"established",created:new Date};this.stateManager.addActiveConnection(o),i.markConnectionRequestProcessed(r.targetInboundTopicId||"",a)}this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{targetAccountId:s,connectionTopicId:l,feeConfigured:!!e.hbarFee,hbarFee:e.hbarFee||0,confirmationResult:d}}}catch(o){throw this.logger.error("Failed to accept connection:",o),o}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 n;if(e.targetIdentifier.includes("@")){const t=e.targetIdentifier.split("@");if(2===t.length){const o=t[1];n=this.stateManager.getConnectionByIdentifier(o),n||this.addNote(`Could not find connection using request key '${e.targetIdentifier}', extracted account ID '${o}'.`)}}if(n||(n=this.stateManager.getConnectionByIdentifier(e.targetIdentifier)),!n){const t=this.stateManager.listConnections().map(e=>`${e.targetAccountId} (${e.connectionTopicId})`);throw new Error(`Connection not found for identifier: ${e.targetIdentifier}. Available connections: ${t.join(", ")||"none"}. Use 'list_connections' to see details.`)}let o=n.connectionTopicId;if(o&&"object"==typeof o&&"toString"in o&&(o=o?.toString()),!o||"string"!=typeof o)throw new Error(`Invalid connection topic ID for ${n.targetAccountId}: ${JSON.stringify(o)} (type: ${typeof o})`);const i=n.targetAgentName,r=`${t.inboundTopicId}@${t.accountId}`,s=await this.sendMessage(o,e.message,`Agent message from ${t.name}`);if(!s.sequenceNumber)throw new Error("Failed to send message");let a=null;e.disableMonitoring?this.addNote("Message sent successfully. Response monitoring was disabled."):a=await this.monitorResponses(o,r,s.sequenceNumber),this.executeResult={success:!0,transactionId:s.transactionId,receipt:s.receipt,scheduleId:void 0,rawResult:{targetAgentName:i,targetAccountId:n.targetAccountId,connectionTopicId:o,sequenceNumber:s.sequenceNumber,reply:a,monitoringEnabled:!e.disableMonitoring,message:e.message,messageResult:s}}}catch(t){throw this.logger.error("Failed to send message to connection:",t),t}return this}async monitorResponses(e,t,n){let o=0;for(;o<30;){try{const o=await this.getMessageStream(e);for(const e of o.messages){if(e.sequence_number<n||e.operator_id===t)continue;return await this.getMessageContent(e.data||"")}}catch(i){this.logger.error(`Error monitoring responses: ${i}`)}await new Promise(e=>setTimeout(e,4e3)),o++}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:n=!1,targetAccountId:o,monitorDurationSeconds:i=120,hbarFees:r=[],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 u=await this.getInboundTopicId(),d=Date.now()+1e3*i;let l=0,g=0;const h=new Set;for(;Date.now()<d;){try{const e=(await this.getMessages(u)).messages.filter(e=>"connection_request"===e.op&&"number"==typeof e.sequence_number);for(const i of e){const e=i.sequence_number;if(!e||h.has(e))continue;const d=i.operator_id?.split("@")[1];if(d)if(l++,o&&d!==o)this.logger.info(`Skipping request from ${d} (not target account)`);else if(n||o===d){let n;if(this.logger.info(`Accepting connection request from ${d}`),r.length>0||s.length>0){const e=new t.FeeConfigBuilder({network:this.network,logger:this.sdkLogger});for(const t of r){const n=t.collectorAccount||c||this.getOperatorId();e.addHbarFee(t.amount,n,a)}for(const t of s){const n=t.collectorAccount||c||this.getOperatorId();e.addTokenFee(t.amount,t.tokenId,n,void 0,a)}n=e}await this.handleConnectionRequest(u,d,e,n),h.add(e),g++}}}catch(p){this.logger.error("Error during connection monitoring:",p)}await new Promise(e=>setTimeout(e,3e3))}return this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{connectionRequestsFound:l,acceptedConnections:g,monitorDurationSeconds:i,processedRequestIds:Array.from(h)}},this.addNote(`Monitoring completed. Found ${l} 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(x);try{const{accountId:n}=this.getAccountAndSigner();await t.fetchConnectionData(n);const o=t.getPendingRequests(),i=t.getConnectionsNeedingConfirmation(),r=[...o,...i];switch(e.action){case"list":this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{requests:r.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=r.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 n=r.find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!n)throw new Error(`Request with key ${e.requestKey} not found`);n.inboundRequestId?t.markConnectionRequestProcessed(n.targetInboundTopicId||"",n.inboundRequestId):n.connectionRequestId&&t.markConnectionRequestProcessed(n.originTopicId||"",n.connectionRequestId),this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{rejectedRequest:{requestKey:e.requestKey,targetAccountId:n.targetAccountId,targetAgentName:n.targetAgentName||`Agent ${n.targetAccountId}`}}};break}}}catch(n){throw this.logger.error("Failed to manage connection requests:",n),n}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,n=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 o=e.filter(e=>"established"===e.status),i=e.filter(e=>e.isPending),r=e.filter(e=>e.needsConfirmation);let s="";o.length>0&&(s+=`🟢 Active Connections (${o.length}):\n`,o.forEach((e,n)=>{s+=this.formatConnection(e,n,t)}),s+="\n"),n&&r.length>0&&(s+=`🟠 Connections Needing Confirmation (${r.length}):\n`,r.forEach((e,n)=>{s+=this.formatConnection(e,n,t)}),s+="\n"),n&&i.length>0&&(s+=`⚪ Pending Connection Requests (${i.length}):\n`,i.forEach((e,n)=>{s+=this.formatConnection(e,n,t)})),this.executeResult={success:!0,rawResult:{connections:e,formattedOutput:s.trim(),activeCount:o.length,pendingCount:i.length,needsConfirmationCount:r.length}}}catch(o){this.logger.error("Failed to list connections:",o),this.executeResult={success:!1,error:`Failed to list connections: ${o instanceof Error?o.message:String(o)}`}}return this}formatConnection(e,t,n){const o=e;let i=`${t+1}. ${o.profileInfo?.display_name||o.targetAgentName||"Unknown Agent"} (${o.targetAccountId})\n`;i+=` Topic: ${o.isPending?"(Pending Request)":o.connectionTopicId}\n`;if(i+=` Status: ${o.status||"unknown"}\n`,n){if(o.profileInfo?.bio&&(i+=` Bio: ${o.profileInfo.bio.substring(0,100)}${o.profileInfo.bio.length>100?"...":""}\n`),o.created){i+=` ${o.isPending?"Request sent":"Connection established"}: ${o.created.toLocaleString()}\n`}o.lastActivity&&(i+=` Last activity: ${o.lastActivity.toLocaleString()}\n`)}return i}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(x),this.stateManager.listConnections();const n=await t.fetchConnectionData(e);for(const o of n)this.stateManager.addActiveConnection(o);return n}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 n=t.connectionTopicId||"";if(!n||!n.match(/^\d+\.\d+\.\d+$/))return this.logger.error(`Invalid connection topic ID format: ${n}`),this.executeResult={success:!1,error:`Invalid connection topic ID format: ${n}. Expected format: 0.0.XXXXX`},this;const o=t.targetAgentName,i=this.stateManager.getLastTimestamp(n);this.logger.info(`Checking messages for connection with ${o} (${t.targetAccountId}) on topic ${n} (fetchLatest: ${e.fetchLatest}, lastCount: ${e.lastMessagesCount}, since: ${i})`);try{const t=(await this.getMessages(n)).messages;if(!t||0===t.length)return this.executeResult={success:!0,rawResult:{messages:[],message:`No messages found on connection topic ${n}.`}},this;let s=[],a=i;const c=!0===e.fetchLatest;if(c){this.logger.info("Fetching latest messages regardless of timestamp.");const n=e.lastMessagesCount??1;s=t.slice(-n)}else this.logger.info(`Filtering for messages newer than ${i}`),s=t.filter(e=>1e6*e.timestamp>i),s.length>0&&(a=s.reduce((e,t)=>Math.max(e,1e6*t.timestamp),i));if(0===s.length){const e=c?`Could not retrieve the latest message(s). No messages found on topic ${n}.`:`No new messages found for connection with ${o} since last check.`;return this.executeResult={success:!0,rawResult:{messages:[],message:e}},this}this.logger.info(`Processing ${s.length} message(s).`);let u=c?`Latest message(s) from ${o}:\n`:`New messages from ${o}:\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 n=t;try{const e=JSON.parse(t||"{}");if("hcs-10"===e.p&&"message"===e.op&&e.data){n=`[${e.operator_id||"unknown_sender"}]: ${e.data}`}else n=t}catch{n=t}u+=`\n[${new Date(e.timestamp).toLocaleString()}] (Seq: ${e.sequence_number})\n${n}\n`,d.push({timestamp:e.timestamp,sequenceNumber:e.sequence_number,content:n,raw:e})}catch(r){const t=`Error processing message (Seq: ${e.sequence_number}): ${r instanceof Error?r.message:String(r)}`;this.logger.error(t),u+=`\n[Error processing message Seq: ${e.sequence_number}]\n`}}!c&&a>i&&(this.logger.debug(`Updating timestamp for topic ${n} to ${a}`),this.stateManager.updateTimestamp(n,a)),this.executeResult={success:!0,rawResult:{messages:d,formattedOutput:u.trim(),targetAgentName:o,connectionTopicId:n}}}catch(r){this.logger.error(`Failed to check messages for topic ${n}: ${r}`),this.executeResult={success:!1,error:`Error checking messages for ${o}: ${r instanceof Error?r.message:String(r)}`}}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 n=await this.standardClient.findRegistrations(t);if(!n.success||n.error)return this.executeResult={success:!1,error:`Error finding registrations: ${n.error||"Unknown error"}`},this;if(!n.registrations||0===n.registrations.length)return this.executeResult={success:!0,rawResult:{registrations:[],message:"No registrations found matching the criteria."}},this;const o=n.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:n.registrations,formattedOutput:`Found ${n.registrations.length} registration(s):\\n${o}`}}}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 n=t.profile,o=t.topicInfo;let i=`Profile for ${e.accountId}:\n`;i+=`Name: ${n.name||"Unknown"}\n`,i+=`Bio: ${n.bio||"No bio provided"}\n`,i+=`Type: ${n.type||"Unknown"}\n`,i+=`Model: ${n.model||"Unknown"}\n`,n.capabilities&&n.capabilities.length>0?i+=`Capabilities: ${n.capabilities.join(", ")}\n`:i+="Capabilities: None listed\n",o&&(i+=`Inbound Topic: ${o.inboundTopic||"Unknown"}\n`,i+=`Outbound Topic: ${o.outboundTopic||"Unknown"}\n`,i+=`Profile Topic: ${o.profileTopicId||"Unknown"}\n`),n.social&&Object.keys(n.social).length>0&&(i+=`Social: ${Object.entries(n.social).map(([e,t])=>`${e}: ${t}`).join(", ")}\n`),n.properties&&Object.keys(n.properties).length>0&&(i+=`Properties: ${JSON.stringify(n.properties)}\n`),this.executeResult={success:!0,rawResult:{profileDetails:i,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 k extends e.BasePlugin{constructor(){super(...arguments),this.id="hedera-hbar-price",this.name="Hedera HBAR Price Plugin",this.description="Provides tools to interact with Hedera network data, specifically HBAR price.",this.version="1.0.0",this.author="Hashgraph Online",this.tools=[]}async initialize(e){await super.initialize(e),this.initializeTools()}initializeTools(){this.tools=[new e.HederaGetHbarPriceTool({hederaKit:this.context.config.hederaKit,logger:this.context.logger})]}getTools(){return this.tools}}Object.defineProperty(exports,"BasePlugin",{enumerable:!0,get:()=>e.BasePlugin}),Object.defineProperty(exports,"GetHbarPriceTool",{enumerable:!0,get:()=>e.HederaGetHbarPriceTool}),Object.defineProperty(exports,"PluginRegistry",{enumerable:!0,get:()=>e.PluginRegistry}),exports.AcceptConnectionRequestTool=q,exports.BaseHCS10QueryTool=a,exports.BaseHCS10TransactionTool=s,exports.CheckMessagesTool=I,exports.ConnectionMonitorTool=C,exports.FindRegistrationsTool=b,exports.HCS10Builder=N,exports.HCS10Client=class{constructor(e,n,o,i){this.standardClient=new t.HCS10Client({network:o,operatorId:e,operatorPrivateKey:n,guardedRegistryBaseUrl:i?.registryUrl,logLevel:i?.logLevel}),this.guardedRegistryBaseUrl=i?.registryUrl||"",this.useEncryption=i?.useEncryption||!1;const r="true"===process.env.DISABLE_LOGGING;this.logger=new t.Logger({level:i?.logLevel||"info",silent:r})}getOperatorId(){const e=this.standardClient.getClient().operatorAccountId;if(!e)throw new Error("Operator Account ID not configured in standard client.");return e.toString()}getNetwork(){return this.standardClient.getNetwork()}async handleConnectionRequest(e,t,n,o){try{return await this.standardClient.handleConnectionRequest(e,t,n,o)}catch(i){throw this.logger.error(`Error handling connection request #${n} for topic ${e}:`,i),new Error(`Failed to handle connection request: ${i instanceof Error?i.message:String(i)}`)}}async getAgentProfile(e){return this.standardClient.retrieveProfile(e)}async submitConnectionRequest(e,t){return this.standardClient.submitConnectionRequest(e,t)}async waitForConnectionConfirmation(e,t,n=60,o=2e3){return this.standardClient.waitForConnectionConfirmation(e,t,n,o)}async createAndRegisterAgent(e){const n=(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&&(n.setInboundTopicType(t.InboundTopicType.FEE_BASED),n.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)`),n.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])=>{n.addSocial(e,t)}),e.properties&&Object.entries(e.properties).forEach(([e,t])=>{n.addProperty(e,t)});try{const t=Boolean(e?.feeConfig),o=await this.standardClient.createAndRegisterAgent(n,{initialBalance:t?50:void 0});return o?.metadata?.inboundTopicId&&o?.metadata?.outboundTopicId&&(this.agentChannels={inboundTopicId:o.metadata.inboundTopicId,outboundTopicId:o.metadata.outboundTopicId}),o}catch(o){throw this.logger.error("Error during agent creation/registration:",o),new Error(`Failed to create/register agent: ${o instanceof Error?o.message:String(o)}`)}}async sendMessage(e,t,n,o){this.useEncryption;try{const i=await this.standardClient.sendMessage(e,t,n,o);return i.topicSequenceNumber?.toNumber()}catch(i){throw this.logger.error(`Error sending message to topic ${e}:`,i),new Error(`Failed to send message: ${i instanceof Error?i.message:String(i)}`)}}async getMessages(e){try{const t=(await this.standardClient.getMessages(e)).messages.map(e=>{const t=e?.created?.getTime()||0;return{...e,timestamp:t,data:e.data,sequence_number:e.sequence_number}});return t.sort((e,t)=>e.timestamp-t.timestamp),{messages:t}}catch(t){return this.logger.error(`Error getting messages from topic ${e}:`,t),{messages:[]}}}async getMessageStream(e){return this.standardClient.getMessageStream(e)}async getMessageContent(e){try{return await this.standardClient.getMessageContent(e)}catch(t){throw this.logger.error(`Error retrieving message content for: ${e}`,t),new Error(`Failed to retrieve message content: ${t instanceof Error?t.message:String(t)}`)}}async getInboundTopicId(){try{const e=this.getOperatorId();this.logger.info(`[HCS10Client] Retrieving profile for operator ${e} to find inbound topic...`);const t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.inboundTopic)return this.logger.info(`[HCS10Client] Found inbound topic for operator ${e}: ${t.topicInfo.inboundTopic}`),t.topicInfo.inboundTopic;throw new Error(`Could not retrieve inbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}catch(e){this.logger.error(`[HCS10Client] Error fetching operator's inbound topic ID (${this.getOperatorId()}):`,e);const t=this.getOperatorId();let n=`Failed to get inbound topic ID for operator ${t}.`;throw e instanceof Error&&e.message.includes("does not have a valid HCS-11 memo")?n+=` The account profile may not exist or is invalid. Please ensure this operator account (${t}) is registered as an HCS-10 agent. You might need to register it first (e.g., using the 'register_agent' tool or SDK function).`:e instanceof Error?n+=` Reason: ${e.message}`:n+=` Unexpected error: ${String(e)}`,new Error(n)}}getAccountAndSigner(){const e=this.standardClient.getAccountAndSigner();return{accountId:e.accountId,signer:e.signer}}async getOutboundTopicId(){const e=this.getOperatorId(),t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.outboundTopic)return t.topicInfo.outboundTopic;throw new Error(`Could not retrieve outbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}setClient(e,n){return this.standardClient=new t.HCS10Client({network:this.getNetwork(),operatorId:e,operatorPrivateKey:n,guardedRegistryBaseUrl:this.guardedRegistryBaseUrl}),this.standardClient}async validateOperator(e){try{this.setClient(e.accountId,e.privateKey);return{isValid:!0,operator:{accountId:this.getOperatorId()}}}catch(t){return this.logger.error(`Validation error: ${t}`),{isValid:!1,error:t instanceof Error?t.message:String(t)}}}async initializeWithValidation(e){const t=await this.validateOperator(e);return t.isValid&&e.stateManager&&e.stateManager.initializeConnectionsManager(this.standardClient),t}},exports.HbarPricePlugin=k,exports.InitiateConnectionTool=h,exports.ListConnectionsTool=f,exports.ListUnapprovedConnectionRequestsTool=M,exports.ManageConnectionRequestsTool=A,exports.OpenConvaiState=P,exports.RegisterAgentTool=u,exports.RetrieveProfileTool=S,exports.SendMessageToConnectionTool=l,exports.initializeStandardsAgentKit=async n=>{const o=n?.clientConfig||{},i=o.operatorId||process.env.HEDERA_OPERATOR_ID,r=o.operatorKey||process.env.HEDERA_OPERATOR_KEY,s=o.network||process.env.HEDERA_NETWORK||"testnet";let a;if("mainnet"===s?a="mainnet":("testnet"===s||console.warn(`Unsupported network specified: '${s}'. Defaulting to 'testnet'.`),a="testnet"),!i||!r)throw new Error("Operator ID and private key must be provided either through options or environment variables.");const c="true"===process.env.DISABLE_LOGGING,d=t.Logger.getInstance({level:o.logLevel||"info",silent:c}),g=n?.stateManager||new P({defaultEnvFilePath:E,defaultPrefix:"TODD"});d.info("State manager initialized");const p=new e.ServerSigner(i,r,a),m=new e.HederaAgentKit(p);await m.initialize(),d.info(`HederaAgentKit initialized for ${i} on ${a}`);const w=new N(m,g,{useEncryption:o.useEncryption,registryUrl:o.registryUrl,logLevel:o.logLevel});let y,v;if(n?.monitoringClient){const t=new e.ServerSigner(i,r,a);y=new e.HederaAgentKit(t),await y.initialize(),v=new N(y,g,{useEncryption:o.useEncryption,registryUrl:o.registryUrl,logLevel:"error"}),d.info("Monitoring client initialized")}const T={};return T.registerAgentTool=new u({hederaKit:m,hcs10Builder:w,logger:void 0}),n?.createAllTools&&(T.findRegistrationsTool=new b({hederaKit:m,hcs10Builder:w,logger:void 0}),T.retrieveProfileTool=new S({hederaKit:m,hcs10Builder:w,logger:void 0}),T.initiateConnectionTool=new h({hederaKit:m,hcs10Builder:w,logger:void 0}),T.listConnectionsTool=new f({hederaKit:m,hcs10Builder:w,logger:void 0}),T.sendMessageToConnectionTool=new l({hederaKit:m,hcs10Builder:w,logger:void 0}),T.checkMessagesTool=new I({hederaKit:m,hcs10Builder:w,logger:void 0}),T.connectionMonitorTool=new C({hederaKit:y||m,hcs10Builder:v||w,logger:void 0}),T.manageConnectionRequestsTool=new A({hederaKit:m,hcs10Builder:w,logger:void 0}),T.acceptConnectionRequestTool=new q({hederaKit:m,hcs10Builder:w,logger:void 0}),T.listUnapprovedConnectionRequestsTool=new M({hederaKit:m,hcs10Builder:w,logger:void 0}),d.info("All tools initialized")),{hederaKit:m,hcs10Builder:w,monitoringHederaKit:y,monitoringHcs10Builder:v,tools:T,stateManager:g}};
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("hedera-agent-kit"),t=require("@hashgraphonline/standards-sdk"),n=require("fs"),o=require("path"),i=require("axios"),r=require("zod");class s extends e.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}class a extends e.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}const c=r.z.object({name:r.z.string().min(1).max(50).describe("A unique name for the agent (1-50 characters)"),description:r.z.string().max(500).optional().describe("Optional bio description for the agent (max 500 characters)"),alias:r.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:r.z.enum(["autonomous","manual"]).optional().describe("Agent type (default: autonomous)"),model:r.z.string().optional().describe("AI model identifier (default: agent-model-2024)"),capabilities:r.z.array(r.z.nativeEnum(t.AIAgentCapability)).optional().describe("Array of agent capabilities (default: [TEXT_GENERATION])"),creator:r.z.string().optional().describe("Creator attribution for the agent"),socials:r.z.record(r.z.enum(["twitter","github","discord","telegram","linkedin","youtube","website","x"]),r.z.string()).optional().describe('Social media links (e.g., {"twitter": "@handle", "discord": "username"})'),properties:r.z.record(r.z.unknown()).optional().describe("Custom metadata properties for the agent"),profilePicture:r.z.union([r.z.string().describe("URL or local file path to profile picture"),r.z.object({url:r.z.string().optional(),path:r.z.string().optional(),filename:r.z.string().optional()})]).optional().describe("Optional profile picture as URL, file path, or object with url/path/filename"),existingProfilePictureTopicId:r.z.string().optional().describe("Topic ID of an existing profile picture to reuse (e.g., 0.0.12345)"),initialBalance:r.z.number().positive().optional().describe("Optional initial HBAR balance for the new agent account (will create new account if provided)"),userAccountId:r.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:r.z.number().positive().optional().describe("Optional HBAR fee amount to charge per message on the inbound topic"),tokenFees:r.z.array(r.z.object({amount:r.z.number().positive(),tokenId:r.z.string()})).optional().describe("Optional token fees to charge per message"),exemptAccountIds:r.z.array(r.z.string()).optional().describe("Optional account IDs to exempt from fees"),setAsCurrent:r.z.boolean().optional().describe("Whether to set as current agent (default: true)"),persistence:r.z.object({prefix:r.z.string().optional()}).optional().describe("Optional persistence configuration")});class d extends s{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. 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=c,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const n=e;this.specificArgs=t;const o={name:t.name};if(void 0!==t.description&&(o.bio=t.description),void 0!==t.alias)o.alias=t.alias;else{const e=Date.now().toString(36);o.alias=`${t.name}${e}`}if(void 0!==t.type&&(o.type=t.type),void 0!==t.model&&(o.model=t.model),void 0!==t.capabilities&&(o.capabilities=t.capabilities),void 0!==t.creator&&(o.creator=t.creator),void 0!==t.socials&&(o.socials=t.socials),void 0!==t.properties&&(o.properties=t.properties),void 0!==t.profilePicture)if("string"==typeof t.profilePicture)o.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),o.profilePicture=e}void 0!==t.existingProfilePictureTopicId&&(o.existingProfilePictureTopicId=t.existingProfilePictureTopicId),void 0!==t.userAccountId&&(o.userAccountId=t.userAccountId),void 0!==t.hbarFee&&(o.hbarFee=t.hbarFee),void 0!==t.tokenFees&&(o.tokenFees=t.tokenFees),void 0!==t.exemptAccountIds&&(o.exemptAccountIds=t.exemptAccountIds),void 0!==t.initialBalance&&(o.initialBalance=t.initialBalance),await n.registerAgent(o)}async _call(e,t){const n=await super._call(e,t),o=!1!==this.specificArgs?.setAsCurrent;if(this.specificArgs&&o)try{const e=JSON.parse(n);e.rawResult?this._handleRegistrationResult(e.rawResult):(e.state||e.accountId||e.metadata)&&this._handleRegistrationResult(e)}catch(i){}return n}_handleRegistrationResult(e){let t=e.accountId||e.metadata?.accountId;if(!t&&e.state?.createdResources){const n=e.state.createdResources.find(e=>e.startsWith("account:"));n&&(t=n.split(":")[1])}const n=e.inboundTopicId||e.metadata?.inboundTopicId||e.state?.inboundTopicId,o=e.outboundTopicId||e.metadata?.outboundTopicId||e.state?.outboundTopicId,i=e.profileTopicId||e.metadata?.profileTopicId||e.state?.profileTopicId,r=e.privateKey||e.metadata?.privateKey;if(t&&n&&o&&this.specificArgs){const e={name:this.specificArgs.name,accountId:t,inboundTopicId:n,outboundTopicId:o,profileTopicId:i,privateKey:r},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 u=r.z.object({targetIdentifier:r.z.string().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."),message:r.z.string().describe("The text message content to send."),disableMonitoring:r.z.boolean().optional().default(!1)});class l extends s{constructor(e){super(e),this.name="send_message_to_connection",this.description="Sends a text message to another agent using an existing active connection. Identify the target agent using their account ID (e.g., 0.0.12345) or the connection number shown in 'list_connections'. Return back the reply from the target agent if possible",this.specificInputSchema=u,this.requiresMultipleTransactions=!0,this.neverScheduleThisTool=!0}async callBuilderMethod(e,t){const n=e;await n.sendMessageToConnection({targetIdentifier:t.targetIdentifier,message:t.message,disableMonitoring:t.disableMonitoring})}}const g=r.z.object({targetAccountId:r.z.string().describe("The Hedera account ID (e.g., 0.0.12345) of the agent you want to connect with."),disableMonitor:r.z.boolean().optional().describe("If true, does not wait for connection confirmation. Returns immediately after sending the request."),memo:r.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 h extends s{constructor(e){super(e),this.name="initiate_connection",this.description="Actively STARTS a NEW HCS-10 connection TO a specific target agent identified by their account ID. Requires the targetAccountId parameter. Use this ONLY to INITIATE an OUTGOING connection request.",this.specificInputSchema=g,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const n=e,o={targetAccountId:t.targetAccountId};void 0!==t.disableMonitor&&(o.disableMonitor=t.disableMonitor),void 0!==t.memo&&(o.memo=t.memo),await n.initiateConnection(o)}}const p=r.z.object({includeDetails:r.z.boolean().optional().describe("Whether to include detailed information about each connection"),showPending:r.z.boolean().optional().describe("Whether to include pending connection requests")});class f extends a{constructor(e){super(e),this.name="list_connections",this.description="Lists the currently active HCS-10 connections with detailed information. Shows connection status, agent details, and recent activity. Use this to get a comprehensive view of all active connections.",this.specificInputSchema=p}async executeQuery(e){const t=this.hcs10Builder,n={};void 0!==e.includeDetails&&(n.includeDetails=e.includeDetails),void 0!==e.showPending&&(n.showPending=e.showPending),await t.listConnections(n);const o=await t.execute();if(o.success&&"rawResult"in o&&o.rawResult){const e=o.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Connections listed"}}return o}}const m=r.z.object({targetIdentifier:r.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:r.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:r.z.number().int().positive().optional().describe("When fetchLatest is true, specifies how many of the most recent messages to retrieve. Defaults to 1.")});class I extends a{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=m}async executeQuery({targetIdentifier:e,fetchLatest:t,lastMessagesCount:n}){const o=this.hcs10Builder;await o.checkMessages({targetIdentifier:e,fetchLatest:t,lastMessagesCount:n||1});const i=await o.execute();if(i.success&&"rawResult"in i&&i.rawResult){const e=i.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Messages checked"}}return i}}const w=r.z.object({accountId:r.z.string().optional().describe("Optional: Filter registrations by a specific Hedera account ID (e.g., 0.0.12345)."),tags:r.z.array(r.z.nativeEnum(t.AIAgentCapability)).optional().describe("Optional: Filter registrations by a list of tags (API filter only).")});class b extends a{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. Returns basic registration info.",this.specificInputSchema=w}async executeQuery({accountId:e,tags:t}){const n=this.hcs10Builder,o={};e&&(o.accountId=e),t&&(o.tags=t),await n.findRegistrations(o);const i=await n.execute();if(i.success&&"rawResult"in i&&i.rawResult){const e=i.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Registrations searched"}}return i}}const y=r.z.object({acceptAll:r.z.boolean().optional().describe("Whether to automatically accept all incoming connection requests. Default is false."),targetAccountId:r.z.string().optional().describe("If provided, only accept connection requests from this specific account ID."),hbarFees:r.z.array(r.z.object({amount:r.z.number(),collectorAccount:r.z.string().optional()})).optional().describe("Array of HBAR fee amounts to charge per message (with optional collector accounts)."),tokenFees:r.z.array(r.z.object({amount:r.z.number(),tokenId:r.z.string(),collectorAccount:r.z.string().optional()})).optional().describe("Array of token fee amounts and IDs to charge per message (with optional collector accounts)."),exemptAccountIds:r.z.array(r.z.string()).optional().describe("Array of account IDs to exempt from ALL fees set in this request."),monitorDurationSeconds:r.z.number().optional().describe("How long to monitor for incoming requests in seconds. Default is 120."),defaultCollectorAccount:r.z.string().optional().describe("Default account to collect fees if not specified at the fee level. Defaults to the agent account.")});class C extends s{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=y,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const n=e;await n.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 v=r.z.object({action:r.z.enum(["list","view","reject"]).describe("The action to perform: list all requests, view details of a specific request, or reject a request"),requestKey:r.z.string().optional().describe("The unique request key to view or reject (required for view and reject actions)")});class A extends a{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=v}async executeQuery({action:e,requestKey:t}){const n=this.hcs10Builder,o={action:e};void 0!==t&&(o.requestKey=t),await n.manageConnectionRequests(o);const i=await n.execute();return"rawResult"in i?i.rawResult:i}}const T=r.z.object({requestKey:r.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:r.z.number().optional().describe("Optional HBAR fee amount to charge the connecting agent per message on the new connection topic."),exemptAccountIds:r.z.array(r.z.string()).optional().describe("Optional list of account IDs to exempt from any configured fees on the new connection topic.")});class R extends s{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=T,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const n=e;await n.acceptConnection({requestKey:t.requestKey,hbarFee:t.hbarFee,exemptAccountIds:t.exemptAccountIds})}}const q=r.z.object({accountId:r.z.string().describe("The Hedera account ID of the agent whose profile you want to retrieve (e.g., 0.0.12345)."),disableCache:r.z.boolean().optional().describe("Optional: Force refresh from the network instead of using cache.")});class S extends a{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=q}async executeQuery({accountId:e,disableCache:t}){const n=this.hcs10Builder,o={accountId:e};void 0!==t&&(o.disableCache=t),await n.retrieveProfile(o);const i=await n.execute();if(i.success&&"rawResult"in i&&i.rawResult){const e=i.rawResult;return{success:!0,data:e.profileDetails||"Profile retrieved",rawProfile:e.rawProfile}}return i}}const $=r.z.object({});class M extends a{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}}const E=o.join(process.cwd(),".env");class P{constructor(e){this.currentAgent=null,this.connectionMessageTimestamps={},this.connectionsManager=null,this.defaultEnvFilePath=e?.defaultEnvFilePath,this.defaultPrefix=e?.defaultPrefix??"TODD";const n=e?.disableLogging||"true"===process.env.DISABLE_LOGGING;this.logger=new t.Logger({module:"OpenConvaiState",silent:n}),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(),n=parseInt(e)-1;if(!isNaN(n)&&n>=0&&n<t.length)return t[n];const o=this.connectionsManager.getConnectionByTopicId(e);if(o)return this.convertToActiveConnection(o);const i=this.connectionsManager.getConnectionByAccountId(e);return i?this.convertToActiveConnection(i):void 0}getLastTimestamp(e){return this.connectionMessageTimestamps[e]||0}updateTimestamp(e,t){if(!(e in this.connectionMessageTimestamps))return void(this.connectionMessageTimestamps[e]=t);t>this.connectionMessageTimestamps[e]&&(this.connectionMessageTimestamps[e]=t)}initializeTimestampIfNeeded(e){e in this.connectionMessageTimestamps||(this.connectionMessageTimestamps[e]=1e6*Date.now())}convertConnectionStatus(e){switch(e){case"pending":return"pending";case"established":default:return"established";case"needs confirmation":return"needs_confirmation"}}convertToActiveConnection(e){return{targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName||`Agent ${e.targetAccountId}`,targetInboundTopicId:e.targetInboundTopicId||"",connectionTopicId:e.connectionTopicId,status:this.convertToStateStatus(e.status),created:e.created,lastActivity:e.lastActivity,isPending:e.isPending,needsConfirmation:e.needsConfirmation,profileInfo:e.profileInfo,connectionRequestId:e.connectionRequestId}}convertToStateStatus(e){switch(e){case"pending":return"pending";case"established":case"closed":return"established";case"needs_confirmation":return"needs confirmation";default:return"unknown"}}async persistAgentData(e,t){if(t?.type&&"env-file"!==t.type)throw new Error(`Unsupported persistence type: ${t.type}. Only 'env-file' is supported.`);const o=t?.envFilePath||this.defaultEnvFilePath||process.env.ENV_FILE_PATH||".env",i=t?.prefix||this.defaultPrefix;if(!e.accountId||!e.inboundTopicId||!e.outboundTopicId)throw new Error("Agent data incomplete, cannot persist to environment");const r={[`${i}_ACCOUNT_ID`]:e.accountId,[`${i}_INBOUND_TOPIC_ID`]:e.inboundTopicId,[`${i}_OUTBOUND_TOPIC_ID`]:e.outboundTopicId};e.privateKey&&(r[`${i}_PRIVATE_KEY`]=e.privateKey),e.profileTopicId&&(r[`${i}_PROFILE_TOPIC_ID`]=e.profileTopicId),await async function(e,t){let o="";n.existsSync(e)&&(o=n.readFileSync(e,"utf8"));const i=[...o.split("\n")];for(const[n,r]of Object.entries(t)){const e=i.findIndex(e=>e.startsWith(`${n}=`));-1!==e?i[e]=`${n}=${r}`:i.push(`${n}=${r}`)}n.writeFileSync(e,i.join("\n"))}(o,r)}}const x="ConnectionsManager not initialized";class N extends e.BaseServiceBuilder{constructor(e,n,o){super(e),this.stateManager=n,this.useEncryption=o?.useEncryption||!1,this.guardedRegistryBaseUrl=o?.registryUrl||"";const i=this.hederaKit.client.network;this.network=i.toString().includes("mainnet")?"mainnet":"testnet";const r=this.hederaKit.signer.getAccountId().toString(),s=this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"";this.sdkLogger=new t.Logger({module:"HCS10Builder",level:o?.logLevel||"info"}),this.standardClient=new t.HCS10Client({network:this.network,operatorId:r,operatorPrivateKey:s,guardedRegistryBaseUrl:this.guardedRegistryBaseUrl,logLevel:o?.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 n=`Failed to get inbound topic ID for operator ${t}.`;throw e instanceof Error&&e.message.includes("does not have a valid HCS-11 memo")?n+=` The account profile may not exist or is invalid. Please ensure this operator account (${t}) is registered as an HCS-10 agent. You might need to register it first (e.g., using the 'register_agent' tool or SDK function).`:e instanceof Error?n+=` Reason: ${e.message}`:n+=` Unexpected error: ${String(e)}`,new Error(n)}}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,n,o){try{const i=await this.standardClient.handleConnectionRequest(e,t,n,o);return i&&i.connectionTopicId&&"object"==typeof i.connectionTopicId&&"toString"in i.connectionTopicId&&(i.connectionTopicId=i.connectionTopicId.toString()),i}catch(i){throw this.logger.error(`Error handling connection request #${n} for topic ${e}:`,i),new Error(`Failed to handle connection request: ${i instanceof Error?i.message:String(i)}`)}}async sendMessage(e,t,n){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 o=await this.standardClient.sendMessage(e,t,n,void 0);return{sequenceNumber:o.topicSequenceNumber?.toNumber(),receipt:o,transactionId:"transactionId"in o?o.transactionId?.toString():void 0}}catch(o){throw this.logger.error(`Error sending message to topic ${e}:`,o),new Error(`Failed to send message: ${o instanceof Error?o.message:String(o)}`)}}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 i.get(e,{responseType:"arraybuffer"}),n=globalThis.Buffer.from(t.data),r=new URL(e).pathname;return{buffer:n,filename:o.basename(r)||"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:o.basename(e)}}}if(e.url){this.logger.info(`Loading profile picture from URL: ${e.url}`);const t=await i.get(e.url,{responseType:"arraybuffer"}),n=globalThis.Buffer.from(t.data);return{buffer:n,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||o.basename(e.path)}}return null}catch(t){return this.logger.error("Failed to load profile picture:",t),null}}async createAndRegisterAgent(e){const n=(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&&n.setAlias(e.alias),e.creator&&n.setCreator(e.creator),e?.feeConfig&&(n.setInboundTopicType(t.InboundTopicType.FEE_BASED),n.setFeeConfig(e.feeConfig)),e.existingProfilePictureTopicId?n.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)`),n.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])=>{n.addSocial(e,t)}),e.properties&&Object.entries(e.properties).forEach(([e,t])=>{n.addProperty(e,t)});try{const t=Boolean(e?.feeConfig);return await this.standardClient.createAndRegisterAgent(n,{initialBalance:t?50:10})}catch(o){throw this.logger.error("Error during agent creation/registration:",o),new Error(`Failed to create/register agent: ${o instanceof Error?o.message:String(o)}`)}}async 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 o={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 n=new t.FeeConfigBuilder({network:this.network,logger:this.sdkLogger}),{accountId:i}=this.getAccountAndSigner();if(!i)throw new Error("Could not determine account ID for fee collection.");this.addNote(`Setting the operator account (${i}) as the fee collector since no specific collector was provided.`);const r=e.exemptAccountIds?.filter(e=>e!==i&&e.startsWith("0.0"))||[];o.feeConfig=n.addHbarFee(e.hbarFee,i,r)}const i=await this.createAndRegisterAgent(o);this.executeResult={success:!0,transactionId:i.transactionId,receipt:void 0,scheduleId:void 0,rawResult:{...i,name:e.name,accountId:i?.metadata?.accountId||i.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 n=t.topicInfo.inboundTopic;let o;void 0!==e.memo?o=e.memo:(o=e.disableMonitor?"false":"true",this.addNote(`No custom memo was provided. Using default memo '${o}' based on monitoring preference.`)),e.disableMonitor||this.addNote("Monitoring will be enabled for this connection request as disableMonitor was not specified.");const i=await this.submitConnectionRequest(n,o);this.executeResult={success:!0,transactionId:"transactionId"in i?i.transactionId?.toString():void 0,receipt:i,scheduleId:void 0,rawResult:{targetAccountId:e.targetAccountId,targetInboundTopicId:n,connectionRequestSent:!0,monitoringEnabled:!e.disableMonitor,...i}}}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 o=this.stateManager?.getCurrentAgent();if(!o)throw new Error("Cannot accept connection request. No agent is currently active. Please register or select an agent first.");const i=this.stateManager?.getConnectionsManager();if(!i)throw new Error(x);await i.fetchConnectionData(o.accountId);const r=[...i.getPendingRequests(),...i.getConnectionsNeedingConfirmation()].find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!r)throw new Error(`Request with key ${e.requestKey} not found or no longer pending.`);if(!r.needsConfirmation||!r.inboundRequestId)throw new Error(`Request with key ${e.requestKey} is not an inbound request that can be accepted.`);const s=r.targetAccountId,a=r.inboundRequestId;let c;if(e.hbarFee&&e.hbarFee>0){const n=new t.FeeConfigBuilder({network:this.network,logger:this.sdkLogger}),{accountId:o}=this.getAccountAndSigner();if(!o)throw new Error("Could not determine account ID for fee collection.");this.addNote(`Setting the operator account (${o}) as the fee collector since no specific collector was provided.`);const i=e.exemptAccountIds?.filter(e=>e!==o&&e.startsWith("0.0"))||[];c=n.addHbarFee(e.hbarFee,o,i)}const d=await this.getInboundTopicId(),u=await this.handleConnectionRequest(d,s,a,c);let l=u?.connectionTopicId;if(l&&"object"==typeof l&&"toString"in l&&(l=l?.toString()),!l||"string"!=typeof l)throw new Error(`Failed to create connection topic. Got: ${JSON.stringify(l)}`);if(this.stateManager){const e=r.targetAgentName||`Agent ${s}`;r.targetAgentName||this.addNote(`No agent name was provided in the connection request, using default name 'Agent ${s}'.`);let t=r.targetInboundTopicId||"";if(!t)try{const e=await this.getAgentProfile(s);e.success&&e.topicInfo?.inboundTopic&&(t=e.topicInfo.inboundTopic)}catch(n){this.logger.warn(`Could not fetch profile for ${s}:`,n)}const o={connectionId:`conn-${Date.now()}`,targetAccountId:s,targetAgentName:e,targetInboundTopicId:t,connectionTopicId:l,status:"established",created:new Date};this.stateManager.addActiveConnection(o),i.markConnectionRequestProcessed(r.targetInboundTopicId||"",a)}this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{targetAccountId:s,connectionTopicId:l,feeConfigured:!!e.hbarFee,hbarFee:e.hbarFee||0,confirmationResult:u}}}catch(o){throw this.logger.error("Failed to accept connection:",o),o}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 n;if(e.targetIdentifier.includes("@")){const t=e.targetIdentifier.split("@");if(2===t.length){const o=t[1];n=this.stateManager.getConnectionByIdentifier(o),n||this.addNote(`Could not find connection using request key '${e.targetIdentifier}', extracted account ID '${o}'.`)}}if(n||(n=this.stateManager.getConnectionByIdentifier(e.targetIdentifier)),!n){const t=this.stateManager.listConnections().map(e=>`${e.targetAccountId} (${e.connectionTopicId})`);throw new Error(`Connection not found for identifier: ${e.targetIdentifier}. Available connections: ${t.join(", ")||"none"}. Use 'list_connections' to see details.`)}let o=n.connectionTopicId;if(o&&"object"==typeof o&&"toString"in o&&(o=o?.toString()),!o||"string"!=typeof o)throw new Error(`Invalid connection topic ID for ${n.targetAccountId}: ${JSON.stringify(o)} (type: ${typeof o})`);const i=n.targetAgentName,r=`${t.inboundTopicId}@${t.accountId}`,s=await this.sendMessage(o,e.message,`Agent message from ${t.name}`);if(!s.sequenceNumber)throw new Error("Failed to send message");let a=null;e.disableMonitoring?this.addNote("Message sent successfully. Response monitoring was disabled."):a=await this.monitorResponses(o,r,s.sequenceNumber),this.executeResult={success:!0,transactionId:s.transactionId,receipt:s.receipt,scheduleId:void 0,rawResult:{targetAgentName:i,targetAccountId:n.targetAccountId,connectionTopicId:o,sequenceNumber:s.sequenceNumber,reply:a,monitoringEnabled:!e.disableMonitoring,message:e.message,messageResult:s}}}catch(t){throw this.logger.error("Failed to send message to connection:",t),t}return this}async monitorResponses(e,t,n){let o=0;for(;o<30;){try{const o=await this.getMessageStream(e);for(const e of o.messages){if(e.sequence_number<n||e.operator_id===t)continue;return await this.getMessageContent(e.data||"")}}catch(i){this.logger.error(`Error monitoring responses: ${i}`)}await new Promise(e=>setTimeout(e,4e3)),o++}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:n=!1,targetAccountId:o,monitorDurationSeconds:i=120,hbarFees:r=[],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 d=await this.getInboundTopicId(),u=Date.now()+1e3*i;let l=0,g=0;const h=new Set;for(;Date.now()<u;){try{const e=(await this.getMessages(d)).messages.filter(e=>"connection_request"===e.op&&"number"==typeof e.sequence_number);for(const i of e){const e=i.sequence_number;if(!e||h.has(e))continue;const u=i.operator_id?.split("@")[1];if(u)if(l++,o&&u!==o)this.logger.info(`Skipping request from ${u} (not target account)`);else if(n||o===u){let n;if(this.logger.info(`Accepting connection request from ${u}`),r.length>0||s.length>0){const e=new t.FeeConfigBuilder({network:this.network,logger:this.sdkLogger});for(const t of r){const n=t.collectorAccount||c||this.getOperatorId();e.addHbarFee(t.amount,n,a)}for(const t of s){const n=t.collectorAccount||c||this.getOperatorId();e.addTokenFee(t.amount,t.tokenId,n,void 0,a)}n=e}await this.handleConnectionRequest(d,u,e,n),h.add(e),g++}}}catch(p){this.logger.error("Error during connection monitoring:",p)}await new Promise(e=>setTimeout(e,3e3))}return this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{connectionRequestsFound:l,acceptedConnections:g,monitorDurationSeconds:i,processedRequestIds:Array.from(h)}},this.addNote(`Monitoring completed. Found ${l} 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(x);try{const{accountId:n}=this.getAccountAndSigner();await t.fetchConnectionData(n);const o=t.getPendingRequests(),i=t.getConnectionsNeedingConfirmation(),r=[...o,...i];switch(e.action){case"list":this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{requests:r.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=r.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 n=r.find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!n)throw new Error(`Request with key ${e.requestKey} not found`);n.inboundRequestId?t.markConnectionRequestProcessed(n.targetInboundTopicId||"",n.inboundRequestId):n.connectionRequestId&&t.markConnectionRequestProcessed(n.originTopicId||"",n.connectionRequestId),this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{rejectedRequest:{requestKey:e.requestKey,targetAccountId:n.targetAccountId,targetAgentName:n.targetAgentName||`Agent ${n.targetAccountId}`}}};break}}}catch(n){throw this.logger.error("Failed to manage connection requests:",n),n}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,n=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 o=e.filter(e=>"established"===e.status),i=e.filter(e=>e.isPending),r=e.filter(e=>e.needsConfirmation);let s="";o.length>0&&(s+=`🟢 Active Connections (${o.length}):\n`,o.forEach((e,n)=>{s+=this.formatConnection(e,n,t)}),s+="\n"),n&&r.length>0&&(s+=`🟠 Connections Needing Confirmation (${r.length}):\n`,r.forEach((e,n)=>{s+=this.formatConnection(e,n,t)}),s+="\n"),n&&i.length>0&&(s+=`⚪ Pending Connection Requests (${i.length}):\n`,i.forEach((e,n)=>{s+=this.formatConnection(e,n,t)})),this.executeResult={success:!0,rawResult:{connections:e,formattedOutput:s.trim(),activeCount:o.length,pendingCount:i.length,needsConfirmationCount:r.length}}}catch(o){this.logger.error("Failed to list connections:",o),this.executeResult={success:!1,error:`Failed to list connections: ${o instanceof Error?o.message:String(o)}`}}return this}formatConnection(e,t,n){const o=e;let i=`${t+1}. ${o.profileInfo?.display_name||o.targetAgentName||"Unknown Agent"} (${o.targetAccountId})\n`;i+=` Topic: ${o.isPending?"(Pending Request)":o.connectionTopicId}\n`;if(i+=` Status: ${o.status||"unknown"}\n`,n){if(o.profileInfo?.bio&&(i+=` Bio: ${o.profileInfo.bio.substring(0,100)}${o.profileInfo.bio.length>100?"...":""}\n`),o.created){i+=` ${o.isPending?"Request sent":"Connection established"}: ${o.created.toLocaleString()}\n`}o.lastActivity&&(i+=` Last activity: ${o.lastActivity.toLocaleString()}\n`)}return i}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(x),this.stateManager.listConnections();const n=await t.fetchConnectionData(e);for(const o of n)this.stateManager.addActiveConnection(o);return n}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 n=t.connectionTopicId||"";if(!n||!n.match(/^\d+\.\d+\.\d+$/))return this.logger.error(`Invalid connection topic ID format: ${n}`),this.executeResult={success:!1,error:`Invalid connection topic ID format: ${n}. Expected format: 0.0.XXXXX`},this;const o=t.targetAgentName,i=this.stateManager.getLastTimestamp(n);this.logger.info(`Checking messages for connection with ${o} (${t.targetAccountId}) on topic ${n} (fetchLatest: ${e.fetchLatest}, lastCount: ${e.lastMessagesCount}, since: ${i})`);try{const t=(await this.getMessages(n)).messages;if(!t||0===t.length)return this.executeResult={success:!0,rawResult:{messages:[],message:`No messages found on connection topic ${n}.`}},this;let s=[],a=i;const c=!0===e.fetchLatest;if(c){this.logger.info("Fetching latest messages regardless of timestamp.");const n=e.lastMessagesCount??1;s=t.slice(-n)}else this.logger.info(`Filtering for messages newer than ${i}`),s=t.filter(e=>1e6*e.timestamp>i),s.length>0&&(a=s.reduce((e,t)=>Math.max(e,1e6*t.timestamp),i));if(0===s.length){const e=c?`Could not retrieve the latest message(s). No messages found on topic ${n}.`:`No new messages found for connection with ${o} since last check.`;return this.executeResult={success:!0,rawResult:{messages:[],message:e}},this}this.logger.info(`Processing ${s.length} message(s).`);let d=c?`Latest message(s) from ${o}:\n`:`New messages from ${o}:\n`;const u=[];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 n=t;try{const e=JSON.parse(t||"{}");if("hcs-10"===e.p&&"message"===e.op&&e.data){n=`[${e.operator_id||"unknown_sender"}]: ${e.data}`}else n=t}catch{n=t}d+=`\n[${new Date(e.timestamp).toLocaleString()}] (Seq: ${e.sequence_number})\n${n}\n`,u.push({timestamp:e.timestamp,sequenceNumber:e.sequence_number,content:n,raw:e})}catch(r){const t=`Error processing message (Seq: ${e.sequence_number}): ${r instanceof Error?r.message:String(r)}`;this.logger.error(t),d+=`\n[Error processing message Seq: ${e.sequence_number}]\n`}}!c&&a>i&&(this.logger.debug(`Updating timestamp for topic ${n} to ${a}`),this.stateManager.updateTimestamp(n,a)),this.executeResult={success:!0,rawResult:{messages:u,formattedOutput:d.trim(),targetAgentName:o,connectionTopicId:n}}}catch(r){this.logger.error(`Failed to check messages for topic ${n}: ${r}`),this.executeResult={success:!1,error:`Error checking messages for ${o}: ${r instanceof Error?r.message:String(r)}`}}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 n=await this.standardClient.findRegistrations(t);if(!n.success||n.error)return this.executeResult={success:!1,error:`Error finding registrations: ${n.error||"Unknown error"}`},this;if(!n.registrations||0===n.registrations.length)return this.executeResult={success:!0,rawResult:{registrations:[],message:"No registrations found matching the criteria."}},this;const o=n.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:n.registrations,formattedOutput:`Found ${n.registrations.length} registration(s):\\n${o}`}}}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 n=t.profile,o=t.topicInfo;let i=`Profile for ${e.accountId}:\n`;i+=`Name: ${n.name||"Unknown"}\n`,i+=`Bio: ${n.bio||"No bio provided"}\n`,i+=`Type: ${n.type||"Unknown"}\n`,i+=`Model: ${n.model||"Unknown"}\n`,n.capabilities&&n.capabilities.length>0?i+=`Capabilities: ${n.capabilities.join(", ")}\n`:i+="Capabilities: None listed\n",o&&(i+=`Inbound Topic: ${o.inboundTopic||"Unknown"}\n`,i+=`Outbound Topic: ${o.outboundTopic||"Unknown"}\n`,i+=`Profile Topic: ${o.profileTopicId||"Unknown"}\n`),n.social&&Object.keys(n.social).length>0&&(i+=`Social: ${Object.entries(n.social).map(([e,t])=>`${e}: ${t}`).join(", ")}\n`),n.properties&&Object.keys(n.properties).length>0&&(i+=`Properties: ${JSON.stringify(n.properties)}\n`),this.executeResult={success:!0,rawResult:{profileDetails:i,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 B extends e.BasePlugin{constructor(){super(...arguments),this.id="hedera-hbar-price",this.name="Hedera HBAR Price Plugin",this.description="Provides tools to interact with Hedera network data, specifically HBAR price.",this.version="1.0.0",this.author="Hashgraph Online",this.tools=[]}async initialize(e){await super.initialize(e),this.initializeTools()}initializeTools(){this.tools=[new e.HederaGetHbarPriceTool({hederaKit:this.context.config.hederaKit,logger:this.context.logger})]}getTools(){return this.tools}}Object.defineProperty(exports,"BasePlugin",{enumerable:!0,get:()=>e.BasePlugin}),Object.defineProperty(exports,"GetHbarPriceTool",{enumerable:!0,get:()=>e.HederaGetHbarPriceTool}),Object.defineProperty(exports,"PluginRegistry",{enumerable:!0,get:()=>e.PluginRegistry}),exports.AcceptConnectionRequestTool=R,exports.BaseHCS10QueryTool=a,exports.BaseHCS10TransactionTool=s,exports.CheckMessagesTool=I,exports.ConnectionMonitorTool=C,exports.FindRegistrationsTool=b,exports.HCS10Builder=N,exports.HCS10Client=class{constructor(e,n,o,i){this.standardClient=new t.HCS10Client({network:o,operatorId:e,operatorPrivateKey:n,guardedRegistryBaseUrl:i?.registryUrl,logLevel:i?.logLevel}),this.guardedRegistryBaseUrl=i?.registryUrl||"",this.useEncryption=i?.useEncryption||!1;const r="true"===process.env.DISABLE_LOGGING;this.logger=new t.Logger({level:i?.logLevel||"info",silent:r})}getOperatorId(){const e=this.standardClient.getClient().operatorAccountId;if(!e)throw new Error("Operator Account ID not configured in standard client.");return e.toString()}getNetwork(){return this.standardClient.getNetwork()}async handleConnectionRequest(e,t,n,o){try{return await this.standardClient.handleConnectionRequest(e,t,n,o)}catch(i){throw this.logger.error(`Error handling connection request #${n} for topic ${e}:`,i),new Error(`Failed to handle connection request: ${i instanceof Error?i.message:String(i)}`)}}async getAgentProfile(e){return this.standardClient.retrieveProfile(e)}async submitConnectionRequest(e,t){return this.standardClient.submitConnectionRequest(e,t)}async waitForConnectionConfirmation(e,t,n=60,o=2e3){return this.standardClient.waitForConnectionConfirmation(e,t,n,o)}async createAndRegisterAgent(e){const n=(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&&(n.setInboundTopicType(t.InboundTopicType.FEE_BASED),n.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)`),n.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])=>{n.addSocial(e,t)}),e.properties&&Object.entries(e.properties).forEach(([e,t])=>{n.addProperty(e,t)});try{const t=Boolean(e?.feeConfig),o=await this.standardClient.createAndRegisterAgent(n,{initialBalance:t?50:void 0});return o?.metadata?.inboundTopicId&&o?.metadata?.outboundTopicId&&(this.agentChannels={inboundTopicId:o.metadata.inboundTopicId,outboundTopicId:o.metadata.outboundTopicId}),o}catch(o){throw this.logger.error("Error during agent creation/registration:",o),new Error(`Failed to create/register agent: ${o instanceof Error?o.message:String(o)}`)}}async sendMessage(e,t,n,o){this.useEncryption;try{const i=await this.standardClient.sendMessage(e,t,n,o);return i.topicSequenceNumber?.toNumber()}catch(i){throw this.logger.error(`Error sending message to topic ${e}:`,i),new Error(`Failed to send message: ${i instanceof Error?i.message:String(i)}`)}}async getMessages(e){try{const t=(await this.standardClient.getMessages(e)).messages.map(e=>{const t=e?.created?.getTime()||0;return{...e,timestamp:t,data:e.data,sequence_number:e.sequence_number}});return t.sort((e,t)=>e.timestamp-t.timestamp),{messages:t}}catch(t){return this.logger.error(`Error getting messages from topic ${e}:`,t),{messages:[]}}}async getMessageStream(e){return this.standardClient.getMessageStream(e)}async getMessageContent(e){try{return await this.standardClient.getMessageContent(e)}catch(t){throw this.logger.error(`Error retrieving message content for: ${e}`,t),new Error(`Failed to retrieve message content: ${t instanceof Error?t.message:String(t)}`)}}async getInboundTopicId(){try{const e=this.getOperatorId();this.logger.info(`[HCS10Client] Retrieving profile for operator ${e} to find inbound topic...`);const t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.inboundTopic)return this.logger.info(`[HCS10Client] Found inbound topic for operator ${e}: ${t.topicInfo.inboundTopic}`),t.topicInfo.inboundTopic;throw new Error(`Could not retrieve inbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}catch(e){this.logger.error(`[HCS10Client] Error fetching operator's inbound topic ID (${this.getOperatorId()}):`,e);const t=this.getOperatorId();let n=`Failed to get inbound topic ID for operator ${t}.`;throw e instanceof Error&&e.message.includes("does not have a valid HCS-11 memo")?n+=` The account profile may not exist or is invalid. Please ensure this operator account (${t}) is registered as an HCS-10 agent. You might need to register it first (e.g., using the 'register_agent' tool or SDK function).`:e instanceof Error?n+=` Reason: ${e.message}`:n+=` Unexpected error: ${String(e)}`,new Error(n)}}getAccountAndSigner(){const e=this.standardClient.getAccountAndSigner();return{accountId:e.accountId,signer:e.signer}}async getOutboundTopicId(){const e=this.getOperatorId(),t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.outboundTopic)return t.topicInfo.outboundTopic;throw new Error(`Could not retrieve outbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}setClient(e,n){return this.standardClient=new t.HCS10Client({network:this.getNetwork(),operatorId:e,operatorPrivateKey:n,guardedRegistryBaseUrl:this.guardedRegistryBaseUrl}),this.standardClient}async validateOperator(e){try{this.setClient(e.accountId,e.privateKey);return{isValid:!0,operator:{accountId:this.getOperatorId()}}}catch(t){return this.logger.error(`Validation error: ${t}`),{isValid:!1,error:t instanceof Error?t.message:String(t)}}}async initializeWithValidation(e){const t=await this.validateOperator(e);return t.isValid&&e.stateManager&&e.stateManager.initializeConnectionsManager(this.standardClient),t}},exports.HbarPricePlugin=B,exports.InitiateConnectionTool=h,exports.ListConnectionsTool=f,exports.ListUnapprovedConnectionRequestsTool=M,exports.ManageConnectionRequestsTool=A,exports.OpenConvaiState=P,exports.RegisterAgentTool=d,exports.RetrieveProfileTool=S,exports.SendMessageToConnectionTool=l,exports.initializeStandardsAgentKit=async n=>{const o=n?.clientConfig||{},i=o.operatorId||process.env.HEDERA_OPERATOR_ID,r=o.operatorKey||process.env.HEDERA_OPERATOR_KEY,s=o.network||process.env.HEDERA_NETWORK||"testnet";let a;if("mainnet"===s?a="mainnet":("testnet"===s||console.warn(`Unsupported network specified: '${s}'. Defaulting to 'testnet'.`),a="testnet"),!i||!r)throw new Error("Operator ID and private key must be provided either through options or environment variables.");const c="true"===process.env.DISABLE_LOGGING,u=t.Logger.getInstance({level:o.logLevel||"info",silent:c}),g=n?.stateManager||new P({defaultEnvFilePath:E,defaultPrefix:"TODD"});u.info("State manager initialized");const p=new e.ServerSigner(i,r,a),m=new e.HederaAgentKit(p);await m.initialize(),u.info(`HederaAgentKit initialized for ${i} on ${a}`);const w=new N(m,g,{useEncryption:o.useEncryption,registryUrl:o.registryUrl,logLevel:o.logLevel});let y,v;if(n?.monitoringClient){const t=new e.ServerSigner(i,r,a);y=new e.HederaAgentKit(t),await y.initialize(),v=new N(y,g,{useEncryption:o.useEncryption,registryUrl:o.registryUrl,logLevel:"error"}),u.info("Monitoring client initialized")}const T={};return T.registerAgentTool=new d({hederaKit:m,hcs10Builder:w,logger:void 0}),n?.createAllTools&&(T.findRegistrationsTool=new b({hederaKit:m,hcs10Builder:w,logger:void 0}),T.retrieveProfileTool=new S({hederaKit:m,hcs10Builder:w,logger:void 0}),T.initiateConnectionTool=new h({hederaKit:m,hcs10Builder:w,logger:void 0}),T.listConnectionsTool=new f({hederaKit:m,hcs10Builder:w,logger:void 0}),T.sendMessageToConnectionTool=new l({hederaKit:m,hcs10Builder:w,logger:void 0}),T.checkMessagesTool=new I({hederaKit:m,hcs10Builder:w,logger:void 0}),T.connectionMonitorTool=new C({hederaKit:y||m,hcs10Builder:v||w,logger:void 0}),T.manageConnectionRequestsTool=new A({hederaKit:m,hcs10Builder:w,logger:void 0}),T.acceptConnectionRequestTool=new R({hederaKit:m,hcs10Builder:w,logger:void 0}),T.listUnapprovedConnectionRequestsTool=new M({hederaKit:m,hcs10Builder:w,logger:void 0}),u.info("All tools initialized")),{hederaKit:m,hcs10Builder:w,monitoringHederaKit:y,monitoringHcs10Builder:v,tools:T,stateManager:g}};
|
|
2
2
|
//# sourceMappingURL=standards-agent-kit.cjs.map
|