@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.
Files changed (70) hide show
  1. package/dist/cjs/conversational-agent.d.ts +67 -8
  2. package/dist/cjs/index.cjs +1 -1
  3. package/dist/cjs/index.cjs.map +1 -1
  4. package/dist/cjs/index.d.ts +1 -0
  5. package/dist/cjs/langchain/ContentAwareAgentExecutor.d.ts +4 -6
  6. package/dist/cjs/langchain-agent.d.ts +8 -0
  7. package/dist/cjs/memory/SmartMemoryManager.d.ts +58 -21
  8. package/dist/cjs/memory/index.d.ts +1 -1
  9. package/dist/esm/index.js +8 -0
  10. package/dist/esm/index.js.map +1 -1
  11. package/dist/esm/index12.js +124 -46
  12. package/dist/esm/index12.js.map +1 -1
  13. package/dist/esm/index13.js +178 -13
  14. package/dist/esm/index13.js.map +1 -1
  15. package/dist/esm/index14.js +604 -100
  16. package/dist/esm/index14.js.map +1 -1
  17. package/dist/esm/index15.js +453 -59
  18. package/dist/esm/index15.js.map +1 -1
  19. package/dist/esm/index16.js +44 -172
  20. package/dist/esm/index16.js.map +1 -1
  21. package/dist/esm/index17.js +11 -156
  22. package/dist/esm/index17.js.map +1 -1
  23. package/dist/esm/index18.js +106 -191
  24. package/dist/esm/index18.js.map +1 -1
  25. package/dist/esm/index19.js +7 -90
  26. package/dist/esm/index19.js.map +1 -1
  27. package/dist/esm/index2.js +22 -13
  28. package/dist/esm/index2.js.map +1 -1
  29. package/dist/esm/index20.js +130 -616
  30. package/dist/esm/index20.js.map +1 -1
  31. package/dist/esm/index21.js +138 -215
  32. package/dist/esm/index21.js.map +1 -1
  33. package/dist/esm/index22.js +45 -159
  34. package/dist/esm/index22.js.map +1 -1
  35. package/dist/esm/index23.js +25 -121
  36. package/dist/esm/index23.js.map +1 -1
  37. package/dist/esm/index24.js +83 -56
  38. package/dist/esm/index24.js.map +1 -1
  39. package/dist/esm/index25.js +236 -32
  40. package/dist/esm/index25.js.map +1 -1
  41. package/dist/esm/index5.js +1 -1
  42. package/dist/esm/index6.js +295 -17
  43. package/dist/esm/index6.js.map +1 -1
  44. package/dist/esm/index8.js +82 -8
  45. package/dist/esm/index8.js.map +1 -1
  46. package/dist/types/conversational-agent.d.ts +67 -8
  47. package/dist/types/index.d.ts +1 -0
  48. package/dist/types/langchain/ContentAwareAgentExecutor.d.ts +4 -6
  49. package/dist/types/langchain-agent.d.ts +8 -0
  50. package/dist/types/memory/SmartMemoryManager.d.ts +58 -21
  51. package/dist/types/memory/index.d.ts +1 -1
  52. package/package.json +3 -3
  53. package/src/context/ReferenceContextManager.ts +9 -4
  54. package/src/context/ReferenceResponseProcessor.ts +3 -4
  55. package/src/conversational-agent.ts +379 -31
  56. package/src/index.ts +2 -0
  57. package/src/langchain/ContentAwareAgentExecutor.ts +4 -97
  58. package/src/langchain-agent.ts +94 -11
  59. package/src/mcp/ContentProcessor.ts +13 -3
  60. package/src/mcp/adapters/langchain.ts +1 -9
  61. package/src/memory/ContentStorage.ts +3 -51
  62. package/src/memory/MemoryWindow.ts +4 -16
  63. package/src/memory/ReferenceIdGenerator.ts +0 -4
  64. package/src/memory/SmartMemoryManager.ts +400 -33
  65. package/src/memory/TokenCounter.ts +12 -16
  66. package/src/memory/index.ts +1 -1
  67. package/src/plugins/hcs-10/HCS10Plugin.ts +44 -14
  68. package/src/services/ContentStoreManager.ts +0 -3
  69. package/src/types/content-reference.ts +8 -8
  70. package/src/types/index.ts +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index14.js","sources":["../../src/services/ContentStoreManager.ts"],"sourcesContent":["import { ContentStorage } from '../memory/ContentStorage';\nimport { \n ContentStoreService, \n extractReferenceId, \n shouldUseReference,\n ContentResolverRegistry,\n type ContentStoreInterface, \n type ContentResolverInterface, \n type ReferenceResolutionResult \n} from '@hashgraphonline/standards-sdk';\nimport type { ContentReferenceConfig } from '../types/content-reference';\nimport { Logger } from '@hashgraphonline/standards-sdk';\n\n/**\n * Adapter to make ContentStorage compatible with ContentStoreInterface\n */\nclass ContentStorageAdapter implements ContentStoreInterface {\n constructor(private storage: ContentStorage) {}\n\n async storeContent(content: Buffer, metadata: any) {\n const contentRef = await this.storage.storeContent(content, metadata);\n return contentRef.referenceId;\n }\n\n async resolveReference(referenceId: string): Promise<ReferenceResolutionResult> {\n const result = await this.storage.resolveReference(referenceId);\n // Convert to match the interface from standards-sdk\n if (result.success && result.content) {\n const response: ReferenceResolutionResult = {\n content: result.content\n };\n if (result.metadata) {\n response.metadata = {\n ...(result.metadata.mimeType !== undefined && { mimeType: result.metadata.mimeType }),\n ...(result.metadata.fileName !== undefined && { fileName: result.metadata.fileName }),\n originalSize: result.metadata.sizeBytes\n };\n }\n return response;\n } else {\n // If resolution fails, throw an error as the interface expects content to be present\n throw new Error(result.error || 'Reference not found');\n }\n }\n\n async hasReference(referenceId: string) {\n return await this.storage.hasReference(referenceId);\n }\n\n async cleanupReference(referenceId: string) {\n await this.storage.cleanupReference(referenceId);\n }\n\n async getStats() {\n return await this.storage.getStats();\n }\n\n async updateConfig(config: any) {\n return await this.storage.updateConfig(config);\n }\n\n async performCleanup() {\n await this.storage.performCleanup();\n }\n\n async dispose() {\n return Promise.resolve(this.storage.dispose());\n }\n}\n\n/**\n * Content resolver implementation for dependency injection\n */\nclass ContentResolver implements ContentResolverInterface {\n constructor(private adapter: ContentStorageAdapter) {}\n\n async resolveReference(referenceId: string): Promise<ReferenceResolutionResult> {\n // The adapter already handles the conversion\n return await this.adapter.resolveReference(referenceId);\n }\n\n shouldUseReference(content: string | Buffer): boolean {\n return shouldUseReference(content);\n }\n\n extractReferenceId(input: string): string | null {\n return extractReferenceId(input);\n }\n}\n\n/**\n * Manages content store lifecycle and cross-package registration\n */\nexport class ContentStoreManager {\n private contentStorage: ContentStorage;\n private adapter: ContentStorageAdapter;\n private resolver: ContentResolver;\n private logger: Logger;\n private isRegistered = false;\n\n constructor(\n maxMessageStorage: number = 1000,\n referenceConfig?: Partial<ContentReferenceConfig>,\n logger?: Logger\n ) {\n this.logger = logger || {\n info: console.log,\n debug: console.log,\n warn: console.warn,\n error: console.error\n } as Logger;\n\n this.contentStorage = new ContentStorage(maxMessageStorage, referenceConfig);\n this.adapter = new ContentStorageAdapter(this.contentStorage);\n this.resolver = new ContentResolver(this.adapter);\n }\n\n /**\n * Initialize and register content storage for cross-package access\n */\n async initialize(): Promise<void> {\n if (this.isRegistered) {\n this.logger.warn('ContentStoreManager is already initialized');\n return;\n }\n\n try {\n await ContentStoreService.setInstance(this.adapter);\n ContentResolverRegistry.register(this.resolver);\n this.isRegistered = true;\n this.logger.info('ContentStoreManager initialized and registered for cross-package access');\n } catch (error) {\n this.logger.error('Failed to initialize ContentStoreManager:', error);\n throw error;\n }\n }\n\n /**\n * Get the underlying ContentStorage instance\n */\n getContentStorage(): ContentStorage {\n return this.contentStorage;\n }\n\n /**\n * Get storage statistics\n */\n async getStats() {\n return await this.contentStorage.getStats();\n }\n\n /**\n * Update configuration\n */\n async updateConfig(config: Partial<ContentReferenceConfig>) {\n return await this.contentStorage.updateConfig(config);\n }\n\n /**\n * Perform manual cleanup\n */\n async performCleanup() {\n return await this.contentStorage.performCleanup();\n }\n\n /**\n * Check if content should be stored as reference\n */\n shouldUseReference(content: Buffer | string): boolean {\n return this.contentStorage.shouldUseReference(content);\n }\n\n /**\n * Store content if it's large enough\n */\n async storeContentIfLarge(content: Buffer | string, metadata: any) {\n return await this.contentStorage.storeContentIfLarge(content, metadata);\n }\n\n /**\n * Cleanup and unregister\n */\n async dispose(): Promise<void> {\n if (this.isRegistered) {\n this.contentStorage.dispose();\n ContentStoreService.dispose();\n ContentResolverRegistry.unregister();\n this.isRegistered = false;\n this.logger.info('ContentStoreManager disposed and unregistered');\n }\n }\n\n /**\n * Check if the manager is initialized\n */\n isInitialized(): boolean {\n return this.isRegistered;\n }\n}"],"names":[],"mappings":";;AAgBA,MAAM,sBAAuD;AAAA,EAC3D,YAAoB,SAAyB;AAAzB,SA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A;AAAA,EAKA,MAAM,iBAAiB;AACrB,WAAO,MAAM,KAAK,eAAe,eAAA;AAAA,EACnC;AAAA;AAAA;AAAA;AAAA,EAKA,mBAAmB,SAAmC;AACpD,WAAO,KAAK,eAAe,mBAAmB,OAAO;AAAA,EACvD;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,oBAAoB,SAA0B,UAAe;AACjE,WAAO,MAAM,KAAK,eAAe,oBAAoB,SAAS,QAAQ;AAAA,EACxE;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,UAAyB;AAC7B,QAAI,KAAK,cAAc;AACrB,WAAK,eAAe,QAAA;AACpB,0BAAoB,QAAA;AACpB,8BAAwB,WAAA;AACxB,WAAK,eAAe;AACpB,WAAK,OAAO,KAAK,+CAA+C;AAAA,IAClE;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,gBAAyB;AACvB,WAAO,KAAK;AAAA,EACd;AACF;"}
1
+ {"version":3,"file":"index14.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 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 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 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 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 const storedMessages: StoredMessage[] = messages.map(message => ({\n message,\n storedAt: now,\n id: this.generateId()\n }));\n\n this.messages.push(...storedMessages);\n\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 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\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 this.updateStatsAfterStore(content.length);\n \n await this.enforceReferenceStorageLimits();\n \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 const duration = Date.now() - startTime;\n this.recordPerformanceMetric('creation', duration);\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 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 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 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 storedContent.metadata.lastAccessedAt = new Date();\n storedContent.metadata.accessCount++;\n \n this.referenceStats.totalResolutions++;\n \n const duration = Date.now() - startTime;\n this.recordPerformanceMetric('resolution', duration);\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 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 this.referenceStats.totalStorageBytes -= storedContent.content.length;\n this.referenceStats.activeReferences--;\n this.referenceStats.recentlyCleanedUp++;\n \n this.contentStore.delete(referenceId);\n \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 if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n delete this.cleanupTimer;\n }\n \n if (this.referenceConfig.enableAutoCleanup) {\n this.startReferenceCleanupTimer();\n }\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 const now = new Date();\n const toCleanup: ReferenceId[] = [];\n \n for (const [referenceId, storedContent] of this.contentStore.entries()) {\n let shouldCleanup = false;\n \n if (storedContent.expiresAt && storedContent.expiresAt < now) {\n shouldCleanup = true;\n storedContent.state = 'expired';\n }\n \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 if (storedContent.state === 'cleanup_pending') {\n shouldCleanup = true;\n }\n \n if (shouldCleanup) {\n toCleanup.push(referenceId);\n }\n }\n \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;\n });\n \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 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 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\n private async enforceReferenceStorageLimits(): Promise<void> {\n if (this.contentStore.size >= this.referenceConfig.maxReferences) {\n await this.performCleanup();\n }\n \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 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 if (contentType === 'html') {\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 }\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 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;\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('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,EAkB3D,YACE,aAAqB,gBAAe,qBACpC,iBACA;AApBF,SAAQ,WAA4B,CAAA;AAEpC,SAAQ,YAAoB;AAE5B,SAAQ,mCAAoD,IAAA;AAiB1D,SAAK,aAAa;AAElB,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;AAGF,QAAI,KAAK,gBAAgB,mBAAmB;AAC1C,WAAK,2BAAA;AAAA,IACP;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,cAAc,UAAsC;AAClD,QAAI,SAAS,WAAW,GAAG;AACzB,aAAO,EAAE,QAAQ,GAAG,SAAS,EAAA;AAAA,IAC/B;AAEA,UAAM,0BAAU,KAAA;AAChB,QAAI,UAAU;AAEd,UAAM,iBAAkC,SAAS,IAAI,CAAA,aAAY;AAAA,MAC/D;AAAA,MACA,UAAU;AAAA,MACV,IAAI,KAAK,WAAA;AAAA,IAAW,EACpB;AAEF,SAAK,SAAS,KAAK,GAAG,cAAc;AAEpC,WAAO,KAAK,SAAS,SAAS,KAAK,YAAY;AAC7C,WAAK,SAAS,MAAA;AACd;AA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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,yCAAyC,KAAK;AAAA,MAC9D;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;AAlyBE,gBAAuB,sBAAsB;AAhBxC,IAAM,iBAAN;"}
@@ -1,73 +1,467 @@
1
- import { AgentExecutor } from "langchain/agents";
2
- import { Logger, shouldUseReference, ContentStoreService } from "@hashgraphonline/standards-sdk";
3
- class ContentAwareAgentExecutor extends AgentExecutor {
4
- // 10KB for MCP tools
5
- constructor(config) {
6
- super(config);
7
- this.MCP_REFERENCE_THRESHOLD = 10 * 1024;
8
- this.logger = new Logger({ module: "ContentAwareAgentExecutor" });
1
+ import { MemoryWindow } from "./index13.js";
2
+ import { ContentStorage } from "./index14.js";
3
+ import { TokenCounter } from "./index12.js";
4
+ const IS_ENTITY_ASSOCIATION_FLAG = '"isEntityAssociation":true';
5
+ const _SmartMemoryManager = class _SmartMemoryManager {
6
+ constructor(config = {}) {
7
+ this.config = { ..._SmartMemoryManager.DEFAULT_CONFIG, ...config };
8
+ this.tokenCounter = new TokenCounter(this.config.modelName);
9
+ this.contentStorage = new ContentStorage(this.config.storageLimit);
10
+ this.memoryWindow = new MemoryWindow(
11
+ this.config.maxTokens,
12
+ this.config.reserveTokens,
13
+ this.tokenCounter
14
+ );
9
15
  }
10
16
  /**
11
- * Override the method that processes tool outputs to intercept large content
17
+ * Add a message to the active memory window
18
+ * Automatically handles pruning and storage of displaced messages
19
+ * @param message - Message to add
12
20
  */
13
- async _call(inputs) {
21
+ addMessage(message) {
22
+ const result = this.memoryWindow.addMessage(message);
23
+ if (result.prunedMessages.length > 0) {
24
+ this.contentStorage.storeMessages(result.prunedMessages);
25
+ }
26
+ }
27
+ /**
28
+ * Get all active messages from the memory window
29
+ * @returns Array of active messages in chronological order
30
+ */
31
+ getMessages() {
32
+ return this.memoryWindow.getMessages();
33
+ }
34
+ /**
35
+ * Clear active memory window
36
+ * @param clearStorage - Whether to also clear the content storage (default: false)
37
+ */
38
+ clear(clearStorage = false) {
39
+ this.memoryWindow.clear();
40
+ if (clearStorage) {
41
+ this.contentStorage.clear();
42
+ }
43
+ }
44
+ /**
45
+ * Set the system prompt for the memory window
46
+ * @param systemPrompt - System prompt text
47
+ */
48
+ setSystemPrompt(systemPrompt) {
49
+ this.memoryWindow.setSystemPrompt(systemPrompt);
50
+ }
51
+ /**
52
+ * Get the current system prompt
53
+ * @returns Current system prompt text
54
+ */
55
+ getSystemPrompt() {
56
+ return this.memoryWindow.getSystemPrompt();
57
+ }
58
+ /**
59
+ * Search through stored message history
60
+ * @param query - Search term or pattern
61
+ * @param options - Search configuration
62
+ * @returns Array of matching messages from history
63
+ */
64
+ searchHistory(query, options = {}) {
65
+ return this.contentStorage.searchMessages(query, options);
66
+ }
67
+ /**
68
+ * Get recent messages from storage history
69
+ * @param count - Number of recent messages to retrieve
70
+ * @returns Array of recent messages from storage
71
+ */
72
+ getRecentHistory(count) {
73
+ return this.contentStorage.getRecentMessages(count);
74
+ }
75
+ /**
76
+ * Check if a message can be added without exceeding limits
77
+ * @param message - Message to test
78
+ * @returns True if message can be added
79
+ */
80
+ canAddMessage(message) {
81
+ return this.memoryWindow.canAddMessage(message);
82
+ }
83
+ /**
84
+ * Get statistics about the active memory window
85
+ * @returns Memory usage statistics
86
+ */
87
+ getMemoryStats() {
88
+ const windowStats = this.memoryWindow.getStats();
89
+ return {
90
+ totalActiveMessages: windowStats.totalMessages,
91
+ currentTokenCount: windowStats.currentTokens,
92
+ maxTokens: windowStats.maxTokens,
93
+ remainingCapacity: windowStats.remainingCapacity,
94
+ systemPromptTokens: windowStats.systemPromptTokens,
95
+ usagePercentage: windowStats.usagePercentage
96
+ };
97
+ }
98
+ /**
99
+ * Get statistics about the content storage
100
+ * @returns Storage usage statistics
101
+ */
102
+ getStorageStats() {
103
+ return this.contentStorage.getStorageStats();
104
+ }
105
+ /**
106
+ * Get combined statistics for both active memory and storage
107
+ * @returns Combined memory and storage statistics
108
+ */
109
+ getOverallStats() {
110
+ const memoryStats = this.getMemoryStats();
111
+ const storageStats = this.getStorageStats();
112
+ return {
113
+ activeMemory: memoryStats,
114
+ storage: storageStats,
115
+ totalMessagesManaged: memoryStats.totalActiveMessages + storageStats.totalMessages,
116
+ activeMemoryUtilization: memoryStats.usagePercentage,
117
+ storageUtilization: storageStats.usagePercentage
118
+ };
119
+ }
120
+ /**
121
+ * Update the configuration and apply changes
122
+ * @param newConfig - New configuration options
123
+ */
124
+ updateConfig(newConfig) {
125
+ this.config = { ...this.config, ...newConfig };
126
+ if (newConfig.maxTokens !== void 0 || newConfig.reserveTokens !== void 0) {
127
+ this.memoryWindow.updateLimits(
128
+ this.config.maxTokens,
129
+ this.config.reserveTokens
130
+ );
131
+ }
132
+ if (newConfig.storageLimit !== void 0) {
133
+ this.contentStorage.updateStorageLimit(this.config.storageLimit);
134
+ }
135
+ }
136
+ /**
137
+ * Get current configuration
138
+ * @returns Current configuration settings
139
+ */
140
+ getConfig() {
141
+ return { ...this.config };
142
+ }
143
+ /**
144
+ * Get messages from storage within a time range
145
+ * @param startTime - Start of time range
146
+ * @param endTime - End of time range
147
+ * @returns Messages within the specified time range
148
+ */
149
+ getHistoryFromTimeRange(startTime, endTime) {
150
+ return this.contentStorage.getMessagesFromTimeRange(startTime, endTime);
151
+ }
152
+ /**
153
+ * Get messages from storage by message type
154
+ * @param messageType - Type of messages to retrieve ('human', 'ai', 'system', etc.)
155
+ * @param limit - Maximum number of messages to return
156
+ * @returns Messages of the specified type
157
+ */
158
+ getHistoryByType(messageType, limit) {
159
+ return this.contentStorage.getMessagesByType(messageType, limit);
160
+ }
161
+ /**
162
+ * Get recent messages from storage within the last N minutes
163
+ * @param minutes - Number of minutes to look back
164
+ * @returns Messages from the last N minutes
165
+ */
166
+ getRecentHistoryByTime(minutes) {
167
+ return this.contentStorage.getRecentMessagesByTime(minutes);
168
+ }
169
+ /**
170
+ * Export the current state for persistence or analysis
171
+ * @returns Serializable representation of memory state
172
+ */
173
+ exportState() {
174
+ return {
175
+ config: this.config,
176
+ activeMessages: this.memoryWindow.getMessages().map((msg) => ({
177
+ content: msg.content,
178
+ type: msg._getType()
179
+ })),
180
+ systemPrompt: this.memoryWindow.getSystemPrompt(),
181
+ memoryStats: this.getMemoryStats(),
182
+ storageStats: this.getStorageStats(),
183
+ storedMessages: this.contentStorage.exportMessages()
184
+ };
185
+ }
186
+ /**
187
+ * Get a summary of conversation context for external use
188
+ * Useful for providing context to other systems or for logging
189
+ * @param includeStoredContext - Whether to include recent stored messages
190
+ * @returns Context summary object
191
+ */
192
+ getContextSummary(includeStoredContext = false) {
193
+ const activeMessages = this.getMessages();
194
+ const summary = {
195
+ activeMessageCount: activeMessages.length,
196
+ systemPrompt: this.getSystemPrompt(),
197
+ recentMessages: activeMessages.slice(-5),
198
+ memoryUtilization: this.getMemoryStats().usagePercentage,
199
+ hasStoredHistory: this.getStorageStats().totalMessages > 0
200
+ };
201
+ if (includeStoredContext) {
202
+ return {
203
+ ...summary,
204
+ recentStoredMessages: this.getRecentHistory(10),
205
+ storageStats: this.getStorageStats()
206
+ };
207
+ }
208
+ return summary;
209
+ }
210
+ /**
211
+ * Perform maintenance operations
212
+ * Optimizes storage and cleans up resources
213
+ */
214
+ performMaintenance() {
215
+ }
216
+ /**
217
+ * Store an entity association for later resolution
218
+ * @param entityId - The blockchain entity ID
219
+ * @param entityName - User-provided or derived friendly name
220
+ * @param entityType - Type of entity (token, account, topic, etc.)
221
+ * @param transactionId - Optional transaction ID that created this entity
222
+ */
223
+ storeEntityAssociation(entityId, entityName, entityType, transactionId) {
224
+ try {
225
+ if (!entityId || typeof entityId !== "string" || entityId.trim().length === 0) {
226
+ console.warn(
227
+ "[SmartMemoryManager] Invalid entityId provided:",
228
+ entityId
229
+ );
230
+ return;
231
+ }
232
+ if (!entityName || typeof entityName !== "string" || entityName.trim().length === 0) {
233
+ console.warn(
234
+ "[SmartMemoryManager] Invalid entityName provided:",
235
+ entityName
236
+ );
237
+ return;
238
+ }
239
+ if (!entityType || typeof entityType !== "string" || entityType.trim().length === 0) {
240
+ console.warn(
241
+ "[SmartMemoryManager] Invalid entityType provided:",
242
+ entityType
243
+ );
244
+ return;
245
+ }
246
+ const sanitizedEntityId = entityId.trim();
247
+ const sanitizedEntityName = entityName.trim().substring(0, 100);
248
+ const sanitizedEntityType = entityType.trim().toLowerCase();
249
+ const association = {
250
+ entityId: sanitizedEntityId,
251
+ entityName: sanitizedEntityName,
252
+ entityType: sanitizedEntityType,
253
+ createdAt: /* @__PURE__ */ new Date(),
254
+ ...transactionId !== void 0 && transactionId !== null && transactionId.trim() !== "" ? { transactionId: transactionId.trim() } : {}
255
+ };
256
+ const content = JSON.stringify(association);
257
+ const entityMessage = {
258
+ _getType: () => "system",
259
+ content,
260
+ id: `entity_${sanitizedEntityId}_${Date.now()}`,
261
+ name: "entity_association",
262
+ additional_kwargs: {
263
+ entityId: sanitizedEntityId,
264
+ entityName: sanitizedEntityName,
265
+ entityType: sanitizedEntityType,
266
+ isEntityAssociation: true
267
+ }
268
+ };
269
+ this.contentStorage.storeMessages([entityMessage]);
270
+ console.debug(
271
+ `[SmartMemoryManager] Stored entity association: ${sanitizedEntityName} (${sanitizedEntityType}) -> ${sanitizedEntityId}`
272
+ );
273
+ } catch (_error) {
274
+ console.error(
275
+ "[SmartMemoryManager] Failed to store entity association:",
276
+ _error
277
+ );
278
+ }
279
+ }
280
+ /**
281
+ * Resolve entity references from natural language queries
282
+ * @param query - Search query (entity name or natural language reference)
283
+ * @param options - Resolution options for filtering and fuzzy matching
284
+ * @returns Array of matching entity associations
285
+ */
286
+ resolveEntityReference(query, options = {}) {
14
287
  try {
15
- const originalTakeNextStep = this._takeNextStep.bind(this);
16
- this._takeNextStep = async (nameToolMap, inputs2, intermediateSteps, runManager, config) => {
17
- const result2 = await originalTakeNextStep(nameToolMap, inputs2, intermediateSteps, runManager, config);
18
- if (Array.isArray(result2)) {
19
- const processedSteps = await Promise.all(
20
- result2.map(async (step) => {
21
- const { action, observation } = step;
22
- if (typeof observation === "string") {
23
- const observationBuffer = Buffer.from(observation, "utf8");
24
- const shouldStore = observationBuffer.length > this.MCP_REFERENCE_THRESHOLD || shouldUseReference(observationBuffer);
25
- if (shouldStore) {
26
- this.logger.info(
27
- `[ContentAwareAgentExecutor] Large tool output detected: ${observationBuffer.length} bytes from ${action.tool}`
28
- );
29
- const contentStore = ContentStoreService.getInstance();
30
- if (contentStore) {
31
- try {
32
- const referenceId = await contentStore.storeContent(observationBuffer, {
33
- contentType: "text",
34
- source: "tool",
35
- toolName: action.tool,
36
- originalSize: observationBuffer.length
37
- });
38
- const referenceMessage = `content-ref:${referenceId}`;
39
- this.logger.info(
40
- `[ContentAwareAgentExecutor] Stored large output as reference: ${referenceMessage}`
41
- );
42
- return { action, observation: referenceMessage };
43
- } catch (error) {
44
- this.logger.warn(
45
- "[ContentAwareAgentExecutor] Failed to store content as reference:",
46
- error
47
- );
48
- }
49
- } else {
50
- this.logger.warn("[ContentAwareAgentExecutor] ContentStoreService not available");
288
+ if (!query || typeof query !== "string") {
289
+ console.warn(
290
+ "[SmartMemoryManager] Invalid query provided for entity resolution:",
291
+ query
292
+ );
293
+ return [];
294
+ }
295
+ const sanitizedQuery = query.trim();
296
+ if (sanitizedQuery.length === 0) {
297
+ return [];
298
+ }
299
+ if (sanitizedQuery.length > 200) {
300
+ console.warn(
301
+ "[SmartMemoryManager] Query too long, truncating:",
302
+ sanitizedQuery.length
303
+ );
304
+ }
305
+ const { entityType, limit = 10, fuzzyMatch = true } = options;
306
+ const safeLimit = Math.max(1, Math.min(limit || 10, 100));
307
+ const searchResults = this.contentStorage.searchMessages(
308
+ sanitizedQuery.substring(0, 200),
309
+ {
310
+ caseSensitive: false,
311
+ limit: safeLimit * 2
312
+ }
313
+ );
314
+ const associations = [];
315
+ for (const message of searchResults) {
316
+ try {
317
+ const content = message.content;
318
+ if (content.includes(IS_ENTITY_ASSOCIATION_FLAG) || content.includes("entityId")) {
319
+ const parsed = JSON.parse(content);
320
+ if (parsed.entityId && parsed.entityName && parsed.entityType) {
321
+ if (entityType && parsed.entityType !== entityType) {
322
+ continue;
323
+ }
324
+ associations.push(parsed);
325
+ }
326
+ }
327
+ } catch {
328
+ continue;
329
+ }
330
+ }
331
+ if (fuzzyMatch && associations.length === 0) {
332
+ const fuzzyQueries = [
333
+ query.toLowerCase(),
334
+ `token`,
335
+ `account`,
336
+ entityType || ""
337
+ ].filter(Boolean);
338
+ for (const fuzzyQuery of fuzzyQueries) {
339
+ if (fuzzyQuery === query.toLowerCase()) continue;
340
+ const fuzzyResults = this.contentStorage.searchMessages(fuzzyQuery, {
341
+ caseSensitive: false,
342
+ limit
343
+ });
344
+ for (const message of fuzzyResults) {
345
+ try {
346
+ const content = message.content;
347
+ if (content.includes(IS_ENTITY_ASSOCIATION_FLAG)) {
348
+ const parsed = JSON.parse(content);
349
+ if (parsed.entityId && parsed.entityName && parsed.entityType) {
350
+ if (entityType && parsed.entityType !== entityType) {
351
+ continue;
51
352
  }
353
+ associations.push(parsed);
52
354
  }
53
355
  }
54
- return step;
55
- })
356
+ } catch {
357
+ continue;
358
+ }
359
+ }
360
+ }
361
+ }
362
+ const uniqueAssociations = associations.filter(
363
+ (assoc, index, arr) => arr.findIndex((a) => a.entityId === assoc.entityId) === index
364
+ ).sort(
365
+ (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
366
+ );
367
+ const results = uniqueAssociations.slice(0, safeLimit);
368
+ if (results.length > 1) {
369
+ console.debug(
370
+ `[SmartMemoryManager] Multiple entities found for "${sanitizedQuery}":`,
371
+ results.map((r) => `${r.entityName} (${r.entityType})`).join(", ")
372
+ );
373
+ }
374
+ return results;
375
+ } catch (_error) {
376
+ console.error(
377
+ "[SmartMemoryManager] Failed to resolve entity reference:",
378
+ _error
379
+ );
380
+ return [];
381
+ }
382
+ }
383
+ /**
384
+ * Get all entity associations, optionally filtered by type
385
+ * @param entityType - Optional filter by entity type
386
+ * @returns Array of entity associations
387
+ */
388
+ getEntityAssociations(entityType) {
389
+ try {
390
+ const sanitizedEntityType = entityType ? entityType.trim().toLowerCase() : void 0;
391
+ if (entityType && (!sanitizedEntityType || sanitizedEntityType.length === 0)) {
392
+ console.warn(
393
+ "[SmartMemoryManager] Invalid entityType filter provided:",
394
+ entityType
395
+ );
396
+ return [];
397
+ }
398
+ const SEARCH_ANY_ENTITY = "entityId";
399
+ const searchQuery = sanitizedEntityType || SEARCH_ANY_ENTITY;
400
+ const searchResults = this.contentStorage.searchMessages(searchQuery, {
401
+ caseSensitive: false,
402
+ limit: 100
403
+ });
404
+ const associations = [];
405
+ for (const message of searchResults) {
406
+ try {
407
+ const content = message.content;
408
+ if (content.includes(IS_ENTITY_ASSOCIATION_FLAG)) {
409
+ const parsed = JSON.parse(content);
410
+ if (parsed.entityId && parsed.entityName && parsed.entityType) {
411
+ if (sanitizedEntityType && parsed.entityType !== sanitizedEntityType) {
412
+ continue;
413
+ }
414
+ if (parsed.createdAt && typeof parsed.createdAt === "string") {
415
+ parsed.createdAt = new Date(parsed.createdAt);
416
+ }
417
+ associations.push(parsed);
418
+ }
419
+ }
420
+ } catch (_parseError) {
421
+ console.debug(
422
+ "[SmartMemoryManager] Skipped malformed association data:",
423
+ _parseError
56
424
  );
57
- return processedSteps;
425
+ continue;
58
426
  }
59
- return result2;
60
- };
61
- const result = await super._call(inputs);
62
- this._takeNextStep = originalTakeNextStep;
63
- return result;
64
- } catch (error) {
65
- this.logger.error("[ContentAwareAgentExecutor] Error in _call:", error);
66
- throw error;
427
+ }
428
+ const results = associations.filter(
429
+ (assoc, index, arr) => arr.findIndex((a) => a.entityId === assoc.entityId) === index
430
+ ).sort((a, b) => {
431
+ const getTime = (d) => d instanceof Date ? d.getTime() : new Date(d).getTime();
432
+ const aTime = getTime(a.createdAt);
433
+ const bTime = getTime(b.createdAt);
434
+ return bTime - aTime;
435
+ });
436
+ console.debug(
437
+ `[SmartMemoryManager] Retrieved ${results.length} entity associations${sanitizedEntityType ? ` of type '${sanitizedEntityType}'` : ""}`
438
+ );
439
+ return results;
440
+ } catch (_error) {
441
+ console.error(
442
+ "[SmartMemoryManager] Failed to get entity associations:",
443
+ _error
444
+ );
445
+ return [];
67
446
  }
68
447
  }
69
- }
448
+ /**
449
+ * Clean up resources and dispose of components
450
+ */
451
+ dispose() {
452
+ this.memoryWindow.dispose();
453
+ this.contentStorage.dispose();
454
+ this.tokenCounter.dispose();
455
+ }
456
+ };
457
+ _SmartMemoryManager.DEFAULT_CONFIG = {
458
+ maxTokens: 8e3,
459
+ reserveTokens: 1e3,
460
+ modelName: "gpt-4o",
461
+ storageLimit: 1e3
462
+ };
463
+ let SmartMemoryManager = _SmartMemoryManager;
70
464
  export {
71
- ContentAwareAgentExecutor
465
+ SmartMemoryManager
72
466
  };
73
467
  //# sourceMappingURL=index15.js.map