@hashgraphonline/standards-agent-kit 0.0.32 → 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.
Files changed (54) hide show
  1. package/dist/cjs/src/init/index.d.ts +1 -0
  2. package/dist/cjs/src/{init.d.ts → init/init.d.ts} +16 -16
  3. package/dist/cjs/standards-agent-kit.cjs +1 -1
  4. package/dist/cjs/standards-agent-kit.cjs.map +1 -1
  5. package/dist/es/src/init/index.d.ts +1 -0
  6. package/dist/es/src/{init.d.ts → init/init.d.ts} +16 -16
  7. package/dist/es/standards-agent-kit.es.js +17 -17
  8. package/dist/es/standards-agent-kit.es10.js +65 -104
  9. package/dist/es/standards-agent-kit.es10.js.map +1 -1
  10. package/dist/es/standards-agent-kit.es11.js +371 -66
  11. package/dist/es/standards-agent-kit.es11.js.map +1 -1
  12. package/dist/es/standards-agent-kit.es12.js +153 -348
  13. package/dist/es/standards-agent-kit.es12.js.map +1 -1
  14. package/dist/es/standards-agent-kit.es13.js +105 -161
  15. package/dist/es/standards-agent-kit.es13.js.map +1 -1
  16. package/dist/es/standards-agent-kit.es14.js +48 -126
  17. package/dist/es/standards-agent-kit.es14.js.map +1 -1
  18. package/dist/es/standards-agent-kit.es15.js +108 -50
  19. package/dist/es/standards-agent-kit.es15.js.map +1 -1
  20. package/dist/es/standards-agent-kit.es16.js +239 -117
  21. package/dist/es/standards-agent-kit.es16.js.map +1 -1
  22. package/dist/es/standards-agent-kit.es17.js +120 -245
  23. package/dist/es/standards-agent-kit.es17.js.map +1 -1
  24. package/dist/es/standards-agent-kit.es2.js +321 -114
  25. package/dist/es/standards-agent-kit.es2.js.map +1 -1
  26. package/dist/es/standards-agent-kit.es23.js +15 -15
  27. package/dist/es/standards-agent-kit.es24.js +3 -24
  28. package/dist/es/standards-agent-kit.es24.js.map +1 -1
  29. package/dist/es/standards-agent-kit.es25.js +81 -3
  30. package/dist/es/standards-agent-kit.es25.js.map +1 -1
  31. package/dist/es/standards-agent-kit.es26.js +22 -79
  32. package/dist/es/standards-agent-kit.es26.js.map +1 -1
  33. package/dist/es/standards-agent-kit.es3.js +347 -284
  34. package/dist/es/standards-agent-kit.es3.js.map +1 -1
  35. package/dist/es/standards-agent-kit.es4.js +56 -366
  36. package/dist/es/standards-agent-kit.es4.js.map +1 -1
  37. package/dist/es/standards-agent-kit.es5.js +142 -58
  38. package/dist/es/standards-agent-kit.es5.js.map +1 -1
  39. package/dist/es/standards-agent-kit.es6.js +73 -143
  40. package/dist/es/standards-agent-kit.es6.js.map +1 -1
  41. package/dist/es/standards-agent-kit.es7.js +65 -64
  42. package/dist/es/standards-agent-kit.es7.js.map +1 -1
  43. package/dist/es/standards-agent-kit.es8.js +91 -77
  44. package/dist/es/standards-agent-kit.es8.js.map +1 -1
  45. package/dist/es/standards-agent-kit.es9.js +109 -90
  46. package/dist/es/standards-agent-kit.es9.js.map +1 -1
  47. package/dist/umd/src/init/index.d.ts +1 -0
  48. package/dist/umd/src/{init.d.ts → init/init.d.ts} +16 -16
  49. package/dist/umd/standards-agent-kit.umd.js +2 -2
  50. package/dist/umd/standards-agent-kit.umd.js.map +1 -1
  51. package/package.json +1 -1
  52. package/src/index.ts +1 -1
  53. package/src/init/index.ts +1 -0
  54. package/src/{init.ts → init/init.ts} +22 -20
@@ -1,69 +1,127 @@
1
1
  import { StructuredTool } from "@langchain/core/tools";
2
2
  import { z } from "zod";
3
3
  import { Logger } from "@hashgraphonline/standards-sdk";
