@hashgraphonline/standards-agent-kit 0.0.31 → 0.0.33
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/src/init/index.d.ts +1 -0
- package/dist/cjs/src/{init.d.ts → init/init.d.ts} +16 -16
- package/dist/cjs/standards-agent-kit.cjs +1 -1
- package/dist/cjs/standards-agent-kit.cjs.map +1 -1
- package/dist/es/src/init/index.d.ts +1 -0
- package/dist/es/src/{init.d.ts → init/init.d.ts} +16 -16
- package/dist/es/standards-agent-kit.es.js +17 -17
- package/dist/es/standards-agent-kit.es10.js +65 -104
- package/dist/es/standards-agent-kit.es10.js.map +1 -1
- package/dist/es/standards-agent-kit.es11.js +371 -66
- package/dist/es/standards-agent-kit.es11.js.map +1 -1
- package/dist/es/standards-agent-kit.es12.js +153 -348
- package/dist/es/standards-agent-kit.es12.js.map +1 -1
- package/dist/es/standards-agent-kit.es13.js +105 -161
- package/dist/es/standards-agent-kit.es13.js.map +1 -1
- package/dist/es/standards-agent-kit.es14.js +48 -126
- package/dist/es/standards-agent-kit.es14.js.map +1 -1
- package/dist/es/standards-agent-kit.es15.js +108 -50
- package/dist/es/standards-agent-kit.es15.js.map +1 -1
- package/dist/es/standards-agent-kit.es16.js +239 -117
- package/dist/es/standards-agent-kit.es16.js.map +1 -1
- package/dist/es/standards-agent-kit.es17.js +120 -245
- package/dist/es/standards-agent-kit.es17.js.map +1 -1
- package/dist/es/standards-agent-kit.es2.js +321 -114
- package/dist/es/standards-agent-kit.es2.js.map +1 -1
- package/dist/es/standards-agent-kit.es23.js +15 -15
- package/dist/es/standards-agent-kit.es24.js +3 -24
- package/dist/es/standards-agent-kit.es24.js.map +1 -1
- package/dist/es/standards-agent-kit.es25.js +81 -3
- package/dist/es/standards-agent-kit.es25.js.map +1 -1
- package/dist/es/standards-agent-kit.es26.js +22 -79
- package/dist/es/standards-agent-kit.es26.js.map +1 -1
- package/dist/es/standards-agent-kit.es3.js +347 -284
- package/dist/es/standards-agent-kit.es3.js.map +1 -1
- package/dist/es/standards-agent-kit.es4.js +56 -366
- package/dist/es/standards-agent-kit.es4.js.map +1 -1
- package/dist/es/standards-agent-kit.es5.js +142 -58
- package/dist/es/standards-agent-kit.es5.js.map +1 -1
- package/dist/es/standards-agent-kit.es6.js +73 -143
- package/dist/es/standards-agent-kit.es6.js.map +1 -1
- package/dist/es/standards-agent-kit.es7.js +65 -64
- package/dist/es/standards-agent-kit.es7.js.map +1 -1
- package/dist/es/standards-agent-kit.es8.js +91 -77
- package/dist/es/standards-agent-kit.es8.js.map +1 -1
- package/dist/es/standards-agent-kit.es9.js +109 -90
- package/dist/es/standards-agent-kit.es9.js.map +1 -1
- package/dist/umd/src/init/index.d.ts +1 -0
- package/dist/umd/src/{init.d.ts → init/init.d.ts} +16 -16
- package/dist/umd/standards-agent-kit.umd.js +2 -2
- package/dist/umd/standards-agent-kit.umd.js.map +1 -1
- package/package.json +2 -3
- package/src/index.ts +1 -1
- package/src/init/index.ts +1 -0
- package/src/{init.ts → init/init.ts} +22 -20
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"standards-agent-kit.es6.js","sources":["../../src/tools/ConnectionTool.ts"],"sourcesContent":["import { HCS10Client } from '../hcs10/HCS10Client';\nimport { StructuredTool, ToolParams } from '@langchain/core/tools';\nimport { z } from 'zod';\n// Import FeeConfigBuilder if needed for explicit fee handling\n// import { FeeConfigBuilder } from '@hashgraphonline/standards-sdk';\nimport { Logger } from '@hashgraphonline/standards-sdk';\nimport {\n IStateManager,\n ActiveConnection,\n} from '../state/state-types'; // Corrected import path/name\n\nexport interface ConnectionToolParams extends ToolParams {\n client: HCS10Client;\n stateManager: IStateManager;\n}\n\n/**\n * ConnectionTool monitors the *current* agent's inbound topic for connection requests\n * and automatically handles them using the HCS-10 standard SDK flow.\n * Use this ONLY to passively LISTEN for other agents trying to connect TO YOU.\n * This tool takes NO arguments and does NOT start outgoing connections.\n */\nexport class ConnectionTool extends StructuredTool {\n name = 'monitor_connections';\n description =\n \"Starts passively LISTENING on the current agent's own inbound topic for INCOMING HCS-10 connection requests. Handles received requests automatically. Takes NO arguments. DO NOT use this to start a new connection TO someone else.\";\n public client: HCS10Client;\n public logger: Logger;\n private stateManager: IStateManager; // Renamed property\n private isMonitoring: boolean = false; // Flag to prevent multiple monitors\n private monitoringTopic: string | null = null;\n\n // Schema now takes NO arguments\n schema = z.object({});\n\n /**\n * @param client - Instance of HCS10Client.\n * @param stateManager - Instance of StateManager for shared state management.\n */\n constructor({ client, stateManager, ...rest }: ConnectionToolParams) {\n super(rest);\n this.client = client;\n this.stateManager = stateManager; // Renamed assignment\n this.logger = Logger.getInstance({\n module: 'ConnectionTool',\n level: 'info',\n });\n }\n\n /**\n * Initiates the connection request monitoring process in the background.\n * Gets the inbound topic ID from the configured client.\n */\n async _call(/* _input: z.infer<typeof this.schema> */): Promise<string> {\n // Get inboundTopicId from the client\n let inboundTopicId: string;\n try {\n // Assuming getInboundTopicId() is implemented and available\n inboundTopicId = await this.client.getInboundTopicId();\n } catch (error) {\n const errorMsg = `Error getting inbound topic ID for monitoring: ${\n error instanceof Error ? error.message : String(error)\n }`;\n this.logger.error(errorMsg);\n return errorMsg;\n }\n\n if (!inboundTopicId) {\n return 'Error: Could not determine the inbound topic ID for the current agent.';\n }\n\n if (this.isMonitoring) {\n if (this.monitoringTopic === inboundTopicId) {\n return `Already monitoring topic ${inboundTopicId}.`;\n } else {\n return `Error: Already monitoring a different topic (${this.monitoringTopic}). Stop the current monitor first.`;\n // TODO: Add a mechanism to stop the monitor if needed.\n }\n }\n\n this.isMonitoring = true;\n this.monitoringTopic = inboundTopicId;\n this.logger.info(\n `Initiating connection request monitoring for topic ${inboundTopicId}...`\n );\n\n // Start the monitoring process asynchronously without awaiting it\n // This allows the tool call to return quickly.\n this.monitorIncomingRequests(inboundTopicId).catch((error) => {\n this.logger.error(\n `Monitoring loop for ${inboundTopicId} encountered an unrecoverable error:`,\n error\n );\n this.isMonitoring = false; // Reset flag on loop failure\n this.monitoringTopic = null;\n });\n\n return `Started monitoring inbound topic ${inboundTopicId} for connection requests in the background.`;\n }\n\n /**\n * The core monitoring loop.\n */\n private async monitorIncomingRequests(inboundTopicId: string): Promise<void> {\n this.logger.info(`Monitoring inbound topic ${inboundTopicId}...`);\n\n let lastProcessedMessageSequence = 0;\n const processedRequestIds = new Set<number>(); // Track processed requests within this monitoring session\n\n // Main monitoring loop\n while (this.isMonitoring && this.monitoringTopic === inboundTopicId) {\n try {\n const messagesResult = await this.client.getMessages(inboundTopicId);\n\n const allMessages = messagesResult.messages;\n\n const connectionRequests = allMessages.filter(\n (msg) =>\n msg.op === 'connection_request' &&\n typeof msg.sequence_number === 'number' // Keep filtering by sequence number if needed, or remove if checking existing confirmations is sufficient\n // msg.sequence_number > lastProcessedMessageSequence // Temporarily remove or adjust this if checking confirmations is the primary method\n );\n\n for (const message of connectionRequests) {\n // Update lastProcessedMessageSequence regardless of handling outcome to avoid re-checking handled/skipped messages in future loops\n lastProcessedMessageSequence = Math.max(\n lastProcessedMessageSequence,\n message.sequence_number || 0 // Use 0 if sequence_number is undefined (though filter should prevent this)\n );\n\n const connectionRequestId = message.sequence_number;\n if (!connectionRequestId) {\n continue; // Skip if sequence number is missing\n }\n\n // --- Check if already handled ---\n const alreadyHandled = allMessages.some(\n (m) => m.op === 'connection_created' && m.connection_id === connectionRequestId\n );\n\n if (alreadyHandled) {\n this.logger.debug(\n `Connection request #${connectionRequestId} already handled (found connection_created). Skipping.`\n );\n continue; // Skip to the next request\n }\n // --- End Check ---\n\n // Extract requesting account ID from the message's operator_id field (topic@account)\n const senderOperatorId = message.operator_id || '';\n const requestingAccountId = senderOperatorId.split('@')[1] || null;\n\n if (!requestingAccountId) {\n this.logger.warn(\n `Could not determine requesting account ID from operator_id '${senderOperatorId}' for request #${connectionRequestId}. Skipping.`\n );\n continue;\n }\n\n if (processedRequestIds.has(connectionRequestId)) {\n this.logger.info(\n `Connection request #${connectionRequestId} already processed in this session. Skipping.`\n );\n continue;\n }\n\n this.logger.info(\n `Processing connection request #${connectionRequestId} from account ${requestingAccountId}...`\n );\n\n try {\n // Handle the connection request using the HCS10Client wrapper\n const confirmation = await this.client.handleConnectionRequest(\n inboundTopicId,\n requestingAccountId,\n connectionRequestId\n );\n\n processedRequestIds.add(connectionRequestId);\n this.logger.info(\n `Connection confirmed for request #${connectionRequestId}. New connection topic: ${confirmation.connectionTopicId}`\n );\n\n // Use stateManager to add connection\n const newConnection: ActiveConnection = {\n targetAccountId: requestingAccountId,\n targetAgentName: `Agent ${requestingAccountId}`,\n targetInboundTopicId: 'N/A',\n connectionTopicId: confirmation.connectionTopicId,\n };\n this.stateManager.addActiveConnection(newConnection);\n this.logger.info(\n `Added new active connection to ${requestingAccountId} state.`\n );\n } catch (handleError) {\n this.logger.error(\n `Error handling connection request #${connectionRequestId} from ${requestingAccountId}:`,\n handleError\n );\n }\n }\n } catch (error) {\n this.logger.error(\n `Error fetching or processing messages for topic ${inboundTopicId}:`,\n error\n );\n // Implement backoff or error threshold if needed\n }\n\n // Wait before the next poll\n await new Promise((resolve) => setTimeout(resolve, 5000)); // Poll every 5 seconds (adjust as needed)\n }\n\n this.logger.info(`Monitoring loop stopped for topic ${inboundTopicId}.`);\n this.isMonitoring = false; // Ensure flag is reset when loop exits\n this.monitoringTopic = null;\n }\n\n // Optional: Method to explicitly stop monitoring\n public stopMonitoring(): void {\n if (this.isMonitoring) {\n this.logger.info(\n `Stopping monitoring for topic ${this.monitoringTopic}...`\n );\n this.isMonitoring = false;\n this.monitoringTopic = null;\n } else {\n this.logger.info('Monitor is not currently running.');\n }\n }\n}\n"],"names":[],"mappings":";;;AAsBO,MAAM,uBAAuB,eAAe;AAAA;AAAA;AAAA;AAAA;AAAA,EAiBjD,YAAY,EAAE,QAAQ,cAAc,GAAG,QAA8B;AACnE,UAAM,IAAI;AAjBL,SAAA,OAAA;AAEL,SAAA,cAAA;AAIF,SAAQ,eAAwB;AAChC,SAA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AAmB,aAAa;AAAA,YAClC;AACK,iBAAA,aAAa,oBAAoB,aAAa;AACnD,iBAAK,OAAO;AAAA,cACV,kCAAkC,mBAAmB;AAAA,YACvD;AAAA,mBACO,aAAa;AACpB,iBAAK,OAAO;AAAA,cACV,sCAAsC,mBAAmB,SAAS,mBAAmB;AAAA,cACrF;AAAA,YACF;AAAA,UAAA;AAAA,QACF;AAAA,eAEK,OAAO;AACd,aAAK,OAAO;AAAA,UACV,mDAAmD,cAAc;AAAA,UACjE;AAAA,QACF;AAAA,MAAA;AAKF,YAAM,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,GAAI,CAAC;AAAA,IAAA;AAG1D,SAAK,OAAO,KAAK,qCAAqC,cAAc,GAAG;AACvE,SAAK,eAAe;AACpB,SAAK,kBAAkB;AAAA,EAAA;AAAA;AAAA,EAIlB,iBAAuB;AAC5B,QAAI,KAAK,cAAc;AACrB,WAAK,OAAO;AAAA,QACV,iCAAiC,KAAK,eAAe;AAAA,MACvD;AACA,WAAK,eAAe;AACpB,WAAK,kBAAkB;AAAA,IAAA,OAClB;AACA,WAAA,OAAO,KAAK,mCAAmC;AAAA,IAAA;AAAA,EACtD;AAEJ;"}
|
|
1
|
+
{"version":3,"file":"standards-agent-kit.es6.js","sources":["../../src/tools/SendMessageToConnectionTool.ts"],"sourcesContent":["// src/tools/send-message-to-connection-tool.ts\n\nimport { StructuredTool, ToolParams } from '@langchain/core/tools';\nimport { z } from 'zod';\nimport { HCS10Client } from '../hcs10/HCS10Client';\nimport { IStateManager } from '../state/state-types';\nimport { Logger } from '@hashgraphonline/standards-sdk'; // Assuming logger utility\n\nexport interface SendMessageToConnectionToolParams extends ToolParams {\n hcsClient: HCS10Client;\n stateManager: IStateManager;\n}\n\n/**\n * A tool to send a message to an agent over an established HCS-10 connection.\n */\nexport class SendMessageToConnectionTool extends StructuredTool {\n name = 'send_message_to_connection';\n description =\n \"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\";\n schema = z.object({\n targetIdentifier: z\n .string()\n .describe(\n \"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.\"\n ),\n message: z.string().describe('The text message content to send.'),\n disableMonitoring: z.boolean().optional().default(false),\n });\n\n private hcsClient: HCS10Client;\n private stateManager: IStateManager;\n private logger: Logger;\n\n constructor({\n hcsClient,\n stateManager,\n ...rest\n }: SendMessageToConnectionToolParams) {\n super(rest);\n this.hcsClient = hcsClient;\n this.stateManager = stateManager;\n this.logger = Logger.getInstance({ module: 'SendMessageToConnectionTool' });\n }\n\n protected async _call({\n targetIdentifier,\n message,\n disableMonitoring,\n }: z.infer<this['schema']>): Promise<string> {\n const currentAgent = this.stateManager.getCurrentAgent();\n if (!currentAgent) {\n return 'Error: Cannot send message. No agent is currently active. Please register or select an agent first.';\n }\n\n const connection =\n this.stateManager.getConnectionByIdentifier(targetIdentifier);\n if (!connection) {\n return `Error: Could not find an active connection matching identifier \"${targetIdentifier}\". Use 'list_connections' to see active connections.`;\n }\n\n const connectionTopicId = connection.connectionTopicId;\n const targetAgentName = connection.targetAgentName;\n\n // Construct the sender's operator ID\n const operatorId = `${currentAgent.inboundTopicId}@${currentAgent.accountId}`;\n\n this.logger.info(\n `Sending message from ${operatorId} to ${targetAgentName} (${connection.targetAccountId}) via connection topic ${connectionTopicId}`\n );\n\n try {\n // Call sendMessage with correct arguments\n const sequenceNumber = await this.hcsClient.sendMessage(\n connectionTopicId,\n message, // Message content as 'data'\n `Agent message from ${currentAgent.name}` // Optional memo\n );\n\n if (!sequenceNumber) {\n throw new Error('Failed to send message');\n }\n\n if (!disableMonitoring) {\n return `Message sent to ${targetAgentName} (${connection.targetAccountId}) via connection ${connectionTopicId}. Sequence Number: ${sequenceNumber}`;\n }\n\n const replyBack = await this.monitorResponses(\n connectionTopicId,\n operatorId,\n sequenceNumber\n );\n\n if (replyBack) {\n this.logger.info(`Got reply from ${targetAgentName}`, replyBack);\n // Format the return string clearly as an observation/reply\n return `Received reply from ${targetAgentName}: ${replyBack}`;\n }\n\n // Return message based on the status string if no reply was received/awaited\n return `Message sent to ${targetAgentName} (${connection.targetAccountId}) via connection ${connectionTopicId}. Sequence Number: ${sequenceNumber}`;\n } catch (error) {\n this.logger.error(\n `Failed to send message via connection ${connectionTopicId}: ${error}`\n );\n return `Error sending message to ${targetAgentName}: ${\n error instanceof Error ? error.message : String(error)\n }`;\n }\n }\n\n private async monitorResponses(\n topicId: string,\n operatorId: string,\n sequenceNumber: number\n ): Promise<string | null> {\n const maxAttempts = 30;\n const attempts = 0;\n\n while (attempts < maxAttempts) {\n try {\n const messages = await this.hcsClient.getMessageStream(topicId);\n\n for (const message of messages.messages) {\n if (\n message.sequence_number < sequenceNumber ||\n message.operator_id === operatorId\n ) {\n continue;\n }\n const content = await this.hcsClient.getMessageContent(message.data || '');\n\n return content;\n }\n } catch (error) {\n this.logger.error(`Error monitoring responses: ${error}`);\n }\n await new Promise((resolve) => setTimeout(resolve, 4000));\n }\n return null;\n }\n}\n"],"names":[],"mappings":";;;AAgBO,MAAM,oCAAoC,eAAe;AAAA,EAkB9D,YAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA,GAAG;AAAA,EAAA,GACiC;AACpC,UAAM,IAAI;AAtBL,SAAA,OAAA;AAEL,SAAA,cAAA;AACF,SAAA,SAAS,EAAE,OAAO;AAAA,MAChB,kBAAkB,EACf,OAAA,EACA;AAAA,QACC;AAAA,MACF;AAAA,MACF,SAAS,EAAE,SAAS,SAAS,mCAAmC;AAAA,MAChE,mBAAmB,EAAE,QAAA,EAAU,SAAS,EAAE,QAAQ,KAAK;AAAA,IAAA,CACxD;AAYC,SAAK,YAAY;AACjB,SAAK,eAAe;AACpB,SAAK,SAAS,OAAO,YAAY,EAAE,QAAQ,+BAA+B;AAAA,EAAA;AAAA,EAG5E,MAAgB,MAAM;AAAA,IACpB;AAAA,IACA;AAAA,IACA;AAAA,EA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wB;AACxB,UAAM,cAAc;AACpB,UAAM,WAAW;AAEjB,WAAO,WAAW,aAAa;AACzB,UAAA;AACF,cAAM,WAAW,MAAM,KAAK,UAAU,iBAAiB,OAAO;AAEnD,mBAAA,WAAW,SAAS,UAAU;AACvC,cACE,QAAQ,kBAAkB,kBAC1B,QAAQ,gBAAgB,YACxB;AACA;AAAA,UAAA;AAEF,gBAAM,UAAU,MAAM,KAAK,UAAU,kBAAkB,QAAQ,QAAQ,EAAE;AAElE,iBAAA;AAAA,QAAA;AAAA,eAEF,OAAO;AACd,aAAK,OAAO,MAAM,+BAA+B,KAAK,EAAE;AAAA,MAAA;AAE1D,YAAM,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,GAAI,CAAC;AAAA,IAAA;AAEnD,WAAA;AAAA,EAAA;AAEX;"}
|
|
@@ -1,98 +1,99 @@
|
|
|
1
1
|
import { StructuredTool } from "@langchain/core/tools";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import { Logger } from "@hashgraphonline/standards-sdk";
|
|
4
|
-
class
|
|
4
|
+
class InitiateConnectionTool extends StructuredTool {
|
|
5
5
|
constructor({
|
|
6
6
|
hcsClient,
|
|
7
7
|
stateManager,
|
|
8
8
|
...rest
|
|
9
9
|
}) {
|
|
10
10
|
super(rest);
|
|
11
|
-
this.name = "
|
|
12
|
-
this.description = "
|
|
11
|
+
this.name = "initiate_connection";
|
|
12
|
+
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.";
|
|
13
13
|
this.schema = z.object({
|
|
14
|
-
|
|
15
|
-
"The account ID (e.g., 0.0.12345) of the
|
|
16
|
-
)
|
|
17
|
-
message: z.string().describe("The text message content to send."),
|
|
18
|
-
disableMonitoring: z.boolean().optional().default(false)
|
|
14
|
+
targetAccountId: z.string().describe(
|
|
15
|
+
"The Hedera account ID (e.g., 0.0.12345) of the agent you want to connect with."
|
|
16
|
+
)
|
|
19
17
|
});
|
|
20
18
|
this.hcsClient = hcsClient;
|
|
21
19
|
this.stateManager = stateManager;
|
|
22
|
-
this.logger = Logger.getInstance({ module: "
|
|
20
|
+
this.logger = Logger.getInstance({ module: "InitiateConnectionTool" });
|
|
23
21
|
}
|
|
24
22
|
async _call({
|
|
25
|
-
|
|
26
|
-
message,
|
|
27
|
-
disableMonitoring
|
|
23
|
+
targetAccountId
|
|
28
24
|
}) {
|
|
29
25
|
const currentAgent = this.stateManager.getCurrentAgent();
|
|
30
26
|
if (!currentAgent) {
|
|
31
|
-
return "Error: Cannot
|
|
27
|
+
return "Error: Cannot initiate connection. No agent is currently active. Please register or select an agent first.";
|
|
32
28
|
}
|
|
33
|
-
const connection = this.stateManager.getConnectionByIdentifier(targetIdentifier);
|
|
34
|
-
if (!connection) {
|
|
35
|
-
return `Error: Could not find an active connection matching identifier "${targetIdentifier}". Use 'list_connections' to see active connections.`;
|
|
36
|
-
}
|
|
37
|
-
const connectionTopicId = connection.connectionTopicId;
|
|
38
|
-
const targetAgentName = connection.targetAgentName;
|
|
39
|
-
const operatorId = `${currentAgent.inboundTopicId}@${currentAgent.accountId}`;
|
|
40
29
|
this.logger.info(
|
|
41
|
-
`
|
|
30
|
+
`Attempting connection from ${currentAgent.accountId} to ${targetAccountId}`
|
|
42
31
|
);
|
|
43
32
|
try {
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
// Message content as 'data'
|
|
48
|
-
`Agent message from ${currentAgent.name}`
|
|
49
|
-
// Optional memo
|
|
50
|
-
);
|
|
51
|
-
if (!sequenceNumber) {
|
|
52
|
-
throw new Error("Failed to send message");
|
|
53
|
-
}
|
|
54
|
-
if (!disableMonitoring) {
|
|
55
|
-
return `Message sent to ${targetAgentName} (${connection.targetAccountId}) via connection ${connectionTopicId}. Sequence Number: ${sequenceNumber}`;
|
|
56
|
-
}
|
|
57
|
-
const replyBack = await this.monitorResponses(
|
|
58
|
-
connectionTopicId,
|
|
59
|
-
operatorId,
|
|
60
|
-
sequenceNumber
|
|
33
|
+
this.logger.debug(`Retrieving profile for ${targetAccountId}...`);
|
|
34
|
+
const targetProfile = await this.hcsClient.getAgentProfile(
|
|
35
|
+
targetAccountId
|
|
61
36
|
);
|
|
62
|
-
if (
|
|
63
|
-
|
|
64
|
-
return `Received reply from ${targetAgentName}: ${replyBack}`;
|
|
37
|
+
if (!targetProfile?.topicInfo?.inboundTopic) {
|
|
38
|
+
return `Error: Could not retrieve profile or find inbound topic ID for target agent ${targetAccountId}. They might not be registered or have a public profile.`;
|
|
65
39
|
}
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
this.
|
|
69
|
-
|
|
40
|
+
const targetInboundTopicId = targetProfile.topicInfo.inboundTopic;
|
|
41
|
+
const targetAgentName = targetProfile.profile.name || `Agent ${targetAccountId}`;
|
|
42
|
+
const requestResult = await this.hcsClient.submitConnectionRequest(
|
|
43
|
+
targetInboundTopicId,
|
|
44
|
+
currentAgent.name
|
|
70
45
|
);
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
try {
|
|
79
|
-
const messages = await this.hcsClient.getMessageStream(topicId);
|
|
80
|
-
for (const message of messages.messages) {
|
|
81
|
-
if (message.sequence_number < sequenceNumber || message.operator_id === operatorId) {
|
|
82
|
-
continue;
|
|
46
|
+
let connectionRequestId = null;
|
|
47
|
+
const sequenceNumberLong = requestResult?.topicSequenceNumber;
|
|
48
|
+
if (sequenceNumberLong !== null) {
|
|
49
|
+
try {
|
|
50
|
+
connectionRequestId = sequenceNumberLong.toNumber();
|
|
51
|
+
if (isNaN(connectionRequestId)) {
|
|
52
|
+
throw new Error("Converted sequence number is NaN.");
|
|
83
53
|
}
|
|
84
|
-
|
|
85
|
-
|
|
54
|
+
} catch (conversionError) {
|
|
55
|
+
throw new Error(
|
|
56
|
+
`Failed to convert connection request sequence number: ${conversionError}`
|
|
57
|
+
);
|
|
86
58
|
}
|
|
87
|
-
}
|
|
88
|
-
|
|
59
|
+
} else {
|
|
60
|
+
throw new Error("Connection request sequence number not found.");
|
|
61
|
+
}
|
|
62
|
+
const confirmationTimeoutMs = 6e4;
|
|
63
|
+
const delayMs = 2e3;
|
|
64
|
+
const maxAttempts = Math.ceil(confirmationTimeoutMs / delayMs);
|
|
65
|
+
const confirmationResult = await this.hcsClient.waitForConnectionConfirmation(
|
|
66
|
+
targetInboundTopicId,
|
|
67
|
+
connectionRequestId,
|
|
68
|
+
maxAttempts,
|
|
69
|
+
delayMs
|
|
70
|
+
);
|
|
71
|
+
if (!confirmationResult?.connectionTopicId) {
|
|
72
|
+
return `Error: Connection confirmation not received from ${targetAccountId} (for request ${connectionRequestId}) within ${confirmationTimeoutMs / 1e3} seconds.`;
|
|
89
73
|
}
|
|
90
|
-
|
|
74
|
+
const connectionTopicId = confirmationResult.connectionTopicId;
|
|
75
|
+
this.logger.info(`Connection confirmed! Topic ID: ${connectionTopicId}`);
|
|
76
|
+
const newConnection = {
|
|
77
|
+
targetAccountId,
|
|
78
|
+
targetAgentName,
|
|
79
|
+
targetInboundTopicId,
|
|
80
|
+
connectionTopicId
|
|
81
|
+
};
|
|
82
|
+
this.stateManager.addActiveConnection(newConnection);
|
|
83
|
+
const connections = this.stateManager.listConnections();
|
|
84
|
+
const addedEntry = connections.find(
|
|
85
|
+
(c) => c.connectionTopicId === connectionTopicId
|
|
86
|
+
);
|
|
87
|
+
const localConnectionId = addedEntry ? connections.indexOf(addedEntry) + 1 : null;
|
|
88
|
+
const idString = localConnectionId ? `#${localConnectionId}` : "";
|
|
89
|
+
return `Successfully established connection ${idString} with ${targetAgentName} (${targetAccountId}). Connection Topic: ${connectionTopicId}. You can now send messages using this connection.`;
|
|
90
|
+
} catch (error) {
|
|
91
|
+
this.logger.error(`Connection initiation failed: ${error}`);
|
|
92
|
+
return `Error initiating connection with ${targetAccountId}: ${error instanceof Error ? error.message : String(error)}`;
|
|
91
93
|
}
|
|
92
|
-
return null;
|
|
93
94
|
}
|
|
94
95
|
}
|
|
95
96
|
export {
|
|
96
|
-
|
|
97
|
+
InitiateConnectionTool
|
|
97
98
|
};
|
|
98
99
|
//# sourceMappingURL=standards-agent-kit.es7.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"standards-agent-kit.es7.js","sources":["../../src/tools/
|
|
1
|
+
{"version":3,"file":"standards-agent-kit.es7.js","sources":["../../src/tools/InitiateConnectionTool.ts"],"sourcesContent":["import { StructuredTool, ToolParams } from '@langchain/core/tools';\nimport { z } from 'zod';\nimport { HCS10Client } from '../hcs10/HCS10Client';\nimport { IStateManager, ActiveConnection } from '../state/state-types';\nimport { Logger } from '@hashgraphonline/standards-sdk';\n\nexport interface InitiateConnectionToolParams extends ToolParams {\n hcsClient: HCS10Client;\n stateManager: IStateManager;\n}\n\n/**\n * A tool to actively START a NEW HCS-10 connection TO a target agent.\n * Requires the target agent's account ID.\n * It retrieves their profile, sends a connection request, waits for confirmation, and stores the connection using the provided stateManager.\n * Use this tool ONLY to actively INITIATE an OUTGOING connection.\n */\nexport class InitiateConnectionTool extends StructuredTool {\n name = 'initiate_connection';\n description =\n '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.';\n schema = z.object({\n targetAccountId: z\n .string()\n .describe(\n 'The Hedera account ID (e.g., 0.0.12345) of the agent you want to connect with.'\n )\n });\n\n private hcsClient: HCS10Client;\n private stateManager: IStateManager;\n private logger: Logger;\n\n constructor({\n hcsClient,\n stateManager,\n ...rest\n }: InitiateConnectionToolParams) {\n super(rest);\n this.hcsClient = hcsClient;\n this.stateManager = stateManager;\n this.logger = Logger.getInstance({ module: 'InitiateConnectionTool' });\n }\n\n protected async _call({\n targetAccountId\n }: z.infer<this['schema']>): Promise<string> {\n const currentAgent = this.stateManager.getCurrentAgent();\n if (!currentAgent) {\n return 'Error: Cannot initiate connection. No agent is currently active. Please register or select an agent first.';\n }\n\n this.logger.info(\n `Attempting connection from ${currentAgent.accountId} to ${targetAccountId}`\n );\n\n try {\n this.logger.debug(`Retrieving profile for ${targetAccountId}...`);\n const targetProfile = await this.hcsClient.getAgentProfile(\n targetAccountId\n );\n if (!targetProfile?.topicInfo?.inboundTopic) {\n return `Error: Could not retrieve profile or find inbound topic ID for target agent ${targetAccountId}. They might not be registered or have a public profile.`;\n }\n const targetInboundTopicId = targetProfile.topicInfo.inboundTopic;\n const targetAgentName =\n targetProfile.profile.name || `Agent ${targetAccountId}`;\n\n const requestResult = await this.hcsClient.submitConnectionRequest(\n targetInboundTopicId,\n currentAgent.name\n );\n let connectionRequestId: number | null = null;\n const sequenceNumberLong = requestResult?.topicSequenceNumber;\n if (sequenceNumberLong !== null) {\n try {\n connectionRequestId = sequenceNumberLong.toNumber();\n if (isNaN(connectionRequestId)) {\n throw new Error('Converted sequence number is NaN.');\n }\n } catch (conversionError) {\n throw new Error(\n `Failed to convert connection request sequence number: ${conversionError}`\n );\n }\n } else {\n throw new Error('Connection request sequence number not found.');\n }\n\n const confirmationTimeoutMs = 60000;\n const delayMs = 2000;\n const maxAttempts = Math.ceil(confirmationTimeoutMs / delayMs);\n\n const confirmationResult =\n await this.hcsClient.waitForConnectionConfirmation(\n targetInboundTopicId,\n connectionRequestId,\n maxAttempts,\n delayMs\n );\n\n if (!confirmationResult?.connectionTopicId) {\n return `Error: Connection confirmation not received from ${targetAccountId} (for request ${connectionRequestId}) within ${\n confirmationTimeoutMs / 1000\n } seconds.`;\n }\n\n const connectionTopicId = confirmationResult.connectionTopicId;\n this.logger.info(`Connection confirmed! Topic ID: ${connectionTopicId}`);\n\n const newConnection: ActiveConnection = {\n targetAccountId: targetAccountId,\n targetAgentName: targetAgentName,\n targetInboundTopicId: targetInboundTopicId,\n connectionTopicId: connectionTopicId,\n };\n this.stateManager.addActiveConnection(newConnection);\n\n const connections = this.stateManager.listConnections();\n const addedEntry = connections.find(\n (c) => c.connectionTopicId === connectionTopicId\n );\n const localConnectionId = addedEntry\n ? connections.indexOf(addedEntry) + 1\n : null;\n\n const idString = localConnectionId ? `#${localConnectionId}` : '';\n\n return `Successfully established connection ${idString} with ${targetAgentName} (${targetAccountId}). Connection Topic: ${connectionTopicId}. You can now send messages using this connection.`;\n } catch (error) {\n this.logger.error(`Connection initiation failed: ${error}`);\n return `Error initiating connection with ${targetAccountId}: ${\n error instanceof Error ? error.message : String(error)\n }`;\n }\n }\n}\n"],"names":[],"mappings":";;;AAiBO,MAAM,+BAA+B,eAAe;AAAA,EAgBzD,YAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA,GAAG;AAAA,EAAA,GAC4B;AAC/B,UAAM,IAAI;AApBL,SAAA,OAAA;AAEL,SAAA,cAAA;AACF,SAAA,SAAS,EAAE,OAAO;AAAA,MAChB,iBAAiB,EACd,OAAA,EACA;AAAA,QACC;AAAA,MAAA;AAAA,IACF,CACH;AAYC,SAAK,YAAY;AACjB,SAAK,eAAe;AACpB,SAAK,SAAS,OAAO,YAAY,EAAE,QAAQ,0BAA0B;AAAA,EAAA;AAAA,EAGvE,MAAgB,MAAM;AAAA,IACpB;AAAA,EAAA,GAC2C;AACrC,UAAA,eAAe,KAAK,aAAa,gBAAgB;AACvD,QAAI,CAAC,cAAc;AACV,aAAA;AAAA,IAAA;AAGT,SAAK,OAAO;AAAA,MACV,8BAA8B,aAAa,SAAS,OAAO,eAAe;AAAA,IAC5E;AAEI,QAAA;AACF,WAAK,OAAO,MAAM,0BAA0B,eAAe,KAAK;AAC1D,YAAA,gBAAgB,MAAM,KAAK,UAAU;AAAA,QACzC;AAAA,MACF;AACI,UAAA,CAAC,eAAe,WAAW,cAAc;AAC3C,eAAO,+EAA+E,eAAe;AAAA,MAAA;AAEjG,YAAA,uBAAuB,cAAc,UAAU;AACrD,YAAM,kBACJ,cAAc,QAAQ,QAAQ,SAAS,eAAe;AAElD,YAAA,gBAAgB,MAAM,KAAK,UAAU;AAAA,QACzC;AAAA,QAC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iB,QAAQ,MAAM,UAAU,OAAO,KAAK,CACvD;AAAA,IAAA;AAAA,EACF;AAEJ;"}
|
|
@@ -1,99 +1,113 @@
|
|
|
1
1
|
import { StructuredTool } from "@langchain/core/tools";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import { Logger } from "@hashgraphonline/standards-sdk";
|
|
4
|
-
class
|
|
5
|
-
constructor({
|
|
6
|
-
hcsClient,
|
|
7
|
-
stateManager,
|
|
8
|
-
...rest
|
|
9
|
-
}) {
|
|
4
|
+
class ListConnectionsTool extends StructuredTool {
|
|
5
|
+
constructor({ stateManager, hcsClient, ...rest }) {
|
|
10
6
|
super(rest);
|
|
11
|
-
this.name = "
|
|
12
|
-
this.description = "
|
|
7
|
+
this.name = "list_connections";
|
|
8
|
+
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.";
|
|
13
9
|
this.schema = z.object({
|
|
14
|
-
|
|
15
|
-
"
|
|
16
|
-
)
|
|
10
|
+
includeDetails: z.boolean().optional().describe(
|
|
11
|
+
"Whether to include detailed information about each connection"
|
|
12
|
+
),
|
|
13
|
+
showPending: z.boolean().optional().describe("Whether to include pending connection requests")
|
|
17
14
|
});
|
|
18
|
-
this.hcsClient = hcsClient;
|
|
19
15
|
this.stateManager = stateManager;
|
|
20
|
-
this.
|
|
16
|
+
this.hcsClient = hcsClient;
|
|
17
|
+
this.logger = new Logger({ module: "ListConnectionsTool" });
|
|
21
18
|
}
|
|
22
|
-
async _call({
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
const
|
|
26
|
-
if (
|
|
27
|
-
return "
|
|
19
|
+
async _call(args) {
|
|
20
|
+
const includeDetails = args.includeDetails ?? true;
|
|
21
|
+
const showPending = args.showPending ?? true;
|
|
22
|
+
const connections = await this.getEnhancedConnections();
|
|
23
|
+
if (connections.length === 0) {
|
|
24
|
+
return "There are currently no active connections.";
|
|
28
25
|
}
|
|
29
|
-
|
|
30
|
-
|
|
26
|
+
const activeConnections = connections.filter(
|
|
27
|
+
(c) => c.status === "established"
|
|
31
28
|
);
|
|
29
|
+
const pendingConnections = connections.filter((c) => c.isPending);
|
|
30
|
+
const needsConfirmation = connections.filter((c) => c.needsConfirmation);
|
|
31
|
+
let output = "";
|
|
32
|
+
if (activeConnections.length > 0) {
|
|
33
|
+
output += `🟢 Active Connections (${activeConnections.length}):
|
|
34
|
+
`;
|
|
35
|
+
activeConnections.forEach((conn, index) => {
|
|
36
|
+
output += this.formatConnection(conn, index, includeDetails);
|
|
37
|
+
});
|
|
38
|
+
output += "\n";
|
|
39
|
+
}
|
|
40
|
+
if (showPending && needsConfirmation.length > 0) {
|
|
41
|
+
output += `🟠 Connections Needing Confirmation (${needsConfirmation.length}):
|
|
42
|
+
`;
|
|
43
|
+
needsConfirmation.forEach((conn, index) => {
|
|
44
|
+
output += this.formatConnection(conn, index, includeDetails);
|
|
45
|
+
});
|
|
46
|
+
output += "\n";
|
|
47
|
+
}
|
|
48
|
+
if (showPending && pendingConnections.length > 0) {
|
|
49
|
+
output += `⚪ Pending Connection Requests (${pendingConnections.length}):
|
|
50
|
+
`;
|
|
51
|
+
pendingConnections.forEach((conn, index) => {
|
|
52
|
+
output += this.formatConnection(conn, index, includeDetails);
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
return output.trim();
|
|
56
|
+
}
|
|
57
|
+
formatConnection(conn, index, includeDetails) {
|
|
58
|
+
let output = `${index + 1}. ${conn.profileInfo?.display_name || conn.targetAgentName || "Unknown Agent"} (${conn.targetAccountId})
|
|
59
|
+
`;
|
|
60
|
+
const displayTopicId = conn.isPending ? "(Pending Request)" : conn.connectionTopicId;
|
|
61
|
+
output += ` Topic: ${displayTopicId}
|
|
62
|
+
`;
|
|
63
|
+
const statusText = conn.status || "unknown";
|
|
64
|
+
output += ` Status: ${statusText}
|
|
65
|
+
`;
|
|
66
|
+
if (includeDetails) {
|
|
67
|
+
if (conn.profileInfo?.bio) {
|
|
68
|
+
output += ` Bio: ${conn.profileInfo.bio.substring(0, 100)}${conn.profileInfo.bio.length > 100 ? "..." : ""}
|
|
69
|
+
`;
|
|
70
|
+
}
|
|
71
|
+
if (conn.created) {
|
|
72
|
+
const createdLabel = conn.isPending ? "Request sent" : "Connection established";
|
|
73
|
+
output += ` ${createdLabel}: ${conn.created.toLocaleString()}
|
|
74
|
+
`;
|
|
75
|
+
}
|
|
76
|
+
if (conn.lastActivity) {
|
|
77
|
+
output += ` Last activity: ${conn.lastActivity.toLocaleString()}
|
|
78
|
+
`;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return output;
|
|
82
|
+
}
|
|
83
|
+
async getEnhancedConnections() {
|
|
84
|
+
if (!this.hcsClient) {
|
|
85
|
+
return this.stateManager.listConnections();
|
|
86
|
+
}
|
|
32
87
|
try {
|
|
33
|
-
this.
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
);
|
|
37
|
-
if (!targetProfile?.topicInfo?.inboundTopic) {
|
|
38
|
-
return `Error: Could not retrieve profile or find inbound topic ID for target agent ${targetAccountId}. They might not be registered or have a public profile.`;
|
|
88
|
+
const { accountId } = this.hcsClient.getAccountAndSigner();
|
|
89
|
+
if (!accountId) {
|
|
90
|
+
return this.stateManager.listConnections();
|
|
39
91
|
}
|
|
40
|
-
const
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
currentAgent.name
|
|
45
|
-
);
|
|
46
|
-
let connectionRequestId = null;
|
|
47
|
-
const sequenceNumberLong = requestResult?.topicSequenceNumber;
|
|
48
|
-
if (sequenceNumberLong !== null) {
|
|
49
|
-
try {
|
|
50
|
-
connectionRequestId = sequenceNumberLong.toNumber();
|
|
51
|
-
if (isNaN(connectionRequestId)) {
|
|
52
|
-
throw new Error("Converted sequence number is NaN.");
|
|
53
|
-
}
|
|
54
|
-
} catch (conversionError) {
|
|
55
|
-
throw new Error(
|
|
56
|
-
`Failed to convert connection request sequence number: ${conversionError}`
|
|
57
|
-
);
|
|
58
|
-
}
|
|
59
|
-
} else {
|
|
60
|
-
throw new Error("Connection request sequence number not found.");
|
|
92
|
+
const connectionManager = this.stateManager.getConnectionsManager();
|
|
93
|
+
if (!connectionManager) {
|
|
94
|
+
this.logger.error("ConnectionsManager not initialized");
|
|
95
|
+
return this.stateManager.listConnections();
|
|
61
96
|
}
|
|
62
|
-
const
|
|
63
|
-
|
|
64
|
-
const maxAttempts = Math.ceil(confirmationTimeoutMs / delayMs);
|
|
65
|
-
const confirmationResult = await this.hcsClient.waitForConnectionConfirmation(
|
|
66
|
-
targetInboundTopicId,
|
|
67
|
-
connectionRequestId,
|
|
68
|
-
maxAttempts,
|
|
69
|
-
delayMs
|
|
97
|
+
const connections = await connectionManager.fetchConnectionData(
|
|
98
|
+
accountId
|
|
70
99
|
);
|
|
71
|
-
|
|
72
|
-
|
|
100
|
+
for (const connection of connections) {
|
|
101
|
+
this.stateManager.updateOrAddConnection(connection);
|
|
73
102
|
}
|
|
74
|
-
|
|
75
|
-
this.logger.info(`Connection confirmed! Topic ID: ${connectionTopicId}`);
|
|
76
|
-
const newConnection = {
|
|
77
|
-
targetAccountId,
|
|
78
|
-
targetAgentName,
|
|
79
|
-
targetInboundTopicId,
|
|
80
|
-
connectionTopicId
|
|
81
|
-
};
|
|
82
|
-
this.stateManager.addActiveConnection(newConnection);
|
|
83
|
-
const connections = this.stateManager.listConnections();
|
|
84
|
-
const addedEntry = connections.find(
|
|
85
|
-
(c) => c.connectionTopicId === connectionTopicId
|
|
86
|
-
);
|
|
87
|
-
const localConnectionId = addedEntry ? connections.indexOf(addedEntry) + 1 : null;
|
|
88
|
-
const idString = localConnectionId ? `#${localConnectionId}` : "";
|
|
89
|
-
return `Successfully established connection ${idString} with ${targetAgentName} (${targetAccountId}). Connection Topic: ${connectionTopicId}. You can now send messages using this connection.`;
|
|
103
|
+
return connections;
|
|
90
104
|
} catch (error) {
|
|
91
|
-
|
|
92
|
-
return
|
|
105
|
+
console.error("Error fetching connection data:", error);
|
|
106
|
+
return this.stateManager.listConnections();
|
|
93
107
|
}
|
|
94
108
|
}
|
|
95
109
|
}
|
|
96
110
|
export {
|
|
97
|
-
|
|
111
|
+
ListConnectionsTool
|
|
98
112
|
};
|
|
99
113
|
//# sourceMappingURL=standards-agent-kit.es8.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"standards-agent-kit.es8.js","sources":["../../src/tools/
|
|
1
|
+
{"version":3,"file":"standards-agent-kit.es8.js","sources":["../../src/tools/ListConnectionsTool.ts"],"sourcesContent":["import { StructuredTool, ToolParams } from '@langchain/core/tools';\nimport { z } from 'zod';\nimport { IStateManager, ActiveConnection } from '../state/state-types';\nimport { HCS10Client } from '../hcs10/HCS10Client';\nimport { Connection, Logger } from '@hashgraphonline/standards-sdk';\n\nexport interface ListConnectionsToolParams extends ToolParams {\n stateManager: IStateManager;\n hcsClient?: HCS10Client;\n}\n\n/**\n * A tool to list currently active HCS-10 connections stored in the state manager.\n * Enhanced to show more details similar to moonscape's implementation.\n */\nexport class ListConnectionsTool extends StructuredTool {\n name = 'list_connections';\n description =\n '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.';\n schema = z.object({\n includeDetails: z\n .boolean()\n .optional()\n .describe(\n 'Whether to include detailed information about each connection'\n ),\n showPending: z\n .boolean()\n .optional()\n .describe('Whether to include pending connection requests'),\n });\n\n private stateManager: IStateManager;\n private hcsClient?: HCS10Client;\n private logger: Logger;\n\n constructor({ stateManager, hcsClient, ...rest }: ListConnectionsToolParams) {\n super(rest);\n this.stateManager = stateManager;\n this.hcsClient = hcsClient;\n this.logger = new Logger({ module: 'ListConnectionsTool' });\n }\n\n protected async _call(args: z.infer<this['schema']>): Promise<string> {\n const includeDetails = args.includeDetails ?? true;\n const showPending = args.showPending ?? true;\n\n const connections = await this.getEnhancedConnections();\n\n if (connections.length === 0) {\n return 'There are currently no active connections.';\n }\n\n const activeConnections = connections.filter(\n (c) => c.status === 'established'\n );\n\n const pendingConnections = connections.filter((c) => c.isPending);\n\n const needsConfirmation = connections.filter((c) => c.needsConfirmation);\n\n let output = '';\n\n if (activeConnections.length > 0) {\n output += `🟢 Active Connections (${activeConnections.length}):\\n`;\n activeConnections.forEach((conn, index) => {\n output += this.formatConnection(conn, index, includeDetails);\n });\n output += '\\n';\n }\n\n if (showPending && needsConfirmation.length > 0) {\n output += `🟠 Connections Needing Confirmation (${needsConfirmation.length}):\\n`;\n needsConfirmation.forEach((conn, index) => {\n output += this.formatConnection(conn, index, includeDetails);\n });\n output += '\\n';\n }\n\n if (showPending && pendingConnections.length > 0) {\n output += `⚪ Pending Connection Requests (${pendingConnections.length}):\\n`;\n pendingConnections.forEach((conn, index) => {\n output += this.formatConnection(conn, index, includeDetails);\n });\n }\n\n return output.trim();\n }\n\n private formatConnection(\n conn: Connection,\n index: number,\n includeDetails: boolean\n ): string {\n let output = `${index + 1}. ${\n conn.profileInfo?.display_name || conn.targetAgentName || 'Unknown Agent'\n } (${conn.targetAccountId})\\n`;\n const displayTopicId = conn.isPending\n ? '(Pending Request)'\n : conn.connectionTopicId;\n output += ` Topic: ${displayTopicId}\\n`;\n const statusText = conn.status || 'unknown';\n output += ` Status: ${statusText}\\n`;\n\n if (includeDetails) {\n if (conn.profileInfo?.bio) {\n output += ` Bio: ${conn.profileInfo.bio.substring(0, 100)}${\n conn.profileInfo.bio.length > 100 ? '...' : ''\n }\\n`;\n }\n\n if (conn.created) {\n const createdLabel = conn.isPending\n ? 'Request sent'\n : 'Connection established';\n output += ` ${createdLabel}: ${conn.created.toLocaleString()}\\n`;\n }\n\n if (conn.lastActivity) {\n output += ` Last activity: ${conn.lastActivity.toLocaleString()}\\n`;\n }\n }\n\n return output;\n }\n\n private async getEnhancedConnections(): Promise<Connection[]> {\n if (!this.hcsClient) {\n return this.stateManager.listConnections() as Connection[];\n }\n\n try {\n const { accountId } = this.hcsClient.getAccountAndSigner();\n if (!accountId) {\n return this.stateManager.listConnections() as Connection[];\n }\n\n const connectionManager = this.stateManager.getConnectionsManager();\n if (!connectionManager) {\n this.logger.error('ConnectionsManager not initialized');\n return this.stateManager.listConnections() as Connection[];\n }\n\n const connections = await connectionManager.fetchConnectionData(\n accountId\n );\n\n for (const connection of connections) {\n this.stateManager.updateOrAddConnection(connection as ActiveConnection);\n }\n\n return connections;\n } catch (error) {\n console.error('Error fetching connection data:', error);\n return this.stateManager.listConnections() as Connection[];\n }\n }\n}\n"],"names":[],"mappings":";;;AAeO,MAAM,4BAA4B,eAAe;AAAA,EAqBtD,YAAY,EAAE,cAAc,WAAW,GAAG,QAAmC;AAC3E,UAAM,IAAI;AArBL,SAAA,OAAA;AAEL,SAAA,cAAA;AACF,SAAA,SAAS,EAAE,OAAO;AAAA,MAChB,gBAAgB,EACb,UACA,SACA,EAAA;AAAA,QACC;AAAA,MACF;AAAA,MACF,aAAa,EACV,QAAA,EACA,SAAS,EACT,SAAS,gDAAgD;AAAA,IAAA,CAC7D;AAQC,SAAK,eAAe;AACpB,SAAK,YAAY;AACjB,SAAK,SAAS,IAAI,OAAO,EAAE,QAAQ,uBAAuB;AAAA,EAAA;AAAA,EAG5D,MAAgB,MAAM,MAAgD;AAC9D,UAAA,iBAAiB,KAAK,kBAAkB;AACxC,UAAA,cAAc,KAAK,eAAe;AAElC,UAAA,cAAc,MAAM,KAAK,uBAAuB;AAElD,QAAA,YAAY,WAAW,GAAG;AACrB,aAAA;AAAA,IAAA;AAGT,UAAM,oBAAoB,YAAY;AAAA,MACpC,CAAC,MAAM,EAAE,WAAW;AAAA,IACtB;AAEA,UAAM,qBAAqB,YAAY,OAAO,CAAC,MAAM,EAAE,SAAS;AAEhE,UAAM,oBAAoB,YAAY,OAAO,CAAC,MAAM,EAAE,iBAAiB;AAEvE,QAAI,SAAS;AAET,QAAA,kBAAkB,SAAS,GAAG;AACtB,gBAAA,0BAA0B,kBAAkB,MAAM;AAAA;AAC1C,wBAAA,QAAQ,CAAC,MAAM,UAAU;AACzC,kB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