@hashgraphonline/conversational-agent 0.1.208 → 0.1.210
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/bin/conversational-agent-cli.js +30 -0
- package/cli/readme.md +181 -0
- package/dist/cjs/base-agent.d.ts +3 -1
- package/dist/cjs/conversational-agent.d.ts +64 -13
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.ts +6 -3
- package/dist/cjs/langchain-agent.d.ts +11 -0
- package/dist/cjs/memory/SmartMemoryManager.d.ts +65 -22
- package/dist/cjs/memory/TokenCounter.d.ts +1 -1
- package/dist/cjs/memory/index.d.ts +1 -1
- package/dist/cjs/plugins/hbar/AirdropToolWrapper.d.ts +43 -0
- package/dist/{types/plugins/hbar-transfer/HbarTransferPlugin.d.ts → cjs/plugins/hbar/HbarPlugin.d.ts} +2 -1
- package/dist/{types/plugins/hbar-transfer → cjs/plugins/hbar}/TransferHbarTool.d.ts +1 -1
- package/dist/cjs/plugins/hbar/index.d.ts +3 -0
- package/dist/cjs/plugins/index.d.ts +2 -1
- package/dist/cjs/services/EntityResolver.d.ts +26 -0
- package/dist/cjs/tools/EntityResolverTool.d.ts +104 -0
- package/dist/cjs/types/inscription.d.ts +37 -0
- package/dist/esm/index.js +16 -2
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/index12.js +121 -46
- package/dist/esm/index12.js.map +1 -1
- package/dist/esm/index13.js +177 -13
- package/dist/esm/index13.js.map +1 -1
- package/dist/esm/index14.js +599 -100
- package/dist/esm/index14.js.map +1 -1
- package/dist/esm/index15.js +426 -9
- package/dist/esm/index15.js.map +1 -1
- package/dist/esm/index16.js +119 -160
- package/dist/esm/index16.js.map +1 -1
- package/dist/esm/index17.js +140 -150
- package/dist/esm/index17.js.map +1 -1
- package/dist/esm/index18.js +44 -231
- package/dist/esm/index18.js.map +1 -1
- package/dist/esm/index19.js +86 -643
- package/dist/esm/index19.js.map +1 -1
- package/dist/esm/index2.js +22 -13
- package/dist/esm/index2.js.map +1 -1
- package/dist/esm/index20.js +20 -230
- package/dist/esm/index20.js.map +1 -1
- package/dist/esm/index21.js +9 -179
- package/dist/esm/index21.js.map +1 -1
- package/dist/esm/index22.js +140 -89
- package/dist/esm/index22.js.map +1 -1
- package/dist/esm/index23.js +141 -81
- package/dist/esm/index23.js.map +1 -1
- package/dist/esm/index24.js +4 -4
- package/dist/esm/index24.js.map +1 -1
- package/dist/esm/index25.js +0 -8
- package/dist/esm/index25.js.map +1 -1
- package/dist/esm/index26.js +95 -0
- package/dist/esm/index26.js.map +1 -0
- package/dist/esm/index27.js +242 -0
- package/dist/esm/index27.js.map +1 -0
- package/dist/esm/index5.js +32 -19
- package/dist/esm/index5.js.map +1 -1
- package/dist/esm/index6.js +276 -37
- package/dist/esm/index6.js.map +1 -1
- package/dist/esm/index7.js +2 -2
- package/dist/esm/index7.js.map +1 -1
- package/dist/esm/index8.js +124 -18
- package/dist/esm/index8.js.map +1 -1
- package/dist/types/base-agent.d.ts +3 -1
- package/dist/types/conversational-agent.d.ts +64 -13
- package/dist/types/index.d.ts +6 -3
- package/dist/types/langchain-agent.d.ts +11 -0
- package/dist/types/memory/SmartMemoryManager.d.ts +65 -22
- package/dist/types/memory/TokenCounter.d.ts +1 -1
- package/dist/types/memory/index.d.ts +1 -1
- package/dist/types/plugins/hbar/AirdropToolWrapper.d.ts +43 -0
- package/dist/{cjs/plugins/hbar-transfer/HbarTransferPlugin.d.ts → types/plugins/hbar/HbarPlugin.d.ts} +2 -1
- package/dist/{cjs/plugins/hbar-transfer → types/plugins/hbar}/TransferHbarTool.d.ts +1 -1
- package/dist/types/plugins/hbar/index.d.ts +3 -0
- package/dist/types/plugins/index.d.ts +2 -1
- package/dist/types/services/EntityResolver.d.ts +26 -0
- package/dist/types/tools/EntityResolverTool.d.ts +104 -0
- package/dist/types/types/inscription.d.ts +37 -0
- package/package.json +13 -4
- package/src/base-agent.ts +14 -9
- package/src/config/system-message.ts +11 -2
- package/src/context/ReferenceContextManager.ts +10 -5
- package/src/context/ReferenceResponseProcessor.ts +3 -4
- package/src/conversational-agent.ts +372 -57
- package/src/index.ts +19 -3
- package/src/langchain/ContentAwareAgentExecutor.ts +0 -1
- package/src/langchain-agent.ts +168 -33
- package/src/mcp/ContentProcessor.ts +11 -3
- package/src/mcp/adapters/langchain.ts +1 -10
- package/src/memory/ContentStorage.ts +2 -55
- package/src/memory/MemoryWindow.ts +4 -17
- package/src/memory/ReferenceIdGenerator.ts +4 -8
- package/src/memory/SmartMemoryManager.ts +375 -47
- package/src/memory/TokenCounter.ts +15 -22
- package/src/memory/index.ts +1 -1
- package/src/plugins/hbar/AirdropToolWrapper.ts +157 -0
- package/src/plugins/hbar/HbarPlugin.ts +86 -0
- package/src/plugins/{hbar-transfer → hbar}/TransferHbarTool.ts +3 -3
- package/src/plugins/hbar/index.ts +3 -0
- package/src/plugins/hcs-10/HCS10Plugin.ts +44 -14
- package/src/plugins/index.ts +2 -1
- package/src/services/ContentStoreManager.ts +0 -3
- package/src/services/EntityResolver.ts +135 -0
- package/src/tools/EntityResolverTool.ts +170 -0
- package/src/types/content-reference.ts +8 -8
- package/src/types/index.ts +0 -1
- package/src/types/inscription.ts +40 -0
- package/dist/cjs/plugins/hbar-transfer/index.d.ts +0 -1
- package/dist/types/plugins/hbar-transfer/index.d.ts +0 -1
- package/src/plugins/hbar-transfer/HbarTransferPlugin.ts +0 -66
- package/src/plugins/hbar-transfer/index.ts +0 -1
- /package/dist/cjs/plugins/{hbar-transfer → hbar}/AccountBuilder.d.ts +0 -0
- /package/dist/cjs/plugins/{hbar-transfer → hbar}/types.d.ts +0 -0
- /package/dist/types/plugins/{hbar-transfer → hbar}/AccountBuilder.d.ts +0 -0
- /package/dist/types/plugins/{hbar-transfer → hbar}/types.d.ts +0 -0
- /package/src/plugins/{hbar-transfer → hbar}/AccountBuilder.ts +0 -0
- /package/src/plugins/{hbar-transfer → hbar}/types.ts +0 -0
package/dist/esm/index19.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index19.js","sources":["../../src/memory/ContentStorage.ts"],"sourcesContent":["import type { BaseMessage } from '@langchain/core/messages';\nimport { ReferenceIdGenerator } from './ReferenceIdGenerator';\nimport {\n ReferenceId,\n ContentReference,\n ContentMetadata,\n ReferenceResolutionResult,\n ContentReferenceConfig,\n ContentReferenceStore,\n ContentReferenceStats,\n ContentReferenceError,\n ContentType,\n ContentSource,\n ReferenceLifecycleState,\n DEFAULT_CONTENT_REFERENCE_CONFIG\n} from '../types/content-reference';\n\n/**\n * Stored message with metadata\n */\ninterface StoredMessage {\n message: BaseMessage;\n storedAt: Date;\n id: string;\n}\n\n/**\n * Search options for message queries\n */\ninterface SearchOptions {\n /** Whether to perform case-sensitive search */\n caseSensitive?: boolean;\n /** Maximum number of results to return */\n limit?: number;\n /** Whether to use regex pattern matching */\n useRegex?: boolean;\n}\n\n/**\n * Result of storing messages\n */\ninterface StoreResult {\n /** Number of messages successfully stored */\n stored: number;\n /** Number of old messages dropped to make room */\n dropped: number;\n}\n\n/**\n * Storage statistics\n */\nexport interface StorageStats {\n /** Total number of messages currently stored */\n totalMessages: number;\n /** Maximum storage capacity */\n maxStorageLimit: number;\n /** Percentage of storage used */\n usagePercentage: number;\n /** Timestamp of oldest message */\n oldestMessageTime: Date | undefined;\n /** Timestamp of newest message */\n newestMessageTime: Date | undefined;\n}\n\n/**\n * Stored content with reference metadata\n */\ninterface StoredContent {\n /** The actual content buffer */\n content: Buffer;\n \n /** Complete metadata */\n metadata: ContentMetadata;\n \n /** Current lifecycle state */\n state: ReferenceLifecycleState;\n \n /** When this reference expires (if applicable) */\n expiresAt?: Date;\n}\n\n/**\n * Content storage for managing pruned conversation messages and large content references\n * Provides searchable storage with time-based querying and automatic cleanup.\n * \n * Extended to support reference-based storage for large content to optimize context window usage.\n */\nexport class ContentStorage implements ContentReferenceStore {\n private messages: StoredMessage[] = [];\n private maxStorage: number;\n private idCounter: number = 0;\n\n // Reference-based content storage\n private contentStore: Map<ReferenceId, StoredContent> = new Map();\n private referenceConfig: ContentReferenceConfig;\n private cleanupTimer?: NodeJS.Timeout;\n private referenceStats: Omit<ContentReferenceStats, 'performanceMetrics'> & {\n performanceMetrics: ContentReferenceStats['performanceMetrics'] & {\n creationTimes: number[];\n resolutionTimes: number[];\n cleanupTimes: number[];\n };\n };\n\n // Default storage limit for messages\n public static readonly DEFAULT_MAX_STORAGE = 1000;\n\n constructor(\n maxStorage: number = ContentStorage.DEFAULT_MAX_STORAGE,\n referenceConfig?: Partial<ContentReferenceConfig>\n ) {\n this.maxStorage = maxStorage;\n \n // Initialize reference-based storage\n this.referenceConfig = { ...DEFAULT_CONTENT_REFERENCE_CONFIG, ...referenceConfig };\n this.referenceStats = {\n activeReferences: 0,\n totalStorageBytes: 0,\n recentlyCleanedUp: 0,\n totalResolutions: 0,\n failedResolutions: 0,\n averageContentSize: 0,\n storageUtilization: 0,\n performanceMetrics: {\n averageCreationTimeMs: 0,\n averageResolutionTimeMs: 0,\n averageCleanupTimeMs: 0,\n creationTimes: [],\n resolutionTimes: [],\n cleanupTimes: []\n }\n };\n \n // Start cleanup timer if enabled\n if (this.referenceConfig.enableAutoCleanup) {\n this.startReferenceCleanupTimer();\n }\n }\n\n /**\n * Store messages in the content storage\n * Automatically drops oldest messages if storage limit is exceeded\n * @param messages - Messages to store\n * @returns Result indicating how many messages were stored and dropped\n */\n storeMessages(messages: BaseMessage[]): StoreResult {\n if (messages.length === 0) {\n return { stored: 0, dropped: 0 };\n }\n\n const now = new Date();\n let dropped = 0;\n\n // Convert messages to stored format\n const storedMessages: StoredMessage[] = messages.map(message => ({\n message,\n storedAt: now,\n id: this.generateId()\n }));\n\n // Add new messages\n this.messages.push(...storedMessages);\n\n // Remove oldest messages if we exceed the limit\n while (this.messages.length > this.maxStorage) {\n this.messages.shift();\n dropped++;\n }\n\n return {\n stored: storedMessages.length,\n dropped\n };\n }\n\n /**\n * Get the most recent messages from storage\n * @param count - Number of recent messages to retrieve\n * @returns Array of recent messages in chronological order\n */\n getRecentMessages(count: number): BaseMessage[] {\n if (count <= 0 || this.messages.length === 0) {\n return [];\n }\n\n const startIndex = Math.max(0, this.messages.length - count);\n return this.messages\n .slice(startIndex)\n .map(stored => stored.message);\n }\n\n /**\n * Search for messages containing specific text or patterns\n * @param query - Search term or regex pattern\n * @param options - Search configuration options\n * @returns Array of matching messages\n */\n searchMessages(query: string, options: SearchOptions = {}): BaseMessage[] {\n if (!query || this.messages.length === 0) {\n return [];\n }\n\n const {\n caseSensitive = false,\n limit,\n useRegex = false\n } = options;\n\n let matches: BaseMessage[] = [];\n\n if (useRegex) {\n try {\n const regex = new RegExp(query, caseSensitive ? 'g' : 'gi');\n matches = this.messages\n .filter(stored => regex.test(stored.message.content as string))\n .map(stored => stored.message);\n } catch (error) {\n console.warn('Invalid regex pattern:', query, error);\n return [];\n }\n } else {\n const searchTerm = caseSensitive ? query : query.toLowerCase();\n matches = this.messages\n .filter(stored => {\n const content = stored.message.content as string;\n const searchContent = caseSensitive ? content : content.toLowerCase();\n return searchContent.includes(searchTerm);\n })\n .map(stored => stored.message);\n }\n\n return limit ? matches.slice(0, limit) : matches;\n }\n\n /**\n * Get messages from a specific time range\n * @param startTime - Start of time range (inclusive)\n * @param endTime - End of time range (inclusive)\n * @returns Array of messages within the time range\n */\n getMessagesFromTimeRange(startTime: Date, endTime: Date): BaseMessage[] {\n if (startTime > endTime || this.messages.length === 0) {\n return [];\n }\n\n return this.messages\n .filter(stored => \n stored.storedAt >= startTime && stored.storedAt <= endTime\n )\n .map(stored => stored.message);\n }\n\n /**\n * Get storage statistics and usage information\n * @returns Current storage statistics\n */\n getStorageStats(): StorageStats {\n const totalMessages = this.messages.length;\n const usagePercentage = totalMessages > 0 \n ? Math.round((totalMessages / this.maxStorage) * 100)\n : 0;\n\n let oldestMessageTime: Date | undefined;\n let newestMessageTime: Date | undefined;\n\n if (totalMessages > 0) {\n oldestMessageTime = this.messages[0].storedAt;\n newestMessageTime = this.messages[totalMessages - 1].storedAt;\n }\n\n return {\n totalMessages,\n maxStorageLimit: this.maxStorage,\n usagePercentage,\n oldestMessageTime,\n newestMessageTime\n };\n }\n\n /**\n * Clear all stored messages\n */\n clear(): void {\n this.messages = [];\n this.idCounter = 0;\n }\n\n /**\n * Get total number of stored messages\n * @returns Number of messages currently in storage\n */\n getTotalStoredMessages(): number {\n return this.messages.length;\n }\n\n /**\n * Update the maximum storage limit\n * @param newLimit - New maximum storage limit\n */\n updateStorageLimit(newLimit: number): void {\n if (newLimit <= 0) {\n throw new Error('Storage limit must be greater than 0');\n }\n\n this.maxStorage = newLimit;\n\n // Prune messages if the new limit is smaller\n while (this.messages.length > this.maxStorage) {\n this.messages.shift();\n }\n }\n\n /**\n * Get messages by message type\n * @param messageType - Type of messages to retrieve ('human', 'ai', 'system', etc.)\n * @param limit - Maximum number of messages to return\n * @returns Array of messages of the specified type\n */\n getMessagesByType(messageType: string, limit?: number): BaseMessage[] {\n const filtered = this.messages\n .filter(stored => stored.message._getType() === messageType)\n .map(stored => stored.message);\n\n return limit ? filtered.slice(0, limit) : filtered;\n }\n\n /**\n * Get the current storage configuration\n * @returns Storage configuration object\n */\n getConfig() {\n return {\n maxStorage: this.maxStorage,\n currentUsage: this.messages.length,\n utilizationPercentage: (this.messages.length / this.maxStorage) * 100\n };\n }\n\n /**\n * Generate a unique ID for stored messages\n * @returns Unique string identifier\n */\n private generateId(): string {\n return `msg_${++this.idCounter}_${Date.now()}`;\n }\n\n /**\n * Get messages stored within the last N minutes\n * @param minutes - Number of minutes to look back\n * @returns Array of messages from the last N minutes\n */\n getRecentMessagesByTime(minutes: number): BaseMessage[] {\n if (minutes <= 0 || this.messages.length === 0) {\n return [];\n }\n\n const cutoffTime = new Date(Date.now() - (minutes * 60 * 1000));\n \n return this.messages\n .filter(stored => stored.storedAt >= cutoffTime)\n .map(stored => stored.message);\n }\n\n /**\n * Export messages to a JSON-serializable format\n * @returns Serializable representation of stored messages\n */\n exportMessages() {\n return this.messages.map(stored => ({\n content: stored.message.content,\n type: stored.message._getType(),\n storedAt: stored.storedAt.toISOString(),\n id: stored.id\n }));\n }\n\n // ========== Reference-Based Content Storage Methods ==========\n\n /**\n * Determine if content should be stored as a reference based on size\n */\n shouldUseReference(content: Buffer | string): boolean {\n const size = Buffer.isBuffer(content) ? content.length : Buffer.byteLength(content, 'utf8');\n return size > this.referenceConfig.sizeThresholdBytes;\n }\n\n /**\n * Store content and return a reference if it exceeds the size threshold\n * Otherwise returns null to indicate direct content should be used\n */\n async storeContentIfLarge(\n content: Buffer | string,\n metadata: {\n contentType?: ContentType;\n mimeType?: string;\n source: ContentSource;\n mcpToolName?: string;\n fileName?: string;\n tags?: string[];\n customMetadata?: Record<string, unknown>;\n }\n ): Promise<ContentReference | null> {\n const buffer = Buffer.isBuffer(content) ? content : Buffer.from(content, 'utf8');\n \n if (!this.shouldUseReference(buffer)) {\n return null;\n }\n \n const storeMetadata: Omit<ContentMetadata, 'createdAt' | 'lastAccessedAt' | 'accessCount'> = {\n contentType: metadata.contentType || this.detectContentType(buffer, metadata.mimeType),\n sizeBytes: buffer.length,\n source: metadata.source,\n tags: []\n };\n \n if (metadata.mimeType !== undefined) {\n storeMetadata.mimeType = metadata.mimeType;\n }\n if (metadata.mcpToolName !== undefined) {\n storeMetadata.mcpToolName = metadata.mcpToolName;\n }\n if (metadata.fileName !== undefined) {\n storeMetadata.fileName = metadata.fileName;\n }\n if (metadata.tags !== undefined) {\n storeMetadata.tags = metadata.tags;\n }\n if (metadata.customMetadata !== undefined) {\n storeMetadata.customMetadata = metadata.customMetadata;\n }\n \n return await this.storeContent(buffer, storeMetadata);\n }\n\n /**\n * Store content and return a reference (implements ContentReferenceStore)\n */\n async storeContent(\n content: Buffer,\n metadata: Omit<ContentMetadata, 'createdAt' | 'lastAccessedAt' | 'accessCount'>\n ): Promise<ContentReference> {\n const startTime = Date.now();\n \n try {\n const now = new Date();\n const referenceId = ReferenceIdGenerator.generateId(content);\n \n const fullMetadata: ContentMetadata = {\n ...metadata,\n createdAt: now,\n lastAccessedAt: now,\n accessCount: 0\n };\n \n const storedContent: StoredContent = {\n content,\n metadata: fullMetadata,\n state: 'active'\n };\n \n const expirationTime = this.calculateExpirationTime(metadata.source);\n if (expirationTime !== undefined) {\n storedContent.expiresAt = expirationTime;\n }\n \n this.contentStore.set(referenceId, storedContent);\n \n // Update statistics\n this.updateStatsAfterStore(content.length);\n \n // Enforce storage limits after storing\n await this.enforceReferenceStorageLimits();\n \n // Create preview\n const preview = this.createContentPreview(content, fullMetadata.contentType);\n \n const referenceMetadata: Pick<ContentMetadata, 'contentType' | 'sizeBytes' | 'source' | 'fileName' | 'mimeType'> = {\n contentType: fullMetadata.contentType,\n sizeBytes: fullMetadata.sizeBytes,\n source: fullMetadata.source\n };\n \n if (fullMetadata.fileName !== undefined) {\n referenceMetadata.fileName = fullMetadata.fileName;\n }\n if (fullMetadata.mimeType !== undefined) {\n referenceMetadata.mimeType = fullMetadata.mimeType;\n }\n \n const reference: ContentReference = {\n referenceId,\n state: 'active',\n preview,\n metadata: referenceMetadata,\n createdAt: now,\n format: 'ref://{id}' as const\n };\n \n // Record performance\n const duration = Date.now() - startTime;\n this.recordPerformanceMetric('creation', duration);\n \n console.log(`[ContentStorage] Stored content with reference ID: ${referenceId} (${content.length} bytes)`);\n \n return reference;\n } catch (error) {\n const duration = Date.now() - startTime;\n this.recordPerformanceMetric('creation', duration);\n \n console.error('[ContentStorage] Failed to store content:', error);\n throw new ContentReferenceError(\n `Failed to store content: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 'system_error',\n undefined,\n ['Try again', 'Check storage limits', 'Contact administrator']\n );\n }\n }\n\n /**\n * Resolve a reference to its content (implements ContentReferenceStore)\n */\n async resolveReference(referenceId: ReferenceId): Promise<ReferenceResolutionResult> {\n const startTime = Date.now();\n \n try {\n // Validate reference ID format\n if (!ReferenceIdGenerator.isValidReferenceId(referenceId)) {\n this.referenceStats.failedResolutions++;\n return {\n success: false,\n error: 'Invalid reference ID format',\n errorType: 'not_found',\n suggestedActions: ['Check the reference ID format', 'Ensure the reference ID is complete']\n };\n }\n \n const storedContent = this.contentStore.get(referenceId);\n \n if (!storedContent) {\n this.referenceStats.failedResolutions++;\n return {\n success: false,\n error: 'Reference not found',\n errorType: 'not_found',\n suggestedActions: ['Verify the reference ID', 'Check if the content has expired', 'Request fresh content']\n };\n }\n \n // Check if expired\n if (storedContent.expiresAt && storedContent.expiresAt < new Date()) {\n storedContent.state = 'expired';\n this.referenceStats.failedResolutions++;\n return {\n success: false,\n error: 'Reference has expired',\n errorType: 'expired',\n suggestedActions: ['Request fresh content', 'Use alternative content source']\n };\n }\n \n // Check state\n if (storedContent.state !== 'active') {\n this.referenceStats.failedResolutions++;\n return {\n success: false,\n error: `Reference is ${storedContent.state}`,\n errorType: storedContent.state === 'expired' ? 'expired' : 'corrupted',\n suggestedActions: ['Request fresh content', 'Check reference validity']\n };\n }\n \n // Update access tracking\n storedContent.metadata.lastAccessedAt = new Date();\n storedContent.metadata.accessCount++;\n \n // Update statistics\n this.referenceStats.totalResolutions++;\n \n // Record performance\n const duration = Date.now() - startTime;\n this.recordPerformanceMetric('resolution', duration);\n \n console.log(`[ContentStorage] Resolved reference ${referenceId} (${storedContent.content.length} bytes, access count: ${storedContent.metadata.accessCount})`);\n \n return {\n success: true,\n content: storedContent.content,\n metadata: storedContent.metadata\n };\n } catch (error) {\n const duration = Date.now() - startTime;\n this.recordPerformanceMetric('resolution', duration);\n \n this.referenceStats.failedResolutions++;\n console.error(`[ContentStorage] Error resolving reference ${referenceId}:`, error);\n \n return {\n success: false,\n error: `System error resolving reference: ${error instanceof Error ? error.message : 'Unknown error'}`,\n errorType: 'system_error',\n suggestedActions: ['Try again', 'Contact administrator']\n };\n }\n }\n\n /**\n * Check if a reference exists and is valid\n */\n async hasReference(referenceId: ReferenceId): Promise<boolean> {\n if (!ReferenceIdGenerator.isValidReferenceId(referenceId)) {\n return false;\n }\n \n const storedContent = this.contentStore.get(referenceId);\n if (!storedContent) {\n return false;\n }\n \n // Check if expired\n if (storedContent.expiresAt && storedContent.expiresAt < new Date()) {\n storedContent.state = 'expired';\n return false;\n }\n \n return storedContent.state === 'active';\n }\n\n /**\n * Mark a reference for cleanup\n */\n async cleanupReference(referenceId: ReferenceId): Promise<boolean> {\n const storedContent = this.contentStore.get(referenceId);\n if (!storedContent) {\n return false;\n }\n \n // Update statistics\n this.referenceStats.totalStorageBytes -= storedContent.content.length;\n this.referenceStats.activeReferences--;\n this.referenceStats.recentlyCleanedUp++;\n \n this.contentStore.delete(referenceId);\n \n console.log(`[ContentStorage] Cleaned up reference ${referenceId} (${storedContent.content.length} bytes)`);\n return true;\n }\n\n /**\n * Get current reference storage statistics (implements ContentReferenceStore)\n */\n async getStats(): Promise<ContentReferenceStats> {\n this.updateReferenceStorageStats();\n \n return {\n ...this.referenceStats,\n performanceMetrics: {\n averageCreationTimeMs: this.calculateAverage(this.referenceStats.performanceMetrics.creationTimes),\n averageResolutionTimeMs: this.calculateAverage(this.referenceStats.performanceMetrics.resolutionTimes),\n averageCleanupTimeMs: this.calculateAverage(this.referenceStats.performanceMetrics.cleanupTimes)\n }\n };\n }\n\n /**\n * Update reference configuration\n */\n async updateConfig(config: Partial<ContentReferenceConfig>): Promise<void> {\n this.referenceConfig = { ...this.referenceConfig, ...config };\n \n // Restart cleanup timer if needed\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n delete this.cleanupTimer;\n }\n \n if (this.referenceConfig.enableAutoCleanup) {\n this.startReferenceCleanupTimer();\n }\n \n console.log('[ContentStorage] Reference configuration updated');\n }\n\n /**\n * Perform cleanup based on current policies (implements ContentReferenceStore)\n */\n async performCleanup(): Promise<{ cleanedUp: number; errors: string[] }> {\n const startTime = Date.now();\n const errors: string[] = [];\n let cleanedUp = 0;\n \n try {\n console.log('[ContentStorage] Starting reference cleanup process...');\n \n const now = new Date();\n const toCleanup: ReferenceId[] = [];\n \n // Identify references for cleanup\n for (const [referenceId, storedContent] of this.contentStore.entries()) {\n let shouldCleanup = false;\n \n // Check expiration\n if (storedContent.expiresAt && storedContent.expiresAt < now) {\n shouldCleanup = true;\n storedContent.state = 'expired';\n }\n \n // Check age-based policies\n const ageMs = now.getTime() - storedContent.metadata.createdAt.getTime();\n const policy = this.getCleanupPolicy(storedContent.metadata.source);\n \n if (ageMs > policy.maxAgeMs) {\n shouldCleanup = true;\n }\n \n // Check if marked for cleanup\n if (storedContent.state === 'cleanup_pending') {\n shouldCleanup = true;\n }\n \n if (shouldCleanup) {\n toCleanup.push(referenceId);\n }\n }\n \n // Sort by priority (higher priority = cleanup first)\n toCleanup.sort((a, b) => {\n const aContent = this.contentStore.get(a)!;\n const bContent = this.contentStore.get(b)!;\n const aPriority = this.getCleanupPolicy(aContent.metadata.source).priority;\n const bPriority = this.getCleanupPolicy(bContent.metadata.source).priority;\n return bPriority - aPriority; // Higher priority first\n });\n \n // Perform cleanup\n for (const referenceId of toCleanup) {\n try {\n const success = await this.cleanupReference(referenceId);\n if (success) {\n cleanedUp++;\n }\n } catch (error) {\n errors.push(`Failed to cleanup ${referenceId}: ${error instanceof Error ? error.message : 'Unknown error'}`);\n }\n }\n \n // Check storage limits and cleanup oldest if needed\n if (this.contentStore.size > this.referenceConfig.maxReferences) {\n const sortedByAge = Array.from(this.contentStore.entries())\n .sort(([, a], [, b]) => a.metadata.lastAccessedAt.getTime() - b.metadata.lastAccessedAt.getTime());\n \n const excessCount = this.contentStore.size - this.referenceConfig.maxReferences;\n for (let i = 0; i < excessCount && i < sortedByAge.length; i++) {\n const [referenceId] = sortedByAge[i];\n try {\n const success = await this.cleanupReference(referenceId);\n if (success) {\n cleanedUp++;\n }\n } catch (error) {\n errors.push(`Failed to cleanup excess reference ${referenceId}: ${error instanceof Error ? error.message : 'Unknown error'}`);\n }\n }\n }\n \n const duration = Date.now() - startTime;\n this.recordPerformanceMetric('cleanup', duration);\n \n console.log(`[ContentStorage] Reference cleanup completed: ${cleanedUp} references cleaned up, ${errors.length} errors`);\n \n return { cleanedUp, errors };\n } catch (error) {\n const duration = Date.now() - startTime;\n this.recordPerformanceMetric('cleanup', duration);\n \n const errorMessage = `Cleanup process failed: ${error instanceof Error ? error.message : 'Unknown error'}`;\n console.error('[ContentStorage]', errorMessage);\n errors.push(errorMessage);\n \n return { cleanedUp, errors };\n }\n }\n\n /**\n * Get reference configuration for debugging\n */\n getReferenceConfig(): ContentReferenceConfig {\n return { ...this.referenceConfig };\n }\n\n // ========== Private Reference Storage Helper Methods ==========\n\n private async enforceReferenceStorageLimits(): Promise<void> {\n // Check reference count limit\n if (this.contentStore.size >= this.referenceConfig.maxReferences) {\n await this.performCleanup();\n }\n \n // Check total storage size limit\n if (this.referenceStats.totalStorageBytes >= this.referenceConfig.maxTotalStorageBytes) {\n await this.performCleanup();\n }\n }\n\n private calculateExpirationTime(source: ContentSource): Date | undefined {\n const policy = this.getCleanupPolicy(source);\n return new Date(Date.now() + policy.maxAgeMs);\n }\n\n private getCleanupPolicy(source: ContentSource) {\n switch (source) {\n case 'mcp_tool':\n return this.referenceConfig.cleanupPolicies.recent;\n case 'user_upload':\n return this.referenceConfig.cleanupPolicies.userContent;\n case 'agent_generated':\n return this.referenceConfig.cleanupPolicies.agentGenerated;\n default:\n return this.referenceConfig.cleanupPolicies.default;\n }\n }\n\n private detectContentType(content: Buffer, mimeType?: string): ContentType {\n if (mimeType) {\n if (mimeType === 'text/html') return 'html';\n if (mimeType === 'text/markdown') return 'markdown';\n if (mimeType === 'application/json') return 'json';\n if (mimeType.startsWith('text/')) return 'text';\n return 'binary';\n }\n \n // Simple content detection\n const contentStr = content.toString('utf8', 0, Math.min(content.length, 1000));\n if (contentStr.startsWith('{') || contentStr.startsWith('[')) return 'json';\n if (contentStr.includes('<html>') || contentStr.includes('<!DOCTYPE')) return 'html';\n if (contentStr.includes('#') && contentStr.includes('\\n')) return 'markdown';\n \n return 'text';\n }\n\n private createContentPreview(content: Buffer, contentType: ContentType): string {\n const maxLength = 200;\n let preview = content.toString('utf8', 0, Math.min(content.length, maxLength * 2));\n \n // Clean up based on content type\n if (contentType === 'html') {\n // Remove all HTML tags and normalize whitespace\n preview = preview\n .replace(/<[^>]*>/g, '')\n .replace(/\\s+/g, ' ')\n .trim();\n } else if (contentType === 'json') {\n try {\n const parsed = JSON.parse(preview);\n preview = JSON.stringify(parsed, null, 0);\n } catch {\n // Keep original if not valid JSON\n }\n }\n \n preview = preview.trim();\n if (preview.length > maxLength) {\n preview = preview.substring(0, maxLength) + '...';\n }\n \n return preview || '[Binary content]';\n }\n\n private updateStatsAfterStore(sizeBytes: number): void {\n this.referenceStats.activeReferences++;\n this.referenceStats.totalStorageBytes += sizeBytes;\n this.updateReferenceStorageStats();\n }\n\n private updateReferenceStorageStats(): void {\n if (this.referenceStats.activeReferences > 0) {\n this.referenceStats.averageContentSize = this.referenceStats.totalStorageBytes / this.referenceStats.activeReferences;\n }\n \n this.referenceStats.storageUtilization = (this.referenceStats.totalStorageBytes / this.referenceConfig.maxTotalStorageBytes) * 100;\n \n // Find most accessed reference\n let mostAccessedId: ReferenceId | undefined;\n let maxAccess = 0;\n \n for (const [referenceId, storedContent] of this.contentStore.entries()) {\n if (storedContent.metadata.accessCount > maxAccess) {\n maxAccess = storedContent.metadata.accessCount;\n mostAccessedId = referenceId;\n }\n }\n \n if (mostAccessedId !== undefined) {\n this.referenceStats.mostAccessedReferenceId = mostAccessedId;\n } else {\n delete this.referenceStats.mostAccessedReferenceId;\n }\n }\n\n private recordPerformanceMetric(type: 'creation' | 'resolution' | 'cleanup', timeMs: number): void {\n const metrics = this.referenceStats.performanceMetrics;\n const maxRecords = 100; // Keep last 100 measurements\n \n switch (type) {\n case 'creation':\n metrics.creationTimes.push(timeMs);\n if (metrics.creationTimes.length > maxRecords) {\n metrics.creationTimes.shift();\n }\n break;\n case 'resolution':\n metrics.resolutionTimes.push(timeMs);\n if (metrics.resolutionTimes.length > maxRecords) {\n metrics.resolutionTimes.shift();\n }\n break;\n case 'cleanup':\n metrics.cleanupTimes.push(timeMs);\n if (metrics.cleanupTimes.length > maxRecords) {\n metrics.cleanupTimes.shift();\n }\n break;\n }\n }\n\n private calculateAverage(times: number[]): number {\n if (times.length === 0) return 0;\n return times.reduce((sum, time) => sum + time, 0) / times.length;\n }\n\n private startReferenceCleanupTimer(): void {\n this.cleanupTimer = setInterval(async () => {\n try {\n await this.performCleanup();\n } catch (error) {\n console.error('[ContentStorage] Error in scheduled reference cleanup:', error);\n }\n }, this.referenceConfig.cleanupIntervalMs);\n }\n\n /**\n * Clean up resources (enhanced to include reference cleanup)\n */\n async dispose(): Promise<void> {\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n delete this.cleanupTimer;\n }\n \n this.contentStore.clear();\n \n this.clear();\n }\n}"],"names":[],"mappings":";;AAuFO,MAAM,kBAAN,MAAM,gBAAgD;AAAA,EAoB3D,YACE,aAAqB,gBAAe,qBACpC,iBACA;AAtBF,SAAQ,WAA4B,CAAA;AAEpC,SAAQ,YAAoB;AAG5B,SAAQ,mCAAoD,IAAA;AAkB1D,SAAK,aAAa;AAGlB,SAAK,kBAAkB,EAAE,GAAG,kCAAkC,GAAG,gBAAA;AACjE,SAAK,iBAAiB;AAAA,MACpB,kBAAkB;AAAA,MAClB,mBAAmB;AAAA,MACnB,mBAAmB;AAAA,MACnB,kBAAkB;AAAA,MAClB,mBAAmB;AAAA,MACnB,oBAAoB;AAAA,MACpB,oBAAoB;AAAA,MACpB,oBAAoB;AAAA,QAClB,uBAAuB;AAAA,QACvB,yBAAyB;AAAA,QACzB,sBAAsB;AAAA,QACtB,eAAe,CAAA;AAAA,QACf,iBAAiB,CAAA;AAAA,QACjB,cAAc,CAAA;AAAA,MAAC;AAAA,IACjB;AAIF,QAAI,KAAK,gBAAgB,mBAAmB;AAC1C,WAAK,2BAAA;AAAA,IACP;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,cAAc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AAK;AAAA,IACd;AAEA,SAAK,aAAa,MAAA;AAElB,SAAK,MAAA;AAAA,EACP;AACF;AAh1BE,gBAAuB,sBAAsB;AAlBxC,IAAM,iBAAN;"}
|
|
1
|
+
{"version":3,"file":"index19.js","sources":["../../src/plugins/hbar/AirdropToolWrapper.ts"],"sourcesContent":["import { StructuredTool } from '@langchain/core/tools';\nimport { z } from 'zod';\nimport { HederaAgentKit } from 'hedera-agent-kit';\nimport { Logger } from '@hashgraphonline/standards-sdk';\n\ninterface TokenInfo {\n decimals: number;\n [key: string]: unknown;\n}\n\ninterface ToolWithCall {\n _call(input: unknown): Promise<string>;\n}\n\ninterface AgentKitWithMirrorNode {\n mirrorNode?: {\n getTokenInfo(tokenId: string): Promise<TokenInfo>;\n };\n network: string;\n}\n\nexport class AirdropToolWrapper extends StructuredTool {\n name = 'hedera-hts-airdrop-token';\n description =\n 'Airdrops fungible tokens to multiple recipients. Automatically converts human-readable amounts to smallest units based on token decimals.';\n\n schema = z.object({\n tokenId: z\n .string()\n .describe('The ID of the fungible token to airdrop (e.g., \"0.0.yyyy\").'),\n recipients: z\n .array(\n z.object({\n accountId: z\n .string()\n .describe('Recipient account ID (e.g., \"0.0.xxxx\").'),\n amount: z\n .union([z.number(), z.string()])\n .describe(\n 'Amount in human-readable format (e.g., \"10\" for 10 tokens).'\n ),\n })\n )\n .min(1)\n .describe('Array of recipient objects, each with accountId and amount.'),\n memo: z.string().optional().describe('Optional. Memo for the transaction.'),\n });\n\n private originalTool: StructuredTool & ToolWithCall;\n private agentKit: HederaAgentKit & AgentKitWithMirrorNode;\n private logger: Logger;\n\n constructor(originalTool: StructuredTool, agentKit: unknown) {\n super();\n this.originalTool = originalTool as StructuredTool & ToolWithCall;\n this.agentKit = agentKit as HederaAgentKit & AgentKitWithMirrorNode;\n this.logger = new Logger({ module: 'AirdropToolWrapper' });\n }\n\n async _call(input: z.infer<typeof this.schema>): Promise<string> {\n try {\n this.logger.info(\n `Processing airdrop request for token ${input.tokenId} with ${input.recipients.length} recipients`\n );\n\n const tokenInfo = await this.getTokenInfo(input.tokenId);\n const decimals = tokenInfo.decimals || 0;\n\n this.logger.info(`Token ${input.tokenId} has ${decimals} decimal places`);\n\n const convertedRecipients = input.recipients.map((recipient) => {\n const humanAmount =\n typeof recipient.amount === 'string'\n ? parseFloat(recipient.amount)\n : recipient.amount;\n const smallestUnitAmount = this.convertToSmallestUnits(\n humanAmount,\n decimals\n );\n\n this.logger.info(\n `Converting amount for ${recipient.accountId}: ${humanAmount} tokens → ${smallestUnitAmount} smallest units`\n );\n\n return {\n ...recipient,\n amount: smallestUnitAmount.toString(),\n };\n });\n\n const convertedInput = {\n ...input,\n recipients: convertedRecipients,\n };\n\n this.logger.info(`Calling original airdrop tool with converted amounts`);\n return await this.originalTool._call(convertedInput);\n } catch (error) {\n this.logger.error('Error in airdrop tool wrapper:', error);\n throw error;\n }\n }\n\n private convertToSmallestUnits(amount: number, decimals: number): number {\n return Math.floor(amount * Math.pow(10, decimals));\n }\n\n private async getTokenInfo(tokenId: string): Promise<TokenInfo> {\n return await this.queryTokenInfo(tokenId);\n }\n\n private async queryTokenInfo(tokenId: string): Promise<TokenInfo> {\n try {\n this.logger.info('Querying token info using mirror node');\n const mirrorNode = this.agentKit.mirrorNode;\n if (!mirrorNode) {\n this.logger.info(\n 'MirrorNode not found in agentKit, attempting to access via fetch'\n );\n const network = this.agentKit.network || 'testnet';\n const mirrorNodeUrl =\n network === 'mainnet'\n ? 'https://mainnet.mirrornode.hedera.com'\n : 'https://testnet.mirrornode.hedera.com';\n\n const response = await fetch(\n `${mirrorNodeUrl}/api/v1/tokens/${tokenId}`\n );\n if (response.ok) {\n const tokenData = (await response.json()) as Record<string, unknown>;\n const decimals = parseInt(String(tokenData.decimals || '0'));\n this.logger.info(\n `Token ${tokenId} found with ${decimals} decimals via API`\n );\n return { ...tokenData, decimals };\n }\n } else {\n const tokenData = await mirrorNode.getTokenInfo(tokenId);\n\n if (tokenData && typeof tokenData.decimals !== 'undefined') {\n const decimals = parseInt(tokenData.decimals.toString()) || 0;\n this.logger.info(`Token ${tokenId} found with ${decimals} decimals`);\n return { ...tokenData, decimals };\n }\n }\n\n throw new Error(`Token data not found or missing decimals field`);\n } catch (error) {\n this.logger.warn(`Failed to query token info for ${tokenId}:`, error);\n\n this.logger.info(\n 'Falling back to assumed 0 decimal places (smallest units)'\n );\n return { decimals: 0 };\n }\n }\n}\n"],"names":[],"mappings":";;;AAqBO,MAAM,2BAA2B,eAAe;AAAA,EA+BrD,YAAY,cAA8B,UAAmB;AAC3D,UAAA;AA/BF,SAAA,OAAO;AACP,SAAA,cACE;AAEF,SAAA,SAAS,EAAE,OAAO;AAAA,MAChB,SAAS,EACN,SACA,SAAS,6DAA6D;AAAA,MACzE,YAAY,EACT;AAAA,QACC,EAAE,OAAO;AAAA,UACP,WAAW,EACR,SACA,SAAS,0CAA0C;AAAA,UACtD,QAAQ,EACL,MAAM,CAAC,EAAE,OAAA,GAAU,EAAE,QAAQ,CAAC,EAC9B;AAAA,YACC;AAAA,UAAA;AAAA,QACF,CACH;AAAA,MAAA,EAEF,IAAI,CAAC,EACL,SAAS,6DAA6D;AAAA,MACzE,MAAM,EAAE,OAAA,EAAS,SAAA,EAAW,SAAS,qCAAqC;AAAA,IAAA,CAC3E;AAQC,SAAK,eAAe;AACpB,SAAK,WAAW;AAChB,SAAK,SAAS,IAAI,OAAO,EAAE,QAAQ,sBAAsB;AAAA,EAC3D;AAAA,EAEA,MAAM,MAAM,OAAqD;AAC/D,QAAI;AACF,WAAK,OAAO;AAAA,QACV,wCAAwC,MAAM,OAAO,SAAS,MAAM,WAAW,MAAM;AAAA,MAAA;AAGvF,YAAM,YAAY,MAAM,KAAK,aAAa,MAAM,OAAO;AACvD,YAAM,WAAW,UAAU,YAAY;AAEvC,WAAK,OAAO,KAAK,SAAS,MAAM,OAAO,QAAQ,QAAQ,iBAAiB;AAExE,YAAM,sBAAsB,MAAM,WAAW,IAAI,CAAC,cAAc;AAC9D,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AAA;AAEzC,iBAAO,EAAE,GAAG,WAAW,SAAA;AAAA,QACzB;AAAA,MACF,OAAO;AACL,cAAM,YAAY,MAAM,WAAW,aAAa,OAAO;AAEvD,YAAI,aAAa,OAAO,UAAU,aAAa,aAAa;AAC1D,gBAAM,WAAW,SAAS,UAAU,SAAS,SAAA,CAAU,KAAK;AAC5D,eAAK,OAAO,KAAK,SAAS,OAAO,eAAe,QAAQ,WAAW;AACnE,iBAAO,EAAE,GAAG,WAAW,SAAA;AAAA,QACzB;AAAA,MACF;AAEA,YAAM,IAAI,MAAM,gDAAgD;AAAA,IAClE,SAAS,OAAO;AACd,WAAK,OAAO,KAAK,kCAAkC,OAAO,KAAK,KAAK;AAEpE,WAAK,OAAO;AAAA,QACV;AAAA,MAAA;AAEF,aAAO,EAAE,UAAU,EAAA;AAAA,IACrB;AAAA,EACF;AACF;"}
|
package/dist/esm/index2.js
CHANGED
|
@@ -27,7 +27,8 @@ class HCS10Plugin extends BasePlugin {
|
|
|
27
27
|
let inboundTopicId = "";
|
|
28
28
|
let outboundTopicId = "";
|
|
29
29
|
try {
|
|
30
|
-
const
|
|
30
|
+
const opKey = hederaKit.signer.getOperatorPrivateKey();
|
|
31
|
+
const privateKey = typeof opKey?.toStringRaw === "function" ? opKey.toStringRaw() : typeof opKey?.toString === "function" ? opKey.toString() : String(opKey);
|
|
31
32
|
const hcs10Client = new HCS10Client({
|
|
32
33
|
network: hederaKit.network,
|
|
33
34
|
operatorId: accountId,
|
|
@@ -50,23 +51,31 @@ class HCS10Plugin extends BasePlugin {
|
|
|
50
51
|
accountId,
|
|
51
52
|
inboundTopicId,
|
|
52
53
|
outboundTopicId,
|
|
53
|
-
privateKey:
|
|
54
|
+
privateKey: (() => {
|
|
55
|
+
const opKey = hederaKit.signer.getOperatorPrivateKey();
|
|
56
|
+
return typeof opKey?.toStringRaw === "function" ? opKey.toStringRaw() : typeof opKey?.toString === "function" ? opKey.toString() : String(opKey);
|
|
57
|
+
})()
|
|
54
58
|
});
|
|
55
59
|
this.context.logger.info(
|
|
56
60
|
`Set current agent: ${accountId} with topics ${inboundTopicId}/${outboundTopicId}`
|
|
57
61
|
);
|
|
58
62
|
if (this.stateManager && !this.stateManager.getConnectionsManager()) {
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
63
|
+
try {
|
|
64
|
+
const opKey = hederaKit.signer.getOperatorPrivateKey();
|
|
65
|
+
const privateKey = typeof opKey?.toStringRaw === "function" ? opKey.toStringRaw() : typeof opKey?.toString === "function" ? opKey.toString() : String(opKey);
|
|
66
|
+
const hcs10Client = new HCS10Client({
|
|
67
|
+
network: hederaKit.network,
|
|
68
|
+
operatorId: accountId,
|
|
69
|
+
operatorPrivateKey: privateKey,
|
|
70
|
+
logLevel: "error"
|
|
71
|
+
});
|
|
72
|
+
this.stateManager.initializeConnectionsManager(hcs10Client);
|
|
73
|
+
this.context.logger.info(
|
|
74
|
+
"ConnectionsManager initialized in HCS10Plugin"
|
|
75
|
+
);
|
|
76
|
+
} catch (cmError) {
|
|
77
|
+
this.context.logger.warn("Could not initialize ConnectionsManager:", cmError);
|
|
78
|
+
}
|
|
70
79
|
}
|
|
71
80
|
this.initializeTools();
|
|
72
81
|
this.context.logger.info("HCS-10 Plugin initialized successfully");
|
package/dist/esm/index2.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index2.js","sources":["../../src/plugins/hcs-10/HCS10Plugin.ts"],"sourcesContent":["import {\n GenericPluginContext,\n HederaTool,\n BasePlugin,\n HederaAgentKit,\n} from 'hedera-agent-kit';\nimport {\n IStateManager,\n OpenConvaiState,\n HCS10Builder,\n RegisterAgentTool,\n FindRegistrationsTool,\n InitiateConnectionTool,\n ListConnectionsTool,\n SendMessageToConnectionTool,\n CheckMessagesTool,\n ConnectionMonitorTool,\n ManageConnectionRequestsTool,\n AcceptConnectionRequestTool,\n RetrieveProfileTool,\n ListUnapprovedConnectionRequestsTool,\n} from '@hashgraphonline/standards-agent-kit';\nimport { HCS10Client } from '@hashgraphonline/standards-sdk';\n\nexport class HCS10Plugin extends BasePlugin {\n id = 'hcs-10';\n name = 'HCS-10 Plugin';\n description =\n 'HCS-10 agent tools for decentralized agent registration, connections, and messaging on Hedera';\n version = '1.0.0';\n author = 'Hashgraph Online';\n namespace = 'hcs10';\n\n private stateManager?: IStateManager;\n private tools: HederaTool[] = [];\n appConfig?: Record<string, unknown>;\n\n override async initialize(context: GenericPluginContext): Promise<void> {\n await super.initialize(context);\n\n const hederaKit = context.config.hederaKit as HederaAgentKit;\n if (!hederaKit) {\n this.context.logger.warn(\n 'HederaKit not found in context. HCS-10 tools will not be available.'\n );\n return;\n }\n\n try {\n this.stateManager =\n (context.stateManager as IStateManager) ||\n (context.config.stateManager as IStateManager) ||\n (this.appConfig?.stateManager as IStateManager) ||\n new OpenConvaiState();\n\n const accountId = hederaKit.signer.getAccountId().toString();\n let inboundTopicId = '';\n let outboundTopicId = '';\n\n try {\n const privateKey = hederaKit.signer.getOperatorPrivateKey().toString();\n\n const hcs10Client = new HCS10Client({\n network: hederaKit.network as 'mainnet' | 'testnet',\n operatorId: accountId,\n operatorPrivateKey: privateKey,\n logLevel: 'error',\n });\n\n const profileResponse = await hcs10Client.retrieveProfile(accountId);\n if (profileResponse.success && profileResponse.topicInfo) {\n inboundTopicId = profileResponse.topicInfo.inboundTopic;\n outboundTopicId = profileResponse.topicInfo.outboundTopic;\n }\n } catch (profileError) {\n this.context.logger.warn(\n 'Could not retrieve profile topics:',\n profileError\n );\n }\n\n this.stateManager.setCurrentAgent({\n name: `Agent ${accountId}`,\n accountId: accountId,\n inboundTopicId,\n outboundTopicId,\n privateKey: hederaKit.signer.getOperatorPrivateKey().toString(),\n });\n\n this.context.logger.info(\n `Set current agent: ${accountId} with topics ${inboundTopicId}/${outboundTopicId}`\n );\n\n if (this.stateManager && !this.stateManager.getConnectionsManager()) {\n const privateKey = hederaKit.signer.getOperatorPrivateKey().toString();\n const hcs10Client = new HCS10Client({\n network: hederaKit.network as 'mainnet' | 'testnet',\n operatorId: accountId,\n operatorPrivateKey: privateKey,\n logLevel: 'error',\n });\n\n this.stateManager.initializeConnectionsManager(hcs10Client as any);\n this.context.logger.info(\n 'ConnectionsManager initialized in HCS10Plugin'\n );\n }\n\n this.initializeTools();\n\n this.context.logger.info('HCS-10 Plugin initialized successfully');\n } catch (error) {\n this.context.logger.error('Failed to initialize HCS-10 plugin:', error);\n }\n }\n\n private initializeTools(): void {\n if (!this.stateManager) {\n throw new Error('StateManager must be initialized before creating tools');\n }\n\n const hederaKit = this.context.config.hederaKit as HederaAgentKit;\n if (!hederaKit) {\n throw new Error('HederaKit not found in context config');\n }\n\n const hcs10Builder = new HCS10Builder(hederaKit, this.stateManager);\n\n this.tools = [\n new RegisterAgentTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new FindRegistrationsTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new RetrieveProfileTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new InitiateConnectionTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new ListConnectionsTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new SendMessageToConnectionTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new CheckMessagesTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new ConnectionMonitorTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new ManageConnectionRequestsTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new AcceptConnectionRequestTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new ListUnapprovedConnectionRequestsTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n ];\n }\n\n getTools(): HederaTool[] {\n return this.tools;\n }\n\n getStateManager(): IStateManager | undefined {\n return this.stateManager;\n }\n\n override async cleanup(): Promise<void> {\n this.tools = [];\n delete this.stateManager;\n if (this.context?.logger) {\n this.context.logger.info('HCS-10 Plugin cleaned up');\n }\n }\n}\n"],"names":[],"mappings":";;;AAwBO,MAAM,oBAAoB,WAAW;AAAA,EAArC,cAAA;AAAA,UAAA,GAAA,SAAA;AACL,SAAA,KAAK;AACL,SAAA,OAAO;AACP,SAAA,cACE;AACF,SAAA,UAAU;AACV,SAAA,SAAS;AACT,SAAA,YAAY;AAGZ,SAAQ,QAAsB,CAAA;AAAA,EAAC;AAAA,EAG/B,MAAe,WAAW,SAA8C;AACtE,UAAM,MAAM,WAAW,OAAO;AAE9B,UAAM,YAAY,QAAQ,OAAO;AACjC,QAAI,CAAC,WAAW;AACd,WAAK,QAAQ,OAAO;AAAA,QAClB;AAAA,MAAA;AAEF;AAAA,IACF;AAEA,QAAI;AACF,WAAK,eACF,QAAQ,gBACR,QAAQ,OAAO,gBACf,KAAK,WAAW,gBACjB,IAAI,gBAAA;AAEN,YAAM,YAAY,UAAU,OAAO,aAAA,EAAe,SAAA;AAClD,UAAI,iBAAiB;AACrB,UAAI,kBAAkB;AAEtB,UAAI;AACF,cAAM,aAAa,UAAU,OAAO,sBAAA,EAAwB,SAAA;AAE5D,cAAM,cAAc,IAAI,YAAY;AAAA,UAClC,SAAS,UAAU;AAAA,UACnB,YAAY;AAAA,UACZ,oBAAoB;AAAA,UACpB,UAAU;AAAA,QAAA,CACX;AAED,cAAM,kBAAkB,MAAM,YAAY,gBAAgB,SAAS;AACnE,YAAI,gBAAgB,WAAW,gBAAgB,WAAW;AAC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B,WAAK,QAAQ,OAAO,KAAK,0BAA0B;AAAA,IACrD;AAAA,EACF;AACF;"}
|
|
1
|
+
{"version":3,"file":"index2.js","sources":["../../src/plugins/hcs-10/HCS10Plugin.ts"],"sourcesContent":["import {\n GenericPluginContext,\n HederaTool,\n BasePlugin,\n HederaAgentKit,\n} from 'hedera-agent-kit';\nimport {\n IStateManager,\n OpenConvaiState,\n HCS10Builder,\n RegisterAgentTool,\n FindRegistrationsTool,\n InitiateConnectionTool,\n ListConnectionsTool,\n SendMessageToConnectionTool,\n CheckMessagesTool,\n ConnectionMonitorTool,\n ManageConnectionRequestsTool,\n AcceptConnectionRequestTool,\n RetrieveProfileTool,\n ListUnapprovedConnectionRequestsTool,\n} from '@hashgraphonline/standards-agent-kit';\nimport { HCS10Client } from '@hashgraphonline/standards-sdk';\n\nexport class HCS10Plugin extends BasePlugin {\n id = 'hcs-10';\n name = 'HCS-10 Plugin';\n description =\n 'HCS-10 agent tools for decentralized agent registration, connections, and messaging on Hedera';\n version = '1.0.0';\n author = 'Hashgraph Online';\n namespace = 'hcs10';\n\n private stateManager?: IStateManager;\n private tools: HederaTool[] = [];\n appConfig?: Record<string, unknown>;\n\n override async initialize(context: GenericPluginContext): Promise<void> {\n await super.initialize(context);\n\n const hederaKit = context.config.hederaKit as HederaAgentKit;\n if (!hederaKit) {\n this.context.logger.warn(\n 'HederaKit not found in context. HCS-10 tools will not be available.'\n );\n return;\n }\n\n try {\n this.stateManager =\n (context.stateManager as IStateManager) ||\n (context.config.stateManager as IStateManager) ||\n (this.appConfig?.stateManager as IStateManager) ||\n new OpenConvaiState();\n\n const accountId = hederaKit.signer.getAccountId().toString();\n let inboundTopicId = '';\n let outboundTopicId = '';\n\n try {\n const opKey = hederaKit.signer.getOperatorPrivateKey() as {\n toString?: () => string;\n toStringRaw?: () => string;\n };\n const privateKey = typeof opKey?.toStringRaw === 'function'\n ? opKey.toStringRaw()\n : typeof opKey?.toString === 'function'\n ? opKey.toString()\n : String(opKey);\n\n const hcs10Client = new HCS10Client({\n network: hederaKit.network as 'mainnet' | 'testnet',\n operatorId: accountId,\n operatorPrivateKey: privateKey,\n logLevel: 'error',\n });\n\n const profileResponse = await hcs10Client.retrieveProfile(accountId);\n if (profileResponse.success && profileResponse.topicInfo) {\n inboundTopicId = profileResponse.topicInfo.inboundTopic;\n outboundTopicId = profileResponse.topicInfo.outboundTopic;\n }\n } catch (profileError) {\n this.context.logger.warn(\n 'Could not retrieve profile topics:',\n profileError\n );\n }\n\n this.stateManager.setCurrentAgent({\n name: `Agent ${accountId}`,\n accountId: accountId,\n inboundTopicId,\n outboundTopicId,\n privateKey: ((): string => {\n const opKey = hederaKit.signer.getOperatorPrivateKey() as {\n toString?: () => string;\n toStringRaw?: () => string;\n };\n return typeof opKey?.toStringRaw === 'function'\n ? opKey.toStringRaw()\n : typeof opKey?.toString === 'function'\n ? opKey.toString()\n : String(opKey);\n })(),\n });\n\n this.context.logger.info(\n `Set current agent: ${accountId} with topics ${inboundTopicId}/${outboundTopicId}`\n );\n\n if (this.stateManager && !this.stateManager.getConnectionsManager()) {\n try {\n const opKey = hederaKit.signer.getOperatorPrivateKey() as {\n toString?: () => string;\n toStringRaw?: () => string;\n };\n const privateKey = typeof opKey?.toStringRaw === 'function'\n ? opKey.toStringRaw()\n : typeof opKey?.toString === 'function'\n ? opKey.toString()\n : String(opKey);\n const hcs10Client = new HCS10Client({\n network: hederaKit.network as 'mainnet' | 'testnet',\n operatorId: accountId,\n operatorPrivateKey: privateKey,\n logLevel: 'error',\n });\n\n this.stateManager.initializeConnectionsManager(hcs10Client as any);\n this.context.logger.info(\n 'ConnectionsManager initialized in HCS10Plugin'\n );\n } catch (cmError) {\n this.context.logger.warn('Could not initialize ConnectionsManager:', cmError);\n }\n }\n\n this.initializeTools();\n\n this.context.logger.info('HCS-10 Plugin initialized successfully');\n } catch (error) {\n this.context.logger.error('Failed to initialize HCS-10 plugin:', error);\n }\n }\n\n private initializeTools(): void {\n if (!this.stateManager) {\n throw new Error('StateManager must be initialized before creating tools');\n }\n\n const hederaKit = this.context.config.hederaKit as HederaAgentKit;\n if (!hederaKit) {\n throw new Error('HederaKit not found in context config');\n }\n\n const hcs10Builder = new HCS10Builder(hederaKit, this.stateManager);\n\n this.tools = [\n new RegisterAgentTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new FindRegistrationsTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new RetrieveProfileTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new InitiateConnectionTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new ListConnectionsTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new SendMessageToConnectionTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new CheckMessagesTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new ConnectionMonitorTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new ManageConnectionRequestsTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new AcceptConnectionRequestTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new ListUnapprovedConnectionRequestsTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n ];\n }\n\n getTools(): HederaTool[] {\n return this.tools;\n }\n\n getStateManager(): IStateManager | undefined {\n return this.stateManager;\n }\n\n override async cleanup(): Promise<void> {\n this.tools = [];\n delete this.stateManager;\n if (this.context?.logger) {\n this.context.logger.info('HCS-10 Plugin cleaned up');\n }\n }\n}\n"],"names":[],"mappings":";;;AAwBO,MAAM,oBAAoB,WA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O,KAAK;AACZ,QAAI,KAAK,SAAS,QAAQ;AACxB,WAAK,QAAQ,OAAO,KAAK,0BAA0B;AAAA,IACrD;AAAA,EACF;AACF;"}
|
package/dist/esm/index20.js
CHANGED
|
@@ -1,233 +1,23 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
totalSize,
|
|
21
|
-
largestContentSize
|
|
22
|
-
};
|
|
23
|
-
}
|
|
24
|
-
async processResponse(response, serverName, toolName) {
|
|
25
|
-
try {
|
|
26
|
-
const analysis = this.analyzeResponse(response);
|
|
27
|
-
if (!analysis.shouldProcess) {
|
|
28
|
-
return {
|
|
29
|
-
content: response,
|
|
30
|
-
wasProcessed: false
|
|
31
|
-
};
|
|
32
|
-
}
|
|
33
|
-
const processedResponse = await this.createReferencedResponse(
|
|
34
|
-
response,
|
|
35
|
-
analysis,
|
|
36
|
-
serverName,
|
|
37
|
-
toolName
|
|
38
|
-
);
|
|
39
|
-
return processedResponse;
|
|
40
|
-
} catch (error) {
|
|
41
|
-
this.logger.error("Error processing MCP response:", error);
|
|
42
|
-
return {
|
|
43
|
-
content: response,
|
|
44
|
-
wasProcessed: false,
|
|
45
|
-
errors: [error instanceof Error ? error.message : "Unknown processing error"]
|
|
46
|
-
};
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
extractContentFromResponse(obj, contents) {
|
|
50
|
-
if (obj === null || obj === void 0) {
|
|
51
|
-
return;
|
|
52
|
-
}
|
|
53
|
-
if (Array.isArray(obj)) {
|
|
54
|
-
obj.forEach((item) => this.extractContentFromResponse(item, contents));
|
|
55
|
-
return;
|
|
56
|
-
}
|
|
57
|
-
if (typeof obj === "object") {
|
|
58
|
-
const record = obj;
|
|
59
|
-
if (record.type === "text" && typeof record.text === "string") {
|
|
60
|
-
contents.push({
|
|
61
|
-
content: record.text,
|
|
62
|
-
type: "text",
|
|
63
|
-
sizeBytes: Buffer.byteLength(record.text, "utf8"),
|
|
64
|
-
mimeType: "text/plain"
|
|
65
|
-
});
|
|
66
|
-
return;
|
|
67
|
-
}
|
|
68
|
-
if (record.type === "image" && typeof record.data === "string") {
|
|
69
|
-
contents.push({
|
|
70
|
-
content: record.data,
|
|
71
|
-
type: "image",
|
|
72
|
-
sizeBytes: Math.ceil(record.data.length * 0.75),
|
|
73
|
-
mimeType: record.mimeType || "image/jpeg"
|
|
74
|
-
});
|
|
75
|
-
return;
|
|
76
|
-
}
|
|
77
|
-
if (record.type === "resource" && record.resource) {
|
|
78
|
-
const resourceStr = JSON.stringify(record.resource);
|
|
79
|
-
contents.push({
|
|
80
|
-
content: resourceStr,
|
|
81
|
-
type: "resource",
|
|
82
|
-
sizeBytes: Buffer.byteLength(resourceStr, "utf8"),
|
|
83
|
-
mimeType: "application/json"
|
|
84
|
-
});
|
|
85
|
-
return;
|
|
86
|
-
}
|
|
87
|
-
Object.values(record).forEach((value) => this.extractContentFromResponse(value, contents));
|
|
88
|
-
return;
|
|
89
|
-
}
|
|
90
|
-
if (typeof obj === "string") {
|
|
91
|
-
if (obj.length > 1e3) {
|
|
92
|
-
contents.push({
|
|
93
|
-
content: obj,
|
|
94
|
-
type: "text",
|
|
95
|
-
sizeBytes: Buffer.byteLength(obj, "utf8"),
|
|
96
|
-
mimeType: this.detectMimeType(obj)
|
|
97
|
-
});
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
async createReferencedResponse(originalResponse, analysis, serverName, toolName) {
|
|
102
|
-
const processedResponse = this.deepClone(originalResponse);
|
|
103
|
-
const errors = [];
|
|
104
|
-
let referenceCreated = false;
|
|
105
|
-
let totalReferenceSize = 0;
|
|
106
|
-
for (const contentInfo of analysis.contents) {
|
|
107
|
-
if (this.contentStorage.shouldUseReference(
|
|
108
|
-
typeof contentInfo.content === "string" ? contentInfo.content : JSON.stringify(contentInfo.content)
|
|
109
|
-
)) {
|
|
110
|
-
try {
|
|
111
|
-
const contentBuffer = Buffer.from(
|
|
112
|
-
typeof contentInfo.content === "string" ? contentInfo.content : JSON.stringify(contentInfo.content),
|
|
113
|
-
"utf8"
|
|
114
|
-
);
|
|
115
|
-
const contentType = this.mapMimeTypeToContentType(contentInfo.mimeType);
|
|
116
|
-
const metadata = {
|
|
117
|
-
contentType,
|
|
118
|
-
source: "mcp_tool",
|
|
119
|
-
mcpToolName: `${serverName}::${toolName}`,
|
|
120
|
-
tags: ["mcp_response", serverName, toolName]
|
|
121
|
-
};
|
|
122
|
-
if (contentInfo.mimeType !== void 0) {
|
|
123
|
-
metadata.mimeType = contentInfo.mimeType;
|
|
124
|
-
}
|
|
125
|
-
const reference = await this.contentStorage.storeContentIfLarge(
|
|
126
|
-
contentBuffer,
|
|
127
|
-
metadata
|
|
128
|
-
);
|
|
129
|
-
if (reference) {
|
|
130
|
-
this.replaceContentInResponse(
|
|
131
|
-
processedResponse,
|
|
132
|
-
contentInfo.content,
|
|
133
|
-
this.createLightweightReference(reference)
|
|
134
|
-
);
|
|
135
|
-
referenceCreated = true;
|
|
136
|
-
totalReferenceSize += contentBuffer.length;
|
|
137
|
-
}
|
|
138
|
-
} catch (error) {
|
|
139
|
-
errors.push(`Failed to create reference: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
const result = {
|
|
144
|
-
content: processedResponse,
|
|
145
|
-
wasProcessed: true,
|
|
146
|
-
referenceCreated,
|
|
147
|
-
originalSize: totalReferenceSize
|
|
148
|
-
};
|
|
149
|
-
if (errors.length > 0) {
|
|
150
|
-
result.errors = errors;
|
|
151
|
-
}
|
|
152
|
-
return result;
|
|
153
|
-
}
|
|
154
|
-
createLightweightReference(reference) {
|
|
155
|
-
return {
|
|
156
|
-
type: "content_reference",
|
|
157
|
-
referenceId: reference.referenceId,
|
|
158
|
-
preview: reference.preview,
|
|
159
|
-
size: reference.metadata.sizeBytes,
|
|
160
|
-
contentType: reference.metadata.contentType,
|
|
161
|
-
format: "ref://{id}",
|
|
162
|
-
_isReference: true
|
|
163
|
-
};
|
|
164
|
-
}
|
|
165
|
-
replaceContentInResponse(obj, oldContent, newContent) {
|
|
166
|
-
if (obj === null || obj === void 0) {
|
|
167
|
-
return;
|
|
168
|
-
}
|
|
169
|
-
if (Array.isArray(obj)) {
|
|
170
|
-
for (let i = 0; i < obj.length; i++) {
|
|
171
|
-
if (obj[i] === oldContent) {
|
|
172
|
-
obj[i] = newContent;
|
|
173
|
-
} else {
|
|
174
|
-
this.replaceContentInResponse(obj[i], oldContent, newContent);
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
return;
|
|
178
|
-
}
|
|
179
|
-
if (typeof obj === "object") {
|
|
180
|
-
const record = obj;
|
|
181
|
-
for (const key in record) {
|
|
182
|
-
if (record[key] === oldContent) {
|
|
183
|
-
record[key] = newContent;
|
|
184
|
-
} else {
|
|
185
|
-
this.replaceContentInResponse(record[key], oldContent, newContent);
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
detectMimeType(content) {
|
|
191
|
-
if (content.trim().startsWith("{") || content.trim().startsWith("[")) {
|
|
192
|
-
return "application/json";
|
|
193
|
-
}
|
|
194
|
-
if (content.includes("<html>") || content.includes("<!DOCTYPE")) {
|
|
195
|
-
return "text/html";
|
|
196
|
-
}
|
|
197
|
-
if (content.includes("# ") || content.includes("## ")) {
|
|
198
|
-
return "text/markdown";
|
|
199
|
-
}
|
|
200
|
-
return "text/plain";
|
|
201
|
-
}
|
|
202
|
-
mapMimeTypeToContentType(mimeType) {
|
|
203
|
-
if (!mimeType) return "text";
|
|
204
|
-
if (mimeType.startsWith("text/plain")) return "text";
|
|
205
|
-
if (mimeType === "application/json") return "json";
|
|
206
|
-
if (mimeType === "text/html") return "html";
|
|
207
|
-
if (mimeType === "text/markdown") return "markdown";
|
|
208
|
-
if (mimeType.startsWith("text/")) return "text";
|
|
209
|
-
return "binary";
|
|
210
|
-
}
|
|
211
|
-
deepClone(obj) {
|
|
212
|
-
if (obj === null || typeof obj !== "object") {
|
|
213
|
-
return obj;
|
|
214
|
-
}
|
|
215
|
-
if (obj instanceof Date) {
|
|
216
|
-
return new Date(obj.getTime());
|
|
217
|
-
}
|
|
218
|
-
if (Array.isArray(obj)) {
|
|
219
|
-
return obj.map((item) => this.deepClone(item));
|
|
220
|
-
}
|
|
221
|
-
const cloned = {};
|
|
222
|
-
for (const key in obj) {
|
|
223
|
-
if (obj.hasOwnProperty(key)) {
|
|
224
|
-
cloned[key] = this.deepClone(obj[key]);
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
return cloned;
|
|
228
|
-
}
|
|
229
|
-
}
|
|
1
|
+
const getSystemMessage = (accountId) => `You are a helpful assistant managing Hashgraph Online HCS-10 connections, messages, HCS-2 registries, content inscription, and Hedera Hashgraph operations.
|
|
2
|
+
|
|
3
|
+
You have access to tools for:
|
|
4
|
+
- HCS-10: registering agents, finding registered agents, initiating connections, listing active connections, sending messages over connections, and checking for new messages
|
|
5
|
+
- HCS-2: creating registries, registering entries, updating entries, deleting entries, migrating registries, and querying registry contents
|
|
6
|
+
- Inscription: inscribing content from URLs, files, or buffers, creating Hashinal NFTs, and retrieving inscriptions
|
|
7
|
+
- Hedera Token Service (HTS): creating tokens, transferring tokens, airdropping tokens, and managing token operations
|
|
8
|
+
|
|
9
|
+
*** IMPORTANT CONTEXT ***
|
|
10
|
+
You are currently operating as agent: ${accountId} on the Hashgraph Online network
|
|
11
|
+
When users ask about "my profile", "my account", "my connections", etc., use this account ID: ${accountId}
|
|
12
|
+
|
|
13
|
+
*** CRITICAL ENTITY HANDLING RULES ***
|
|
14
|
+
- When users refer to entities (tokens, topics, accounts) with pronouns like "it", "that", "the token/topic", etc., ALWAYS use the most recently created entity of that type
|
|
15
|
+
- Entity IDs look like "0.0.XXXXXX" and are stored in memory after creation
|
|
16
|
+
- NEVER use example or placeholder IDs like "0.0.123456" - always use actual created entity IDs
|
|
17
|
+
- Account ID ${accountId} is NOT a token - tokens and accounts are different entities
|
|
18
|
+
|
|
19
|
+
Remember the connection numbers when listing connections, as users might refer to them.`;
|
|
230
20
|
export {
|
|
231
|
-
|
|
21
|
+
getSystemMessage
|
|
232
22
|
};
|
|
233
23
|
//# sourceMappingURL=index20.js.map
|
package/dist/esm/index20.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index20.js","sources":["../../src/mcp/ContentProcessor.ts"],"sourcesContent":["import type { ContentType, ContentSource } from '../types/content-reference';\nimport type { ContentStorage } from '../memory/ContentStorage';\nimport { Logger } from '@hashgraphonline/standards-sdk';\n\nexport interface MCPResponseContent {\n content: unknown;\n type: 'text' | 'image' | 'resource' | 'text[]' | 'image[]';\n sizeBytes: number;\n mimeType?: string;\n}\n\nexport interface ProcessedResponse {\n content: unknown;\n wasProcessed: boolean;\n referenceCreated?: boolean;\n referenceId?: string;\n originalSize?: number;\n errors?: string[];\n}\n\nexport interface ContentAnalysis {\n shouldProcess: boolean;\n contents: MCPResponseContent[];\n totalSize: number;\n largestContentSize: number;\n}\n\nexport class MCPContentProcessor {\n private contentStorage: ContentStorage;\n private logger: Logger;\n\n constructor(contentStorage: ContentStorage, logger: Logger) {\n this.contentStorage = contentStorage;\n this.logger = logger;\n }\n\n analyzeResponse(response: unknown): ContentAnalysis {\n const contents: MCPResponseContent[] = [];\n let totalSize = 0;\n\n this.extractContentFromResponse(response, contents);\n\n totalSize = contents.reduce((sum, content) => sum + content.sizeBytes, 0);\n const largestContentSize = contents.reduce((max, content) => \n Math.max(max, content.sizeBytes), 0);\n\n const shouldProcess = contents.some(content => \n this.contentStorage.shouldUseReference(\n typeof content.content === 'string' \n ? content.content \n : JSON.stringify(content.content)\n )\n );\n\n return {\n shouldProcess,\n contents,\n totalSize,\n largestContentSize\n };\n }\n\n async processResponse(\n response: unknown,\n serverName: string,\n toolName: string\n ): Promise<ProcessedResponse> {\n try {\n const analysis = this.analyzeResponse(response);\n \n if (!analysis.shouldProcess) {\n return {\n content: response,\n wasProcessed: false\n };\n }\n\n const processedResponse = await this.createReferencedResponse(\n response,\n analysis,\n serverName,\n toolName\n );\n\n return processedResponse;\n } catch (error) {\n this.logger.error('Error processing MCP response:', error);\n return {\n content: response,\n wasProcessed: false,\n errors: [error instanceof Error ? error.message : 'Unknown processing error']\n };\n }\n }\n\n private extractContentFromResponse(obj: unknown, contents: MCPResponseContent[]): void {\n if (obj === null || obj === undefined) {\n return;\n }\n\n if (Array.isArray(obj)) {\n obj.forEach(item => this.extractContentFromResponse(item, contents));\n return;\n }\n\n if (typeof obj === 'object') {\n const record = obj as Record<string, unknown>;\n \n if (record.type === 'text' && typeof record.text === 'string') {\n contents.push({\n content: record.text,\n type: 'text',\n sizeBytes: Buffer.byteLength(record.text, 'utf8'),\n mimeType: 'text/plain'\n });\n return;\n }\n\n if (record.type === 'image' && typeof record.data === 'string') {\n contents.push({\n content: record.data,\n type: 'image',\n sizeBytes: Math.ceil(record.data.length * 0.75),\n mimeType: record.mimeType as string || 'image/jpeg'\n });\n return;\n }\n\n if (record.type === 'resource' && record.resource) {\n const resourceStr = JSON.stringify(record.resource);\n contents.push({\n content: resourceStr,\n type: 'resource',\n sizeBytes: Buffer.byteLength(resourceStr, 'utf8'),\n mimeType: 'application/json'\n });\n return;\n }\n\n Object.values(record).forEach(value => \n this.extractContentFromResponse(value, contents));\n return;\n }\n\n if (typeof obj === 'string') {\n if (obj.length > 1000) {\n contents.push({\n content: obj,\n type: 'text',\n sizeBytes: Buffer.byteLength(obj, 'utf8'),\n mimeType: this.detectMimeType(obj)\n });\n }\n }\n }\n\n private async createReferencedResponse(\n originalResponse: unknown,\n analysis: ContentAnalysis,\n serverName: string,\n toolName: string\n ): Promise<ProcessedResponse> {\n const processedResponse = this.deepClone(originalResponse);\n const errors: string[] = [];\n let referenceCreated = false;\n let totalReferenceSize = 0;\n\n for (const contentInfo of analysis.contents) {\n if (this.contentStorage.shouldUseReference(\n typeof contentInfo.content === 'string' \n ? contentInfo.content \n : JSON.stringify(contentInfo.content)\n )) {\n try {\n const contentBuffer = Buffer.from(\n typeof contentInfo.content === 'string' \n ? contentInfo.content \n : JSON.stringify(contentInfo.content),\n 'utf8'\n );\n\n const contentType = this.mapMimeTypeToContentType(contentInfo.mimeType);\n \n const metadata: Parameters<typeof this.contentStorage.storeContentIfLarge>[1] = {\n contentType,\n source: 'mcp_tool' as ContentSource,\n mcpToolName: `${serverName}::${toolName}`,\n tags: ['mcp_response', serverName, toolName]\n };\n \n if (contentInfo.mimeType !== undefined) {\n metadata.mimeType = contentInfo.mimeType;\n }\n \n const reference = await this.contentStorage.storeContentIfLarge(\n contentBuffer,\n metadata\n );\n\n if (reference) {\n this.replaceContentInResponse(\n processedResponse,\n contentInfo.content,\n this.createLightweightReference(reference)\n );\n referenceCreated = true;\n totalReferenceSize += contentBuffer.length;\n }\n } catch (error) {\n errors.push(`Failed to create reference: ${error instanceof Error ? error.message : 'Unknown error'}`);\n }\n }\n }\n\n const result: ProcessedResponse = {\n content: processedResponse,\n wasProcessed: true,\n referenceCreated,\n originalSize: totalReferenceSize\n };\n \n if (errors.length > 0) {\n result.errors = errors;\n }\n \n return result;\n }\n\n private createLightweightReference(reference: any): Record<string, unknown> {\n return {\n type: 'content_reference',\n referenceId: reference.referenceId,\n preview: reference.preview,\n size: reference.metadata.sizeBytes,\n contentType: reference.metadata.contentType,\n format: 'ref://{id}',\n _isReference: true\n };\n }\n\n private replaceContentInResponse(obj: unknown, oldContent: unknown, newContent: unknown): void {\n if (obj === null || obj === undefined) {\n return;\n }\n\n if (Array.isArray(obj)) {\n for (let i = 0; i < obj.length; i++) {\n if (obj[i] === oldContent) {\n obj[i] = newContent;\n } else {\n this.replaceContentInResponse(obj[i], oldContent, newContent);\n }\n }\n return;\n }\n\n if (typeof obj === 'object') {\n const record = obj as Record<string, unknown>;\n \n for (const key in record) {\n if (record[key] === oldContent) {\n record[key] = newContent;\n } else {\n this.replaceContentInResponse(record[key], oldContent, newContent);\n }\n }\n }\n }\n\n private detectMimeType(content: string): string {\n if (content.trim().startsWith('{') || content.trim().startsWith('[')) {\n return 'application/json';\n }\n if (content.includes('<html>') || content.includes('<!DOCTYPE')) {\n return 'text/html';\n }\n if (content.includes('# ') || content.includes('## ')) {\n return 'text/markdown';\n }\n return 'text/plain';\n }\n\n private mapMimeTypeToContentType(mimeType?: string): ContentType {\n if (!mimeType) return 'text';\n \n if (mimeType.startsWith('text/plain')) return 'text';\n if (mimeType === 'application/json') return 'json';\n if (mimeType === 'text/html') return 'html';\n if (mimeType === 'text/markdown') return 'markdown';\n if (mimeType.startsWith('text/')) return 'text';\n \n return 'binary';\n }\n\n private deepClone<T>(obj: T): T {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n \n if (obj instanceof Date) {\n return new Date(obj.getTime()) as T;\n }\n \n if (Array.isArray(obj)) {\n return obj.map(item => this.deepClone(item)) as T;\n }\n \n const cloned = {} as T;\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n cloned[key] = this.deepClone(obj[key]);\n }\n }\n \n return cloned;\n }\n}"],"names":[],"mappings":"AA2BO,MAAM,oBAAoB;AAAA,EAI/B,YAAY,gBAAgC,QAAgB;AAC1D,SAAK,iBAAiB;AACtB,SAAK,SAAS;AAAA,EAChB;AAAA,EAEA,gBAAgB,UAAoC;AAClD,UAAM,WAAiC,CAAA;AACvC,QAAI,YAAY;AAEhB,SAAK,2BAA2B,UAAU,QAAQ;AAElD,gBAAY,SAAS,OAAO,CAAC,KAAK,YAAY,MAAM,QAAQ,WAAW,CAAC;AACxE,UAAM,qBAAqB,SAAS,OAAO,CAAC,KAAK,YAC/C,KAAK,IAAI,KAAK,QAAQ,SAAS,GAAG,CAAC;AA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AU,IAAI,CAAC;AAAA,IAC7C;AAEA,UAAM,SAAS,CAAA;AACf,eAAW,OAAO,KAAK;AACrB,UAAI,IAAI,eAAe,GAAG,GAAG;AAC3B,eAAO,GAAG,IAAI,KAAK,UAAU,IAAI,GAAG,CAAC;AAAA,MACvC;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AACF;"}
|
|
1
|
+
{"version":3,"file":"index20.js","sources":["../../src/config/system-message.ts"],"sourcesContent":["export const getSystemMessage = (\n accountId: string\n): string => `You are a helpful assistant managing Hashgraph Online HCS-10 connections, messages, HCS-2 registries, content inscription, and Hedera Hashgraph operations.\n\nYou have access to tools for:\n- HCS-10: registering agents, finding registered agents, initiating connections, listing active connections, sending messages over connections, and checking for new messages\n- HCS-2: creating registries, registering entries, updating entries, deleting entries, migrating registries, and querying registry contents\n- Inscription: inscribing content from URLs, files, or buffers, creating Hashinal NFTs, and retrieving inscriptions\n- Hedera Token Service (HTS): creating tokens, transferring tokens, airdropping tokens, and managing token operations\n\n*** IMPORTANT CONTEXT ***\nYou are currently operating as agent: ${accountId} on the Hashgraph Online network\nWhen users ask about \"my profile\", \"my account\", \"my connections\", etc., use this account ID: ${accountId}\n\n*** CRITICAL ENTITY HANDLING RULES ***\n- When users refer to entities (tokens, topics, accounts) with pronouns like \"it\", \"that\", \"the token/topic\", etc., ALWAYS use the most recently created entity of that type\n- Entity IDs look like \"0.0.XXXXXX\" and are stored in memory after creation\n- NEVER use example or placeholder IDs like \"0.0.123456\" - always use actual created entity IDs\n- Account ID ${accountId} is NOT a token - tokens and accounts are different entities\n\nRemember the connection numbers when listing connections, as users might refer to them.`;\n"],"names":[],"mappings":"AAAO,MAAM,mBAAmB,CAC9B,cACW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wCAS2B,SAAS;AAAA,gGAC+C,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,eAM1F,SAAS;AAAA;AAAA;"}
|