4
- class RetrieveProfileTool extends StructuredTool {
5
- /**
6
- * Creates a new RetrieveProfileTool instance.
7
- * @param client - An instance of HCS10Client.
8
- */
9
- constructor(client) {
10
- super();
11
- this.name = "retrieve_profile";
12
- this.description = "Retrieves the HCS-11 profile data associated with a given Hedera account ID. If no account ID is provided, it defaults to the current operator account ID. Returns the profile object as a JSON string on success.";
4
+ class ListUnapprovedConnectionRequestsTool extends StructuredTool {
5
+ constructor({
6
+ hcsClient,
7
+ stateManager,
8
+ ...rest
9
+ }) {
10
+ super(rest);
11
+ this.name = "list_unapproved_connection_requests";
12
+ this.description = "Lists all connection requests that are not fully established, including incoming requests needing approval and outgoing requests waiting for confirmation.";
13
13
  this.schema = z.object({
14
- accountId: z.string().optional().describe(
15
- "The Hedera account ID (e.g., 0.0.12345) to retrieve the profile for. If omitted, defaults to the current operator account ID."
14
+ sortBy: z.enum(["time_asc", "time_desc", "name_asc", "name_desc"]).optional().describe(
15
+ "Optional sorting criteria for the requests list (default: time_desc, newest first)"
16
16
  ),
17
- disableCache: z.boolean().optional().describe(
18
- "Optional: Set to true to bypass the cache and fetch fresh profile data."
17
+ limit: z.number().optional().describe(
18
+ "Optional limit on the number of requests to return (default: all)"
19
19
  )
20
20
  });
21
- this.client = client;
22
- this.logger = Logger.getInstance({ module: this.name });
21
+ this.hcsClient = hcsClient;
22
+ this.stateManager = stateManager;
23
+ this.logger = Logger.getInstance({
24
+ module: "ListPendingRequestsTool",
25
+ level: "debug"
26
+ });
27
+ }
28
+ async _call({
29
+ sortBy = "time_desc",
30
+ limit
31
+ }) {
32
+ const currentAgent = this.stateManager.getCurrentAgent();
33
+ if (!currentAgent) {
34
+ return "Error: Cannot list pending requests. No agent is currently active. Please register or select an agent first.";
35
+ }
36
+ try {
37
+ const pendingRequests = await this.findAllPendingRequests();
38
+ return this.formatRequestsList(pendingRequests, sortBy, limit);
39
+ } catch (error) {
40
+ this.logger.error(`Error in ${this.name}: ${error}`);
41
+ return `Error listing pending requests: ${error instanceof Error ? error.message : String(error)}`;
42
+ }
23
43
  }
24
44
  /**
25
- * Executes the profile retrieval.
26
- * @param input - The input object containing accountId and optional disableCache flag.
27
- * @returns A JSON string of the profile on success, or an error message string.
45
+ * Processes the connection connectionMap to find all requests
46
+ * that are not fully established (incoming unapproved and outgoing pending).
28
47
  */
29
- async _call(input) {
30
- let targetAccountId;
31
- try {
32
- if (input.accountId) {
33
- targetAccountId = input.accountId;
34
- } else {
35
- this.logger.info("accountId not provided, defaulting to operator ID.");
36
- targetAccountId = this.client.getOperatorId();
48
+ async findAllPendingRequests() {
49
+ const connectionsManager = this.stateManager.getConnectionsManager();
50
+ if (!connectionsManager) {
51
+ return [];
52
+ }
53
+ const currentAgent = this.stateManager.getCurrentAgent();
54
+ if (!currentAgent) {
55
+ return [];
56
+ }
57
+ await connectionsManager.fetchConnectionData(currentAgent.accountId);
58
+ const pendingRequests = connectionsManager.getPendingRequests();
59
+ const connectionsNeedingConfirmation = connectionsManager.getConnectionsNeedingConfirmation();
60
+ return [...pendingRequests, ...connectionsNeedingConfirmation];
61
+ }
62
+ /**
63
+ * Formats the list of pending requests for display.
64
+ */
65
+ formatRequestsList(requests, sortBy, limit) {
66
+ if (requests.length === 0) {
67
+ return "No pending connection requests found (incoming or outgoing).";
68
+ }
69
+ const sortedRequests = this.sortRequests(requests, sortBy);
70
+ const limitedRequests = limit ? sortedRequests.slice(0, limit) : sortedRequests;
71
+ let output = `Found ${requests.length} pending connection request(s):
72
+
73
+ `;
74
+ limitedRequests.forEach((request, index) => {
75
+ const statusIndicator = request.status === "needs_confirmation" ? "🟠 Incoming" : "⚪️ Outgoing";
76
+ output += `${index + 1}. ${statusIndicator} - ID: ${request.uniqueRequestKey}
77
+ `;
78
+ output += ` ${request.status === "needs_confirmation" ? "From:" : "To: "} ${request.targetAgentName} (${request.targetAccountId})
79
+ `;
80
+ output += ` Sent/Rcvd: ${request.created.toLocaleString()}
81
+ `;
82
+ if (request.memo) {
83
+ output += ` Memo: ${request.memo}
84
+ `;
37
85
  }
38
- if (!targetAccountId) {
39
- throw new Error("Could not determine target account ID.");
86
+ if (request.profileInfo?.bio) {
87
+ output += ` Bio: ${request.profileInfo.bio.substring(0, 100)}${request.profileInfo.bio.length > 100 ? "..." : ""}
88
+ `;
40
89
  }
41
- this.logger.info(
42
- `Attempting to retrieve profile for account: ${targetAccountId}, Disable Cache: ${!!input.disableCache}`
43
- );
44
- const result = await this.client.standardClient.retrieveProfile(
45
- targetAccountId,
46
- input.disableCache
47
- );
48
- if (result.success && result.profile) {
49
- this.logger.info(
50
- `Successfully retrieved profile for ${targetAccountId}.`
90
+ output += "\n";
91
+ });
92
+ output += "Use related tools (manage_requests, accept_request) to handle these items.";
93
+ return output;
94
+ }
95
+ /**
96
+ * Sorts connection requests based on the specified criteria.
97
+ */
98
+ sortRequests(requests, sortBy) {
99
+ const requestsCopy = [...requests];
100
+ switch (sortBy) {
101
+ case "time_asc":
102
+ return requestsCopy.sort(
103
+ (a, b) => a.created.getTime() - b.created.getTime()
104
+ );
105
+ case "time_desc":
106
+ return requestsCopy.sort(
107
+ (a, b) => b.created.getTime() - a.created.getTime()
108
+ );
109
+ case "name_asc":
110
+ return requestsCopy.sort(
111
+ (a, b) => a.targetAgentName?.localeCompare(b?.targetAgentName || "") || 0
112
+ );
113
+ case "name_desc":
114
+ return requestsCopy.sort(
115
+ (a, b) => b.targetAgentName?.localeCompare(a?.targetAgentName || "") || 0
116
+ );
117
+ default:
118
+ return requestsCopy.sort(
119
+ (a, b) => b.created.getTime() - a.created.getTime()
51
120
  );
52
- return JSON.stringify(result.profile, null, 2);
53
- } else {
54
- const errorMessage = `Error retrieving profile for ${targetAccountId}: ${result.error || "Profile not found or invalid."}`;
55
- this.logger.error(errorMessage);
56
- return errorMessage;
57
- }
58
- } catch (error) {
59
- const idForError = input.accountId || "operator default";
60
- const errorMessage = `Unexpected error retrieving profile for ${idForError}: ${error instanceof Error ? error.message : String(error)}`;
61
- this.logger.error(errorMessage, error);
62
- return errorMessage;
63
121
  }
64
122
  }
65
123
  }
66
124
  export {
67
- RetrieveProfileTool
125
+ ListUnapprovedConnectionRequestsTool
68
126
  };
69
127
  //# sourceMappingURL=standards-agent-kit.es15.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"standards-agent-kit.es15.js","sources":["../../src/tools/RetrieveProfileTool.ts"],"sourcesContent":["import { StructuredTool } from '@langchain/core/tools';\nimport { z } from 'zod';\nimport { HCS10Client } from '../hcs10/HCS10Client';\nimport { Logger } from '@hashgraphonline/standards-sdk';\n\n/**\n * Tool for retrieving the HCS-11 profile associated with a Hedera account ID.\n * Utilizes the HCS10Client's retrieveProfile method, which handles fetching.\n */\nexport class RetrieveProfileTool extends StructuredTool {\n name = 'retrieve_profile';\n description =\n 'Retrieves the HCS-11 profile data associated with a given Hedera account ID. If no account ID is provided, it defaults to the current operator account ID. Returns the profile object as a JSON string on success.';\n\n private client: HCS10Client;\n private logger: Logger;\n\n schema = z.object({\n accountId: z\n .string()\n .optional()\n .describe(\n 'The Hedera account ID (e.g., 0.0.12345) to retrieve the profile for. If omitted, defaults to the current operator account ID.'\n ),\n disableCache: z\n .boolean()\n .optional()\n .describe(\n 'Optional: Set to true to bypass the cache and fetch fresh profile data.'\n ),\n });\n\n /**\n * Creates a new RetrieveProfileTool instance.\n * @param client - An instance of HCS10Client.\n */\n constructor(client: HCS10Client) {\n super();\n this.client = client;\n this.logger = Logger.getInstance({ module: this.name });\n }\n\n /**\n * Executes the profile retrieval.\n * @param input - The input object containing accountId and optional disableCache flag.\n * @returns A JSON string of the profile on success, or an error message string.\n */\n async _call(input: z.infer<typeof this.schema>): Promise<string> {\n let targetAccountId: string;\n try {\n if (input.accountId) {\n targetAccountId = input.accountId;\n } else {\n this.logger.info('accountId not provided, defaulting to operator ID.');\n targetAccountId = this.client.getOperatorId();\n }\n\n if (!targetAccountId) {\n throw new Error('Could not determine target account ID.');\n }\n\n this.logger.info(\n `Attempting to retrieve profile for account: ${targetAccountId}, Disable Cache: ${!!input.disableCache}`\n );\n\n // Call retrieveProfile via the standardClient instance using the determined ID\n const result = await this.client.standardClient.retrieveProfile(\n targetAccountId,\n input.disableCache\n );\n\n if (result.success && result.profile) {\n this.logger.info(\n `Successfully retrieved profile for ${targetAccountId}.`\n );\n\n return JSON.stringify(result.profile, null, 2); \n } else {\n const errorMessage = `Error retrieving profile for ${targetAccountId}: ${\n result.error || 'Profile not found or invalid.'\n }`;\n this.logger.error(errorMessage);\n return errorMessage;\n }\n } catch (error) {\n const idForError = input.accountId || 'operator default';\n const errorMessage = `Unexpected error retrieving profile for ${idForError}: ${\n error instanceof Error ? error.message : String(error)\n }`;\n this.logger.error(errorMessage, error);\n return errorMessage;\n }\n }\n}\n"],"names":[],"mappings":";;;AASO,MAAM,4BAA4B,eAAe;AAAA;AAAA;AAAA;AAAA;AAAA,EA2BtD,YAAY,QAAqB;AACzB,UAAA;AA3BD,SAAA,OAAA;AAEL,SAAA,cAAA;AAKF,SAAA,SAAS,EAAE,OAAO;AAAA,MAChB,WAAW,EACR,SACA,SACA,EAAA;AAAA,QACC;AAAA,MACF;AAAA,MACF,cAAc,EACX,UACA,SACA,EAAA;AAAA,QACC;AAAA,MAAA;AAAA,IACF,CACH;AAQC,SAAK,SAAS;AACd,SAAK,SAAS,OAAO,YAAY,EAAE,QAAQ,KAAK,MAAM;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQxD,MAAM,MAAM,OAAqD;AAC3D,QAAA;AACA,QAAA;AACF,UAAI,MAAM,WAAW;AACnB,0BAAkB,MAAM;AAAA,MAAA,OACnB;AACA,aAAA,OAAO,KAAK,oDAAoD;AACnD,0BAAA,KAAK,OAAO,cAAc;AAAA,MAAA;AAG9C,UAAI,CAAC,iBAAiB;AACd,cAAA,IAAI,MAAM,wCAAwC;AAAA,MAAA;AAG1D,WAAK,OAAO;AAAA,QACV,+CAA+C,eAAe,oBAAoB,CAAC,CAAC,MAAM,YAAY;AAAA,MACxG;AAGA,YAAM,SAAS,MAAM,KAAK,OAAO,eAAe;AAAA,QAC9C;AAAA,QACA,MAAM;AAAA,MACR;AAEI,UAAA,OAAO,WAAW,OAAO,SAAS;AACpC,aAAK,OAAO;AAAA,UACV,sCAAsC,eAAe;AAAA,QACvD;AAEA,eAAO,KAAK,UAAU,OAAO,SAAS,MAAM,CAAC;AAAA,MAAA,OACxC;AACL,cAAM,eAAe,gCAAgC,eAAe,KAClE,OAAO,SAAS,+BAClB;AACK,aAAA,OAAO,MAAM,YAAY;AACvB,eAAA;AAAA,MAAA;AAAA,aAEF,OAAO;AACR,YAAA,aAAa,MAAM,aAAa;AAChC,YAAA,eAAe,2CAA2C,UAAU,KACxE,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CACvD;AACK,WAAA,OAAO,MAAM,cAAc,KAAK;AAC9B,aAAA;AAAA,IAAA;AAAA,EACT;AAEJ;"}
1
+ {"version":3,"file":"standards-agent-kit.es15.js","sources":["../../src/tools/ListUnapprovedConnectionRequestsTool.ts"],"sourcesContent":["import { StructuredTool, ToolParams } from '@langchain/core/tools';\nimport { z } from 'zod';\nimport {\n IStateManager,\n} from '../state/state-types';\nimport { HCS10Client } from '../hcs10/HCS10Client';\nimport {\n Logger,\n Connection,\n} from '@hashgraphonline/standards-sdk';\n\n\ntype ListPendingRequestsToolParams = ToolParams & {\n hcsClient: HCS10Client;\n stateManager: IStateManager;\n};\n\nexport class ListUnapprovedConnectionRequestsTool extends StructuredTool {\n name = 'list_unapproved_connection_requests';\n description =\n 'Lists all connection requests that are not fully established, including incoming requests needing approval and outgoing requests waiting for confirmation.';\n schema = z.object({\n sortBy: z\n .enum(['time_asc', 'time_desc', 'name_asc', 'name_desc'])\n .optional()\n .describe(\n 'Optional sorting criteria for the requests list (default: time_desc, newest first)'\n ),\n limit: z\n .number()\n .optional()\n .describe(\n 'Optional limit on the number of requests to return (default: all)'\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 }: ListPendingRequestsToolParams) {\n super(rest);\n this.hcsClient = hcsClient;\n this.stateManager = stateManager;\n this.logger = Logger.getInstance({\n module: 'ListPendingRequestsTool',\n level: 'debug',\n });\n }\n\n protected async _call({\n sortBy = 'time_desc',\n limit,\n }: z.infer<this['schema']>): Promise<string> {\n const currentAgent = this.stateManager.getCurrentAgent();\n if (!currentAgent) {\n return 'Error: Cannot list pending requests. No agent is currently active. Please register or select an agent first.';\n }\n\n try {\n const pendingRequests = await this.findAllPendingRequests();\n return this.formatRequestsList(pendingRequests, sortBy, limit);\n } catch (error) {\n this.logger.error(`Error in ${this.name}: ${error}`);\n return `Error listing pending requests: ${\n error instanceof Error ? error.message : String(error)\n }`;\n }\n }\n\n /**\n * Processes the connection connectionMap to find all requests\n * that are not fully established (incoming unapproved and outgoing pending).\n */\n private async findAllPendingRequests(): Promise<Connection[]> {\n const connectionsManager = this.stateManager.getConnectionsManager();\n if (!connectionsManager) {\n return [];\n }\n const currentAgent = this.stateManager.getCurrentAgent();\n if (!currentAgent) {\n return [];\n }\n\n await connectionsManager.fetchConnectionData(currentAgent.accountId);\n const pendingRequests = connectionsManager.getPendingRequests();\n const connectionsNeedingConfirmation = connectionsManager.getConnectionsNeedingConfirmation();\n\n return [...pendingRequests, ...connectionsNeedingConfirmation];\n }\n\n /**\n * Formats the list of pending requests for display.\n */\n private formatRequestsList(\n requests: Connection[],\n sortBy: string,\n limit?: number\n ): string {\n if (requests.length === 0) {\n return 'No pending connection requests found (incoming or outgoing).';\n }\n\n const sortedRequests = this.sortRequests(requests, sortBy);\n const limitedRequests = limit\n ? sortedRequests.slice(0, limit)\n : sortedRequests;\n\n let output = `Found ${requests.length} pending connection request(s):\\n\\n`;\n\n limitedRequests.forEach((request, index) => {\n const statusIndicator =\n request.status === 'needs_confirmation'\n ? '🟠 Incoming'\n : '⚪️ Outgoing';\n output += `${index + 1}. ${statusIndicator} - ID: ${request.uniqueRequestKey}\\n`;\n output += ` ${\n request.status === 'needs_confirmation' ? 'From:' : 'To: '\n } ${request.targetAgentName} (${request.targetAccountId})\\n`;\n output += ` Sent/Rcvd: ${request.created.toLocaleString()}\\n`;\n if (request.memo) {\n output += ` Memo: ${request.memo}\\n`;\n }\n if (request.profileInfo?.bio) {\n output += ` Bio: ${request.profileInfo.bio.substring(0, 100)}${\n request.profileInfo.bio.length > 100 ? '...' : ''\n }\\n`;\n }\n output += '\\n';\n });\n\n output +=\n 'Use related tools (manage_requests, accept_request) to handle these items.';\n return output;\n }\n\n /**\n * Sorts connection requests based on the specified criteria.\n */\n private sortRequests(\n requests: Connection[],\n sortBy: string\n ): Connection[] {\n const requestsCopy = [...requests];\n\n switch (sortBy) {\n case 'time_asc':\n return requestsCopy.sort(\n (a, b) => a.created.getTime() - b.created.getTime()\n );\n case 'time_desc':\n return requestsCopy.sort(\n (a, b) => b.created.getTime() - a.created.getTime()\n );\n case 'name_asc':\n return requestsCopy.sort((a, b) =>\n a.targetAgentName?.localeCompare(b?.targetAgentName || '') || 0\n );\n case 'name_desc':\n return requestsCopy.sort((a, b) =>\n b.targetAgentName?.localeCompare(a?.targetAgentName || '') || 0\n );\n default:\n return requestsCopy.sort(\n (a, b) => b.created.getTime() - a.created.getTime()\n );\n }\n }\n}\n"],"names":[],"mappings":"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"}
@@ -1,127 +1,249 @@
1
- import { StructuredTool } from "@langchain/core/tools";
2
- import { z } from "zod";
3
- import { Logger } from "@hashgraphonline/standards-sdk";
4
- class ListUnapprovedConnectionRequestsTool extends StructuredTool {
5
- constructor({
6
- hcsClient,
7
- stateManager,
8
- ...rest
9
- }) {
10
- super(rest);
11
- this.name = "list_unapproved_connection_requests";
12
- this.description = "Lists all connection requests that are not fully established, including incoming requests needing approval and outgoing requests waiting for confirmation.";
13
- this.schema = z.object({
14
- sortBy: z.enum(["time_asc", "time_desc", "name_asc", "name_desc"]).optional().describe(
15
- "Optional sorting criteria for the requests list (default: time_desc, newest first)"
16
- ),
17
- limit: z.number().optional().describe(
18
- "Optional limit on the number of requests to return (default: all)"
19
- )
20
- });
21
- this.hcsClient = hcsClient;
22
- this.stateManager = stateManager;
23
- this.logger = Logger.getInstance({
24
- module: "ListPendingRequestsTool",
25
- level: "debug"
26
- });
27
- }
28
- async _call({
29
- sortBy = "time_desc",
30
- limit
31
- }) {
32
- const currentAgent = this.stateManager.getCurrentAgent();
33
- if (!currentAgent) {
34
- return "Error: Cannot list pending requests. No agent is currently active. Please register or select an agent first.";
35
- }
36
- try {
37
- const pendingRequests = await this.findAllPendingRequests();
38
- return this.formatRequestsList(pendingRequests, sortBy, limit);
39
- } catch (error) {
40
- this.logger.error(`Error in ${this.name}: ${error}`);
41
- return `Error listing pending requests: ${error instanceof Error ? error.message : String(error)}`;
42
- }
43
- }
44
- /**
45
- * Processes the connection connectionMap to find all requests
46
- * that are not fully established (incoming unapproved and outgoing pending).
47
- */
48
- async findAllPendingRequests() {
49
- const connectionsManager = this.stateManager.getConnectionsManager();
50
- if (!connectionsManager) {
51
- return [];
1
+ import { updateEnvFile } from "./standards-agent-kit.es26.js";
2
+ import { Logger, ConnectionsManager } from "@hashgraphonline/standards-sdk";
3
+ class OpenConvaiState {
4
+ /**
5
+ * Creates a new OpenConvaiState instance
6
+ * @param options - Options for environment variable persistence
7
+ */
8
+ constructor(options) {
9
+ this.currentAgent = null;
10
+ this.connectionMessageTimestamps = {};
11
+ this.connectionsManager = null;
12
+ this.defaultEnvFilePath = options?.defaultEnvFilePath;
13
+ this.defaultPrefix = options?.defaultPrefix ?? "TODD";
14
+ const shouldSilence = options?.disableLogging || process.env.DISABLE_LOGGING === "true";
15
+ this.logger = new Logger({ module: "OpenConvaiState", silent: shouldSilence });
16
+ if (options?.baseClient) {
17
+ this.initializeConnectionsManager(options.baseClient);
18
+ }
19
+ }
20
+ /**
21
+ * Initializes the ConnectionsManager
22
+ * @param baseClient - HCS10BaseClient instance to use
23
+ */
24
+ initializeConnectionsManager(baseClient) {
25
+ if (!this.connectionsManager) {
26
+ this.logger.debug("Initializing ConnectionsManager");
27
+ this.connectionsManager = new ConnectionsManager({
28
+ baseClient,
29
+ logLevel: "error"
30
+ });
31
+ } else {
32
+ this.logger.debug("ConnectionsManager already initialized");
33
+ }
34
+ return this.connectionsManager;
35
+ }
36
+ /**
37
+ * Gets the ConnectionsManager instance
38
+ * @returns The ConnectionsManager instance, or null if not initialized
39
+ */
40
+ getConnectionsManager() {
41
+ return this.connectionsManager;
42
+ }
43
+ /**
44
+ * Sets the current active agent and clears any previous connection data.
45
+ * This should be called when switching between agents.
46
+ */
47
+ setCurrentAgent(agent) {
48
+ this.currentAgent = agent;
49
+ this.connectionMessageTimestamps = {};
50
+ if (this.connectionsManager) {
51
+ this.connectionsManager.clearAll();
52
+ }
53
+ }
54
+ /**
55
+ * Returns the currently active agent or null if none is set.
56
+ */
57
+ getCurrentAgent() {
58
+ return this.currentAgent;
59
+ }
60
+ /**
61
+ * Adds a new connection to the active connections list.
62
+ * Ensures no duplicates are added based on connectionTopicId.
63
+ * Initializes timestamp tracking for the connection.
64
+ */
65
+ addActiveConnection(connection) {
66
+ if (!this.connectionsManager) {
67
+ this.logger.error(
68
+ "ConnectionsManager not initialized. Call initializeConnectionsManager before adding connections."
69
+ );
70
+ throw new Error(
71
+ "ConnectionsManager not initialized. Call initializeConnectionsManager before adding connections."
72
+ );
52
73
  }
53
- const currentAgent = this.stateManager.getCurrentAgent();
54
- if (!currentAgent) {
74
+ const sdkConnection = {
75
+ connectionTopicId: connection.connectionTopicId,
76
+ targetAccountId: connection.targetAccountId,
77
+ targetAgentName: connection.targetAgentName,
78
+ targetInboundTopicId: connection.targetInboundTopicId,
79
+ status: this.convertConnectionStatus(connection.status || "established"),
80
+ isPending: connection.isPending || false,
81
+ needsConfirmation: connection.needsConfirmation || false,
82
+ created: connection.created || /* @__PURE__ */ new Date(),
83
+ lastActivity: connection.lastActivity,
84
+ profileInfo: connection.profileInfo,
85
+ connectionRequestId: connection.connectionRequestId,
86
+ processed: true
87
+ };
88
+ this.connectionsManager.updateOrAddConnection(sdkConnection);
89
+ this.initializeTimestampIfNeeded(connection.connectionTopicId);
90
+ }
91
+ /**
92
+ * Updates an existing connection or adds it if not found.
93
+ * Preserves existing properties when updating by merging objects.
94
+ */
95
+ updateOrAddConnection(connection) {
96
+ this.addActiveConnection(connection);
97
+ }
98
+ /**
99
+ * Returns a copy of all active connections.
100
+ */
101
+ listConnections() {
102
+ if (!this.connectionsManager) {
103
+ this.logger.debug(
104
+ "ConnectionsManager not initialized, returning empty connections list"
105
+ );
55
106
  return [];
56
107
  }
57
- await connectionsManager.fetchConnectionData(currentAgent.accountId);
58
- const pendingRequests = connectionsManager.getPendingRequests();
59
- const connectionsNeedingConfirmation = connectionsManager.getConnectionsNeedingConfirmation();
60
- return [...pendingRequests, ...connectionsNeedingConfirmation];
61
- }
62
- /**
63
- * Formats the list of pending requests for display.
64
- */
65
- formatRequestsList(requests, sortBy, limit) {
66
- if (requests.length === 0) {
67
- return "No pending connection requests found (incoming or outgoing).";
68
- }
69
- const sortedRequests = this.sortRequests(requests, sortBy);
70
- const limitedRequests = limit ? sortedRequests.slice(0, limit) : sortedRequests;
71
- let output = `Found ${requests.length} pending connection request(s):
72
-
73
- `;
74
- limitedRequests.forEach((request, index) => {
75
- const statusIndicator = request.status === "needs_confirmation" ? "🟠 Incoming" : "⚪️ Outgoing";
76
- output += `${index + 1}. ${statusIndicator} - ID: ${request.uniqueRequestKey}
77
- `;
78
- output += ` ${request.status === "needs_confirmation" ? "From:" : "To: "} ${request.targetAgentName} (${request.targetAccountId})
79
- `;
80
- output += ` Sent/Rcvd: ${request.created.toLocaleString()}
81
- `;
82
- if (request.memo) {
83
- output += ` Memo: ${request.memo}
84
- `;
85
- }
86
- if (request.profileInfo?.bio) {
87
- output += ` Bio: ${request.profileInfo.bio.substring(0, 100)}${request.profileInfo.bio.length > 100 ? "..." : ""}
88
- `;
89
- }
90
- output += "\n";
91
- });
92
- output += "Use related tools (manage_requests, accept_request) to handle these items.";
93
- return output;
94
- }
95
- /**
96
- * Sorts connection requests based on the specified criteria.
97
- */
98
- sortRequests(requests, sortBy) {
99
- const requestsCopy = [...requests];
100
- switch (sortBy) {
101
- case "time_asc":
102
- return requestsCopy.sort(
103
- (a, b) => a.created.getTime() - b.created.getTime()
104
- );
105
- case "time_desc":
106
- return requestsCopy.sort(
107
- (a, b) => b.created.getTime() - a.created.getTime()
108
- );
109
- case "name_asc":
110
- return requestsCopy.sort(
111
- (a, b) => a.targetAgentName?.localeCompare(b?.targetAgentName || "") || 0
112
- );
113
- case "name_desc":
114
- return requestsCopy.sort(
115
- (a, b) => b.targetAgentName?.localeCompare(a?.targetAgentName || "") || 0
116
- );
108
+ return this.connectionsManager.getAllConnections().map((conn) => this.convertToActiveConnection(conn));
109
+ }
110
+ /**
111
+ * Finds a connection by its identifier, which can be:
112
+ * - A 1-based index as displayed in the connection list
113
+ * - A target account ID string
114
+ * - A connection topic ID string
115
+ */
116
+ getConnectionByIdentifier(identifier) {
117
+ if (!this.connectionsManager) {
118
+ return void 0;
119
+ }
120
+ const connections = this.listConnections();
121
+ const numericIndex = parseInt(identifier) - 1;
122
+ if (!isNaN(numericIndex) && numericIndex >= 0 && numericIndex < connections.length) {
123
+ return connections[numericIndex];
124
+ }
125
+ const byTopicId = this.connectionsManager.getConnectionByTopicId(identifier);
126
+ if (byTopicId) {
127
+ return this.convertToActiveConnection(byTopicId);
128
+ }
129
+ const byAccountId = this.connectionsManager.getConnectionByAccountId(identifier);
130
+ if (byAccountId) {
131
+ return this.convertToActiveConnection(byAccountId);
132
+ }
133
+ return void 0;
134
+ }
135
+ /**
136
+ * Gets the last processed message timestamp for a connection.
137
+ * Returns 0 if no timestamp has been recorded.
138
+ */
139
+ getLastTimestamp(connectionTopicId) {
140
+ return this.connectionMessageTimestamps[connectionTopicId] || 0;
141
+ }
142
+ /**
143
+ * Updates the last processed message timestamp for a connection,
144
+ * but only if the new timestamp is more recent than the existing one.
145
+ */
146
+ updateTimestamp(connectionTopicId, timestampNanos) {
147
+ if (!(connectionTopicId in this.connectionMessageTimestamps)) {
148
+ this.connectionMessageTimestamps[connectionTopicId] = timestampNanos;
149
+ return;
150
+ }
151
+ const currentTimestamp = this.connectionMessageTimestamps[connectionTopicId];
152
+ if (timestampNanos > currentTimestamp) {
153
+ this.connectionMessageTimestamps[connectionTopicId] = timestampNanos;
154
+ }
155
+ }
156
+ /**
157
+ * Helper method to initialize timestamp tracking for a connection
158
+ * if it doesn't already exist.
159
+ */
160
+ initializeTimestampIfNeeded(connectionTopicId) {
161
+ if (!(connectionTopicId in this.connectionMessageTimestamps)) {
162
+ this.connectionMessageTimestamps[connectionTopicId] = Date.now() * 1e6;
163
+ }
164
+ }
165
+ /**
166
+ * Converts ConnectionStatus to SDK status format
167
+ */
168
+ convertConnectionStatus(status) {
169
+ switch (status) {
170
+ case "pending":
171
+ return "pending";
172
+ case "established":
173
+ return "established";
174
+ case "needs confirmation":
175
+ return "needs_confirmation";
176
+ default:
177
+ return "established";
178
+ }
179
+ }
180
+ /**
181
+ * Converts SDK Connection to ActiveConnection
182
+ */
183
+ convertToActiveConnection(conn) {
184
+ return {
185
+ targetAccountId: conn.targetAccountId,
186
+ targetAgentName: conn.targetAgentName || `Agent ${conn.targetAccountId}`,
187
+ targetInboundTopicId: conn.targetInboundTopicId || "",
188
+ connectionTopicId: conn.connectionTopicId,
189
+ status: this.convertToStateStatus(conn.status),
190
+ created: conn.created,
191
+ lastActivity: conn.lastActivity,
192
+ isPending: conn.isPending,
193
+ needsConfirmation: conn.needsConfirmation,
194
+ profileInfo: conn.profileInfo,
195
+ connectionRequestId: conn.connectionRequestId
196
+ };
197
+ }
198
+ /**
199
+ * Converts SDK status to state status format
200
+ */
201
+ convertToStateStatus(status) {
202
+ switch (status) {
203
+ case "pending":
204
+ return "pending";
205
+ case "established":
206
+ return "established";
207
+ case "needs_confirmation":
208
+ return "needs confirmation";
209
+ case "closed":
210
+ return "established";
211
+ // Mapping closed to established for compatibility
117
212
  default:
118
- return requestsCopy.sort(
119
- (a, b) => b.created.getTime() - a.created.getTime()
120
- );
213
+ return "unknown";
214
+ }
215
+ }
216
+ /**
217
+ * Persists agent data to environment variables
218
+ * @param agent - The agent data to persist
219
+ * @param options - Environment file persistence options
220
+ */
221
+ async persistAgentData(agent, options) {
222
+ if (options?.type && options.type !== "env-file") {
223
+ throw new Error(
224
+ `Unsupported persistence type: ${options.type}. Only 'env-file' is supported.`
225
+ );
226
+ }
227
+ const envFilePath = options?.envFilePath || this.defaultEnvFilePath || process.env.ENV_FILE_PATH || ".env";
228
+ const prefix = options?.prefix || this.defaultPrefix;
229
+ if (!agent.accountId || !agent.inboundTopicId || !agent.outboundTopicId) {
230
+ throw new Error("Agent data incomplete, cannot persist to environment");
231
+ }
232
+ const updates = {
233
+ [`${prefix}_ACCOUNT_ID`]: agent.accountId,
234
+ [`${prefix}_INBOUND_TOPIC_ID`]: agent.inboundTopicId,
235
+ [`${prefix}_OUTBOUND_TOPIC_ID`]: agent.outboundTopicId
236
+ };
237
+ if (agent.privateKey) {
238
+ updates[`${prefix}_PRIVATE_KEY`] = agent.privateKey;
239
+ }
240
+ if (agent.profileTopicId) {
241
+ updates[`${prefix}_PROFILE_TOPIC_ID`] = agent.profileTopicId;
121
242
  }
243
+ await updateEnvFile(envFilePath, updates);
122
244
  }
123
245
  }
124
246
  export {
125
- ListUnapprovedConnectionRequestsTool
247
+ OpenConvaiState
126
248
  };
127
249
  //# sourceMappingURL=standards-agent-kit.es16.js.map