@hashgraphonline/conversational-agent 0.1.208 → 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-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 +464 -9
- 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 +9 -660
- 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 +150 -206
- package/dist/esm/index20.js.map +1 -1
- package/dist/esm/index21.js +140 -166
- package/dist/esm/index21.js.map +1 -1
- package/dist/esm/index22.js +47 -105
- package/dist/esm/index22.js.map +1 -1
- package/dist/esm/index23.js +24 -89
- 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-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 +0 -1
- 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/index14.js.map
CHANGED
|
@@ -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,SAAA,UAAA;AAAA,EAA0B;AAAA,EAE9C,MAAM,aAAa,SAAiB,UAAe;AACjD,UAAM,aAAa,MAAM,KAAK,QAAQ,aAAa,SAAS,QAAQ;AACpE,WAAO,WAAW;AAAA,EACpB;AAAA,EAEA,MAAM,iBAAiB,aAAyD;AAC9E,UAAM,SAAS,MAAM,KAAK,QAAQ,iBAAiB,WAA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ACjE,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,qB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,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;"}
|
package/dist/esm/index15.js
CHANGED
|
@@ -1,12 +1,467 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
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
|
+
);
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Add a message to the active memory window
|
|
18
|
+
* Automatically handles pruning and storage of displaced messages
|
|
19
|
+
* @param message - Message to add
|
|
20
|
+
*/
|
|
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 = {}) {
|
|
287
|
+
try {
|
|
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;
|
|
352
|
+
}
|
|
353
|
+
associations.push(parsed);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
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
|
|
424
|
+
);
|
|
425
|
+
continue;
|
|
426
|
+
}
|
|
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 [];
|
|
446
|
+
}
|
|
447
|
+
}
|
|
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;
|
|
9
464
|
export {
|
|
10
|
-
|
|
465
|
+
SmartMemoryManager
|
|
11
466
|
};
|
|
12
467
|
//# sourceMappingURL=index15.js.map
|
package/dist/esm/index15.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index15.js","sources":["../../src/langchain/ContentAwareAgentExecutor.ts"],"sourcesContent":["import { AgentExecutor } from 'langchain/agents';\nimport type { ChainValues } from '@langchain/core/utils/types';\nimport { Logger } from '@hashgraphonline/standards-sdk';\n\n/**\n * Custom AgentExecutor that intercepts large tool outputs and converts them to content references\n * before they are sent to the LLM to avoid token limit issues.\n * \n * Note: The content reference conversion is already handled in the MCP adapter,\n * so this class currently just extends AgentExecutor without modifications.\n * We keep it as a placeholder for future enhancements.\n */\nexport class ContentAwareAgentExecutor extends AgentExecutor {\n private logger: Logger;\n\n constructor(config: any) {\n super(config);\n this.logger = new Logger({ module: 'ContentAwareAgentExecutor' });\n }\n}"],"names":[],"mappings":";;AAYO,MAAM,kCAAkC,cAAc;AAAA,EAG3D,YAAY,QAAa;AACvB,UAAM,MAAM;AACZ,SAAK,SAAS,IAAI,OAAO,EAAE,QAAQ,6BAA6B;AAAA,EAClE;AACF;"}
|
|
1
|
+
{"version":3,"file":"index15.js","sources":["../../src/memory/SmartMemoryManager.ts"],"sourcesContent":["import type { BaseMessage } from '@langchain/core/messages';\nimport { MemoryWindow } from './MemoryWindow';\nimport { ContentStorage } from './ContentStorage';\nimport { TokenCounter } from './TokenCounter';\n\n/**\n * Entity association for storing blockchain entity contexts\n */\nexport interface EntityAssociation {\n /** The blockchain entity ID (e.g., tokenId, accountId, topicId) */\n entityId: string;\n /** User-provided or derived friendly name */\n entityName: string;\n /** Type of entity (token, account, topic, schedule, etc.) */\n entityType: string;\n /** When the entity was created/associated */\n createdAt: Date;\n /** Transaction ID that created this entity */\n transactionId?: string;\n}\n\n/**\n * Options for resolving entity references\n */\nexport interface EntityResolutionOptions {\n /** Filter by specific entity type */\n entityType?: string;\n /** Maximum number of results to return */\n limit?: number;\n /** Whether to use fuzzy matching for natural language queries */\n fuzzyMatch?: boolean;\n}\n\n/**\n * Configuration for SmartMemoryManager\n */\nexport interface SmartMemoryConfig {\n /** Maximum tokens for active memory window */\n maxTokens?: number;\n /** Reserve tokens for response generation */\n reserveTokens?: number;\n /** Model name for token counting */\n modelName?: string;\n /** Maximum messages to store in content storage */\n storageLimit?: number;\n}\n\n/**\n * Search options for history search\n */\nexport interface 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 * Memory statistics for active memory window\n */\nexport interface MemoryStats {\n /** Total active messages in memory window */\n totalActiveMessages: number;\n /** Current token count including system prompt */\n currentTokenCount: number;\n /** Maximum token capacity */\n maxTokens: number;\n /** Remaining token capacity */\n remainingCapacity: number;\n /** System prompt token count */\n systemPromptTokens: number;\n /** Memory usage percentage */\n usagePercentage: number;\n}\n\nconst IS_ENTITY_ASSOCIATION_FLAG = '\"isEntityAssociation\":true';\n\n/**\n * Smart memory manager that combines active memory window with long-term storage\n * Provides context-aware memory management with automatic pruning and searchable history\n */\nexport class SmartMemoryManager {\n private memoryWindow: MemoryWindow;\n private contentStorage: ContentStorage;\n private tokenCounter: TokenCounter;\n private config: Required<SmartMemoryConfig>;\n\n private static readonly DEFAULT_CONFIG: Required<SmartMemoryConfig> = {\n maxTokens: 8000,\n reserveTokens: 1000,\n modelName: 'gpt-4o',\n storageLimit: 1000,\n };\n\n constructor(config: SmartMemoryConfig = {}) {\n this.config = { ...SmartMemoryManager.DEFAULT_CONFIG, ...config };\n\n this.tokenCounter = new TokenCounter(this.config.modelName as any);\n this.contentStorage = new ContentStorage(this.config.storageLimit);\n this.memoryWindow = new MemoryWindow(\n this.config.maxTokens,\n this.config.reserveTokens,\n this.tokenCounter\n );\n }\n\n /**\n * Add a message to the active memory window\n * Automatically handles pruning and storage of displaced messages\n * @param message - Message to add\n */\n addMessage(message: BaseMessage): void {\n const result = this.memoryWindow.addMessage(message);\n\n if (result.prunedMessages.length > 0) {\n this.contentStorage.storeMessages(result.prunedMessages);\n }\n }\n\n /**\n * Get all active messages from the memory window\n * @returns Array of active messages in chronological order\n */\n getMessages(): BaseMessage[] {\n return this.memoryWindow.getMessages();\n }\n\n /**\n * Clear active memory window\n * @param clearStorage - Whether to also clear the content storage (default: false)\n */\n clear(clearStorage: boolean = false): void {\n this.memoryWindow.clear();\n\n if (clearStorage) {\n this.contentStorage.clear();\n }\n }\n\n /**\n * Set the system prompt for the memory window\n * @param systemPrompt - System prompt text\n */\n setSystemPrompt(systemPrompt: string): void {\n this.memoryWindow.setSystemPrompt(systemPrompt);\n }\n\n /**\n * Get the current system prompt\n * @returns Current system prompt text\n */\n getSystemPrompt(): string {\n return this.memoryWindow.getSystemPrompt();\n }\n\n /**\n * Search through stored message history\n * @param query - Search term or pattern\n * @param options - Search configuration\n * @returns Array of matching messages from history\n */\n searchHistory(query: string, options: SearchOptions = {}): BaseMessage[] {\n return this.contentStorage.searchMessages(query, options);\n }\n\n /**\n * Get recent messages from storage history\n * @param count - Number of recent messages to retrieve\n * @returns Array of recent messages from storage\n */\n getRecentHistory(count: number): BaseMessage[] {\n return this.contentStorage.getRecentMessages(count);\n }\n\n /**\n * Check if a message can be added without exceeding limits\n * @param message - Message to test\n * @returns True if message can be added\n */\n canAddMessage(message: BaseMessage): boolean {\n return this.memoryWindow.canAddMessage(message);\n }\n\n /**\n * Get statistics about the active memory window\n * @returns Memory usage statistics\n */\n getMemoryStats(): MemoryStats {\n const windowStats = this.memoryWindow.getStats();\n\n return {\n totalActiveMessages: windowStats.totalMessages,\n currentTokenCount: windowStats.currentTokens,\n maxTokens: windowStats.maxTokens,\n remainingCapacity: windowStats.remainingCapacity,\n systemPromptTokens: windowStats.systemPromptTokens,\n usagePercentage: windowStats.usagePercentage,\n };\n }\n\n /**\n * Get statistics about the content storage\n * @returns Storage usage statistics\n */\n getStorageStats(): ReturnType<ContentStorage['getStorageStats']> {\n return this.contentStorage.getStorageStats();\n }\n\n /**\n * Get combined statistics for both active memory and storage\n * @returns Combined memory and storage statistics\n */\n getOverallStats(): {\n activeMemory: MemoryStats;\n storage: ReturnType<ContentStorage['getStorageStats']>;\n totalMessagesManaged: number;\n activeMemoryUtilization: number;\n storageUtilization: number;\n } {\n const memoryStats = this.getMemoryStats();\n const storageStats = this.getStorageStats();\n\n return {\n activeMemory: memoryStats,\n storage: storageStats,\n totalMessagesManaged:\n memoryStats.totalActiveMessages + storageStats.totalMessages,\n activeMemoryUtilization: memoryStats.usagePercentage,\n storageUtilization: storageStats.usagePercentage,\n };\n }\n\n /**\n * Update the configuration and apply changes\n * @param newConfig - New configuration options\n */\n updateConfig(newConfig: Partial<SmartMemoryConfig>): void {\n this.config = { ...this.config, ...newConfig };\n\n if (\n newConfig.maxTokens !== undefined ||\n newConfig.reserveTokens !== undefined\n ) {\n this.memoryWindow.updateLimits(\n this.config.maxTokens,\n this.config.reserveTokens\n );\n }\n\n if (newConfig.storageLimit !== undefined) {\n this.contentStorage.updateStorageLimit(this.config.storageLimit);\n }\n\n }\n\n /**\n * Get current configuration\n * @returns Current configuration settings\n */\n getConfig(): Required<SmartMemoryConfig> {\n return { ...this.config };\n }\n\n /**\n * Get messages from storage within a time range\n * @param startTime - Start of time range\n * @param endTime - End of time range\n * @returns Messages within the specified time range\n */\n getHistoryFromTimeRange(startTime: Date, endTime: Date): BaseMessage[] {\n return this.contentStorage.getMessagesFromTimeRange(startTime, endTime);\n }\n\n /**\n * Get messages from storage 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 Messages of the specified type\n */\n getHistoryByType(messageType: string, limit?: number): BaseMessage[] {\n return this.contentStorage.getMessagesByType(messageType, limit);\n }\n\n /**\n * Get recent messages from storage within the last N minutes\n * @param minutes - Number of minutes to look back\n * @returns Messages from the last N minutes\n */\n getRecentHistoryByTime(minutes: number): BaseMessage[] {\n return this.contentStorage.getRecentMessagesByTime(minutes);\n }\n\n /**\n * Export the current state for persistence or analysis\n * @returns Serializable representation of memory state\n */\n exportState(): {\n config: Required<SmartMemoryConfig>;\n activeMessages: Array<{ content: unknown; type: string }>;\n systemPrompt: string;\n memoryStats: MemoryStats;\n storageStats: ReturnType<ContentStorage['getStorageStats']>;\n storedMessages: ReturnType<ContentStorage['exportMessages']>;\n } {\n return {\n config: this.config,\n activeMessages: this.memoryWindow.getMessages().map((msg) => ({\n content: msg.content,\n type: msg._getType(),\n })),\n systemPrompt: this.memoryWindow.getSystemPrompt(),\n memoryStats: this.getMemoryStats(),\n storageStats: this.getStorageStats(),\n storedMessages: this.contentStorage.exportMessages(),\n };\n }\n\n /**\n * Get a summary of conversation context for external use\n * Useful for providing context to other systems or for logging\n * @param includeStoredContext - Whether to include recent stored messages\n * @returns Context summary object\n */\n getContextSummary(includeStoredContext: boolean = false): {\n activeMessageCount: number;\n systemPrompt: string;\n recentMessages: BaseMessage[];\n memoryUtilization: number;\n hasStoredHistory: boolean;\n recentStoredMessages?: BaseMessage[];\n storageStats?: ReturnType<ContentStorage['getStorageStats']>;\n } {\n const activeMessages = this.getMessages();\n const summary = {\n activeMessageCount: activeMessages.length,\n systemPrompt: this.getSystemPrompt(),\n recentMessages: activeMessages.slice(-5),\n memoryUtilization: this.getMemoryStats().usagePercentage,\n hasStoredHistory: this.getStorageStats().totalMessages > 0,\n };\n\n if (includeStoredContext) {\n return {\n ...summary,\n recentStoredMessages: this.getRecentHistory(10),\n storageStats: this.getStorageStats(),\n };\n }\n\n return summary;\n }\n\n /**\n * Perform maintenance operations\n * Optimizes storage and cleans up resources\n */\n performMaintenance(): void {\n }\n\n\n /**\n * Store an entity association for later resolution\n * @param entityId - The blockchain entity ID\n * @param entityName - User-provided or derived friendly name\n * @param entityType - Type of entity (token, account, topic, etc.)\n * @param transactionId - Optional transaction ID that created this entity\n */\n storeEntityAssociation(\n entityId: string,\n entityName: string,\n entityType: string,\n transactionId?: string\n ): void {\n try {\n if (\n !entityId ||\n typeof entityId !== 'string' ||\n entityId.trim().length === 0\n ) {\n console.warn(\n '[SmartMemoryManager] Invalid entityId provided:',\n entityId\n );\n return;\n }\n\n if (\n !entityName ||\n typeof entityName !== 'string' ||\n entityName.trim().length === 0\n ) {\n console.warn(\n '[SmartMemoryManager] Invalid entityName provided:',\n entityName\n );\n return;\n }\n\n if (\n !entityType ||\n typeof entityType !== 'string' ||\n entityType.trim().length === 0\n ) {\n console.warn(\n '[SmartMemoryManager] Invalid entityType provided:',\n entityType\n );\n return;\n }\n\n const sanitizedEntityId = entityId.trim();\n const sanitizedEntityName = entityName.trim().substring(0, 100);\n const sanitizedEntityType = entityType.trim().toLowerCase();\n\n const association: EntityAssociation = {\n entityId: sanitizedEntityId,\n entityName: sanitizedEntityName,\n entityType: sanitizedEntityType,\n createdAt: new Date(),\n ...(transactionId !== undefined && transactionId !== null && transactionId.trim() !== ''\n ? { transactionId: transactionId.trim() }\n : {})\n };\n\n const content = JSON.stringify(association);\n type LangChainLikeMessage = {\n _getType: () => string;\n content: unknown;\n id: string;\n name?: string;\n additional_kwargs?: Record<string, unknown>;\n };\n\n const entityMessage: LangChainLikeMessage = {\n _getType: () => 'system',\n content: content,\n id: `entity_${sanitizedEntityId}_${Date.now()}`,\n name: 'entity_association',\n additional_kwargs: {\n entityId: sanitizedEntityId,\n entityName: sanitizedEntityName,\n entityType: sanitizedEntityType,\n isEntityAssociation: true,\n }\n };\n \n this.contentStorage.storeMessages([entityMessage as any]);\n\n console.debug(\n `[SmartMemoryManager] Stored entity association: ${sanitizedEntityName} (${sanitizedEntityType}) -> ${sanitizedEntityId}`\n );\n } catch (_error) {\n console.error(\n '[SmartMemoryManager] Failed to store entity association:',\n _error\n );\n }\n }\n\n /**\n * Resolve entity references from natural language queries\n * @param query - Search query (entity name or natural language reference)\n * @param options - Resolution options for filtering and fuzzy matching\n * @returns Array of matching entity associations\n */\n resolveEntityReference(\n query: string,\n options: EntityResolutionOptions = {}\n ): EntityAssociation[] {\n try {\n if (!query || typeof query !== 'string') {\n console.warn(\n '[SmartMemoryManager] Invalid query provided for entity resolution:',\n query\n );\n return [];\n }\n\n const sanitizedQuery = query.trim();\n if (sanitizedQuery.length === 0) {\n return [];\n }\n\n if (sanitizedQuery.length > 200) {\n console.warn(\n '[SmartMemoryManager] Query too long, truncating:',\n sanitizedQuery.length\n );\n }\n\n const { entityType, limit = 10, fuzzyMatch = true } = options;\n\n const safeLimit = Math.max(1, Math.min(limit || 10, 100));\n\n const searchResults = this.contentStorage.searchMessages(\n sanitizedQuery.substring(0, 200),\n {\n caseSensitive: false,\n limit: safeLimit * 2,\n }\n );\n\n const associations: EntityAssociation[] = [];\n\n for (const message of searchResults) {\n try {\n const content = message.content as string;\n if (\n content.includes(IS_ENTITY_ASSOCIATION_FLAG) ||\n content.includes('entityId')\n ) {\n const parsed = JSON.parse(content);\n if (parsed.entityId && parsed.entityName && parsed.entityType) {\n if (entityType && parsed.entityType !== entityType) {\n continue;\n }\n\n associations.push(parsed as EntityAssociation);\n }\n }\n } catch {\n continue;\n }\n }\n\n if (fuzzyMatch && associations.length === 0) {\n const fuzzyQueries = [\n query.toLowerCase(),\n `token`,\n `account`,\n entityType || '',\n ].filter(Boolean);\n\n for (const fuzzyQuery of fuzzyQueries) {\n if (fuzzyQuery === query.toLowerCase()) continue;\n\n const fuzzyResults = this.contentStorage.searchMessages(fuzzyQuery, {\n caseSensitive: false,\n limit: limit,\n });\n\n for (const message of fuzzyResults) {\n try {\n const content = message.content as string;\n if (content.includes(IS_ENTITY_ASSOCIATION_FLAG)) {\n const parsed = JSON.parse(content);\n if (parsed.entityId && parsed.entityName && parsed.entityType) {\n if (entityType && parsed.entityType !== entityType) {\n continue;\n }\n associations.push(parsed as EntityAssociation);\n }\n }\n } catch {\n continue;\n }\n }\n }\n }\n\n const uniqueAssociations = associations\n .filter(\n (assoc, index, arr) =>\n arr.findIndex((a) => a.entityId === assoc.entityId) === index\n )\n .sort(\n (a, b) =>\n new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()\n );\n\n const results = uniqueAssociations.slice(0, safeLimit);\n\n if (results.length > 1) {\n console.debug(\n `[SmartMemoryManager] Multiple entities found for \"${sanitizedQuery}\":`,\n results.map((r) => `${r.entityName} (${r.entityType})`).join(', ')\n );\n }\n\n return results;\n } catch (_error) {\n console.error(\n '[SmartMemoryManager] Failed to resolve entity reference:',\n _error\n );\n return [];\n }\n }\n\n /**\n * Get all entity associations, optionally filtered by type\n * @param entityType - Optional filter by entity type\n * @returns Array of entity associations\n */\n getEntityAssociations(entityType?: string): EntityAssociation[] {\n try {\n const sanitizedEntityType = entityType\n ? entityType.trim().toLowerCase()\n : undefined;\n\n if (\n entityType &&\n (!sanitizedEntityType || sanitizedEntityType.length === 0)\n ) {\n console.warn(\n '[SmartMemoryManager] Invalid entityType filter provided:',\n entityType\n );\n return [];\n }\n\n const SEARCH_ANY_ENTITY = 'entityId';\n const searchQuery = sanitizedEntityType || SEARCH_ANY_ENTITY;\n const searchResults = this.contentStorage.searchMessages(searchQuery, {\n caseSensitive: false,\n limit: 100,\n });\n\n const associations: EntityAssociation[] = [];\n\n for (const message of searchResults) {\n try {\n const content = message.content as string;\n if (content.includes(IS_ENTITY_ASSOCIATION_FLAG)) {\n const parsed = JSON.parse(content);\n\n if (parsed.entityId && parsed.entityName && parsed.entityType) {\n if (\n sanitizedEntityType &&\n parsed.entityType !== sanitizedEntityType\n ) {\n continue;\n }\n\n if (parsed.createdAt && typeof parsed.createdAt === 'string') {\n parsed.createdAt = new Date(parsed.createdAt);\n }\n\n associations.push(parsed as EntityAssociation);\n }\n }\n } catch (_parseError) {\n console.debug(\n '[SmartMemoryManager] Skipped malformed association data:',\n _parseError\n );\n continue;\n }\n }\n\n const results = associations\n .filter(\n (assoc, index, arr) =>\n arr.findIndex((a) => a.entityId === assoc.entityId) === index\n )\n .sort((a, b): number => {\n const getTime = (d: Date | string): number =>\n d instanceof Date ? d.getTime() : new Date(d).getTime();\n const aTime = getTime(a.createdAt);\n const bTime = getTime(b.createdAt);\n return bTime - aTime;\n });\n\n console.debug(\n `[SmartMemoryManager] Retrieved ${results.length} entity associations${\n sanitizedEntityType ? ` of type '${sanitizedEntityType}'` : ''\n }`\n );\n\n return results;\n } catch (_error) {\n console.error(\n '[SmartMemoryManager] Failed to get entity associations:',\n _error\n );\n return [];\n }\n }\n\n /**\n * Clean up resources and dispose of components\n */\n dispose(): void {\n this.memoryWindow.dispose();\n this.contentStorage.dispose();\n this.tokenCounter.dispose();\n }\n}\n"],"names":[],"mappings":";;;AA6EA,MAAM,6BAA6B;AAM5B,MAAM,sBAAN,MAAM,oBAAmB;AAAA,EAa9B,YAAY,SAA4B,IAAI;AAC1C,SAAK,SAAS,EAAE,GAAG,oBAAmB,gBAAgB,GAAG,OAAA;AAEzD,SAAK,eAAe,IAAI,aAAa,KAAK,OAAO,SAAgB;AACjE,SAAK,iBAAiB,IAAI,eAAe,KAAK,OAAO,YAAY;AACjE,SAAK,eAAe,IAAI;AAAA,MACtB,KAAK,OAAO;AAAA,MACZ,KAAK,OAAO;AAAA,MACZ,KAAK;AAAA,IAAA;AAAA,EAET;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,WAAW,SAA4B;AACrC,UAAM,SAAS,KAAK,aAAa,WAAW,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