@hashgraphonline/conversational-agent 0.1.207 → 0.1.209
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/conversational-agent.d.ts +67 -8
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.ts +1 -0
- package/dist/cjs/langchain/ContentAwareAgentExecutor.d.ts +4 -6
- package/dist/cjs/langchain-agent.d.ts +8 -0
- package/dist/cjs/memory/SmartMemoryManager.d.ts +58 -21
- package/dist/cjs/memory/index.d.ts +1 -1
- package/dist/esm/index.js +8 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/index12.js +124 -46
- package/dist/esm/index12.js.map +1 -1
- package/dist/esm/index13.js +178 -13
- package/dist/esm/index13.js.map +1 -1
- package/dist/esm/index14.js +604 -100
- package/dist/esm/index14.js.map +1 -1
- package/dist/esm/index15.js +453 -59
- package/dist/esm/index15.js.map +1 -1
- package/dist/esm/index16.js +44 -172
- package/dist/esm/index16.js.map +1 -1
- package/dist/esm/index17.js +11 -156
- package/dist/esm/index17.js.map +1 -1
- package/dist/esm/index18.js +106 -191
- package/dist/esm/index18.js.map +1 -1
- package/dist/esm/index19.js +7 -90
- 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 +130 -616
- package/dist/esm/index20.js.map +1 -1
- package/dist/esm/index21.js +138 -215
- package/dist/esm/index21.js.map +1 -1
- package/dist/esm/index22.js +45 -159
- package/dist/esm/index22.js.map +1 -1
- package/dist/esm/index23.js +25 -121
- package/dist/esm/index23.js.map +1 -1
- package/dist/esm/index24.js +83 -56
- package/dist/esm/index24.js.map +1 -1
- package/dist/esm/index25.js +236 -32
- package/dist/esm/index25.js.map +1 -1
- package/dist/esm/index5.js +1 -1
- package/dist/esm/index6.js +295 -17
- package/dist/esm/index6.js.map +1 -1
- package/dist/esm/index8.js +82 -8
- package/dist/esm/index8.js.map +1 -1
- package/dist/types/conversational-agent.d.ts +67 -8
- package/dist/types/index.d.ts +1 -0
- package/dist/types/langchain/ContentAwareAgentExecutor.d.ts +4 -6
- package/dist/types/langchain-agent.d.ts +8 -0
- package/dist/types/memory/SmartMemoryManager.d.ts +58 -21
- package/dist/types/memory/index.d.ts +1 -1
- package/package.json +3 -3
- package/src/context/ReferenceContextManager.ts +9 -4
- package/src/context/ReferenceResponseProcessor.ts +3 -4
- package/src/conversational-agent.ts +379 -31
- package/src/index.ts +2 -0
- package/src/langchain/ContentAwareAgentExecutor.ts +4 -97
- package/src/langchain-agent.ts +94 -11
- package/src/mcp/ContentProcessor.ts +13 -3
- package/src/mcp/adapters/langchain.ts +1 -9
- package/src/memory/ContentStorage.ts +3 -51
- package/src/memory/MemoryWindow.ts +4 -16
- package/src/memory/ReferenceIdGenerator.ts +0 -4
- package/src/memory/SmartMemoryManager.ts +400 -33
- package/src/memory/TokenCounter.ts +12 -16
- package/src/memory/index.ts +1 -1
- package/src/plugins/hcs-10/HCS10Plugin.ts +44 -14
- package/src/services/ContentStoreManager.ts +0 -3
- package/src/types/content-reference.ts +8 -8
- package/src/types/index.ts +0 -1
package/dist/esm/index20.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index20.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.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;AACH,gBAAQ,gBAAgB,KAAK,MAAM;AACnC,YAAI,QAAQ,gBAAgB,SAAS,YAAY;AAC/C,kBAAQ,gBAAgB,MAAA;AAAA,QAC1B;AACA;AAAA,MACF,KAAK;AACH,gBAAQ,aAAa,KAAK,MAAM;AAChC,YAAI,QAAQ,aAAa,SAAS,YAAY;AAC5C,kBAAQ,aAAa,MAAA;AAAA,QACvB;AACA;AAAA,IAAA;AAAA,EAEN;AAAA,EAEQ,iBAAiB,OAAyB;AAChD,QAAI,MAAM,WAAW,EAAG,QAAO;AAC/B,WAAO,MAAM,OAAO,CAAC,KAAK,SAAS,MAAM,MAAM,CAAC,IAAI,MAAM;AAAA,EAC5D;AAAA,EAEQ,6BAAmC;AACzC,SAAK,eAAe,YAAY,YAAY;AAC1C,UAAI;AACF,cAAM,KAAK,eAAA;AAAA,MACb,SAAS,OAAO;AACd,gBAAQ,MAAM,0DAA0D,KAAK;AAAA,MAC/E;AAAA,IACF,GAAG,KAAK,gBAAgB,iBAAiB;AAAA,EAC3C;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,UAAyB;AAC7B,QAAI,KAAK,cAAc;AACrB,oBAAc,KAAK,YAAY;AAC/B,aAAO,KAAK;AAAA,IACd;AAEA,SAAK,aAAa,MAAA;AAElB,SAAK,MAAA;AAAA,EACP;AACF;AAh1BE,gBAAuB,sBAAsB;AAlBxC,IAAM,iBAAN;"}
|
|
1
|
+
{"version":3,"file":"index20.js","sources":["../../src/mcp/MCPClientManager.ts"],"sourcesContent":["import { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';\nimport type { MCPServerConfig, MCPToolInfo, MCPConnectionStatus } from './types';\nimport { Logger } from '@hashgraphonline/standards-sdk';\nimport type { ContentStorage } from '../memory/ContentStorage';\nimport { MCPContentProcessor, ProcessedResponse } from './ContentProcessor';\n\n/**\n * Manages connections to MCP servers and tool discovery\n */\nexport class MCPClientManager {\n private clients: Map<string, Client> = new Map();\n private tools: Map<string, MCPToolInfo[]> = new Map();\n private logger: Logger;\n private contentProcessor?: MCPContentProcessor;\n\n constructor(logger: Logger, contentStorage?: ContentStorage) {\n this.logger = logger;\n if (contentStorage) {\n this.contentProcessor = new MCPContentProcessor(contentStorage, logger);\n }\n }\n\n /**\n * Connect to an MCP server and discover its tools\n */\n async connectServer(config: MCPServerConfig): Promise<MCPConnectionStatus> {\n try {\n if (this.isServerConnected(config.name)) {\n return {\n serverName: config.name,\n connected: false,\n error: `Server ${config.name} is already connected`,\n tools: [],\n };\n }\n\n if (config.transport && config.transport !== 'stdio') {\n throw new Error(`Transport ${config.transport} not yet supported`);\n }\n\n const transport = new StdioClientTransport({\n command: config.command,\n args: config.args,\n ...(config.env && { env: config.env }),\n });\n\n const client = new Client({\n name: `conversational-agent-${config.name}`,\n version: '1.0.0',\n }, {\n capabilities: {},\n });\n\n await client.connect(transport);\n this.clients.set(config.name, client);\n\n const toolsResponse = await client.listTools();\n const toolsWithServer: MCPToolInfo[] = toolsResponse.tools.map(tool => ({\n ...tool,\n serverName: config.name,\n }));\n\n this.tools.set(config.name, toolsWithServer);\n this.logger.info(`Connected to MCP server ${config.name} with ${toolsWithServer.length} tools`);\n\n return {\n serverName: config.name,\n connected: true,\n tools: toolsWithServer,\n };\n } catch (error) {\n this.logger.error(`Failed to connect to MCP server ${config.name}:`, error);\n return {\n serverName: config.name,\n connected: false,\n error: error instanceof Error ? error.message : 'Unknown error',\n tools: [],\n };\n }\n }\n\n /**\n * Execute a tool on a specific MCP server\n */\n async executeTool(serverName: string, toolName: string, args: Record<string, unknown>): Promise<unknown> {\n const client = this.clients.get(serverName);\n if (!client) {\n throw new Error(`MCP server ${serverName} not connected`);\n }\n\n this.logger.debug(`Executing MCP tool ${toolName} on server ${serverName}`, args);\n\n try {\n const result = await client.callTool({\n name: toolName,\n arguments: args,\n });\n\n if (this.contentProcessor) {\n const processed = await this.contentProcessor.processResponse(result, serverName, toolName);\n \n if (processed.wasProcessed) {\n this.logger.debug(\n `Processed MCP response from ${serverName}::${toolName}`,\n {\n referenceCreated: processed.referenceCreated,\n originalSize: processed.originalSize,\n errors: processed.errors\n }\n );\n\n if (processed.errors && processed.errors.length > 0) {\n this.logger.warn(`Content processing warnings for ${serverName}::${toolName}:`, processed.errors);\n }\n }\n\n return processed.content;\n }\n\n return result;\n } catch (error) {\n this.logger.error(`Error executing MCP tool ${toolName}:`, error);\n throw error;\n }\n }\n\n /**\n * Disconnect all MCP servers\n */\n async disconnectAll(): Promise<void> {\n for (const [name, client] of this.clients) {\n try {\n await client.close();\n this.logger.info(`Disconnected from MCP server ${name}`);\n } catch (error) {\n this.logger.error(`Error disconnecting MCP server ${name}:`, error);\n }\n }\n this.clients.clear();\n this.tools.clear();\n }\n\n /**\n * Get all discovered tools from all connected servers\n */\n getAllTools(): MCPToolInfo[] {\n const allTools: MCPToolInfo[] = [];\n for (const tools of this.tools.values()) {\n allTools.push(...tools);\n }\n return allTools;\n }\n\n /**\n * Get tools from a specific server\n */\n getServerTools(serverName: string): MCPToolInfo[] {\n return this.tools.get(serverName) || [];\n }\n\n /**\n * Check if a server is connected\n */\n isServerConnected(serverName: string): boolean {\n return this.clients.has(serverName);\n }\n\n /**\n * Get list of connected server names\n */\n getConnectedServers(): string[] {\n return Array.from(this.clients.keys());\n }\n\n /**\n * Enable content processing with content storage\n */\n enableContentProcessing(contentStorage: ContentStorage): void {\n this.contentProcessor = new MCPContentProcessor(contentStorage, this.logger);\n this.logger.info('Content processing enabled for MCP responses');\n }\n\n /**\n * Disable content processing\n */\n disableContentProcessing(): void {\n delete this.contentProcessor;\n this.logger.info('Content processing disabled for MCP responses');\n }\n\n /**\n * Check if content processing is enabled\n */\n isContentProcessingEnabled(): boolean {\n return this.contentProcessor !== undefined;\n }\n\n /**\n * Analyze a response without processing it (for testing/debugging)\n */\n analyzeResponseContent(response: unknown): unknown {\n if (!this.contentProcessor) {\n throw new Error('Content processing is not enabled');\n }\n return this.contentProcessor.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C1B,YAAM,IAAI,MAAM,mCAAmC;AAAA,IACrD;AACA,WAAO,KAAK,iBAAiB,gBAAgB,QAAQ;AAAA,EACvD;AACF;"}
|
package/dist/esm/index21.js
CHANGED
|
@@ -1,233 +1,156 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
import { DynamicStructuredTool } from "@langchain/core/tools";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { shouldUseReference, ContentStoreService } from "@hashgraphonline/standards-sdk";
|
|
4
|
+
function convertMCPToolToLangChain(tool, mcpManager, serverConfig) {
|
|
5
|
+
const zodSchema = jsonSchemaToZod(tool.inputSchema);
|
|
6
|
+
const sanitizedName = `${tool.serverName}_${tool.name}`.replace(
|
|
7
|
+
/[^a-zA-Z0-9_]/g,
|
|
8
|
+
"_"
|
|
9
|
+
);
|
|
10
|
+
let description = tool.description || `MCP tool ${tool.name} from ${tool.serverName}`;
|
|
11
|
+
if (serverConfig?.toolDescriptions?.[tool.name]) {
|
|
12
|
+
description = `${description}
|
|
13
|
+
|
|
14
|
+
${serverConfig.toolDescriptions[tool.name]}`;
|
|
5
15
|
}
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
totalSize = contents.reduce((sum, content) => sum + content.sizeBytes, 0);
|
|
11
|
-
const largestContentSize = contents.reduce((max, content) => Math.max(max, content.sizeBytes), 0);
|
|
12
|
-
const shouldProcess = contents.some(
|
|
13
|
-
(content) => this.contentStorage.shouldUseReference(
|
|
14
|
-
typeof content.content === "string" ? content.content : JSON.stringify(content.content)
|
|
15
|
-
)
|
|
16
|
-
);
|
|
17
|
-
return {
|
|
18
|
-
shouldProcess,
|
|
19
|
-
contents,
|
|
20
|
-
totalSize,
|
|
21
|
-
largestContentSize
|
|
22
|
-
};
|
|
16
|
+
if (serverConfig?.additionalContext) {
|
|
17
|
+
description = `${description}
|
|
18
|
+
|
|
19
|
+
Context: ${serverConfig.additionalContext}`;
|
|
23
20
|
}
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
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;
|
|
21
|
+
return new DynamicStructuredTool({
|
|
22
|
+
name: sanitizedName,
|
|
23
|
+
description,
|
|
24
|
+
schema: zodSchema,
|
|
25
|
+
func: async (input) => {
|
|
26
|
+
try {
|
|
27
|
+
const result = await mcpManager.executeTool(
|
|
28
|
+
tool.serverName,
|
|
29
|
+
tool.name,
|
|
30
|
+
input
|
|
31
|
+
);
|
|
32
|
+
let responseText = "";
|
|
33
|
+
if (typeof result === "string") {
|
|
34
|
+
responseText = result;
|
|
35
|
+
} else if (result && typeof result === "object" && "content" in result) {
|
|
36
|
+
const content = result.content;
|
|
37
|
+
if (Array.isArray(content)) {
|
|
38
|
+
const textParts = content.filter(
|
|
39
|
+
(item) => typeof item === "object" && item !== null && "type" in item && item.type === "text" && "text" in item
|
|
40
|
+
).map((item) => item.text);
|
|
41
|
+
responseText = textParts.join("\n");
|
|
42
|
+
} else {
|
|
43
|
+
responseText = JSON.stringify(content);
|
|
124
44
|
}
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
45
|
+
} else {
|
|
46
|
+
responseText = JSON.stringify(result);
|
|
47
|
+
}
|
|
48
|
+
const responseBuffer = Buffer.from(responseText, "utf8");
|
|
49
|
+
const MCP_REFERENCE_THRESHOLD = 10 * 1024;
|
|
50
|
+
const shouldStoreMCPContent = responseBuffer.length > MCP_REFERENCE_THRESHOLD;
|
|
51
|
+
if (shouldStoreMCPContent || shouldUseReference(responseBuffer)) {
|
|
52
|
+
const contentStore = ContentStoreService.getInstance();
|
|
53
|
+
if (contentStore) {
|
|
54
|
+
try {
|
|
55
|
+
const referenceId = await contentStore.storeContent(responseBuffer, {
|
|
56
|
+
contentType: "text",
|
|
57
|
+
source: "mcp",
|
|
58
|
+
mcpToolName: `${tool.serverName}_${tool.name}`,
|
|
59
|
+
originalSize: responseBuffer.length
|
|
60
|
+
});
|
|
61
|
+
return `content-ref:${referenceId}`;
|
|
62
|
+
} catch (storeError) {
|
|
63
|
+
console.warn("Failed to store large MCP content as reference:", storeError);
|
|
64
|
+
}
|
|
137
65
|
}
|
|
138
|
-
} catch (error) {
|
|
139
|
-
errors.push(`Failed to create reference: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
140
66
|
}
|
|
67
|
+
return responseText;
|
|
68
|
+
} catch (error) {
|
|
69
|
+
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
70
|
+
return `Error executing MCP tool ${tool.name}: ${errorMessage}`;
|
|
141
71
|
}
|
|
142
72
|
}
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
};
|
|
149
|
-
if (errors.length > 0) {
|
|
150
|
-
result.errors = errors;
|
|
151
|
-
}
|
|
152
|
-
return result;
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
function jsonSchemaToZod(schema) {
|
|
76
|
+
if (!schema || typeof schema !== "object") {
|
|
77
|
+
return z.object({});
|
|
153
78
|
}
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
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
|
-
};
|
|
79
|
+
const schemaObj = schema;
|
|
80
|
+
if (schemaObj.type && schemaObj.type !== "object") {
|
|
81
|
+
return convertType(schemaObj);
|
|
164
82
|
}
|
|
165
|
-
|
|
166
|
-
|
|
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
|
-
}
|
|
83
|
+
if (!schemaObj.properties || typeof schemaObj.properties !== "object") {
|
|
84
|
+
return z.object({});
|
|
189
85
|
}
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
if (
|
|
195
|
-
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
return "text/markdown";
|
|
199
|
-
}
|
|
200
|
-
return "text/plain";
|
|
86
|
+
const shape = {};
|
|
87
|
+
for (const [key, value] of Object.entries(schemaObj.properties)) {
|
|
88
|
+
let zodType = convertType(value);
|
|
89
|
+
const isRequired = Array.isArray(schemaObj.required) && schemaObj.required.includes(key);
|
|
90
|
+
if (!isRequired) {
|
|
91
|
+
zodType = zodType.optional();
|
|
92
|
+
}
|
|
93
|
+
shape[key] = zodType;
|
|
201
94
|
}
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
if (mimeType === "text/markdown") return "markdown";
|
|
208
|
-
if (mimeType.startsWith("text/")) return "text";
|
|
209
|
-
return "binary";
|
|
95
|
+
return z.object(shape);
|
|
96
|
+
}
|
|
97
|
+
function convertType(schema) {
|
|
98
|
+
if (!schema || typeof schema !== "object" || !("type" in schema)) {
|
|
99
|
+
return z.unknown();
|
|
210
100
|
}
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
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]);
|
|
101
|
+
const schemaObj = schema;
|
|
102
|
+
let zodType;
|
|
103
|
+
switch (schemaObj.type) {
|
|
104
|
+
case "string":
|
|
105
|
+
zodType = z.string();
|
|
106
|
+
if (schemaObj.enum && Array.isArray(schemaObj.enum)) {
|
|
107
|
+
zodType = z.enum(schemaObj.enum);
|
|
225
108
|
}
|
|
226
|
-
|
|
227
|
-
|
|
109
|
+
break;
|
|
110
|
+
case "number":
|
|
111
|
+
zodType = z.number();
|
|
112
|
+
if ("minimum" in schemaObj && typeof schemaObj.minimum === "number") {
|
|
113
|
+
zodType = zodType.min(schemaObj.minimum);
|
|
114
|
+
}
|
|
115
|
+
if ("maximum" in schemaObj && typeof schemaObj.maximum === "number") {
|
|
116
|
+
zodType = zodType.max(schemaObj.maximum);
|
|
117
|
+
}
|
|
118
|
+
break;
|
|
119
|
+
case "integer":
|
|
120
|
+
zodType = z.number().int();
|
|
121
|
+
if ("minimum" in schemaObj && typeof schemaObj.minimum === "number") {
|
|
122
|
+
zodType = zodType.min(schemaObj.minimum);
|
|
123
|
+
}
|
|
124
|
+
if ("maximum" in schemaObj && typeof schemaObj.maximum === "number") {
|
|
125
|
+
zodType = zodType.max(schemaObj.maximum);
|
|
126
|
+
}
|
|
127
|
+
break;
|
|
128
|
+
case "boolean":
|
|
129
|
+
zodType = z.boolean();
|
|
130
|
+
break;
|
|
131
|
+
case "array":
|
|
132
|
+
if (schemaObj.items) {
|
|
133
|
+
zodType = z.array(convertType(schemaObj.items));
|
|
134
|
+
} else {
|
|
135
|
+
zodType = z.array(z.unknown());
|
|
136
|
+
}
|
|
137
|
+
break;
|
|
138
|
+
case "object":
|
|
139
|
+
if ("properties" in schemaObj) {
|
|
140
|
+
zodType = jsonSchemaToZod(schemaObj);
|
|
141
|
+
} else {
|
|
142
|
+
zodType = z.object({}).passthrough();
|
|
143
|
+
}
|
|
144
|
+
break;
|
|
145
|
+
default:
|
|
146
|
+
zodType = z.unknown();
|
|
147
|
+
}
|
|
148
|
+
if ("description" in schemaObj && typeof schemaObj.description === "string") {
|
|
149
|
+
zodType = zodType.describe(schemaObj.description);
|
|
228
150
|
}
|
|
151
|
+
return zodType;
|
|
229
152
|
}
|
|
230
153
|
export {
|
|
231
|
-
|
|
154
|
+
convertMCPToolToLangChain
|
|
232
155
|
};
|
|
233
156
|
//# sourceMappingURL=index21.js.map
|
package/dist/esm/index21.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index21.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;AAErC,UAAM,gBAAgB,SAAS;AAAA,MAAK,CAAA,YAClC,KAAK,eAAe;AAAA,QAClB,OAAO,QAAQ,YAAY,WACvB,QAAQ,UACR,KAAK,UAAU,QAAQ,OAAO;AAAA,MA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UAAU,IAAI,GAAG,CAAC;AAAA,MACvC;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AACF;"}
|
|
1
|
+
{"version":3,"file":"index21.js","sources":["../../src/mcp/adapters/langchain.ts"],"sourcesContent":["import { DynamicStructuredTool } from '@langchain/core/tools';\nimport { z } from 'zod';\nimport type { MCPToolInfo, MCPServerConfig } from '../types';\nimport type { MCPClientManager } from '../MCPClientManager';\nimport { ContentStoreService, shouldUseReference } from '@hashgraphonline/standards-sdk';\nimport type { ContentSource } from '../../types/content-reference';\n\n/**\n * Convert an MCP tool to a LangChain DynamicStructuredTool\n */\nexport function convertMCPToolToLangChain(\n tool: MCPToolInfo,\n mcpManager: MCPClientManager,\n serverConfig?: MCPServerConfig\n): DynamicStructuredTool {\n const zodSchema = jsonSchemaToZod(tool.inputSchema);\n\n const sanitizedName = `${tool.serverName}_${tool.name}`.replace(\n /[^a-zA-Z0-9_]/g,\n '_'\n );\n\n let description = tool.description || `MCP tool ${tool.name} from ${tool.serverName}`;\n \n if (serverConfig?.toolDescriptions?.[tool.name]) {\n description = `${description}\\n\\n${serverConfig.toolDescriptions[tool.name]}`;\n }\n \n if (serverConfig?.additionalContext) {\n description = `${description}\\n\\nContext: ${serverConfig.additionalContext}`;\n }\n\n return new DynamicStructuredTool({\n name: sanitizedName,\n description,\n schema: zodSchema,\n func: async (input) => {\n try {\n const result = await mcpManager.executeTool(\n tool.serverName,\n tool.name,\n input\n );\n\n let responseText = '';\n \n if (typeof result === 'string') {\n responseText = result;\n } else if (\n result &&\n typeof result === 'object' &&\n 'content' in result\n ) {\n const content = (result as { content: unknown }).content;\n if (Array.isArray(content)) {\n const textParts = content\n .filter(\n (item): item is { type: string; text: string } =>\n typeof item === 'object' &&\n item !== null &&\n 'type' in item &&\n item.type === 'text' &&\n 'text' in item\n )\n .map((item) => item.text);\n responseText = textParts.join('\\n');\n } else {\n responseText = JSON.stringify(content);\n }\n } else {\n responseText = JSON.stringify(result);\n }\n\n const responseBuffer = Buffer.from(responseText, 'utf8');\n \n const MCP_REFERENCE_THRESHOLD = 10 * 1024;\n const shouldStoreMCPContent = responseBuffer.length > MCP_REFERENCE_THRESHOLD;\n \n if (shouldStoreMCPContent || shouldUseReference(responseBuffer)) {\n const contentStore = ContentStoreService.getInstance();\n if (contentStore) {\n try {\n const referenceId = await contentStore.storeContent(responseBuffer, {\n contentType: 'text' as ContentSource,\n source: 'mcp',\n mcpToolName: `${tool.serverName}_${tool.name}`,\n originalSize: responseBuffer.length\n });\n return `content-ref:${referenceId}`;\n } catch (storeError) {\n console.warn('Failed to store large MCP content as reference:', storeError);\n }\n }\n }\n\n return responseText;\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : 'Unknown error';\n return `Error executing MCP tool ${tool.name}: ${errorMessage}`;\n }\n },\n });\n}\n\n/**\n * Convert JSON Schema to Zod schema\n * This is a simplified converter that handles common cases\n */\nfunction jsonSchemaToZod(schema: unknown): z.ZodTypeAny {\n if (!schema || typeof schema !== 'object') {\n return z.object({});\n }\n\n const schemaObj = schema as Record<string, unknown>;\n\n if (schemaObj.type && schemaObj.type !== 'object') {\n return convertType(schemaObj);\n }\n\n if (!schemaObj.properties || typeof schemaObj.properties !== 'object') {\n return z.object({});\n }\n\n const shape: Record<string, z.ZodTypeAny> = {};\n\n for (const [key, value] of Object.entries(schemaObj.properties)) {\n let zodType = convertType(value);\n\n const isRequired =\n Array.isArray(schemaObj.required) && schemaObj.required.includes(key);\n if (!isRequired) {\n zodType = zodType.optional();\n }\n\n shape[key] = zodType;\n }\n\n return z.object(shape);\n}\n\n/**\n * Convert a single JSON Schema type to Zod\n */\nfunction convertType(schema: unknown): z.ZodTypeAny {\n if (!schema || typeof schema !== 'object' || !('type' in schema)) {\n return z.unknown();\n }\n\n const schemaObj = schema as {\n type: string;\n enum?: unknown[];\n items?: unknown;\n };\n let zodType: z.ZodTypeAny;\n\n switch (schemaObj.type) {\n case 'string':\n zodType = z.string();\n if (schemaObj.enum && Array.isArray(schemaObj.enum)) {\n zodType = z.enum(schemaObj.enum as [string, ...string[]]);\n }\n break;\n\n case 'number':\n zodType = z.number();\n if ('minimum' in schemaObj && typeof schemaObj.minimum === 'number') {\n zodType = (zodType as z.ZodNumber).min(schemaObj.minimum);\n }\n if ('maximum' in schemaObj && typeof schemaObj.maximum === 'number') {\n zodType = (zodType as z.ZodNumber).max(schemaObj.maximum);\n }\n break;\n\n case 'integer':\n zodType = z.number().int();\n if ('minimum' in schemaObj && typeof schemaObj.minimum === 'number') {\n zodType = (zodType as z.ZodNumber).min(schemaObj.minimum);\n }\n if ('maximum' in schemaObj && typeof schemaObj.maximum === 'number') {\n zodType = (zodType as z.ZodNumber).max(schemaObj.maximum);\n }\n break;\n\n case 'boolean':\n zodType = z.boolean();\n break;\n\n case 'array':\n if (schemaObj.items) {\n zodType = z.array(convertType(schemaObj.items));\n } else {\n zodType = z.array(z.unknown());\n }\n break;\n\n case 'object':\n if ('properties' in schemaObj) {\n zodType = jsonSchemaToZod(schemaObj);\n } else {\n zodType = z.object({}).passthrough();\n }\n break;\n\n default:\n zodType = z.unknown();\n }\n\n if ('description' in schemaObj && typeof schemaObj.description === 'string') {\n zodType = zodType.describe(schemaObj.description);\n }\n\n return zodType;\n}\n"],"names":[],"mappings":";;;AAUO,SAAS,0BACd,MACA,YACA,cACuB;AACvB,QAAM,YAAY,gBAAgB,KAAK,WAAW;AAElD,QAAM,gBAAgB,GAAG,KAAK,UAAU,IAAI,KAAK,IAAI,GAAG;AAAA,IACtD;AAAA,IACA;AAAA,EAAA;AAGF,MAAI,cAAc,KAAK,eAAe,YAAY,KAAK,IAAI,SAAS,KAAK,UAAU;AAEnF,MAAI,cAAc,mBAAmB,KAAK,IAAI,GAAG;AAC/C,kBAAc,GAAG,WAAW;AAAA;AAAA,EAAO,aAAa,iBAAiB,KAAK,IAAI,CAAC;AAAA,EAC7E;AAEA,MAAI,cAAc,mBAAmB;AACnC,kBAAc,GAAG,WAAW;AAAA;AAAA,WAAgB,aAAa,iB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