@hashgraphonline/standards-agent-kit 0.0.28-canary.2 → 0.0.30-canary.0
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/state/open-convai-state.d.ts +1 -0
- package/dist/cjs/standards-agent-kit.cjs +1 -1
- package/dist/cjs/standards-agent-kit.cjs.map +1 -1
- package/dist/es/src/state/open-convai-state.d.ts +1 -0
- package/dist/es/standards-agent-kit.es17.js +2 -1
- package/dist/es/standards-agent-kit.es17.js.map +1 -1
- package/dist/es/standards-agent-kit.es2.js +3 -1
- package/dist/es/standards-agent-kit.es2.js.map +1 -1
- package/dist/es/standards-agent-kit.es3.js +3 -1
- package/dist/es/standards-agent-kit.es3.js.map +1 -1
- package/dist/umd/src/state/open-convai-state.d.ts +1 -0
- package/dist/umd/standards-agent-kit.umd.js +7 -7
- package/dist/umd/standards-agent-kit.umd.js.map +1 -1
- package/package.json +2 -2
- package/src/hcs10/HCS10Client.ts +2 -0
- package/src/init.ts +2 -0
- package/src/plugins/openconvai/index.ts +0 -2
- package/src/state/open-convai-state.ts +3 -1
- package/src/utils/connectionUtils.ts +5 -1
|
@@ -11,7 +11,8 @@ class OpenConvaiState {
|
|
|
11
11
|
this.connectionsManager = null;
|
|
12
12
|
this.defaultEnvFilePath = options?.defaultEnvFilePath;
|
|
13
13
|
this.defaultPrefix = options?.defaultPrefix ?? "TODD";
|
|
14
|
-
|
|
14
|
+
const shouldSilence = options?.disableLogging || process.env.DISABLE_LOGGING === "true";
|
|
15
|
+
this.logger = new Logger({ module: "OpenConvaiState", silent: shouldSilence });
|
|
15
16
|
if (options?.baseClient) {
|
|
16
17
|
this.initializeConnectionsManager(options.baseClient);
|
|
17
18
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"standards-agent-kit.es17.js","sources":["../../src/state/open-convai-state.ts"],"sourcesContent":["import { updateEnvFile } from '../utils/state-tools';\nimport {\n RegisteredAgent,\n ActiveConnection,\n IStateManager,\n AgentPersistenceOptions,\n EnvFilePersistenceOptions,\n ConnectionStatus,\n} from './state-types';\nimport {\n ConnectionsManager,\n HCS10BaseClient,\n Connection,\n Logger,\n IConnectionsManager,\n} from '@hashgraphonline/standards-sdk';\n\n/**\n * Implementation of the IStateManager interface for the OpenConvai system.\n * Manages agent state and connection information with thread safety and\n * proper timestamp tracking.\n */\nexport class OpenConvaiState implements IStateManager {\n private currentAgent: RegisteredAgent | null = null;\n private connectionMessageTimestamps: Record<string, number> = {};\n private defaultEnvFilePath?: string;\n private defaultPrefix: string;\n private connectionsManager: IConnectionsManager | null = null;\n private logger: Logger;\n\n /**\n * Creates a new OpenConvaiState instance\n * @param options - Options for environment variable persistence\n */\n constructor(options?: {\n defaultEnvFilePath?: string;\n defaultPrefix?: string;\n baseClient?: HCS10BaseClient;\n }) {\n this.defaultEnvFilePath = options?.defaultEnvFilePath;\n this.defaultPrefix = options?.defaultPrefix ?? 'TODD';\n this.logger = new Logger({ module: 'OpenConvaiState' });\n\n // Initialize ConnectionsManager immediately if baseClient is provided\n if (options?.baseClient) {\n this.initializeConnectionsManager(options.baseClient);\n }\n }\n\n /**\n * Initializes the ConnectionsManager\n * @param baseClient - HCS10BaseClient instance to use\n */\n initializeConnectionsManager(\n baseClient: HCS10BaseClient\n ): IConnectionsManager {\n if (!this.connectionsManager) {\n this.logger.debug('Initializing ConnectionsManager');\n this.connectionsManager = new ConnectionsManager({\n baseClient,\n logLevel: 'error',\n });\n } else {\n this.logger.debug('ConnectionsManager already initialized');\n }\n return this.connectionsManager;\n }\n\n /**\n * Gets the ConnectionsManager instance\n * @returns The ConnectionsManager instance, or null if not initialized\n */\n getConnectionsManager(): IConnectionsManager | null {\n return this.connectionsManager;\n }\n\n /**\n * Sets the current active agent and clears any previous connection data.\n * This should be called when switching between agents.\n */\n setCurrentAgent(agent: RegisteredAgent | null): void {\n this.currentAgent = agent;\n this.connectionMessageTimestamps = {};\n\n // Clear connections manager when changing agents\n if (this.connectionsManager) {\n this.connectionsManager.clearAll();\n }\n }\n\n /**\n * Returns the currently active agent or null if none is set.\n */\n getCurrentAgent(): RegisteredAgent | null {\n return this.currentAgent;\n }\n\n /**\n * Adds a new connection to the active connections list.\n * Ensures no duplicates are added based on connectionTopicId.\n * Initializes timestamp tracking for the connection.\n */\n addActiveConnection(connection: ActiveConnection): void {\n if (!this.connectionsManager) {\n this.logger.error(\n 'ConnectionsManager not initialized. Call initializeConnectionsManager before adding connections.'\n );\n throw new Error(\n 'ConnectionsManager not initialized. Call initializeConnectionsManager before adding connections.'\n );\n }\n\n // Convert from ActiveConnection to Connection\n const sdkConnection: Connection = {\n connectionTopicId: connection.connectionTopicId,\n targetAccountId: connection.targetAccountId,\n targetAgentName: connection.targetAgentName,\n targetInboundTopicId: connection.targetInboundTopicId,\n status: this.convertConnectionStatus(connection.status || 'established'),\n isPending: connection.isPending || false,\n needsConfirmation: connection.needsConfirmation || false,\n created: connection.created || new Date(),\n lastActivity: connection.lastActivity,\n profileInfo: connection.profileInfo,\n connectionRequestId: connection.connectionRequestId,\n processed: true,\n };\n\n // Add to ConnectionsManager\n this.connectionsManager.updateOrAddConnection(sdkConnection);\n\n // Initialize timestamp tracking\n this.initializeTimestampIfNeeded(connection.connectionTopicId);\n }\n\n /**\n * Updates an existing connection or adds it if not found.\n * Preserves existing properties when updating by merging objects.\n */\n updateOrAddConnection(connection: ActiveConnection): void {\n this.addActiveConnection(connection);\n }\n\n /**\n * Returns a copy of all active connections.\n */\n listConnections(): ActiveConnection[] {\n if (!this.connectionsManager) {\n this.logger.debug(\n 'ConnectionsManager not initialized, returning empty connections list'\n );\n return [];\n }\n\n // Convert SDK Connections to ActiveConnection\n return this.connectionsManager\n .getAllConnections()\n .map((conn) => this.convertToActiveConnection(conn));\n }\n\n /**\n * Finds a connection by its identifier, which can be:\n * - A 1-based index as displayed in the connection list\n * - A target account ID string\n * - A connection topic ID string\n */\n getConnectionByIdentifier(identifier: string): ActiveConnection | undefined {\n if (!this.connectionsManager) {\n return undefined;\n }\n\n const connections = this.listConnections();\n\n // Check if it's a 1-based index\n const numericIndex = parseInt(identifier) - 1;\n if (\n !isNaN(numericIndex) &&\n numericIndex >= 0 &&\n numericIndex < connections.length\n ) {\n return connections[numericIndex];\n }\n\n // Check if it's a topic ID\n const byTopicId =\n this.connectionsManager.getConnectionByTopicId(identifier);\n if (byTopicId) {\n return this.convertToActiveConnection(byTopicId);\n }\n\n // Check if it's an account ID\n const byAccountId =\n this.connectionsManager.getConnectionByAccountId(identifier);\n if (byAccountId) {\n return this.convertToActiveConnection(byAccountId);\n }\n\n return undefined;\n }\n\n /**\n * Gets the last processed message timestamp for a connection.\n * Returns 0 if no timestamp has been recorded.\n */\n getLastTimestamp(connectionTopicId: string): number {\n return this.connectionMessageTimestamps[connectionTopicId] || 0;\n }\n\n /**\n * Updates the last processed message timestamp for a connection,\n * but only if the new timestamp is more recent than the existing one.\n */\n updateTimestamp(connectionTopicId: string, timestampNanos: number): void {\n // Initialize if this is first update and skip the comparison logic\n if (!(connectionTopicId in this.connectionMessageTimestamps)) {\n this.connectionMessageTimestamps[connectionTopicId] = timestampNanos;\n return;\n }\n\n // Otherwise, only update if newer\n const currentTimestamp =\n this.connectionMessageTimestamps[connectionTopicId];\n if (timestampNanos > currentTimestamp) {\n this.connectionMessageTimestamps[connectionTopicId] = timestampNanos;\n }\n }\n\n /**\n * Helper method to initialize timestamp tracking for a connection\n * if it doesn't already exist.\n */\n private initializeTimestampIfNeeded(connectionTopicId: string): void {\n if (!(connectionTopicId in this.connectionMessageTimestamps)) {\n this.connectionMessageTimestamps[connectionTopicId] =\n Date.now() * 1_000_000;\n }\n }\n\n /**\n * Converts ConnectionStatus to SDK status format\n */\n private convertConnectionStatus(\n status: string\n ): 'pending' | 'established' | 'needs_confirmation' | 'closed' {\n switch (status) {\n case 'pending':\n return 'pending';\n case 'established':\n return 'established';\n case 'needs confirmation':\n return 'needs_confirmation';\n default:\n return 'established';\n }\n }\n\n /**\n * Converts SDK Connection to ActiveConnection\n */\n private convertToActiveConnection(conn: Connection): ActiveConnection {\n return {\n targetAccountId: conn.targetAccountId,\n targetAgentName: conn.targetAgentName || `Agent ${conn.targetAccountId}`,\n targetInboundTopicId: conn.targetInboundTopicId || '',\n connectionTopicId: conn.connectionTopicId,\n status: this.convertToStateStatus(conn.status),\n created: conn.created,\n lastActivity: conn.lastActivity,\n isPending: conn.isPending,\n needsConfirmation: conn.needsConfirmation,\n profileInfo: conn.profileInfo,\n connectionRequestId: conn.connectionRequestId,\n };\n }\n\n /**\n * Converts SDK status to state status format\n */\n private convertToStateStatus(status: string): ConnectionStatus {\n switch (status) {\n case 'pending':\n return 'pending';\n case 'established':\n return 'established';\n case 'needs_confirmation':\n return 'needs confirmation';\n case 'closed':\n return 'established'; // Mapping closed to established for compatibility\n default:\n return 'unknown';\n }\n }\n\n /**\n * Persists agent data to environment variables\n * @param agent - The agent data to persist\n * @param options - Environment file persistence options\n */\n async persistAgentData(\n agent: RegisteredAgent,\n options?: AgentPersistenceOptions\n ): Promise<void> {\n if (options?.type && options.type !== 'env-file') {\n throw new Error(\n `Unsupported persistence type: ${options.type}. Only 'env-file' is supported.`\n );\n }\n\n const envFilePath =\n (options as EnvFilePersistenceOptions)?.envFilePath ||\n this.defaultEnvFilePath ||\n process.env.ENV_FILE_PATH ||\n '.env';\n\n if (!envFilePath) {\n throw new Error(\n 'Environment file path could not be determined for agent data persistence'\n );\n }\n\n const prefix =\n (options as EnvFilePersistenceOptions)?.prefix || this.defaultPrefix;\n\n if (!agent.accountId || !agent.inboundTopicId || !agent.outboundTopicId) {\n throw new Error('Agent data incomplete, cannot persist to environment');\n }\n\n const updates: Record<string, string> = {\n [`${prefix}_ACCOUNT_ID`]: agent.accountId,\n [`${prefix}_INBOUND_TOPIC_ID`]: agent.inboundTopicId,\n [`${prefix}_OUTBOUND_TOPIC_ID`]: agent.outboundTopicId,\n };\n\n if (agent.privateKey) {\n updates[`${prefix}_PRIVATE_KEY`] = agent.privateKey;\n }\n\n if (agent.profileTopicId) {\n updates[`${prefix}_PROFILE_TOPIC_ID`] = agent.profileTopicId;\n }\n\n await updateEnvFile(envFilePath, updates);\n }\n}\n"],"names":[],"mappings":";;AAsBO,MAAM,gBAAyC;AAAA;AAAA;AAAA;AAAA;AAAA,EAYpD,YAAY,SAIT;AAfH,SAAQ,eAAuC;AAC/C,SAAQ,8BAAsD,CAAC;AAG/D,SAAQ,qBAAiD;AAYvD,SAAK,qBAAqB,SAAS;AAC9B,SAAA,gBAAgB,SAAS,iBAAiB;AAC/C,SAAK,SAAS,IAAI,OAAO,EAAE,QAAQ,mBAAmB;AAGtD,QAAI,SAAS,YAAY;AAClB,WAAA,6BAA6B,QAAQ,UAAU;AAAA,IAAA;AAAA,EACtD;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,6BACE,YACqB;AACjB,QAAA,CAAC,KAAK,oBAAoB;AACvB,WAAA,OAAO,MAAM,iCAAiC;AAC9C,WAAA,qBAAqB,IAAI,mBAAmB;AAAA,QAC/C;AAAA,QACA,UAAU;AAAA,MAAA,CACX;AAAA,IAAA,OACI;AACA,WAAA,OAAO,MAAM,wCAAwC;AAAA,IAAA;AAE5D,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOd,wBAAoD;AAClD,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOd,gBAAgB,OAAqC;AACnD,SAAK,eAAe;AACpB,SAAK,8BAA8B,CAAC;AAGpC,QAAI,KAAK,oBAAoB;AAC3B,WAAK,mBAAmB,SAAS;AAAA,IAAA;AAAA,EACnC;AAAA;AAAA;AAAA;AAAA,EAMF,kBAA0C;AACxC,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQd,oBAAoB,YAAoC;AAClD,QAAA,CAAC,KAAK,oBAAoB;AAC5B,WAAK,OAAO;AAAA,QACV;AAAA,MACF;AACA,YAAM,IAA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mBAAmB,KAAK;AAAA,MACxB,aAAa,KAAK;AAAA,MAClB,qBAAqB,KAAK;AAAA,IAC5B;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMM,qBAAqB,QAAkC;AAC7D,YAAQ,QAAQ;AAAA,MACd,KAAK;AACI,eAAA;AAAA,MACT,KAAK;AACI,eAAA;AAAA,MACT,KAAK;AACI,eAAA;AAAA,MACT,KAAK;AACI,eAAA;AAAA;AAAA,MACT;AACS,eAAA;AAAA,IAAA;AAAA,EACX;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQF,MAAM,iBACJ,OACA,SACe;AACf,QAAI,SAAS,QAAQ,QAAQ,SAAS,YAAY;AAChD,YAAM,IAAI;AAAA,QACR,iCAAiC,QAAQ,IAAI;AAAA,MAC/C;AAAA,IAAA;AAGF,UAAM,cACH,SAAuC,eACxC,KAAK,sBACL,QAAQ,IAAI,iBACZ;AAQI,UAAA,SACH,SAAuC,UAAU,KAAK;AAErD,QAAA,CAAC,MAAM,aAAa,CAAC,MAAM,kBAAkB,CAAC,MAAM,iBAAiB;AACjE,YAAA,IAAI,MAAM,sDAAsD;AAAA,IAAA;AAGxE,UAAM,UAAkC;AAAA,MACtC,CAAC,GAAG,MAAM,aAAa,GAAG,MAAM;AAAA,MAChC,CAAC,GAAG,MAAM,mBAAmB,GAAG,MAAM;AAAA,MACtC,CAAC,GAAG,MAAM,oBAAoB,GAAG,MAAM;AAAA,IACzC;AAEA,QAAI,MAAM,YAAY;AACpB,cAAQ,GAAG,MAAM,cAAc,IAAI,MAAM;AAAA,IAAA;AAG3C,QAAI,MAAM,gBAAgB;AACxB,cAAQ,GAAG,MAAM,mBAAmB,IAAI,MAAM;AAAA,IAAA;AAG1C,UAAA,cAAc,aAAa,OAAO;AAAA,EAAA;AAE5C;"}
|
|
1
|
+
{"version":3,"file":"standards-agent-kit.es17.js","sources":["../../src/state/open-convai-state.ts"],"sourcesContent":["import { updateEnvFile } from '../utils/state-tools';\nimport {\n RegisteredAgent,\n ActiveConnection,\n IStateManager,\n AgentPersistenceOptions,\n EnvFilePersistenceOptions,\n ConnectionStatus,\n} from './state-types';\nimport {\n ConnectionsManager,\n HCS10BaseClient,\n Connection,\n Logger,\n IConnectionsManager,\n} from '@hashgraphonline/standards-sdk';\n\n/**\n * Implementation of the IStateManager interface for the OpenConvai system.\n * Manages agent state and connection information with thread safety and\n * proper timestamp tracking.\n */\nexport class OpenConvaiState implements IStateManager {\n private currentAgent: RegisteredAgent | null = null;\n private connectionMessageTimestamps: Record<string, number> = {};\n private defaultEnvFilePath?: string;\n private defaultPrefix: string;\n private connectionsManager: IConnectionsManager | null = null;\n private logger: Logger;\n\n /**\n * Creates a new OpenConvaiState instance\n * @param options - Options for environment variable persistence\n */\n constructor(options?: {\n defaultEnvFilePath?: string;\n defaultPrefix?: string;\n baseClient?: HCS10BaseClient;\n disableLogging?: boolean;\n }) {\n this.defaultEnvFilePath = options?.defaultEnvFilePath;\n this.defaultPrefix = options?.defaultPrefix ?? 'TODD';\n const shouldSilence = options?.disableLogging || process.env.DISABLE_LOGGING === 'true';\n this.logger = new Logger({ module: 'OpenConvaiState', silent: shouldSilence });\n\n // Initialize ConnectionsManager immediately if baseClient is provided\n if (options?.baseClient) {\n this.initializeConnectionsManager(options.baseClient);\n }\n }\n\n /**\n * Initializes the ConnectionsManager\n * @param baseClient - HCS10BaseClient instance to use\n */\n initializeConnectionsManager(\n baseClient: HCS10BaseClient\n ): IConnectionsManager {\n if (!this.connectionsManager) {\n this.logger.debug('Initializing ConnectionsManager');\n this.connectionsManager = new ConnectionsManager({\n baseClient,\n logLevel: 'error',\n });\n } else {\n this.logger.debug('ConnectionsManager already initialized');\n }\n return this.connectionsManager;\n }\n\n /**\n * Gets the ConnectionsManager instance\n * @returns The ConnectionsManager instance, or null if not initialized\n */\n getConnectionsManager(): IConnectionsManager | null {\n return this.connectionsManager;\n }\n\n /**\n * Sets the current active agent and clears any previous connection data.\n * This should be called when switching between agents.\n */\n setCurrentAgent(agent: RegisteredAgent | null): void {\n this.currentAgent = agent;\n this.connectionMessageTimestamps = {};\n\n // Clear connections manager when changing agents\n if (this.connectionsManager) {\n this.connectionsManager.clearAll();\n }\n }\n\n /**\n * Returns the currently active agent or null if none is set.\n */\n getCurrentAgent(): RegisteredAgent | null {\n return this.currentAgent;\n }\n\n /**\n * Adds a new connection to the active connections list.\n * Ensures no duplicates are added based on connectionTopicId.\n * Initializes timestamp tracking for the connection.\n */\n addActiveConnection(connection: ActiveConnection): void {\n if (!this.connectionsManager) {\n this.logger.error(\n 'ConnectionsManager not initialized. Call initializeConnectionsManager before adding connections.'\n );\n throw new Error(\n 'ConnectionsManager not initialized. Call initializeConnectionsManager before adding connections.'\n );\n }\n\n // Convert from ActiveConnection to Connection\n const sdkConnection: Connection = {\n connectionTopicId: connection.connectionTopicId,\n targetAccountId: connection.targetAccountId,\n targetAgentName: connection.targetAgentName,\n targetInboundTopicId: connection.targetInboundTopicId,\n status: this.convertConnectionStatus(connection.status || 'established'),\n isPending: connection.isPending || false,\n needsConfirmation: connection.needsConfirmation || false,\n created: connection.created || new Date(),\n lastActivity: connection.lastActivity,\n profileInfo: connection.profileInfo,\n connectionRequestId: connection.connectionRequestId,\n processed: true,\n };\n\n // Add to ConnectionsManager\n this.connectionsManager.updateOrAddConnection(sdkConnection);\n\n // Initialize timestamp tracking\n this.initializeTimestampIfNeeded(connection.connectionTopicId);\n }\n\n /**\n * Updates an existing connection or adds it if not found.\n * Preserves existing properties when updating by merging objects.\n */\n updateOrAddConnection(connection: ActiveConnection): void {\n this.addActiveConnection(connection);\n }\n\n /**\n * Returns a copy of all active connections.\n */\n listConnections(): ActiveConnection[] {\n if (!this.connectionsManager) {\n this.logger.debug(\n 'ConnectionsManager not initialized, returning empty connections list'\n );\n return [];\n }\n\n // Convert SDK Connections to ActiveConnection\n return this.connectionsManager\n .getAllConnections()\n .map((conn) => this.convertToActiveConnection(conn));\n }\n\n /**\n * Finds a connection by its identifier, which can be:\n * - A 1-based index as displayed in the connection list\n * - A target account ID string\n * - A connection topic ID string\n */\n getConnectionByIdentifier(identifier: string): ActiveConnection | undefined {\n if (!this.connectionsManager) {\n return undefined;\n }\n\n const connections = this.listConnections();\n\n // Check if it's a 1-based index\n const numericIndex = parseInt(identifier) - 1;\n if (\n !isNaN(numericIndex) &&\n numericIndex >= 0 &&\n numericIndex < connections.length\n ) {\n return connections[numericIndex];\n }\n\n // Check if it's a topic ID\n const byTopicId =\n this.connectionsManager.getConnectionByTopicId(identifier);\n if (byTopicId) {\n return this.convertToActiveConnection(byTopicId);\n }\n\n // Check if it's an account ID\n const byAccountId =\n this.connectionsManager.getConnectionByAccountId(identifier);\n if (byAccountId) {\n return this.convertToActiveConnection(byAccountId);\n }\n\n return undefined;\n }\n\n /**\n * Gets the last processed message timestamp for a connection.\n * Returns 0 if no timestamp has been recorded.\n */\n getLastTimestamp(connectionTopicId: string): number {\n return this.connectionMessageTimestamps[connectionTopicId] || 0;\n }\n\n /**\n * Updates the last processed message timestamp for a connection,\n * but only if the new timestamp is more recent than the existing one.\n */\n updateTimestamp(connectionTopicId: string, timestampNanos: number): void {\n // Initialize if this is first update and skip the comparison logic\n if (!(connectionTopicId in this.connectionMessageTimestamps)) {\n this.connectionMessageTimestamps[connectionTopicId] = timestampNanos;\n return;\n }\n\n // Otherwise, only update if newer\n const currentTimestamp =\n this.connectionMessageTimestamps[connectionTopicId];\n if (timestampNanos > currentTimestamp) {\n this.connectionMessageTimestamps[connectionTopicId] = timestampNanos;\n }\n }\n\n /**\n * Helper method to initialize timestamp tracking for a connection\n * if it doesn't already exist.\n */\n private initializeTimestampIfNeeded(connectionTopicId: string): void {\n if (!(connectionTopicId in this.connectionMessageTimestamps)) {\n this.connectionMessageTimestamps[connectionTopicId] =\n Date.now() * 1_000_000;\n }\n }\n\n /**\n * Converts ConnectionStatus to SDK status format\n */\n private convertConnectionStatus(\n status: string\n ): 'pending' | 'established' | 'needs_confirmation' | 'closed' {\n switch (status) {\n case 'pending':\n return 'pending';\n case 'established':\n return 'established';\n case 'needs confirmation':\n return 'needs_confirmation';\n default:\n return 'established';\n }\n }\n\n /**\n * Converts SDK Connection to ActiveConnection\n */\n private convertToActiveConnection(conn: Connection): ActiveConnection {\n return {\n targetAccountId: conn.targetAccountId,\n targetAgentName: conn.targetAgentName || `Agent ${conn.targetAccountId}`,\n targetInboundTopicId: conn.targetInboundTopicId || '',\n connectionTopicId: conn.connectionTopicId,\n status: this.convertToStateStatus(conn.status),\n created: conn.created,\n lastActivity: conn.lastActivity,\n isPending: conn.isPending,\n needsConfirmation: conn.needsConfirmation,\n profileInfo: conn.profileInfo,\n connectionRequestId: conn.connectionRequestId,\n };\n }\n\n /**\n * Converts SDK status to state status format\n */\n private convertToStateStatus(status: string): ConnectionStatus {\n switch (status) {\n case 'pending':\n return 'pending';\n case 'established':\n return 'established';\n case 'needs_confirmation':\n return 'needs confirmation';\n case 'closed':\n return 'established'; // Mapping closed to established for compatibility\n default:\n return 'unknown';\n }\n }\n\n /**\n * Persists agent data to environment variables\n * @param agent - The agent data to persist\n * @param options - Environment file persistence options\n */\n async persistAgentData(\n agent: RegisteredAgent,\n options?: AgentPersistenceOptions\n ): Promise<void> {\n if (options?.type && options.type !== 'env-file') {\n throw new Error(\n `Unsupported persistence type: ${options.type}. Only 'env-file' is supported.`\n );\n }\n\n const envFilePath =\n (options as EnvFilePersistenceOptions)?.envFilePath ||\n this.defaultEnvFilePath ||\n process.env.ENV_FILE_PATH ||\n '.env';\n\n if (!envFilePath) {\n throw new Error(\n 'Environment file path could not be determined for agent data persistence'\n );\n }\n\n const prefix =\n (options as EnvFilePersistenceOptions)?.prefix || this.defaultPrefix;\n\n if (!agent.accountId || !agent.inboundTopicId || !agent.outboundTopicId) {\n throw new Error('Agent data incomplete, cannot persist to environment');\n }\n\n const updates: Record<string, string> = {\n [`${prefix}_ACCOUNT_ID`]: agent.accountId,\n [`${prefix}_INBOUND_TOPIC_ID`]: agent.inboundTopicId,\n [`${prefix}_OUTBOUND_TOPIC_ID`]: agent.outboundTopicId,\n };\n\n if (agent.privateKey) {\n updates[`${prefix}_PRIVATE_KEY`] = agent.privateKey;\n }\n\n if (agent.profileTopicId) {\n updates[`${prefix}_PROFILE_TOPIC_ID`] = agent.profileTopicId;\n }\n\n await updateEnvFile(envFilePath, updates);\n }\n}\n"],"names":[],"mappings":";;AAsBO,MAAM,gBAAyC;AAAA;AAAA;AAAA;AAAA;AAAA,EAYpD,YAAY,SAKT;AAhBH,SAAQ,eAAuC;AAC/C,SAAQ,8BAAsD,CAAC;AAG/D,SAAQ,qBAAiD;AAavD,SAAK,qBAAqB,SAAS;AAC9B,SAAA,gBAAgB,SAAS,iBAAiB;AAC/C,UAAM,gBAAgB,SAAS,kBAAkB,QAAQ,IAAI,oBAAoB;AAC5E,SAAA,SAAS,IAAI,OAAO,EAAE,QAAQ,mBAAmB,QAAQ,eAAe;AAG7E,QAAI,SAAS,YAAY;AAClB,WAAA,6BAA6B,QAAQ,UAAU;AAAA,IAAA;AAAA,EACtD;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,6BACE,YACqB;AACjB,QAAA,CAAC,KAAK,oBAAoB;AACvB,WAAA,OAAO,MAAM,iCAAiC;AAC9C,WAAA,qBAAqB,IAAI,mBAAmB;AAAA,QAC/C;AAAA,QACA,UAAU;AAAA,MAAA,CACX;AAAA,IAAA,OACI;AACA,WAAA,OAAO,MAAM,wCAAwC;AAAA,IAAA;AAE5D,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOd,wBAAoD;AAClD,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOd,gBAAgB,OAAqC;AACnD,SAAK,eAAe;AACpB,SAAK,8BAA8B,CAAC;AAGpC,QAAI,KAAK,oBAAoB;AAC3B,WAAK,mBAAmB,SAAS;AAAA,IAAA;AAAA,EACnC;AAAA;AAAA;AAAA;AAAA,EAMF,kBAA0C;AACxC,WAAO,KAAK;AA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cAAc,aAAa,OAAO;AAAA,EAAA;AAE5C;"}
|
|
@@ -36,8 +36,10 @@ function initializeHCS10Client(options) {
|
|
|
36
36
|
"Operator ID and private key must be provided either through options or environment variables."
|
|
37
37
|
);
|
|
38
38
|
}
|
|
39
|
+
const shouldSilence = process.env.DISABLE_LOGGING === "true";
|
|
39
40
|
const logger = Logger.getInstance({
|
|
40
|
-
level: config.logLevel || "info"
|
|
41
|
+
level: config.logLevel || "info",
|
|
42
|
+
silent: shouldSilence
|
|
41
43
|
});
|
|
42
44
|
const stateManager = options?.stateManager || new OpenConvaiState({
|
|
43
45
|
defaultEnvFilePath: ENV_FILE_PATH,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"standards-agent-kit.es2.js","sources":["../../src/init.ts"],"sourcesContent":["import { HCS10Client, StandardNetworkType } from './hcs10/HCS10Client';\nimport { RegisterAgentTool } from './tools/RegisterAgentTool';\nimport { SendMessageTool } from './tools/SendMessageTool';\nimport { ConnectionTool } from './tools/ConnectionTool';\nimport { IStateManager } from './state/state-types';\nimport { OpenConvaiState } from './state/open-convai-state';\nimport { FindRegistrationsTool } from './tools/FindRegistrationsTool';\nimport { InitiateConnectionTool } from './tools/InitiateConnectionTool';\nimport { ListConnectionsTool } from './tools/ListConnectionsTool';\nimport { SendMessageToConnectionTool } from './tools/SendMessageToConnectionTool';\nimport { CheckMessagesTool } from './tools/CheckMessagesTool';\nimport { ConnectionMonitorTool } from './tools/ConnectionMonitorTool';\nimport { ManageConnectionRequestsTool } from './tools/ManageConnectionRequestsTool';\nimport { AcceptConnectionRequestTool } from './tools/AcceptConnectionRequestTool';\nimport { RetrieveProfileTool } from './tools/RetrieveProfileTool';\nimport { ListUnapprovedConnectionRequestsTool } from './tools/ListUnapprovedConnectionRequestsTool';\nimport { Logger } from '@hashgraphonline/standards-sdk';\nimport { ENV_FILE_PATH } from './utils/state-tools';\n\nexport interface HCS10ClientConfig {\n operatorId?: string;\n operatorKey?: string;\n network?: StandardNetworkType;\n useEncryption?: boolean;\n registryUrl?: string;\n logLevel?: 'debug' | 'info' | 'warn' | 'error';\n}\n\nexport interface HCS10InitializationOptions {\n clientConfig?: HCS10ClientConfig;\n stateManager?: IStateManager;\n createAllTools?: boolean;\n monitoringClient?: boolean;\n}\n\n/**\n * Tool collection containing all available tools from the standards-agent-kit\n */\nexport interface HCS10Tools {\n registerAgentTool: RegisterAgentTool;\n findRegistrationsTool: FindRegistrationsTool;\n retrieveProfileTool: RetrieveProfileTool;\n initiateConnectionTool: InitiateConnectionTool;\n listConnectionsTool: ListConnectionsTool;\n sendMessageToConnectionTool: SendMessageToConnectionTool;\n checkMessagesTool: CheckMessagesTool;\n sendMessageTool: SendMessageTool;\n connectionTool: ConnectionTool;\n connectionMonitorTool: ConnectionMonitorTool;\n manageConnectionRequestsTool: ManageConnectionRequestsTool;\n acceptConnectionRequestTool: AcceptConnectionRequestTool;\n listUnapprovedConnectionRequestsTool: ListUnapprovedConnectionRequestsTool;\n}\n\n/**\n * Initializes the HCS10 client and returns pre-registered LangChain tools.\n *\n * @param options - Initialization options\n * @returns Object containing hcs10Client and requested tools\n */\nexport function initializeHCS10Client(options?: HCS10InitializationOptions): {\n hcs10Client: HCS10Client;\n monitoringClient?: HCS10Client;\n tools: Partial<HCS10Tools>;\n stateManager: IStateManager;\n} {\n const config = options?.clientConfig || {};\n\n const operatorId = config.operatorId || process.env.HEDERA_OPERATOR_ID;\n const operatorPrivateKey =\n config.operatorKey || process.env.HEDERA_OPERATOR_KEY;\n\n const networkEnv = config.network || process.env.HEDERA_NETWORK || 'testnet';\n\n let network: StandardNetworkType;\n if (networkEnv === 'mainnet') {\n network = 'mainnet';\n } else if (networkEnv === 'testnet') {\n network = 'testnet';\n } else {\n console.warn(\n `Unsupported network specified: '${networkEnv}'. Defaulting to 'testnet'.`\n );\n network = 'testnet';\n }\n\n if (!operatorId || !operatorPrivateKey) {\n throw new Error(\n 'Operator ID and private key must be provided either through options or environment variables.'\n );\n }\n\n const logger = Logger.getInstance({\n level: config.logLevel || 'info',\n });\n\n const stateManager =\n options?.stateManager ||\n new OpenConvaiState({\n defaultEnvFilePath: ENV_FILE_PATH,\n defaultPrefix: 'TODD',\n });\n logger.info('State manager initialized');\n\n const hcs10Client = new HCS10Client(operatorId, operatorPrivateKey, network, {\n useEncryption: config.useEncryption,\n registryUrl: config.registryUrl,\n });\n logger.info(`HCS10Client initialized for ${operatorId} on ${network}`);\n\n let monitoringClient: HCS10Client | undefined;\n if (options?.monitoringClient) {\n monitoringClient = new HCS10Client(\n operatorId,\n operatorPrivateKey,\n network,\n {\n useEncryption: config.useEncryption,\n registryUrl: config.registryUrl,\n logLevel: 'error',\n }\n );\n logger.info('Monitoring client initialized');\n }\n\n const tools: Partial<HCS10Tools> = {};\n\n tools.registerAgentTool = new RegisterAgentTool(hcs10Client, stateManager);\n tools.sendMessageTool = new SendMessageTool(hcs10Client);\n tools.connectionTool = new ConnectionTool({\n client: monitoringClient || hcs10Client,\n stateManager,\n });\n\n if (options?.createAllTools) {\n tools.findRegistrationsTool = new FindRegistrationsTool({\n hcsClient: hcs10Client,\n });\n tools.retrieveProfileTool = new RetrieveProfileTool(hcs10Client);\n tools.initiateConnectionTool = new InitiateConnectionTool({\n hcsClient: hcs10Client,\n stateManager,\n });\n tools.listConnectionsTool = new ListConnectionsTool({\n hcsClient: hcs10Client,\n stateManager,\n });\n tools.sendMessageToConnectionTool = new SendMessageToConnectionTool({\n hcsClient: hcs10Client,\n stateManager,\n });\n tools.checkMessagesTool = new CheckMessagesTool({\n hcsClient: hcs10Client,\n stateManager,\n });\n tools.connectionMonitorTool = new ConnectionMonitorTool({\n hcsClient: monitoringClient || hcs10Client,\n stateManager,\n });\n tools.manageConnectionRequestsTool = new ManageConnectionRequestsTool({\n hcsClient: hcs10Client,\n stateManager,\n });\n tools.acceptConnectionRequestTool = new AcceptConnectionRequestTool({\n hcsClient: hcs10Client,\n stateManager,\n });\n tools.listUnapprovedConnectionRequestsTool =\n new ListUnapprovedConnectionRequestsTool({\n stateManager,\n hcsClient: hcs10Client,\n });\n\n logger.info('All tools initialized');\n }\n\n return {\n hcs10Client,\n monitoringClient,\n tools,\n stateManager,\n };\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AA4DO,SAAS,sBAAsB,SAKpC;AACM,QAAA,SAAS,SAAS,gBAAgB,CAAC;AAEzC,QAAM,aAAa,OAAO,cAAc,QAAQ,IAAI;AACpD,QAAM,qBACJ,OAAO,eAAe,QAAQ,IAAI;AAEpC,QAAM,aAAa,OAAO,WAAW,QAAQ,IAAI,kBAAkB;AAE/D,MAAA;AACJ,MAAI,eAAe,WAAW;AAClB,cAAA;AAAA,EAAA,WACD,eAAe,WAAW;AACzB,cAAA;AAAA,EAAA,OACL;AACG,YAAA;AAAA,MACN,mCAAmC,UAAU;AAAA,IAC/C;AACU,cAAA;AAAA,EAAA;AAGR,MAAA,CAAC,cAAc,CAAC,oBAAoB;AACtC,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EAAA;AAGI,QAAA,SAAS,OAAO,YAAY;AAAA,IAChC,OAAO,OAAO,YAAY;AAAA,EAAA,
|
|
1
|
+
{"version":3,"file":"standards-agent-kit.es2.js","sources":["../../src/init.ts"],"sourcesContent":["import { HCS10Client, StandardNetworkType } from './hcs10/HCS10Client';\nimport { RegisterAgentTool } from './tools/RegisterAgentTool';\nimport { SendMessageTool } from './tools/SendMessageTool';\nimport { ConnectionTool } from './tools/ConnectionTool';\nimport { IStateManager } from './state/state-types';\nimport { OpenConvaiState } from './state/open-convai-state';\nimport { FindRegistrationsTool } from './tools/FindRegistrationsTool';\nimport { InitiateConnectionTool } from './tools/InitiateConnectionTool';\nimport { ListConnectionsTool } from './tools/ListConnectionsTool';\nimport { SendMessageToConnectionTool } from './tools/SendMessageToConnectionTool';\nimport { CheckMessagesTool } from './tools/CheckMessagesTool';\nimport { ConnectionMonitorTool } from './tools/ConnectionMonitorTool';\nimport { ManageConnectionRequestsTool } from './tools/ManageConnectionRequestsTool';\nimport { AcceptConnectionRequestTool } from './tools/AcceptConnectionRequestTool';\nimport { RetrieveProfileTool } from './tools/RetrieveProfileTool';\nimport { ListUnapprovedConnectionRequestsTool } from './tools/ListUnapprovedConnectionRequestsTool';\nimport { Logger } from '@hashgraphonline/standards-sdk';\nimport { ENV_FILE_PATH } from './utils/state-tools';\n\nexport interface HCS10ClientConfig {\n operatorId?: string;\n operatorKey?: string;\n network?: StandardNetworkType;\n useEncryption?: boolean;\n registryUrl?: string;\n logLevel?: 'debug' | 'info' | 'warn' | 'error';\n}\n\nexport interface HCS10InitializationOptions {\n clientConfig?: HCS10ClientConfig;\n stateManager?: IStateManager;\n createAllTools?: boolean;\n monitoringClient?: boolean;\n}\n\n/**\n * Tool collection containing all available tools from the standards-agent-kit\n */\nexport interface HCS10Tools {\n registerAgentTool: RegisterAgentTool;\n findRegistrationsTool: FindRegistrationsTool;\n retrieveProfileTool: RetrieveProfileTool;\n initiateConnectionTool: InitiateConnectionTool;\n listConnectionsTool: ListConnectionsTool;\n sendMessageToConnectionTool: SendMessageToConnectionTool;\n checkMessagesTool: CheckMessagesTool;\n sendMessageTool: SendMessageTool;\n connectionTool: ConnectionTool;\n connectionMonitorTool: ConnectionMonitorTool;\n manageConnectionRequestsTool: ManageConnectionRequestsTool;\n acceptConnectionRequestTool: AcceptConnectionRequestTool;\n listUnapprovedConnectionRequestsTool: ListUnapprovedConnectionRequestsTool;\n}\n\n/**\n * Initializes the HCS10 client and returns pre-registered LangChain tools.\n *\n * @param options - Initialization options\n * @returns Object containing hcs10Client and requested tools\n */\nexport function initializeHCS10Client(options?: HCS10InitializationOptions): {\n hcs10Client: HCS10Client;\n monitoringClient?: HCS10Client;\n tools: Partial<HCS10Tools>;\n stateManager: IStateManager;\n} {\n const config = options?.clientConfig || {};\n\n const operatorId = config.operatorId || process.env.HEDERA_OPERATOR_ID;\n const operatorPrivateKey =\n config.operatorKey || process.env.HEDERA_OPERATOR_KEY;\n\n const networkEnv = config.network || process.env.HEDERA_NETWORK || 'testnet';\n\n let network: StandardNetworkType;\n if (networkEnv === 'mainnet') {\n network = 'mainnet';\n } else if (networkEnv === 'testnet') {\n network = 'testnet';\n } else {\n console.warn(\n `Unsupported network specified: '${networkEnv}'. Defaulting to 'testnet'.`\n );\n network = 'testnet';\n }\n\n if (!operatorId || !operatorPrivateKey) {\n throw new Error(\n 'Operator ID and private key must be provided either through options or environment variables.'\n );\n }\n\n const shouldSilence = process.env.DISABLE_LOGGING === 'true';\n const logger = Logger.getInstance({\n level: config.logLevel || 'info',\n silent: shouldSilence,\n });\n\n const stateManager =\n options?.stateManager ||\n new OpenConvaiState({\n defaultEnvFilePath: ENV_FILE_PATH,\n defaultPrefix: 'TODD',\n });\n logger.info('State manager initialized');\n\n const hcs10Client = new HCS10Client(operatorId, operatorPrivateKey, network, {\n useEncryption: config.useEncryption,\n registryUrl: config.registryUrl,\n });\n logger.info(`HCS10Client initialized for ${operatorId} on ${network}`);\n\n let monitoringClient: HCS10Client | undefined;\n if (options?.monitoringClient) {\n monitoringClient = new HCS10Client(\n operatorId,\n operatorPrivateKey,\n network,\n {\n useEncryption: config.useEncryption,\n registryUrl: config.registryUrl,\n logLevel: 'error',\n }\n );\n logger.info('Monitoring client initialized');\n }\n\n const tools: Partial<HCS10Tools> = {};\n\n tools.registerAgentTool = new RegisterAgentTool(hcs10Client, stateManager);\n tools.sendMessageTool = new SendMessageTool(hcs10Client);\n tools.connectionTool = new ConnectionTool({\n client: monitoringClient || hcs10Client,\n stateManager,\n });\n\n if (options?.createAllTools) {\n tools.findRegistrationsTool = new FindRegistrationsTool({\n hcsClient: hcs10Client,\n });\n tools.retrieveProfileTool = new RetrieveProfileTool(hcs10Client);\n tools.initiateConnectionTool = new InitiateConnectionTool({\n hcsClient: hcs10Client,\n stateManager,\n });\n tools.listConnectionsTool = new ListConnectionsTool({\n hcsClient: hcs10Client,\n stateManager,\n });\n tools.sendMessageToConnectionTool = new SendMessageToConnectionTool({\n hcsClient: hcs10Client,\n stateManager,\n });\n tools.checkMessagesTool = new CheckMessagesTool({\n hcsClient: hcs10Client,\n stateManager,\n });\n tools.connectionMonitorTool = new ConnectionMonitorTool({\n hcsClient: monitoringClient || hcs10Client,\n stateManager,\n });\n tools.manageConnectionRequestsTool = new ManageConnectionRequestsTool({\n hcsClient: hcs10Client,\n stateManager,\n });\n tools.acceptConnectionRequestTool = new AcceptConnectionRequestTool({\n hcsClient: hcs10Client,\n stateManager,\n });\n tools.listUnapprovedConnectionRequestsTool =\n new ListUnapprovedConnectionRequestsTool({\n stateManager,\n hcsClient: hcs10Client,\n });\n\n logger.info('All tools initialized');\n }\n\n return {\n hcs10Client,\n monitoringClient,\n tools,\n stateManager,\n };\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AA4DO,SAAS,sBAAsB,SAKpC;AACM,QAAA,SAAS,SAAS,gBAAgB,CAAC;AAEzC,QAAM,aAAa,OAAO,cAAc,QAAQ,IAAI;AACpD,QAAM,qBACJ,OAAO,eAAe,QAAQ,IAAI;AAEpC,QAAM,aAAa,OAAO,WAAW,QAAQ,IAAI,kBAAkB;AAE/D,MAAA;AACJ,MAAI,eAAe,WAAW;AAClB,cAAA;AAAA,EAAA,WACD,eAAe,WAAW;AACzB,cAAA;AAAA,EAAA,OACL;AACG,YAAA;AAAA,MACN,mCAAmC,UAAU;AAAA,IAC/C;AACU,cAAA;AAAA,EAAA;AAGR,MAAA,CAAC,cAAc,CAAC,oBAAoB;AACtC,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EAAA;AAGI,QAAA,gBAAgB,QAAQ,IAAI,oBAAoB;AAChD,QAAA,SAAS,OAAO,YAAY;AAAA,IAChC,OAAO,OAAO,YAAY;AAAA,IAC1B,QAAQ;AAAA,EAAA,CACT;AAED,QAAM,eACJ,SAAS,gBACT,IAAI,gBAAgB;AAAA,IAClB,oBAAoB;AAAA,IACpB,eAAe;AAAA,EAAA,CAChB;AACH,SAAO,KAAK,2BAA2B;AA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K,UAAA,8BAA8B,IAAI,4BAA4B;AAAA,MAClE,WAAW;AAAA,MACX;AAAA,IAAA,CACD;AACK,UAAA,uCACJ,IAAI,qCAAqC;AAAA,MACvC;AAAA,MACA,WAAW;AAAA,IAAA,CACZ;AAEH,WAAO,KAAK,uBAAuB;AAAA,EAAA;AAG9B,SAAA;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;"}
|
|
@@ -11,8 +11,10 @@ class HCS10Client {
|
|
|
11
11
|
});
|
|
12
12
|
this.guardedRegistryBaseUrl = options?.registryUrl || "";
|
|
13
13
|
this.useEncryption = options?.useEncryption || false;
|
|
14
|
+
const shouldSilence = process.env.DISABLE_LOGGING === "true";
|
|
14
15
|
this.logger = new Logger({
|
|
15
|
-
level: options?.logLevel || "info"
|
|
16
|
+
level: options?.logLevel || "info",
|
|
17
|
+
silent: shouldSilence
|
|
16
18
|
});
|
|
17
19
|
}
|
|
18
20
|
getOperatorId() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"standards-agent-kit.es3.js","sources":["../../src/hcs10/HCS10Client.ts"],"sourcesContent":["import { TransactionReceipt, PrivateKey } from '@hashgraph/sdk';\nimport {\n HCS10Client as StandardSDKClient,\n AgentBuilder,\n InboundTopicType as StandardInboundTopicType,\n AIAgentCapability as StandardAIAgentCapability,\n AgentRegistrationResult,\n WaitForConnectionConfirmationResponse,\n ProfileResponse as SDKProfileResponse,\n HCSMessage,\n LogLevel,\n Logger,\n FeeConfigBuilderInterface,\n SocialPlatform,\n} from '@hashgraphonline/standards-sdk';\nimport { AgentMetadata, AgentChannels } from './types';\nimport { encryptMessage } from '../utils/Encryption';\nimport { IStateManager } from '../state/state-types';\n\n// Keep type alias as they were removed accidentally\ntype StandardHandleConnectionRequest = InstanceType<\n typeof StandardSDKClient\n>['handleConnectionRequest'];\ntype HandleConnectionRequestResponse = Awaited<\n ReturnType<StandardHandleConnectionRequest>\n>;\nexport type StandardNetworkType = 'mainnet' | 'testnet';\n\nexport interface ClientValidationOptions {\n accountId: string;\n privateKey: string;\n network?: StandardNetworkType;\n stateManager?: IStateManager;\n}\n\nexport interface HCSMessageWithTimestamp extends HCSMessage {\n timestamp: number;\n data?: string;\n sequence_number: number;\n}\n\nexport interface ExtendedAgentMetadata extends AgentMetadata {\n pfpBuffer?: Buffer;\n pfpFileName?: string;\n feeConfig?: FeeConfigBuilderInterface;\n}\n\n/**\n * HCS10Client wraps the HCS-10 functionalities using the @hashgraphonline/standards-sdk.\n * - Creates and registers agents using the standard SDK flow.\n * - Manages agent communication channels (handled by standard SDK).\n * - Sends messages on Hedera topics (currently manual, potential for standard SDK integration).\n */\nexport class HCS10Client {\n public standardClient: StandardSDKClient;\n private useEncryption: boolean;\n public agentChannels?: AgentChannels;\n public guardedRegistryBaseUrl: string;\n public logger: Logger;\n\n constructor(\n operatorId: string,\n operatorPrivateKey: string,\n network: StandardNetworkType,\n options?: {\n useEncryption?: boolean;\n registryUrl?: string;\n logLevel?: LogLevel;\n }\n ) {\n this.standardClient = new StandardSDKClient({\n network: network,\n operatorId: operatorId,\n operatorPrivateKey: operatorPrivateKey,\n guardedRegistryBaseUrl: options?.registryUrl,\n logLevel: options?.logLevel,\n });\n this.guardedRegistryBaseUrl = options?.registryUrl || '';\n this.useEncryption = options?.useEncryption || false;\n this.logger = new Logger({\n level: options?.logLevel || 'info',\n });\n }\n\n public getOperatorId(): string {\n const operator = this.standardClient.getClient().operatorAccountId;\n if (!operator) {\n throw new Error('Operator Account ID not configured in standard client.');\n }\n return operator.toString();\n }\n\n public getNetwork(): StandardNetworkType {\n return this.standardClient.getNetwork() as StandardNetworkType;\n }\n\n public async handleConnectionRequest(\n inboundTopicId: string,\n requestingAccountId: string,\n connectionRequestId: number,\n feeConfig?: FeeConfigBuilderInterface\n ): Promise<HandleConnectionRequestResponse> {\n try {\n const result = await this.standardClient.handleConnectionRequest(\n inboundTopicId,\n requestingAccountId,\n connectionRequestId,\n feeConfig\n );\n return result;\n } catch (error) {\n this.logger.error(\n `Error handling connection request #${connectionRequestId} for topic ${inboundTopicId}:`,\n error\n );\n throw new Error(\n `Failed to handle connection request: ${\n error instanceof Error ? error.message : String(error)\n }`\n );\n }\n }\n\n /**\n * Retrieves the profile for a given account ID using the standard SDK.\n */\n public async getAgentProfile(accountId: string): Promise<SDKProfileResponse> {\n return this.standardClient.retrieveProfile(accountId);\n }\n\n /**\n * Exposes the standard SDK's submitConnectionRequest method.\n */\n public async submitConnectionRequest(\n inboundTopicId: string,\n memo: string\n ): Promise<TransactionReceipt> {\n return this.standardClient.submitConnectionRequest(\n inboundTopicId,\n memo\n ) as Promise<TransactionReceipt>;\n }\n\n /**\n * Exposes the standard SDK's waitForConnectionConfirmation method.\n */\n public async waitForConnectionConfirmation(\n outboundTopicId: string,\n connectionRequestId: number,\n maxAttempts = 60,\n delayMs = 2000\n ): Promise<WaitForConnectionConfirmationResponse> {\n return this.standardClient.waitForConnectionConfirmation(\n outboundTopicId,\n connectionRequestId,\n maxAttempts,\n delayMs\n );\n }\n\n /**\n * Creates and registers an agent using the standard SDK's HCS10Client.\n * This handles account creation, key generation, topic setup, and registration.\n *\n * When metadata includes fee configuration:\n * 1. The properties.feeConfig will be passed to the AgentBuilder\n * 2. The properties.inboundTopicType will be set to FEE_BASED\n * 3. The SDK's createAndRegisterAgent will apply the fees to the agent's inbound topic\n *\n * @param metadata - The agent's metadata, potentially including pfpBuffer, pfpFileName,\n * and fee configuration in properties.feeConfig\n * @returns The registration result from the standard SDK, containing accountId, keys, topics etc.\n */\n public async createAndRegisterAgent(\n metadata: ExtendedAgentMetadata\n ): Promise<AgentRegistrationResult> {\n const builder = new AgentBuilder()\n .setName(metadata.name)\n .setBio(metadata.description || '')\n .setCapabilities(\n metadata.capabilities\n ? metadata.capabilities\n : [StandardAIAgentCapability.TEXT_GENERATION]\n )\n .setType((metadata.type || 'autonomous') as 'autonomous' | 'manual')\n .setModel(metadata.model || 'agent-model-2024')\n .setNetwork(this.getNetwork())\n .setInboundTopicType(StandardInboundTopicType.PUBLIC);\n\n if (metadata?.feeConfig) {\n builder.setInboundTopicType(StandardInboundTopicType.FEE_BASED);\n builder.setFeeConfig(metadata.feeConfig);\n }\n\n if (metadata.pfpBuffer && metadata.pfpFileName) {\n if (metadata.pfpBuffer.byteLength === 0) {\n this.logger.warn(\n 'Provided PFP buffer is empty. Skipping profile picture.'\n );\n } else {\n this.logger.info(\n `Setting profile picture: ${metadata.pfpFileName} (${metadata.pfpBuffer.byteLength} bytes)`\n );\n builder.setProfilePicture(metadata.pfpBuffer, metadata.pfpFileName);\n }\n } else {\n this.logger.warn(\n 'Profile picture not provided in metadata. Agent creation might fail if required by the underlying SDK builder.'\n );\n }\n\n if (metadata.social) {\n Object.entries(metadata.social).forEach(([platform, handle]) => {\n builder.addSocial(platform as SocialPlatform, handle);\n });\n }\n\n if (metadata.properties) {\n Object.entries(metadata.properties).forEach(([key, value]) => {\n builder.addProperty(key, value);\n });\n }\n\n try {\n const hasFees = Boolean(metadata?.feeConfig);\n const result = await this.standardClient.createAndRegisterAgent(builder, {\n initialBalance: hasFees ? 50 : undefined,\n });\n if (\n result?.metadata?.inboundTopicId &&\n result?.metadata?.outboundTopicId\n ) {\n this.agentChannels = {\n inboundTopicId: result.metadata.inboundTopicId,\n outboundTopicId: result.metadata.outboundTopicId,\n };\n }\n return result;\n } catch (error) {\n this.logger.error('Error during agent creation/registration:', error);\n throw new Error(\n `Failed to create/register agent: ${\n error instanceof Error ? error.message : String(error)\n }`\n );\n }\n }\n\n /**\n * Sends a structured HCS-10 message to the specified topic using the standard SDK client.\n * Handles potential inscription for large messages.\n *\n * @param topicId - The target topic ID (likely a connection topic).\n * @param operatorId - The operator ID string (e.g., \"inboundTopic@accountId\").\n * @param data - The actual message content/data.\n * @param memo - Optional memo for the message.\n * @param submitKey - Optional private key for topics requiring specific submit keys.\n * @returns A confirmation status string from the transaction receipt.\n */\n public async sendMessage(\n topicId: string,\n data: string,\n memo?: string,\n submitKey?: PrivateKey\n ): Promise<number | undefined> {\n if (this.useEncryption) {\n data = encryptMessage(data);\n }\n\n try {\n const messageResponse = await this.standardClient.sendMessage(\n topicId,\n data,\n memo,\n submitKey\n );\n return messageResponse.topicSequenceNumber?.toNumber();\n } catch (error) {\n this.logger.error(`Error sending message to topic ${topicId}:`, error);\n throw new Error(\n `Failed to send message: ${\n error instanceof Error ? error.message : String(error)\n }`\n );\n }\n }\n\n /**\n * Retrieves messages from a topic using the standard SDK client.\n *\n * @param topicId - The topic ID to get messages from.\n * @returns Messages from the topic, mapped to the expected format.\n */\n public async getMessages(topicId: string): Promise<{\n messages: HCSMessageWithTimestamp[];\n }> {\n try {\n const result = await this.standardClient.getMessages(topicId);\n\n const mappedMessages = result.messages.map((sdkMessage) => {\n const timestamp = sdkMessage?.created?.getTime() || 0;\n\n return {\n ...sdkMessage,\n timestamp: timestamp,\n data: sdkMessage.data,\n sequence_number: sdkMessage.sequence_number,\n };\n });\n mappedMessages.sort(\n (a: { timestamp: number }, b: { timestamp: number }) =>\n a.timestamp - b.timestamp\n );\n return { messages: mappedMessages };\n } catch (error) {\n this.logger.error(`Error getting messages from topic ${topicId}:`, error);\n return { messages: [] };\n }\n }\n\n public async getMessageStream(topicId: string): Promise<{\n messages: HCSMessage[];\n }> {\n return this.standardClient.getMessageStream(topicId);\n }\n\n /**\n * Retrieves content from an inscribed message using the standard SDK client.\n * @param inscriptionIdOrData - The inscription ID (hcs://...) or potentially raw data string.\n * @returns The resolved message content.\n */\n public async getMessageContent(inscriptionIdOrData: string): Promise<string> {\n try {\n const content = await this.standardClient.getMessageContent(\n inscriptionIdOrData\n );\n return content as string;\n } catch (error) {\n this.logger.error(\n `Error retrieving message content for: ${inscriptionIdOrData}`,\n error\n );\n throw new Error(\n `Failed to retrieve message content: ${\n error instanceof Error ? error.message : String(error)\n }`\n );\n }\n }\n\n /**\n * Retrieves the inbound topic ID associated with the current operator.\n * This typically involves fetching the operator's own HCS-10 profile.\n * @returns A promise that resolves to the operator's inbound topic ID.\n * @throws {Error} If the operator ID cannot be determined or the profile/topic cannot be retrieved.\n */\n public async getInboundTopicId(): Promise<string> {\n try {\n const operatorId = this.getOperatorId();\n this.logger.info(\n `[HCS10Client] Retrieving profile for operator ${operatorId} to find inbound topic...`\n );\n const profileResponse = await this.getAgentProfile(operatorId);\n if (profileResponse.success && profileResponse.topicInfo?.inboundTopic) {\n this.logger.info(\n `[HCS10Client] Found inbound topic for operator ${operatorId}: ${profileResponse.topicInfo.inboundTopic}`\n );\n return profileResponse.topicInfo.inboundTopic;\n } else {\n throw new Error(\n `Could not retrieve inbound topic from profile for ${operatorId}. Profile success: ${profileResponse.success}, Error: ${profileResponse.error}`\n );\n }\n } catch (error) {\n this.logger.error(\n `[HCS10Client] Error fetching operator's inbound topic ID (${this.getOperatorId()}):`,\n error\n );\n const operatorId = this.getOperatorId();\n let detailedMessage = `Failed to get inbound topic ID for operator ${operatorId}.`;\n if (\n error instanceof Error &&\n error.message.includes('does not have a valid HCS-11 memo')\n ) {\n detailedMessage += ` The account profile may not exist or is invalid. Please ensure this operator account (${operatorId}) is registered as an HCS-10 agent. You might need to register it first (e.g., using the 'register_agent' tool or SDK function).`;\n } else if (error instanceof Error) {\n detailedMessage += ` Reason: ${error.message}`;\n } else {\n detailedMessage += ` Unexpected error: ${String(error)}`;\n }\n throw new Error(detailedMessage);\n }\n }\n\n /**\n * Retrieves the configured operator account ID and private key.\n * Required by tools needing to identify the current agent instance.\n */\n public getAccountAndSigner(): { accountId: string; signer: PrivateKey } {\n const result = this.standardClient.getAccountAndSigner();\n return {\n accountId: result.accountId,\n signer: result.signer as unknown as PrivateKey,\n };\n }\n\n /**\n * Retrieves the outbound topic ID for the current operator.\n * Fetches the operator's profile if necessary.\n * @returns The outbound topic ID string.\n * @throws If the outbound topic cannot be determined.\n */\n public async getOutboundTopicId(): Promise<string> {\n const operatorId = this.getOperatorId();\n const profile = await this.getAgentProfile(operatorId);\n if (profile.success && profile.topicInfo?.outboundTopic) {\n return profile.topicInfo.outboundTopic;\n } else {\n throw new Error(\n `Could not retrieve outbound topic from profile for ${operatorId}. Profile success: ${profile.success}, Error: ${profile.error}`\n );\n }\n }\n\n public setClient(accountId: string, privateKey: string): StandardSDKClient {\n this.standardClient = new StandardSDKClient({\n network: this.getNetwork(),\n operatorId: accountId,\n operatorPrivateKey: privateKey,\n guardedRegistryBaseUrl: this.guardedRegistryBaseUrl,\n });\n return this.standardClient;\n }\n\n /**\n * Validates that the operator account exists and has proper access for agent operations\n */\n private async validateOperator(\n options: ClientValidationOptions\n ): Promise<{\n isValid: boolean;\n operator?: { accountId: string };\n error?: string;\n }> {\n try {\n // Set up client with provided operator details\n this.setClient(options.accountId, options.privateKey);\n\n // Check if we can retrieve the operator ID\n const operatorId = this.getOperatorId();\n\n // If we got this far, basic validation passed\n return {\n isValid: true,\n operator: { accountId: operatorId },\n };\n } catch (error) {\n this.logger.error(`Validation error: ${error}`);\n return {\n isValid: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n async initializeWithValidation(\n options: ClientValidationOptions\n ): Promise<{\n isValid: boolean;\n operator?: { accountId: string };\n error?: string;\n }> {\n const validationResult = await this.validateOperator(options);\n\n if (validationResult.isValid) {\n // If we have access to the state manager, initialize its connections manager\n if (options.stateManager) {\n options.stateManager.initializeConnectionsManager(this.standardClient);\n }\n }\n\n return validationResult;\n }\n}\n"],"names":["StandardSDKClient","StandardAIAgentCapability","StandardInboundTopicType"],"mappings":";;AAqDO,MAAM,YAAY;AAAA,EAOvB,YACE,YACA,oBACA,SACA,SAKA;AACK,SAAA,iBAAiB,IAAIA,cAAkB;AAAA,MAC1C;AAAA,MACA;AAAA,MACA;AAAA,MACA,wBAAwB,SAAS;AAAA,MACjC,UAAU,SAAS;AAAA,IAAA,CACpB;AACI,SAAA,yBAAyB,SAAS,eAAe;AACjD,SAAA,gBAAgB,SAAS,iBAAiB;AAC1C,SAAA,SAAS,IAAI,OAAO;AAAA,MACvB,OAAO,SAAS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AAM,UAAU,OAAO,KAAK;AAAA,MAC9D;AAAA,IAAA;AAAA,EACF;AAAA,EAGF,MAAM,yBACJ,SAKC;AACD,UAAM,mBAAmB,MAAM,KAAK,iBAAiB,OAAO;AAE5D,QAAI,iBAAiB,SAAS;AAE5B,UAAI,QAAQ,cAAc;AAChB,gBAAA,aAAa,6BAA6B,KAAK,cAAc;AAAA,MAAA;AAAA,IACvE;AAGK,WAAA;AAAA,EAAA;AAEX;"}
|
|
1
|
+
{"version":3,"file":"standards-agent-kit.es3.js","sources":["../../src/hcs10/HCS10Client.ts"],"sourcesContent":["import { TransactionReceipt, PrivateKey } from '@hashgraph/sdk';\nimport {\n HCS10Client as StandardSDKClient,\n AgentBuilder,\n InboundTopicType as StandardInboundTopicType,\n AIAgentCapability as StandardAIAgentCapability,\n AgentRegistrationResult,\n WaitForConnectionConfirmationResponse,\n ProfileResponse as SDKProfileResponse,\n HCSMessage,\n LogLevel,\n Logger,\n FeeConfigBuilderInterface,\n SocialPlatform,\n} from '@hashgraphonline/standards-sdk';\nimport { AgentMetadata, AgentChannels } from './types';\nimport { encryptMessage } from '../utils/Encryption';\nimport { IStateManager } from '../state/state-types';\n\n// Keep type alias as they were removed accidentally\ntype StandardHandleConnectionRequest = InstanceType<\n typeof StandardSDKClient\n>['handleConnectionRequest'];\ntype HandleConnectionRequestResponse = Awaited<\n ReturnType<StandardHandleConnectionRequest>\n>;\nexport type StandardNetworkType = 'mainnet' | 'testnet';\n\nexport interface ClientValidationOptions {\n accountId: string;\n privateKey: string;\n network?: StandardNetworkType;\n stateManager?: IStateManager;\n}\n\nexport interface HCSMessageWithTimestamp extends HCSMessage {\n timestamp: number;\n data?: string;\n sequence_number: number;\n}\n\nexport interface ExtendedAgentMetadata extends AgentMetadata {\n pfpBuffer?: Buffer;\n pfpFileName?: string;\n feeConfig?: FeeConfigBuilderInterface;\n}\n\n/**\n * HCS10Client wraps the HCS-10 functionalities using the @hashgraphonline/standards-sdk.\n * - Creates and registers agents using the standard SDK flow.\n * - Manages agent communication channels (handled by standard SDK).\n * - Sends messages on Hedera topics (currently manual, potential for standard SDK integration).\n */\nexport class HCS10Client {\n public standardClient: StandardSDKClient;\n private useEncryption: boolean;\n public agentChannels?: AgentChannels;\n public guardedRegistryBaseUrl: string;\n public logger: Logger;\n\n constructor(\n operatorId: string,\n operatorPrivateKey: string,\n network: StandardNetworkType,\n options?: {\n useEncryption?: boolean;\n registryUrl?: string;\n logLevel?: LogLevel;\n }\n ) {\n this.standardClient = new StandardSDKClient({\n network: network,\n operatorId: operatorId,\n operatorPrivateKey: operatorPrivateKey,\n guardedRegistryBaseUrl: options?.registryUrl,\n logLevel: options?.logLevel,\n });\n this.guardedRegistryBaseUrl = options?.registryUrl || '';\n this.useEncryption = options?.useEncryption || false;\n const shouldSilence = process.env.DISABLE_LOGGING === 'true'; \n this.logger = new Logger({\n level: options?.logLevel || 'info',\n silent: shouldSilence,\n });\n }\n\n public getOperatorId(): string {\n const operator = this.standardClient.getClient().operatorAccountId;\n if (!operator) {\n throw new Error('Operator Account ID not configured in standard client.');\n }\n return operator.toString();\n }\n\n public getNetwork(): StandardNetworkType {\n return this.standardClient.getNetwork() as StandardNetworkType;\n }\n\n public async handleConnectionRequest(\n inboundTopicId: string,\n requestingAccountId: string,\n connectionRequestId: number,\n feeConfig?: FeeConfigBuilderInterface\n ): Promise<HandleConnectionRequestResponse> {\n try {\n const result = await this.standardClient.handleConnectionRequest(\n inboundTopicId,\n requestingAccountId,\n connectionRequestId,\n feeConfig\n );\n return result;\n } catch (error) {\n this.logger.error(\n `Error handling connection request #${connectionRequestId} for topic ${inboundTopicId}:`,\n error\n );\n throw new Error(\n `Failed to handle connection request: ${\n error instanceof Error ? error.message : String(error)\n }`\n );\n }\n }\n\n /**\n * Retrieves the profile for a given account ID using the standard SDK.\n */\n public async getAgentProfile(accountId: string): Promise<SDKProfileResponse> {\n return this.standardClient.retrieveProfile(accountId);\n }\n\n /**\n * Exposes the standard SDK's submitConnectionRequest method.\n */\n public async submitConnectionRequest(\n inboundTopicId: string,\n memo: string\n ): Promise<TransactionReceipt> {\n return this.standardClient.submitConnectionRequest(\n inboundTopicId,\n memo\n ) as Promise<TransactionReceipt>;\n }\n\n /**\n * Exposes the standard SDK's waitForConnectionConfirmation method.\n */\n public async waitForConnectionConfirmation(\n outboundTopicId: string,\n connectionRequestId: number,\n maxAttempts = 60,\n delayMs = 2000\n ): Promise<WaitForConnectionConfirmationResponse> {\n return this.standardClient.waitForConnectionConfirmation(\n outboundTopicId,\n connectionRequestId,\n maxAttempts,\n delayMs\n );\n }\n\n /**\n * Creates and registers an agent using the standard SDK's HCS10Client.\n * This handles account creation, key generation, topic setup, and registration.\n *\n * When metadata includes fee configuration:\n * 1. The properties.feeConfig will be passed to the AgentBuilder\n * 2. The properties.inboundTopicType will be set to FEE_BASED\n * 3. The SDK's createAndRegisterAgent will apply the fees to the agent's inbound topic\n *\n * @param metadata - The agent's metadata, potentially including pfpBuffer, pfpFileName,\n * and fee configuration in properties.feeConfig\n * @returns The registration result from the standard SDK, containing accountId, keys, topics etc.\n */\n public async createAndRegisterAgent(\n metadata: ExtendedAgentMetadata\n ): Promise<AgentRegistrationResult> {\n const builder = new AgentBuilder()\n .setName(metadata.name)\n .setBio(metadata.description || '')\n .setCapabilities(\n metadata.capabilities\n ? metadata.capabilities\n : [StandardAIAgentCapability.TEXT_GENERATION]\n )\n .setType((metadata.type || 'autonomous') as 'autonomous' | 'manual')\n .setModel(metadata.model || 'agent-model-2024')\n .setNetwork(this.getNetwork())\n .setInboundTopicType(StandardInboundTopicType.PUBLIC);\n\n if (metadata?.feeConfig) {\n builder.setInboundTopicType(StandardInboundTopicType.FEE_BASED);\n builder.setFeeConfig(metadata.feeConfig);\n }\n\n if (metadata.pfpBuffer && metadata.pfpFileName) {\n if (metadata.pfpBuffer.byteLength === 0) {\n this.logger.warn(\n 'Provided PFP buffer is empty. Skipping profile picture.'\n );\n } else {\n this.logger.info(\n `Setting profile picture: ${metadata.pfpFileName} (${metadata.pfpBuffer.byteLength} bytes)`\n );\n builder.setProfilePicture(metadata.pfpBuffer, metadata.pfpFileName);\n }\n } else {\n this.logger.warn(\n 'Profile picture not provided in metadata. Agent creation might fail if required by the underlying SDK builder.'\n );\n }\n\n if (metadata.social) {\n Object.entries(metadata.social).forEach(([platform, handle]) => {\n builder.addSocial(platform as SocialPlatform, handle);\n });\n }\n\n if (metadata.properties) {\n Object.entries(metadata.properties).forEach(([key, value]) => {\n builder.addProperty(key, value);\n });\n }\n\n try {\n const hasFees = Boolean(metadata?.feeConfig);\n const result = await this.standardClient.createAndRegisterAgent(builder, {\n initialBalance: hasFees ? 50 : undefined,\n });\n if (\n result?.metadata?.inboundTopicId &&\n result?.metadata?.outboundTopicId\n ) {\n this.agentChannels = {\n inboundTopicId: result.metadata.inboundTopicId,\n outboundTopicId: result.metadata.outboundTopicId,\n };\n }\n return result;\n } catch (error) {\n this.logger.error('Error during agent creation/registration:', error);\n throw new Error(\n `Failed to create/register agent: ${\n error instanceof Error ? error.message : String(error)\n }`\n );\n }\n }\n\n /**\n * Sends a structured HCS-10 message to the specified topic using the standard SDK client.\n * Handles potential inscription for large messages.\n *\n * @param topicId - The target topic ID (likely a connection topic).\n * @param operatorId - The operator ID string (e.g., \"inboundTopic@accountId\").\n * @param data - The actual message content/data.\n * @param memo - Optional memo for the message.\n * @param submitKey - Optional private key for topics requiring specific submit keys.\n * @returns A confirmation status string from the transaction receipt.\n */\n public async sendMessage(\n topicId: string,\n data: string,\n memo?: string,\n submitKey?: PrivateKey\n ): Promise<number | undefined> {\n if (this.useEncryption) {\n data = encryptMessage(data);\n }\n\n try {\n const messageResponse = await this.standardClient.sendMessage(\n topicId,\n data,\n memo,\n submitKey\n );\n return messageResponse.topicSequenceNumber?.toNumber();\n } catch (error) {\n this.logger.error(`Error sending message to topic ${topicId}:`, error);\n throw new Error(\n `Failed to send message: ${\n error instanceof Error ? error.message : String(error)\n }`\n );\n }\n }\n\n /**\n * Retrieves messages from a topic using the standard SDK client.\n *\n * @param topicId - The topic ID to get messages from.\n * @returns Messages from the topic, mapped to the expected format.\n */\n public async getMessages(topicId: string): Promise<{\n messages: HCSMessageWithTimestamp[];\n }> {\n try {\n const result = await this.standardClient.getMessages(topicId);\n\n const mappedMessages = result.messages.map((sdkMessage) => {\n const timestamp = sdkMessage?.created?.getTime() || 0;\n\n return {\n ...sdkMessage,\n timestamp: timestamp,\n data: sdkMessage.data,\n sequence_number: sdkMessage.sequence_number,\n };\n });\n mappedMessages.sort(\n (a: { timestamp: number }, b: { timestamp: number }) =>\n a.timestamp - b.timestamp\n );\n return { messages: mappedMessages };\n } catch (error) {\n this.logger.error(`Error getting messages from topic ${topicId}:`, error);\n return { messages: [] };\n }\n }\n\n public async getMessageStream(topicId: string): Promise<{\n messages: HCSMessage[];\n }> {\n return this.standardClient.getMessageStream(topicId);\n }\n\n /**\n * Retrieves content from an inscribed message using the standard SDK client.\n * @param inscriptionIdOrData - The inscription ID (hcs://...) or potentially raw data string.\n * @returns The resolved message content.\n */\n public async getMessageContent(inscriptionIdOrData: string): Promise<string> {\n try {\n const content = await this.standardClient.getMessageContent(\n inscriptionIdOrData\n );\n return content as string;\n } catch (error) {\n this.logger.error(\n `Error retrieving message content for: ${inscriptionIdOrData}`,\n error\n );\n throw new Error(\n `Failed to retrieve message content: ${\n error instanceof Error ? error.message : String(error)\n }`\n );\n }\n }\n\n /**\n * Retrieves the inbound topic ID associated with the current operator.\n * This typically involves fetching the operator's own HCS-10 profile.\n * @returns A promise that resolves to the operator's inbound topic ID.\n * @throws {Error} If the operator ID cannot be determined or the profile/topic cannot be retrieved.\n */\n public async getInboundTopicId(): Promise<string> {\n try {\n const operatorId = this.getOperatorId();\n this.logger.info(\n `[HCS10Client] Retrieving profile for operator ${operatorId} to find inbound topic...`\n );\n const profileResponse = await this.getAgentProfile(operatorId);\n if (profileResponse.success && profileResponse.topicInfo?.inboundTopic) {\n this.logger.info(\n `[HCS10Client] Found inbound topic for operator ${operatorId}: ${profileResponse.topicInfo.inboundTopic}`\n );\n return profileResponse.topicInfo.inboundTopic;\n } else {\n throw new Error(\n `Could not retrieve inbound topic from profile for ${operatorId}. Profile success: ${profileResponse.success}, Error: ${profileResponse.error}`\n );\n }\n } catch (error) {\n this.logger.error(\n `[HCS10Client] Error fetching operator's inbound topic ID (${this.getOperatorId()}):`,\n error\n );\n const operatorId = this.getOperatorId();\n let detailedMessage = `Failed to get inbound topic ID for operator ${operatorId}.`;\n if (\n error instanceof Error &&\n error.message.includes('does not have a valid HCS-11 memo')\n ) {\n detailedMessage += ` The account profile may not exist or is invalid. Please ensure this operator account (${operatorId}) is registered as an HCS-10 agent. You might need to register it first (e.g., using the 'register_agent' tool or SDK function).`;\n } else if (error instanceof Error) {\n detailedMessage += ` Reason: ${error.message}`;\n } else {\n detailedMessage += ` Unexpected error: ${String(error)}`;\n }\n throw new Error(detailedMessage);\n }\n }\n\n /**\n * Retrieves the configured operator account ID and private key.\n * Required by tools needing to identify the current agent instance.\n */\n public getAccountAndSigner(): { accountId: string; signer: PrivateKey } {\n const result = this.standardClient.getAccountAndSigner();\n return {\n accountId: result.accountId,\n signer: result.signer as unknown as PrivateKey,\n };\n }\n\n /**\n * Retrieves the outbound topic ID for the current operator.\n * Fetches the operator's profile if necessary.\n * @returns The outbound topic ID string.\n * @throws If the outbound topic cannot be determined.\n */\n public async getOutboundTopicId(): Promise<string> {\n const operatorId = this.getOperatorId();\n const profile = await this.getAgentProfile(operatorId);\n if (profile.success && profile.topicInfo?.outboundTopic) {\n return profile.topicInfo.outboundTopic;\n } else {\n throw new Error(\n `Could not retrieve outbound topic from profile for ${operatorId}. Profile success: ${profile.success}, Error: ${profile.error}`\n );\n }\n }\n\n public setClient(accountId: string, privateKey: string): StandardSDKClient {\n this.standardClient = new StandardSDKClient({\n network: this.getNetwork(),\n operatorId: accountId,\n operatorPrivateKey: privateKey,\n guardedRegistryBaseUrl: this.guardedRegistryBaseUrl,\n });\n return this.standardClient;\n }\n\n /**\n * Validates that the operator account exists and has proper access for agent operations\n */\n private async validateOperator(\n options: ClientValidationOptions\n ): Promise<{\n isValid: boolean;\n operator?: { accountId: string };\n error?: string;\n }> {\n try {\n // Set up client with provided operator details\n this.setClient(options.accountId, options.privateKey);\n\n // Check if we can retrieve the operator ID\n const operatorId = this.getOperatorId();\n\n // If we got this far, basic validation passed\n return {\n isValid: true,\n operator: { accountId: operatorId },\n };\n } catch (error) {\n this.logger.error(`Validation error: ${error}`);\n return {\n isValid: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n async initializeWithValidation(\n options: ClientValidationOptions\n ): Promise<{\n isValid: boolean;\n operator?: { accountId: string };\n error?: string;\n }> {\n const validationResult = await this.validateOperator(options);\n\n if (validationResult.isValid) {\n // If we have access to the state manager, initialize its connections manager\n if (options.stateManager) {\n options.stateManager.initializeConnectionsManager(this.standardClient);\n }\n }\n\n return validationResult;\n }\n}\n"],"names":["StandardSDKClient","StandardAIAgentCapability","StandardInboundTopicType"],"mappings":";;AAqDO,MAAM,YAAY;AAAA,EAOvB,YACE,YACA,oBACA,SACA,SAKA;AACK,SAAA,iBAAiB,IAAIA,cAAkB;AAAA,MAC1C;AAAA,MACA;AAAA,MACA;AAAA,MACA,wBAAwB,SAAS;AAAA,MACjC,UAAU,SAAS;AAAA,IAAA,CACpB;AACI,SAAA,yBAAyB,SAAS,eAAe;AACjD,SAAA,gBAAgB,SAAS,iBAAiB;AACzC,UAAA,gBAAgB,QAAQ,IAAI,oBAAoB;AACjD,SAAA,SAAS,IAAI,OAAO;AAAA,MACvB,OAAO,SAAS,YAAY;AAAA,MAC5B,QAAQ;AAAA,IAAA,CACT;AAAA,EAAA;AAAA,EAGI,gBAAwB;AAC7B,UAAM,WAAW,KAAK,eAAe,UAAY,EAAA;AACjD,QAAI,CAAC,UAAU;AACP,YAAA,IAAI,MAAM,wDAAwD;AAAA,IAAA;AAE1E,WAAO,SAAS,SAAS;AAAA,EAAA;AAAA,EAGpB,aAAkC;AAChC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